Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature[Panama-generator] #57

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .mvn/jvm.config

This file was deleted.

15 changes: 9 additions & 6 deletions panama-generator/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>io.github.dreamlike-ocean</groupId>
<artifactId>PanamaUring</artifactId>
<version>1.0.3</version>
<version>1.0.5</version>
</parent>

<artifactId>panama-generator</artifactId>
Expand All @@ -28,6 +28,14 @@
</profiles>

<dependencies>

<dependency>
<groupId>io.github.dreamlike-ocean</groupId>
<artifactId>unsafe-vt</artifactId>
<version>1.0.5</version>
<scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.graalvm.sdk/nativeimage -->
<dependency>
<groupId>org.graalvm.sdk</groupId>
Expand Down Expand Up @@ -59,11 +67,6 @@
<configuration>
<target>${java.version}</target>
<source>${java.version}</source>
<compilerArgs>
<compilerArg>
--enable-preview
</compilerArg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import java.util.concurrent.Callable;

public class MemoryLifetimeScope {
static ScopedValue<SegmentAllocator> currentAllocator = ScopedValue.newInstance();
static ThreadLocal<SegmentAllocator> currentAllocator = new ThreadLocal<>();
final SegmentAllocator allocator;

private MemoryLifetimeScope(SegmentAllocator allocator) {
Expand All @@ -23,13 +23,21 @@ public static MemoryLifetimeScope auto() {
}

public <T> T active(Callable<T> callable) throws Exception {
return ScopedValue.where(currentAllocator, allocator)
.call(callable::call);
try {
currentAllocator.set(allocator);
return callable.call();
} finally {
currentAllocator.remove();
}
}

public void active(Runnable runnable) {
ScopedValue.where(currentAllocator, allocator)
.run(runnable);
try {
currentAllocator.set(allocator);
runnable.run();
} finally {
currentAllocator.remove();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,34 @@
import top.dreamlike.panama.generator.annotation.NativeFunction;
import top.dreamlike.panama.generator.annotation.Pointer;
import top.dreamlike.panama.generator.exception.StructException;
import top.dreamlike.panama.generator.helper.*;

import java.io.*;
import java.lang.classfile.AccessFlags;
import top.dreamlike.panama.generator.helper.ClassFileHelper;
import top.dreamlike.panama.generator.helper.DowncallContext;
import top.dreamlike.panama.generator.helper.FunctionPointer;
import top.dreamlike.panama.generator.helper.NativeAddressable;
import top.dreamlike.panama.generator.helper.NativeGeneratorHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.classfile.ClassBuilder;
import java.lang.classfile.ClassFile;
import java.lang.classfile.CodeBuilder;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDescs;
import java.lang.constant.DynamicCallSiteDesc;
import java.lang.foreign.*;
import java.lang.invoke.*;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.AccessFlag;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
Expand Down Expand Up @@ -58,7 +74,7 @@ public class NativeCallGenerator {
private static final Method GENERATE_IN_GENERATOR_CONTEXT;

public volatile boolean use_lmf = !NativeImageHelper.inExecutable();
private Map<String, MemorySegment> foreignFunctionAddressCache = new ConcurrentHashMap<>();
private final Map<String, MemorySegment> foreignFunctionAddressCache = new ConcurrentHashMap<>();
private volatile boolean use_indy = !NativeImageHelper.inExecutable();

final Map<Class<?>, Supplier<Object>> ctorCaches = new ConcurrentHashMap<>();
Expand Down Expand Up @@ -410,7 +426,7 @@ private Class generateRuntimeProxyClass(MethodHandles.Lookup lookup, Class nativ
var thisClassDesc = ClassDesc.ofDescriptor("L" + className.replace(".", "/") + ";");
var thisClass = classFile.build(thisClassDesc, classBuilder -> {
classBuilder.withInterfaceSymbols(ClassFileHelper.toDesc(nativeInterface));
classBuilder.withField(GENERATOR_FIELD_NAME, ClassFileHelper.toDesc(NativeCallGenerator.class), AccessFlags.ofField(AccessFlag.PUBLIC, AccessFlag.STATIC, AccessFlag.FINAL).flagsMask());
classBuilder.withField(GENERATOR_FIELD_NAME, ClassFileHelper.toDesc(NativeCallGenerator.class), AccessFlag.PUBLIC.mask() | AccessFlag.STATIC.mask() | AccessFlag.FINAL.mask());
ArrayList<Consumer<CodeBuilder>> clinits = new ArrayList<>();
//初始化内部的genertor字段
clinits.add(it -> {
Expand Down Expand Up @@ -454,11 +470,11 @@ private Class generateRuntimeProxyClass(MethodHandles.Lookup lookup, Class nativ
private Consumer<CodeBuilder> invokeByMh(Method method, ClassBuilder thisClass, String className) {
String mhFieldName = method.getName() + "_native_method_handle";
ClassDesc thisClassDesc = ClassDesc.of(className);
thisClass.withMethodBody(method.getName(), ClassFileHelper.toMethodDescriptor(method), AccessFlags.ofMethod(AccessFlag.PUBLIC).flagsMask(), it -> {
thisClass.withMethodBody(method.getName(), ClassFileHelper.toMethodDescriptor(method), AccessFlag.PUBLIC.mask(), it -> {
it.getstatic(thisClassDesc, mhFieldName, ClassFileHelper.toDesc(MethodHandle.class));
ClassFileHelper.invokeMethodHandleExactWithAllArgs(method, it);
});
thisClass.withField(mhFieldName, ClassFileHelper.toDesc(MethodHandle.class), AccessFlags.ofField(AccessFlag.PUBLIC, AccessFlag.STATIC, AccessFlag.FINAL).flagsMask());
thisClass.withField(mhFieldName, ClassFileHelper.toDesc(MethodHandle.class), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC | ClassFile.ACC_FINAL);
return it -> {
it.getstatic(thisClassDesc, GENERATOR_FIELD_NAME, ClassFileHelper.toDesc(NativeCallGenerator.class));
ClassDesc nativeInterfaceClassDesc = ClassFileHelper.toDesc(method.getDeclaringClass());
Expand All @@ -471,7 +487,7 @@ private Consumer<CodeBuilder> invokeByMh(Method method, ClassBuilder thisClass,
}

private void invokeByIndy(Method method, ClassBuilder thisClass, String className) {
thisClass.withMethodBody(method.getName(), ClassFileHelper.toMethodDescriptor(method), AccessFlags.ofMethod(AccessFlag.PUBLIC).flagsMask(), it -> {
thisClass.withMethodBody(method.getName(), ClassFileHelper.toMethodDescriptor(method), ClassFile.ACC_PUBLIC, it -> {
ClassFileHelper.loadAllArgs(method, it);
it.invokedynamic(
DynamicCallSiteDesc.of(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
package top.dreamlike.panama.generator.proxy;

import java.lang.foreign.*;
import io.github.dreamlike.unsafe.vthread.TerminatingThreadLocal;

import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SegmentAllocator;
import java.lang.foreign.StructLayout;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
Expand Down Expand Up @@ -30,6 +40,7 @@ class NativeLookup implements SymbolLookup {
private static final MethodHandle MEMORY_SEGMENT_HEAP_SHORT_MH;


private static final boolean TERMINATING_THREAD_LOCAL_ENABLE;
private static final VarHandle errorHandle;

//sb java 只能枚举全部原始类型了
Expand Down Expand Up @@ -63,22 +74,66 @@ class NativeLookup implements SymbolLookup {
FILL_ERROR_CODE_ADDRESS_MH = lookup
.findStatic(NativeLookup.class, "fillTLErrorAddress", MethodType.methodType(MemorySegment.class, MemorySegment.class));

MEMORY_SEGMENT_HEAP_INT_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, int[].class));
MEMORY_SEGMENT_HEAP_LONG_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, long[].class));
MEMORY_SEGMENT_HEAP_CHAR_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, char[].class));
MEMORY_SEGMENT_HEAP_FLOAT_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, float[].class));
MEMORY_SEGMENT_HEAP_DOUBLE_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, double[].class));
MEMORY_SEGMENT_HEAP_BYTE_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, byte[].class));
MEMORY_SEGMENT_HEAP_SHORT_MH = lookup.findStatic(MemorySegment.class,"ofArray", MethodType.methodType(MemorySegment.class, short[].class));
MEMORY_SEGMENT_HEAP_INT_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, int[].class));
MEMORY_SEGMENT_HEAP_LONG_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, long[].class));
MEMORY_SEGMENT_HEAP_CHAR_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, char[].class));
MEMORY_SEGMENT_HEAP_FLOAT_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, float[].class));
MEMORY_SEGMENT_HEAP_DOUBLE_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, double[].class));
MEMORY_SEGMENT_HEAP_BYTE_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, byte[].class));
MEMORY_SEGMENT_HEAP_SHORT_MH = lookup.findStatic(MemorySegment.class, "ofArray", MethodType.methodType(MemorySegment.class, short[].class));

boolean enableTerminatingThreadLocal;

if (NativeImageHelper.inExecutable()) {
enableTerminatingThreadLocal = false;
} else {
try {
Class.forName("io.github.dreamlike.unsafe.vthread.TerminatingThreadLocal");
enableTerminatingThreadLocal = true;
} catch (ClassNotFoundException e) {
enableTerminatingThreadLocal = false;
}
}

TERMINATING_THREAD_LOCAL_ENABLE = enableTerminatingThreadLocal;
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}

public static MemorySegment allocateErrorBuffer() {
SegmentAllocator allocator = MemoryLifetimeScope.currentAllocator.orElseThrow(() -> new IllegalStateException("please active MemoryLifetimeScope first!"));
SegmentAllocator allocator = MemoryLifetimeScope.currentAllocator.get();
StructLayout structLayout = Linker.Option.captureStateLayout();
MemorySegment buffer = allocator.allocate(structLayout);
MemorySegment buffer;

if (allocator != null) {
buffer = allocator.allocate(structLayout);
} else {
if (!TERMINATING_THREAD_LOCAL_ENABLE) {
throw new IllegalStateException("please active MemoryLifetimeScope first!");
} else {
//lazy init
class Holder {
static final TerminatingThreadLocal<ErrorBufferHolder> errorBufferHolder = new TerminatingThreadLocal<>() {
@Override
protected void threadTerminated(ErrorBufferHolder value) {
value.allocator.close();
}
};
}

ErrorBufferHolder errorBufferHolder = Holder.errorBufferHolder.get();
if (errorBufferHolder == null) {
Arena arena = Arena.ofConfined();
buffer = arena.allocate(structLayout);
Holder.errorBufferHolder.set(new ErrorBufferHolder(arena, buffer));
} else {
buffer = errorBufferHolder.buffer;
}
}
}


errorBuffer.set(buffer);
return buffer;
}
Expand Down Expand Up @@ -169,6 +224,21 @@ public static MemorySegment fillTLErrorAddress(MemorySegment returnValue) {
return returnValue;
}

public static MemoryLayout primitiveMapToMemoryLayout(Class source) {
return switch (source) {
case Class c when c == int.class -> ValueLayout.JAVA_INT;
case Class c when c == long.class -> ValueLayout.JAVA_LONG;
case Class c when c == double.class -> ValueLayout.JAVA_DOUBLE;
case Class c when c == float.class -> ValueLayout.JAVA_FLOAT;
case Class c when c == byte.class -> ValueLayout.JAVA_BYTE;
case Class c when c == boolean.class -> ValueLayout.JAVA_BOOLEAN;
case Class c when c == char.class -> ValueLayout.JAVA_CHAR;
case Class c when c == short.class -> ValueLayout.JAVA_SHORT;
// case Class c when NativeStructEnhanceMark.class.isAssignableFrom(c) -> ValueLayout.ADDRESS;
default -> null;
};
}

@Override
public Optional<MemorySegment> find(String name) {
return SymbolLookup.loaderLookup()
Expand All @@ -187,19 +257,7 @@ public MethodHandle downcallHandle(String name, FunctionDescriptor functionDescr
.orElseThrow(() -> new IllegalArgumentException("cant link " + name));
}

public static MemoryLayout primitiveMapToMemoryLayout(Class source) {
return switch (source) {
case Class c when c == int.class -> ValueLayout.JAVA_INT;
case Class c when c == long.class -> ValueLayout.JAVA_LONG;
case Class c when c == double.class -> ValueLayout.JAVA_DOUBLE;
case Class c when c == float.class -> ValueLayout.JAVA_FLOAT;
case Class c when c == byte.class -> ValueLayout.JAVA_BYTE;
case Class c when c == boolean.class -> ValueLayout.JAVA_BOOLEAN;
case Class c when c == char.class -> ValueLayout.JAVA_CHAR;
case Class c when c == short.class -> ValueLayout.JAVA_SHORT;
// case Class c when NativeStructEnhanceMark.class.isAssignableFrom(c) -> ValueLayout.ADDRESS;
default -> null;
};
record ErrorBufferHolder(Arena allocator, MemorySegment buffer) {
}


Expand Down
Loading