-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathdartjni.c
919 lines (835 loc) · 30.5 KB
/
dartjni.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <jni.h>
#include <stdarg.h>
#include <stdint.h>
#include "dartjni.h"
#ifndef _WIN32
pthread_key_t tlsKey;
#endif
/// Load class through platform-specific mechanism.
///
/// Currently uses application classloader on android,
/// and JNIEnv->FindClass on other platforms.
jclass FindClass(const char* name) {
attach_thread();
jclass cls;
load_class_platform(&cls, name);
if (!(*jniEnv)->ExceptionCheck(jniEnv)) {
cls = to_global_ref(cls);
}
return cls;
};
/// Stores class and method references for obtaining exception details
typedef struct JniExceptionMethods {
jclass objectClass, exceptionClass, printStreamClass;
jclass byteArrayOutputStreamClass;
jmethodID toStringMethod, printStackTraceMethod;
jmethodID byteArrayOutputStreamCtor, printStreamCtor;
} JniExceptionMethods;
// Context and shared global state. Initialized once or if thread-local, initialized once in a thread.
JniContext jni_context = {
.jvm = NULL,
.classLoader = NULL,
.loadClassMethod = NULL,
.appContext = NULL,
.currentActivity = NULL,
};
JniContext* jni = &jni_context;
THREAD_LOCAL JNIEnv* jniEnv = NULL;
JniExceptionMethods exceptionMethods;
void init() {
#ifndef _WIN32
// Init TLS keys.
pthread_key_create(&tlsKey, detach_thread);
#endif
// Init locks.
init_lock(&jni_context.locks.classLoadingLock);
// Init exception handling classes and methods.
exceptionMethods.objectClass = FindClass("java/lang/Object");
exceptionMethods.exceptionClass = FindClass("java/lang/Exception");
exceptionMethods.printStreamClass = FindClass("java/io/PrintStream");
exceptionMethods.byteArrayOutputStreamClass =
FindClass("java/io/ByteArrayOutputStream");
load_method(exceptionMethods.objectClass, &exceptionMethods.toStringMethod,
"toString", "()Ljava/lang/String;");
load_method(exceptionMethods.exceptionClass,
&exceptionMethods.printStackTraceMethod, "printStackTrace",
"(Ljava/io/PrintStream;)V");
load_method(exceptionMethods.byteArrayOutputStreamClass,
&exceptionMethods.byteArrayOutputStreamCtor, "<init>", "()V");
load_method(exceptionMethods.printStreamClass,
&exceptionMethods.printStreamCtor, "<init>",
"(Ljava/io/OutputStream;)V");
}
void deinit() {
#ifndef _WIN32
// Delete TLS keys.
pthread_key_delete(tlsKey);
#endif
// Destroy locks.
destroy_lock(&jni_context.locks.classLoadingLock);
// Delete references to exception handling classes.
if (jniEnv != NULL) {
(*jniEnv)->DeleteGlobalRef(jniEnv, exceptionMethods.objectClass);
(*jniEnv)->DeleteGlobalRef(jniEnv, exceptionMethods.exceptionClass);
(*jniEnv)->DeleteGlobalRef(jniEnv, exceptionMethods.printStreamClass);
(*jniEnv)->DeleteGlobalRef(jniEnv,
exceptionMethods.byteArrayOutputStreamClass);
}
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* jvm, void* reserved) {
deinit();
}
/// Get JVM associated with current process.
/// Returns NULL if no JVM is running.
FFI_PLUGIN_EXPORT
JavaVM* GetJavaVM() {
return jni_context.jvm;
}
// Android specifics
FFI_PLUGIN_EXPORT
jobject GetClassLoader() {
attach_thread();
return (*jniEnv)->NewGlobalRef(jniEnv, jni_context.classLoader);
}
FFI_PLUGIN_EXPORT
jobject GetApplicationContext() {
attach_thread();
return (*jniEnv)->NewGlobalRef(jniEnv, jni_context.appContext);
}
FFI_PLUGIN_EXPORT
jobject GetCurrentActivity() {
attach_thread();
return (*jniEnv)->NewGlobalRef(jniEnv, jni_context.currentActivity);
}
// JNI Initialization
#ifdef __ANDROID__
JNIEXPORT void JNICALL
Java_com_github_dart_1lang_jni_JniPlugin_initializeJni(JNIEnv* env,
jobject obj,
jobject appContext,
jobject classLoader) {
jniEnv = env;
(*env)->GetJavaVM(env, &jni_context.jvm);
jni_context.classLoader = (*env)->NewGlobalRef(env, classLoader);
jni_context.appContext = (*env)->NewGlobalRef(env, appContext);
jclass classLoaderClass = (*env)->GetObjectClass(env, classLoader);
jni_context.loadClassMethod =
(*env)->GetMethodID(env, classLoaderClass, "loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;");
init();
}
JNIEXPORT void JNICALL
Java_com_github_dart_1lang_jni_JniPlugin_setJniActivity(JNIEnv* env,
jobject obj,
jobject activity,
jobject context) {
jniEnv = env;
if (jni_context.currentActivity != NULL) {
(*env)->DeleteGlobalRef(env, jni_context.currentActivity);
}
jni_context.currentActivity = (*env)->NewGlobalRef(env, activity);
if (jni_context.appContext != NULL) {
(*env)->DeleteGlobalRef(env, jni_context.appContext);
}
jni_context.appContext = (*env)->NewGlobalRef(env, context);
}
// Sometimes you may get linker error trying to link JNI_CreateJavaVM APIs
// on Android NDK. So IFDEF is required.
#else
#ifdef _WIN32
// Pre-initialization of critical section on windows - this is required because
// there's no coordination between multiple isolates calling Spawn.
//
// Taken from https://stackoverflow.com/a/12858955
CRITICAL_SECTION spawnLock = {0};
BOOL WINAPI DllMain(HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved) { // reserved
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
InitializeCriticalSection(&spawnLock);
break;
case DLL_THREAD_DETACH:
if (jniEnv != NULL) {
detach_thread(jniEnv);
}
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
DeleteCriticalSection(&spawnLock);
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
#else
pthread_mutex_t spawnLock = PTHREAD_MUTEX_INITIALIZER;
#endif
FFI_PLUGIN_EXPORT
int SpawnJvm(JavaVMInitArgs* initArgs) {
if (jni_context.jvm != NULL) {
return DART_JNI_SINGLETON_EXISTS;
}
acquire_lock(&spawnLock);
// Init may have happened in the meanwhile.
if (jni_context.jvm != NULL) {
release_lock(&spawnLock);
return DART_JNI_SINGLETON_EXISTS;
}
JavaVMOption jvmopt[1];
char class_path[] = "-Djava.class.path=.";
jvmopt[0].optionString = class_path;
JavaVMInitArgs vmArgs;
if (!initArgs) {
vmArgs.version = JNI_VERSION_1_6;
vmArgs.nOptions = 1;
vmArgs.options = jvmopt;
vmArgs.ignoreUnrecognized = JNI_TRUE;
initArgs = &vmArgs;
}
const long flag =
JNI_CreateJavaVM(&jni_context.jvm, __ENVP_CAST & jniEnv, initArgs);
if (flag != JNI_OK) {
return flag;
}
init();
release_lock(&spawnLock);
return JNI_OK;
}
#endif
// accessors - a bunch of functions which are directly called by jnigen generated bindings
// and also package:jni reflective method access.
JniClassLookupResult getClass(char* internalName) {
JniClassLookupResult result = {NULL, NULL};
result.value = FindClass(internalName);
result.exception = check_exception();
return result;
}
typedef void* (*MemberGetter)(JNIEnv* env, jclass clazz, char* name, char* sig);
static inline JniPointerResult _getId(MemberGetter getter,
jclass cls,
char* name,
char* sig) {
JniPointerResult result = {NULL, NULL};
result.value = getter(jniEnv, cls, name, sig);
result.exception = check_exception();
return result;
}
JniPointerResult getMethodID(jclass cls, char* name, char* sig) {
attach_thread();
return _getId((MemberGetter)(*jniEnv)->GetMethodID, cls, name, sig);
}
JniPointerResult getStaticMethodID(jclass cls, char* name, char* sig) {
attach_thread();
return _getId((MemberGetter)(*jniEnv)->GetStaticMethodID, cls, name, sig);
}
JniPointerResult getFieldID(jclass cls, char* name, char* sig) {
attach_thread();
return _getId((MemberGetter)(*jniEnv)->GetFieldID, cls, name, sig);
}
JniPointerResult getStaticFieldID(jclass cls, char* name, char* sig) {
attach_thread();
return _getId((MemberGetter)(*jniEnv)->GetStaticFieldID, cls, name, sig);
}
JniResult callMethod(jobject obj,
jmethodID fieldID,
int callType,
jvalue* args) {
attach_thread();
jvalue result = {.j = 0};
switch (callType) {
case booleanType:
result.z = (*jniEnv)->CallBooleanMethodA(jniEnv, obj, fieldID, args);
break;
case byteType:
result.b = (*jniEnv)->CallByteMethodA(jniEnv, obj, fieldID, args);
break;
case shortType:
result.s = (*jniEnv)->CallShortMethodA(jniEnv, obj, fieldID, args);
break;
case charType:
result.c = (*jniEnv)->CallCharMethodA(jniEnv, obj, fieldID, args);
break;
case intType:
result.i = (*jniEnv)->CallIntMethodA(jniEnv, obj, fieldID, args);
break;
case longType:
result.j = (*jniEnv)->CallLongMethodA(jniEnv, obj, fieldID, args);
break;
case floatType:
result.f = (*jniEnv)->CallFloatMethodA(jniEnv, obj, fieldID, args);
break;
case doubleType:
result.d = (*jniEnv)->CallDoubleMethodA(jniEnv, obj, fieldID, args);
break;
case objectType:
result.l = (*jniEnv)->CallObjectMethodA(jniEnv, obj, fieldID, args);
break;
case voidType:
(*jniEnv)->CallVoidMethodA(jniEnv, obj, fieldID, args);
break;
}
jthrowable exception = check_exception();
if (callType == objectType && exception == NULL) {
result.l = to_global_ref(result.l);
}
JniResult jniResult = {.value = result, .exception = exception};
return jniResult;
}
// TODO(#60): Any way to reduce this boilerplate?
JniResult callStaticMethod(jclass cls,
jmethodID methodID,
int callType,
jvalue* args) {
attach_thread();
jvalue result = {.j = 0};
switch (callType) {
case booleanType:
result.z =
(*jniEnv)->CallStaticBooleanMethodA(jniEnv, cls, methodID, args);
break;
case byteType:
result.b = (*jniEnv)->CallStaticByteMethodA(jniEnv, cls, methodID, args);
break;
case shortType:
result.s = (*jniEnv)->CallStaticShortMethodA(jniEnv, cls, methodID, args);
break;
case charType:
result.c = (*jniEnv)->CallStaticCharMethodA(jniEnv, cls, methodID, args);
break;
case intType:
result.i = (*jniEnv)->CallStaticIntMethodA(jniEnv, cls, methodID, args);
break;
case longType:
result.j = (*jniEnv)->CallStaticLongMethodA(jniEnv, cls, methodID, args);
break;
case floatType:
result.f = (*jniEnv)->CallStaticFloatMethodA(jniEnv, cls, methodID, args);
break;
case doubleType:
result.d =
(*jniEnv)->CallStaticDoubleMethodA(jniEnv, cls, methodID, args);
break;
case objectType:
result.l =
(*jniEnv)->CallStaticObjectMethodA(jniEnv, cls, methodID, args);
break;
case voidType:
(*jniEnv)->CallStaticVoidMethodA(jniEnv, cls, methodID, args);
break;
}
jthrowable exception = check_exception();
if (callType == objectType && exception == NULL) {
result.l = to_global_ref(result.l);
}
JniResult jniResult = {.value = result, .exception = exception};
return jniResult;
}
JniResult getField(jobject obj, jfieldID fieldID, int callType) {
attach_thread();
jvalue result = {.j = 0};
switch (callType) {
case booleanType:
result.z = (*jniEnv)->GetBooleanField(jniEnv, obj, fieldID);
break;
case byteType:
result.b = (*jniEnv)->GetByteField(jniEnv, obj, fieldID);
break;
case shortType:
result.s = (*jniEnv)->GetShortField(jniEnv, obj, fieldID);
break;
case charType:
result.c = (*jniEnv)->GetCharField(jniEnv, obj, fieldID);
break;
case intType:
result.i = (*jniEnv)->GetIntField(jniEnv, obj, fieldID);
break;
case longType:
result.j = (*jniEnv)->GetLongField(jniEnv, obj, fieldID);
break;
case floatType:
result.f = (*jniEnv)->GetFloatField(jniEnv, obj, fieldID);
break;
case doubleType:
result.d = (*jniEnv)->GetDoubleField(jniEnv, obj, fieldID);
break;
case objectType:
result.l = (*jniEnv)->GetObjectField(jniEnv, obj, fieldID);
break;
case voidType:
// This error should have been handled in Dart.
break;
}
jthrowable exception = check_exception();
if (callType == objectType && exception == NULL) {
result.l = to_global_ref(result.l);
}
JniResult jniResult = {.value = result, .exception = exception};
return jniResult;
}
FFI_PLUGIN_EXPORT
JniResult getStaticField(jclass cls, jfieldID fieldID, int callType) {
attach_thread();
jvalue result = {.j = 0};
switch (callType) {
case booleanType:
result.z = (*jniEnv)->GetStaticBooleanField(jniEnv, cls, fieldID);
break;
case byteType:
result.b = (*jniEnv)->GetStaticByteField(jniEnv, cls, fieldID);
break;
case shortType:
result.s = (*jniEnv)->GetStaticShortField(jniEnv, cls, fieldID);
break;
case charType:
result.c = (*jniEnv)->GetStaticCharField(jniEnv, cls, fieldID);
break;
case intType:
result.i = (*jniEnv)->GetStaticIntField(jniEnv, cls, fieldID);
break;
case longType:
result.j = (*jniEnv)->GetStaticLongField(jniEnv, cls, fieldID);
break;
case floatType:
result.f = (*jniEnv)->GetStaticFloatField(jniEnv, cls, fieldID);
break;
case doubleType:
result.d = (*jniEnv)->GetStaticDoubleField(jniEnv, cls, fieldID);
break;
case objectType:
result.l = (*jniEnv)->GetStaticObjectField(jniEnv, cls, fieldID);
break;
case voidType:
// This error should have been handled in dart.
// is there a way to mark this as unreachable?
// or throw exception in Dart using Dart's C API.
break;
}
jthrowable exception = check_exception();
if (callType == objectType && exception == NULL) {
result.l = to_global_ref(result.l);
}
JniResult jniResult = {.value = result, .exception = exception};
return jniResult;
}
JniResult newObject(jclass cls, jmethodID ctor, jvalue* args) {
attach_thread();
jobject result = (*jniEnv)->NewObjectA(jniEnv, cls, ctor, args);
return to_global_ref_result(result);
}
JniResult newPrimitiveArray(jsize length, int type) {
attach_thread();
jarray array;
switch (type) {
case booleanType:
array = (*jniEnv)->NewBooleanArray(jniEnv, length);
break;
case byteType:
array = (*jniEnv)->NewByteArray(jniEnv, length);
break;
case shortType:
array = (*jniEnv)->NewShortArray(jniEnv, length);
break;
case charType:
array = (*jniEnv)->NewCharArray(jniEnv, length);
break;
case intType:
array = (*jniEnv)->NewIntArray(jniEnv, length);
break;
case longType:
array = (*jniEnv)->NewLongArray(jniEnv, length);
break;
case floatType:
array = (*jniEnv)->NewFloatArray(jniEnv, length);
break;
case doubleType:
array = (*jniEnv)->NewDoubleArray(jniEnv, length);
break;
case objectType:
case voidType:
// This error should have been handled in dart.
// is there a way to mark this as unreachable?
// or throw exception in Dart using Dart's C API.
array = NULL;
break;
}
return to_global_ref_result(array);
}
JniResult newObjectArray(jsize length,
jclass elementClass,
jobject initialElement) {
attach_thread();
jarray array =
(*jniEnv)->NewObjectArray(jniEnv, length, elementClass, initialElement);
return to_global_ref_result(array);
}
JniResult getArrayElement(jarray array, int index, int type) {
attach_thread();
jvalue value;
switch (type) {
case booleanType:
(*jniEnv)->GetBooleanArrayRegion(jniEnv, array, index, 1, &value.z);
break;
case byteType:
(*jniEnv)->GetByteArrayRegion(jniEnv, array, index, 1, &value.b);
break;
case shortType:
(*jniEnv)->GetShortArrayRegion(jniEnv, array, index, 1, &value.s);
break;
case charType:
(*jniEnv)->GetCharArrayRegion(jniEnv, array, index, 1, &value.c);
break;
case intType:
(*jniEnv)->GetIntArrayRegion(jniEnv, array, index, 1, &value.i);
break;
case longType:
(*jniEnv)->GetLongArrayRegion(jniEnv, array, index, 1, &value.j);
break;
case floatType:
(*jniEnv)->GetFloatArrayRegion(jniEnv, array, index, 1, &value.f);
break;
case doubleType:
(*jniEnv)->GetDoubleArrayRegion(jniEnv, array, index, 1, &value.d);
break;
case objectType:
value.l = (*jniEnv)->GetObjectArrayElement(jniEnv, array, index);
case voidType:
// This error should have been handled in dart.
// is there a way to mark this as unreachable?
// or throw exception in Dart using Dart's C API.
break;
}
jthrowable exception = check_exception();
if (type == objectType && exception == NULL) {
value.l = to_global_ref(value.l);
}
JniResult jniResult = {.value = value, .exception = exception};
return jniResult;
}
jthrowable setBooleanArrayElement(jarray array, int index, jboolean value) {
attach_thread();
(*jniEnv)->SetBooleanArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setByteArrayElement(jarray array, int index, jbyte value) {
attach_thread();
(*jniEnv)->SetByteArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setShortArrayElement(jarray array, int index, jshort value) {
attach_thread();
(*jniEnv)->SetShortArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setCharArrayElement(jarray array, int index, jchar value) {
attach_thread();
(*jniEnv)->SetCharArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setIntArrayElement(jarray array, int index, jint value) {
attach_thread();
(*jniEnv)->SetIntArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setLongArrayElement(jarray array, int index, jlong value) {
attach_thread();
(*jniEnv)->SetLongArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setFloatArrayElement(jarray array, int index, jfloat value) {
attach_thread();
(*jniEnv)->SetFloatArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
jthrowable setDoubleArrayElement(jarray array, int index, jdouble value) {
attach_thread();
(*jniEnv)->SetDoubleArrayRegion(jniEnv, array, index, 1, &value);
jthrowable exception = check_exception();
return exception;
}
JniExceptionDetails getExceptionDetails(jthrowable exception) {
JniExceptionDetails details;
details.message = (*jniEnv)->CallObjectMethod(
jniEnv, exception, exceptionMethods.toStringMethod);
// No exception is thrown from toString.
(*jniEnv)->ExceptionClear(jniEnv);
jobject buffer =
(*jniEnv)->NewObject(jniEnv, exceptionMethods.byteArrayOutputStreamClass,
exceptionMethods.byteArrayOutputStreamCtor);
jobject printStream =
(*jniEnv)->NewObject(jniEnv, exceptionMethods.printStreamClass,
exceptionMethods.printStreamCtor, buffer);
(*jniEnv)->CallVoidMethod(
jniEnv, exception, exceptionMethods.printStackTraceMethod, printStream);
// No exception is thrown from printStackTrace.
(*jniEnv)->ExceptionClear(jniEnv);
details.stacktrace = (*jniEnv)->CallObjectMethod(
jniEnv, buffer, exceptionMethods.toStringMethod);
// No exception is thrown from toString.
(*jniEnv)->ExceptionClear(jniEnv);
details.message = to_global_ref(details.message);
details.stacktrace = to_global_ref(details.stacktrace);
return details;
}
JniAccessorsStruct accessors = {
.getClass = getClass,
.getFieldID = getFieldID,
.getStaticFieldID = getStaticFieldID,
.getMethodID = getMethodID,
.getStaticMethodID = getStaticMethodID,
.newObject = newObject,
.newPrimitiveArray = newPrimitiveArray,
.newObjectArray = newObjectArray,
.getArrayElement = getArrayElement,
.setBooleanArrayElement = setBooleanArrayElement,
.setByteArrayElement = setByteArrayElement,
.setShortArrayElement = setShortArrayElement,
.setCharArrayElement = setCharArrayElement,
.setIntArrayElement = setIntArrayElement,
.setLongArrayElement = setLongArrayElement,
.setFloatArrayElement = setFloatArrayElement,
.setDoubleArrayElement = setDoubleArrayElement,
.callMethod = callMethod,
.callStaticMethod = callStaticMethod,
.getField = getField,
.getStaticField = getStaticField,
.getExceptionDetails = getExceptionDetails,
};
FFI_PLUGIN_EXPORT JniAccessorsStruct* GetAccessors() {
return &accessors;
}
// These will not be required after migrating to Dart-only bindings.
FFI_PLUGIN_EXPORT JniContext* GetJniContextPtr() {
return jni;
}
FFI_PLUGIN_EXPORT JNIEnv* GetJniEnv() {
if (jni_context.jvm == NULL) {
return NULL;
}
attach_thread();
return jniEnv;
}
FFI_PLUGIN_EXPORT intptr_t InitDartApiDL(void* data) {
return Dart_InitializeApiDL(data);
}
// com.github.dart_lang.jni.DartException
jclass _c_DartException = NULL;
jmethodID _m_DartException__ctor = NULL;
FFI_PLUGIN_EXPORT JniResult DartException__ctor(jstring message) {
attach_thread();
load_class_global_ref(&_c_DartException,
"com/github/dart_lang/jni/PortProxy$DartException");
if (_c_DartException == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
load_method(_c_DartException, &_m_DartException__ctor, "<init>",
"(Ljava/lang/String;)V");
if (_m_DartException__ctor == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
jobject _result = (*jniEnv)->NewObject(jniEnv, _c_DartException,
_m_DartException__ctor, message);
jthrowable exception = check_exception();
if (exception == NULL) {
_result = to_global_ref(_result);
}
return (JniResult){.value = {.l = _result}, .exception = check_exception()};
}
JNIEXPORT void JNICALL
Java_com_github_dart_1lang_jni_PortContinuation__1resumeWith(JNIEnv* env,
jclass clazz,
jlong port,
jobject result) {
attach_thread();
Dart_CObject c_post;
c_post.type = Dart_CObject_kInt64;
c_post.value.as_int64 = (jlong)((*env)->NewGlobalRef(env, result));
Dart_PostCObject_DL(port, &c_post);
}
// com.github.dart_lang.jni.PortContinuation
jclass _c_PortContinuation = NULL;
jmethodID _m_PortContinuation__ctor = NULL;
FFI_PLUGIN_EXPORT
JniResult PortContinuation__ctor(int64_t j) {
attach_thread();
load_class_global_ref(&_c_PortContinuation,
"com/github/dart_lang/jni/PortContinuation");
if (_c_PortContinuation == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
load_method(_c_PortContinuation, &_m_PortContinuation__ctor, "<init>",
"(J)V");
if (_m_PortContinuation__ctor == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
jobject _result = (*jniEnv)->NewObject(jniEnv, _c_PortContinuation,
_m_PortContinuation__ctor, j);
jthrowable exception = check_exception();
if (exception == NULL) {
_result = to_global_ref(_result);
}
return (JniResult){.value = {.l = _result}, .exception = check_exception()};
}
// com.github.dart_lang.jni.PortProxy
jclass _c_PortProxy = NULL;
jmethodID _m_PortProxy__newInstance = NULL;
FFI_PLUGIN_EXPORT
JniResult PortProxy__newInstance(jobject binaryName,
int64_t port,
int64_t functionPtr) {
attach_thread();
load_class_global_ref(&_c_PortProxy, "com/github/dart_lang/jni/PortProxy");
if (_c_PortProxy == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
load_static_method(_c_PortProxy, &_m_PortProxy__newInstance, "newInstance",
"(Ljava/lang/String;JJJ)Ljava/lang/Object;");
if (_m_PortProxy__newInstance == NULL)
return (JniResult){.value = {.j = 0}, .exception = check_exception()};
jobject _result = (*jniEnv)->CallStaticObjectMethod(
jniEnv, _c_PortProxy, _m_PortProxy__newInstance, binaryName, port,
(jlong)Dart_CurrentIsolate_DL(), functionPtr);
return to_global_ref_result(_result);
}
FFI_PLUGIN_EXPORT
void resultFor(CallbackResult* result, jobject object) {
acquire_lock(&result->lock);
result->ready = 1;
result->object = object;
signal_cond(&result->cond);
release_lock(&result->lock);
}
void doNotFinalize(void* isolate_callback_data, void* peer) {}
void finalizeLocal(void* isolate_callback_data, void* peer) {
attach_thread();
(*jniEnv)->DeleteLocalRef(jniEnv, peer);
}
void finalizeGlobal(void* isolate_callback_data, void* peer) {
attach_thread();
(*jniEnv)->DeleteGlobalRef(jniEnv, peer);
}
void finalizeWeakGlobal(void* isolate_callback_data, void* peer) {
attach_thread();
(*jniEnv)->DeleteWeakGlobalRef(jniEnv, peer);
}
void freeBoolean(void* isolate_callback_data, void* peer) {
// To match the platform implementation of Dart's calloc.
free_mem(peer);
}
FFI_PLUGIN_EXPORT
Dart_FinalizableHandle newJObjectFinalizableHandle(Dart_Handle object,
jobject reference,
jobjectRefType refType) {
switch (refType) {
case JNIInvalidRefType:
return Dart_NewFinalizableHandle_DL(object, reference, 0, doNotFinalize);
case JNILocalRefType:
return Dart_NewFinalizableHandle_DL(object, reference, 0, finalizeLocal);
case JNIGlobalRefType:
return Dart_NewFinalizableHandle_DL(object, reference, 0, finalizeGlobal);
case JNIWeakGlobalRefType:
return Dart_NewFinalizableHandle_DL(object, reference, 0,
finalizeWeakGlobal);
}
return NULL; // Never happens.
}
FFI_PLUGIN_EXPORT
Dart_FinalizableHandle newBooleanFinalizableHandle(Dart_Handle object,
bool* reference) {
return Dart_NewFinalizableHandle_DL(object, reference, 1, freeBoolean);
}
FFI_PLUGIN_EXPORT
void deleteFinalizableHandle(Dart_FinalizableHandle finalizableHandle,
Dart_Handle object) {
Dart_DeleteFinalizableHandle_DL(finalizableHandle, object);
}
jclass _c_Object = NULL;
jclass _c_Long = NULL;
jmethodID _m_Long_init = NULL;
JNIEXPORT jobjectArray JNICALL
Java_com_github_dart_1lang_jni_PortProxy__1invoke(JNIEnv* env,
jclass clazz,
jlong port,
jlong isolateId,
jlong functionPtr,
jobject proxy,
jstring methodDescriptor,
jobjectArray args) {
CallbackResult* result = (CallbackResult*)malloc(sizeof(CallbackResult));
if (isolateId != (jlong)Dart_CurrentIsolate_DL()) {
init_lock(&result->lock);
init_cond(&result->cond);
acquire_lock(&result->lock);
result->ready = 0;
result->object = NULL;
Dart_CObject c_result;
c_result.type = Dart_CObject_kInt64;
c_result.value.as_int64 = (jlong)result;
Dart_CObject c_method;
c_method.type = Dart_CObject_kInt64;
c_method.value.as_int64 =
(jlong)((*env)->NewGlobalRef(env, methodDescriptor));
Dart_CObject c_args;
c_args.type = Dart_CObject_kInt64;
c_args.value.as_int64 = (jlong)((*env)->NewGlobalRef(env, args));
Dart_CObject* c_post_arr[] = {&c_result, &c_method, &c_args};
Dart_CObject c_post;
c_post.type = Dart_CObject_kArray;
c_post.value.as_array.values = c_post_arr;
c_post.value.as_array.length = sizeof(c_post_arr) / sizeof(c_post_arr[0]);
Dart_PostCObject_DL(port, &c_post);
while (!result->ready) {
wait_for(&result->cond, &result->lock);
}
release_lock(&result->lock);
destroy_lock(&result->lock);
destroy_cond(&result->cond);
} else {
result->object = ((jobject(*)(uint64_t, jobject, jobject))functionPtr)(
port, (*env)->NewGlobalRef(env, methodDescriptor),
(*env)->NewGlobalRef(env, args));
}
// Returning an array of length 2.
// [0]: The result pointer, used for cleaning up the global reference, and
// freeing the memory since we passed the ownership to Java.
// [1]: The returned object.
attach_thread();
load_class_global_ref(&_c_Object, "java/lang/Object");
load_class_global_ref(&_c_Long, "java/lang/Long");
load_method(_c_Long, &_m_Long_init, "<init>", "(J)V");
jobject first = (*env)->NewObject(env, _c_Long, _m_Long_init, (jlong)result);
jobject second = result->object;
jobjectArray arr = (*env)->NewObjectArray(env, 2, _c_Object, NULL);
(*env)->SetObjectArrayElement(env, arr, 0, first);
(*env)->SetObjectArrayElement(env, arr, 1, second);
return arr;
}
JNIEXPORT void JNICALL
Java_com_github_dart_1lang_jni_PortProxy__1cleanUp(JNIEnv* env,
jclass clazz,
jlong resultPtr) {
CallbackResult* result = (CallbackResult*)resultPtr;
(*env)->DeleteGlobalRef(env, result->object);
free(result);
}
JNIEXPORT void JNICALL
Java_com_github_dart_1lang_jni_PortCleaner_clean(JNIEnv* env,
jclass clazz,
jlong port) {
Dart_CObject close_signal;
close_signal.type = Dart_CObject_kNull;
Dart_PostCObject_DL(port, &close_signal);
}
JNIEXPORT jobject JNICALL
Java_com_github_dart_1lang_jni_JniUtils_fromReferenceAddress(JNIEnv* env,
jclass clazz,
jlong id) {
attach_thread();
return (jobject)(id);
}