1 /*
 2  * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 #include "jni.h"
25 #include "testlib_threads.h"
26 
27 typedef struct {
28    JavaVM* jvm;
29    jobject linker;
30    jobject desc;
31    jobject opts;
32    jthrowable exception;
33 } Context;
34 
35 void call(void* arg) {
36     Context* context = (Context*)arg;
37     JNIEnv* env;
38     context->jvm->AttachCurrentThread((void**)&env, NULL);
39     jclass linkerClass = env->FindClass("java/lang/foreign/Linker");
40     jmethodID nativeLinkerMethod = env->GetMethodID(linkerClass, "downcallHandle",
41             "(Ljava/lang/foreign/FunctionDescriptor;[Ljava/lang/foreign/Linker$Option;)Ljava/lang/invoke/MethodHandle;");
42     env->CallVoidMethod(context->linker, nativeLinkerMethod, context->desc, context->opts);
43     context->exception = (jthrowable) env->NewGlobalRef(env->ExceptionOccurred());
44     env->ExceptionClear();
45     context->jvm->DetachCurrentThread();
46 }
47 
48 extern "C" {
49     JNIEXPORT void JNICALL
50     Java_org_openjdk_foreigntest_PanamaMainJNI_nativeLinker0(JNIEnv *env, jclass cls, jobject linker, jobject desc, jobjectArray opts) {
51         Context context;
52         env->GetJavaVM(&context.jvm);
53         context.linker = env->NewGlobalRef(linker);
54         context.desc = env->NewGlobalRef(desc);
55         context.opts = env->NewGlobalRef(opts);
56         run_in_new_thread_and_join(call, &context);
57         if (context.exception != nullptr) {
58             env->Throw(context.exception); // transfer exception to this thread
59         }
60         env->DeleteGlobalRef(context.linker);
61         env->DeleteGlobalRef(context.desc);
62         env->DeleteGlobalRef(context.opts);
63         env->DeleteGlobalRef(context.exception);
64     }
65 }