Search in sources :

Example 21 with CEntryPoint

use of org.graalvm.nativeimage.c.function.CEntryPoint in project graal by oracle.

the class PolyglotNativeAPI method polyglot_value_as_int8.

@CEntryPoint(name = "polyglot_value_as_int8")
public static PolyglotStatus polyglot_value_as_int8(IsolateThread isolate_thread, PolyglotValuePointer value, CCharPointer result) {
    return withHandledErrors(() -> {
        Value valueObject = fetchHandle(value);
        result.write(valueObject.asByte());
    });
}
Also used : Value(org.graalvm.polyglot.Value) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint)

Example 22 with CEntryPoint

use of org.graalvm.nativeimage.c.function.CEntryPoint in project graal by oracle.

the class PolyglotNativeAPI method polyglot_create_function.

@CEntryPoint(name = "polyglot_create_function")
public static PolyglotStatus polyglot_create_function(IsolateThread isolate_thread, PolyglotContextPointer polyglot_context, PolyglotCallbackPointer callback, VoidPointer data, PolyglotValuePointerPointer value) {
    return withHandledErrors(() -> {
        Context c = ObjectHandles.getGlobal().get(polyglot_context);
        ProxyExecutable executable = (Value... arguments) -> {
            ObjectHandle[] handleArgs = new ObjectHandle[arguments.length];
            for (int i = 0; i < arguments.length; i++) {
                handleArgs[i] = createHandle(arguments[i]);
            }
            PolyglotCallbackInfo cbInfo = (PolyglotCallbackInfo) createHandle(new PolyglotCallbackInfoInternal(handleArgs, data));
            try {
                PolyglotValuePointer result = callback.invoke(CEntryPointContext.getCurrentIsolateThread(), cbInfo);
                CallbackException ce = exceptionsTL.get();
                if (ce != null) {
                    exceptionsTL.remove();
                    throw ce;
                } else {
                    return PolyglotNativeAPI.fetchHandle(result);
                }
            } finally {
                PolyglotCallbackInfoInternal info = fetchHandle(cbInfo);
                for (ObjectHandle arg : info.arguments) {
                    freeHandle(arg);
                }
                freeHandle(cbInfo);
            }
        };
        value.write(createHandle(c.asValue(executable)));
    });
}
Also used : CEntryPointContext(org.graalvm.nativeimage.c.function.CEntryPointContext) Context(org.graalvm.polyglot.Context) PolyglotCallbackInfo(org.graalvm.polyglot.nativeapi.PolyglotNativeAPITypes.PolyglotCallbackInfo) ProxyExecutable(org.graalvm.polyglot.proxy.ProxyExecutable) ObjectHandle(org.graalvm.nativeimage.ObjectHandle) Value(org.graalvm.polyglot.Value) PolyglotValuePointer(org.graalvm.polyglot.nativeapi.PolyglotNativeAPITypes.PolyglotValuePointer) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint)

Example 23 with CEntryPoint

use of org.graalvm.nativeimage.c.function.CEntryPoint in project graal by oracle.

the class NativeImageGeneratorRunner method buildImage.

@SuppressWarnings("try")
private int buildImage(String[] arguments, String[] classpath, ClassLoader classLoader) {
    if (!verifyValidJavaVersionAndPlatform()) {
        return -1;
    }
    Timer totalTimer = new Timer("[total]", false);
    ForkJoinPool analysisExecutor = null;
    ForkJoinPool compilationExecutor = null;
    try (StopTimer ignored = totalTimer.start()) {
        ImageClassLoader imageClassLoader;
        Timer classlistTimer = new Timer("classlist", false);
        try (StopTimer ignored1 = classlistTimer.start()) {
            imageClassLoader = ImageClassLoader.create(defaultPlatform(), classpath, classLoader);
        }
        HostedOptionParser optionParser = new HostedOptionParser(imageClassLoader);
        String[] remainingArgs = optionParser.parse(arguments);
        if (remainingArgs.length > 0) {
            throw UserError.abort("Unknown options: " + Arrays.toString(remainingArgs));
        }
        /*
             * We do not have the VMConfiguration and the HostedOptionValues set up yet, so we need
             * to pass the OptionValues explicitly when accessing options.
             */
        OptionValues parsedHostedOptions = new OptionValues(optionParser.getHostedValues());
        DebugContext debug = DebugContext.create(parsedHostedOptions, new GraalDebugHandlersFactory(GraalAccess.getOriginalSnippetReflection()));
        String imageName = NativeImageOptions.Name.getValue(parsedHostedOptions);
        if (imageName.length() == 0) {
            throw UserError.abort("No output file name specified. " + "Use '" + SubstrateOptionsParser.commandArgument(NativeImageOptions.Name, "<output-file>") + "'.");
        }
        // print the time here to avoid interactions with flags processing
        classlistTimer.print();
        Map<Method, CEntryPointData> entryPoints = new HashMap<>();
        Method mainEntryPoint = null;
        JavaMainSupport javaMainSupport = null;
        AbstractBootImage.NativeImageKind k = AbstractBootImage.NativeImageKind.valueOf(NativeImageOptions.Kind.getValue(parsedHostedOptions));
        if (k == AbstractBootImage.NativeImageKind.EXECUTABLE) {
            String className = NativeImageOptions.Class.getValue(parsedHostedOptions);
            if (className == null || className.length() == 0) {
                throw UserError.abort("Must specify main entry point class when building " + AbstractBootImage.NativeImageKind.EXECUTABLE + " native image. " + "Use '" + SubstrateOptionsParser.commandArgument(NativeImageOptions.Class, "<fully-qualified-class-name>") + "'.");
            }
            Class<?> mainClass;
            try {
                mainClass = Class.forName(className, false, classLoader);
            } catch (ClassNotFoundException ex) {
                throw UserError.abort("Main entry point class '" + className + "' not found.");
            }
            String mainEntryPointName = NativeImageOptions.Method.getValue(parsedHostedOptions);
            if (mainEntryPointName == null || mainEntryPointName.length() == 0) {
                throw UserError.abort("Must specify main entry point method when building " + AbstractBootImage.NativeImageKind.EXECUTABLE + " native image. " + "Use '" + SubstrateOptionsParser.commandArgument(NativeImageOptions.Method, "<method-name>") + "'.");
            }
            try {
                /* First look for an main method with the C-level signature for arguments. */
                mainEntryPoint = mainClass.getDeclaredMethod(mainEntryPointName, int.class, CCharPointerPointer.class);
            } catch (NoSuchMethodException ignored2) {
                try {
                    /*
                         * If no C-level main method was found, look for a Java-level main method
                         * and use our wrapper to invoke it.
                         */
                    Method javaMainMethod = mainClass.getDeclaredMethod(mainEntryPointName, String[].class);
                    javaMainMethod.setAccessible(true);
                    if (javaMainMethod.getReturnType() != void.class) {
                        throw UserError.abort("Java main method must have return type void. Change the return type of method '" + mainClass.getName() + "." + mainEntryPointName + "(String[])'.");
                    }
                    final int mainMethodModifiers = javaMainMethod.getModifiers();
                    if (!Modifier.isPublic(mainMethodModifiers)) {
                        throw UserError.abort("Method '" + mainClass.getName() + "." + mainEntryPointName + "(String[])' is not accessible.  Please make it 'public'.");
                    }
                    javaMainSupport = new JavaMainSupport(javaMainMethod);
                    mainEntryPoint = JavaMainWrapper.class.getDeclaredMethod("run", int.class, CCharPointerPointer.class);
                } catch (NoSuchMethodException ex) {
                    throw UserError.abort("Method '" + mainClass.getName() + "." + mainEntryPointName + "' is declared as the main entry point but it can not be found. " + "Make sure that class '" + mainClass.getName() + "' is on the classpath and that method '" + mainEntryPointName + "(String[])' exists in that class.");
                }
            }
            CEntryPoint annotation = mainEntryPoint.getAnnotation(CEntryPoint.class);
            if (annotation == null) {
                throw UserError.abort("Entry point must have the '@" + CEntryPoint.class.getSimpleName() + "' annotation");
            }
            entryPoints.put(mainEntryPoint, CEntryPointData.create(mainEntryPoint));
            Class<?>[] pt = mainEntryPoint.getParameterTypes();
            if (pt.length != 2 || pt[0] != int.class || pt[1] != CCharPointerPointer.class || mainEntryPoint.getReturnType() != int.class) {
                throw UserError.abort("Main entry point must have signature 'int main(int argc, CCharPointerPointer argv)'.");
            }
        }
        int maxConcurrentThreads = NativeImageOptions.getMaximumNumberOfConcurrentThreads(parsedHostedOptions);
        analysisExecutor = Inflation.createExecutor(debug, NativeImageOptions.getMaximumNumberOfAnalysisThreads(parsedHostedOptions));
        compilationExecutor = Inflation.createExecutor(debug, maxConcurrentThreads);
        generator = new NativeImageGenerator(imageClassLoader, optionParser);
        generator.run(entryPoints, mainEntryPoint, javaMainSupport, imageName, k, SubstitutionProcessor.IDENTITY, analysisExecutor, compilationExecutor, optionParser.getRuntimeOptionNames());
    } catch (InterruptImageBuilding e) {
        if (analysisExecutor != null) {
            analysisExecutor.shutdownNow();
        }
        if (compilationExecutor != null) {
            compilationExecutor.shutdownNow();
        }
        e.getReason().ifPresent(NativeImageGeneratorRunner::info);
        return 0;
    } catch (UserException e) {
        e.getMessages().iterator().forEachRemaining(NativeImageGeneratorRunner::reportUserError);
        return -1;
    } catch (AnalysisError e) {
        NativeImageGeneratorRunner.reportUserError(e.getMessage());
        return -1;
    } catch (ParallelExecutionException pee) {
        boolean hasUserError = false;
        for (Throwable exception : pee.getExceptions()) {
            if (exception instanceof UserException) {
                ((UserException) exception).getMessages().iterator().forEachRemaining(NativeImageGeneratorRunner::reportUserError);
                hasUserError = true;
            } else if (exception instanceof AnalysisError) {
                NativeImageGeneratorRunner.reportUserError(exception.getMessage());
                hasUserError = true;
            }
        }
        if (hasUserError) {
            return -1;
        }
        if (pee.getExceptions().size() > 1) {
            System.err.println(pee.getExceptions().size() + " fatal errors detected:");
        }
        for (Throwable exception : pee.getExceptions()) {
            NativeImageGeneratorRunner.reportFatalError(exception);
        }
        return -1;
    } catch (Throwable e) {
        NativeImageGeneratorRunner.reportFatalError(e);
        return -1;
    }
    totalTimer.print();
    return 0;
}
Also used : OptionValues(org.graalvm.compiler.options.OptionValues) HashMap(java.util.HashMap) AnalysisError(com.oracle.graal.pointsto.util.AnalysisError) AbstractBootImage(com.oracle.svm.hosted.image.AbstractBootImage) HostedOptionParser(com.oracle.svm.hosted.option.HostedOptionParser) CEntryPointData(com.oracle.svm.hosted.code.CEntryPointData) ParallelExecutionException(com.oracle.graal.pointsto.util.ParallelExecutionException) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint) InterruptImageBuilding(com.oracle.svm.core.util.InterruptImageBuilding) UserException(com.oracle.svm.core.util.UserError.UserException) DebugContext(org.graalvm.compiler.debug.DebugContext) Method(java.lang.reflect.Method) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint) GraalDebugHandlersFactory(org.graalvm.compiler.printer.GraalDebugHandlersFactory) JavaMainSupport(com.oracle.svm.core.JavaMainWrapper.JavaMainSupport) StopTimer(com.oracle.graal.pointsto.util.Timer.StopTimer) Timer(com.oracle.graal.pointsto.util.Timer) StopTimer(com.oracle.graal.pointsto.util.Timer.StopTimer) CCharPointerPointer(org.graalvm.nativeimage.c.type.CCharPointerPointer) ForkJoinPool(java.util.concurrent.ForkJoinPool)

Example 24 with CEntryPoint

use of org.graalvm.nativeimage.c.function.CEntryPoint in project graal by oracle.

the class JNIFunctions method UnregisterNatives.

/*
     * jint UnregisterNatives(JNIEnv *env, jclass clazz);
     */
@CEntryPoint
@CEntryPointOptions(prologue = JNIEnvironmentEnterPrologue.class, exceptionHandler = JNIExceptionHandlerReturnJniErr.class, publishAs = Publish.NotPublished, include = CEntryPointOptions.NotIncludedAutomatically.class)
static int UnregisterNatives(JNIEnvironment env, JNIObjectHandle hclazz) {
    Class<?> clazz = JNIObjectHandles.getObject(hclazz);
    String internalName = MetaUtil.toInternalName(clazz.getName());
    for (JNINativeLinkage linkage : JNIReflectionDictionary.singleton().getLinkages(internalName)) {
        linkage.unsetEntryPoint();
    }
    return JNIErrors.JNI_OK();
}
Also used : JNINativeLinkage(com.oracle.svm.jni.access.JNINativeLinkage) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint) CEntryPointOptions(com.oracle.svm.core.c.function.CEntryPointOptions)

Example 25 with CEntryPoint

use of org.graalvm.nativeimage.c.function.CEntryPoint in project graal by oracle.

the class JNIFunctions method GetStringUTFRegion.

/*
     * void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);
     */
@CEntryPoint
@CEntryPointOptions(prologue = JNIEnvironmentEnterPrologue.class, exceptionHandler = JNIExceptionHandlerVoid.class, publishAs = Publish.NotPublished, include = CEntryPointOptions.NotIncludedAutomatically.class)
static void GetStringUTFRegion(JNIEnvironment env, JNIObjectHandle hstr, int start, int len, CCharPointer buf) {
    String str = JNIObjectHandles.getObject(hstr);
    if (start < 0) {
        throw new StringIndexOutOfBoundsException(start);
    }
    if (start + len > str.length()) {
        throw new StringIndexOutOfBoundsException(start + len);
    }
    if (len < 0) {
        throw new StringIndexOutOfBoundsException(len);
    }
    // estimate: caller must pre-allocate
    int capacity = Utf8.maxUtf8ByteLength(len, true);
    // enough
    ByteBuffer buffer = SubstrateUtil.wrapAsByteBuffer(buf, capacity);
    Utf8.substringToUtf8(buffer, str, start, start + len, true);
}
Also used : ByteBuffer(java.nio.ByteBuffer) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint) CEntryPoint(org.graalvm.nativeimage.c.function.CEntryPoint) CEntryPointOptions(com.oracle.svm.core.c.function.CEntryPointOptions)

Aggregations

CEntryPoint (org.graalvm.nativeimage.c.function.CEntryPoint)81 CEntryPointOptions (com.oracle.svm.core.c.function.CEntryPointOptions)26 Value (org.graalvm.polyglot.Value)23 CEntryPointContext (org.graalvm.nativeimage.c.function.CEntryPointContext)19 Context (org.graalvm.polyglot.Context)19 Uninterruptible (com.oracle.svm.core.annotate.Uninterruptible)7 ObjectHandle (org.graalvm.nativeimage.ObjectHandle)5 TruffleObject (com.oracle.truffle.api.interop.TruffleObject)4 CCharPointer (org.graalvm.nativeimage.c.type.CCharPointer)4 CIntPointer (org.graalvm.nativeimage.c.type.CIntPointer)4 JNIObjectHandle (com.oracle.svm.jni.nativeapi.JNIObjectHandle)3 PinnedObject (org.graalvm.nativeimage.PinnedObject)3 Log (com.oracle.svm.core.log.Log)2 JNIAccessibleMethodDescriptor (com.oracle.svm.jni.access.JNIAccessibleMethodDescriptor)2 JNINativeLinkage (com.oracle.svm.jni.access.JNINativeLinkage)2 JNIMethodId (com.oracle.svm.jni.nativeapi.JNIMethodId)2 JNINativeMethod (com.oracle.svm.jni.nativeapi.JNINativeMethod)2 Executable (java.lang.reflect.Executable)2 Method (java.lang.reflect.Method)2 ByteBuffer (java.nio.ByteBuffer)2