1 /*
 2  * Copyright (c) 2021, 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 <stdlib.h>
26 
27 #include "JNICB.h"
28 #include "jlong.h"
29 
30 #define CHECK_NULL(thing, message) \
31     if (thing == NULL) { \
32         jclass cls = (*env)->FindClass(env, "java/lang/Exception"); \
33         (*env)->ThrowNew(env, cls, message); \
34         return 0; \
35     }
36 
37 JNIEXPORT jlong JNICALL Java_org_openjdk_bench_jdk_incubator_foreign_JNICB_makeCB
38   (JNIEnv *env, jclass cls, jstring holderName, jstring methodName, jstring descriptor) {
39 
40   const char* holderNameC = (*env)->GetStringUTFChars(env, holderName, NULL);
41   const char* methodNameC = (*env)->GetStringUTFChars(env, methodName, NULL);
42   const char* descriptorC = (*env)->GetStringUTFChars(env, descriptor, NULL);
43 
44   JNICB cb = malloc(sizeof *cb);
45   CHECK_NULL(cb, "Can not allocate cb");
46 
47   jclass holder = (*env)->FindClass(env, holderNameC);
48   CHECK_NULL(holder, "Can not find class");
49   holder = (jclass) (*env)->NewGlobalRef(env, holder);
50   cb->holder = holder;
51 
52   jmethodID methodID = (*env)->GetStaticMethodID(env, holder, methodNameC, descriptorC);
53   CHECK_NULL(methodID, "Can not find method");
54   //methodID = (jmethodID) (*env)->NewGlobalRef(env, methodID); // DON'T DO THIS! -> Crashes GC
55   cb->mid = methodID;
56 
57   (*env)->ReleaseStringUTFChars(env, holderName, holderNameC);
58   (*env)->ReleaseStringUTFChars(env, methodName, methodNameC);
59   (*env)->ReleaseStringUTFChars(env, descriptor, descriptorC);
60 
61   return ptr_to_jlong(cb);
62 }