-
Notifications
You must be signed in to change notification settings - Fork 528
/
JNIEnv.cs
2129 lines (1825 loc) · 69.8 KB
/
JNIEnv.cs
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using Java.Interop;
using Java.Interop.Tools.TypeNameMappings;
#if JAVA_INTEROP
using JniNativeMethod = Java.Interop.JniNativeMethodRegistration;
#else
using JniNativeMethod = Android.Runtime.JNIEnv.JNINativeMethod;
#endif // JAVA_INTEROP
namespace Android.Runtime {
struct JnienvInitializeArgs {
public IntPtr javaVm;
public IntPtr env;
public IntPtr grefLoader;
public IntPtr Loader_loadClass;
public IntPtr grefClass;
public IntPtr Class_forName;
public uint logCategories;
public IntPtr Class_getName;
public int version;
public int androidSdkVersion;
public int localRefsAreIndirect;
public int grefGcThreshold;
public IntPtr grefIGCUserPeer;
public int isRunningOnDesktop;
}
public static partial class JNIEnv {
static IntPtr java_class_loader;
static IntPtr java_vm;
static IntPtr load_class_id;
static IntPtr gref_class;
static IntPtr mid_Class_forName;
static int version;
static int androidSdkVersion;
static bool AllocObjectSupported;
static IntPtr cid_System;
static IntPtr mid_System_identityHashCode;
internal static int gref_gc_threshold;
internal static IntPtr mid_Class_getName;
internal static bool PropagateExceptions;
static UncaughtExceptionHandler defaultUncaughtExceptionHandler;
internal static bool IsRunningOnDesktop;
#if !JAVA_INTEROP
static JNIInvokeInterface invoke_iface;
[ThreadStatic] static IntPtr handle;
[ThreadStatic] static JniNativeInterfaceInvoker env;
static JniNativeInterfaceInvoker Env {
get {
if (Handle == IntPtr.Zero) // Forces thread attach if necessary.
throw new Exception ("JNIEnv handle is NULL");
return env;
}
}
static void SetEnv ()
{
int r;
if ((r = invoke_iface.GetEnv (java_vm, out handle, version)) != 0)
AndroidEnvironment.FailFast ("Unable to get JNI Environment pointer! " +
"GetEnv(vm=0x" + java_vm.ToString ("x") + ", version=0x" + version.ToString ("x") + ")=" + r +
"; gettid()=" + gettid () +
"; Thread.ManagedThreadId=" + Thread.CurrentThread.ManagedThreadId +
"; Thread.Name=\"" + Thread.CurrentThread.Name + "\"" +
"; at: " + new StackTrace (true).ToString ());
env = CreateNativeInterface ();
}
#endif // !JAVA_INTEROP
public static IntPtr Handle {
get {
#if JAVA_INTEROP
return JniEnvironment.EnvironmentPointer;
#else // !JAVA_INTEROP
if (handle == IntPtr.Zero) {
SetEnv ();
}
return handle;
#endif // !JAVA_INTEROP
}
}
public static void CheckHandle (IntPtr jnienv)
{
#if JAVA_INTEROP
new JniTransition (jnienv).Dispose ();
#else // !JAVA_INTEROP
if (Handle != jnienv) {
SetEnv ();
}
#endif // !JAVA_INTEROP
}
[DllImport ("libc")]
static extern int gettid ();
delegate Delegate GetCallbackHandler ();
static MethodInfo dynamic_callback_gen;
static Delegate CreateDynamicCallback (MethodInfo method)
{
if (dynamic_callback_gen == null) {
var assembly = Assembly.Load ("Mono.Android.Export");
if (assembly == null)
throw new InvalidOperationException ("To use methods marked with ExportAttribute, Mono.Android.Export.dll needs to be referenced in the application");
var type = assembly.GetType ("Java.Interop.DynamicCallbackCodeGenerator");
if (type == null)
throw new InvalidOperationException ("The referenced Mono.Android.Export.dll does not match the expected version. The required type was not found.");
dynamic_callback_gen = type.GetMethod ("Create");
if (dynamic_callback_gen == null)
throw new InvalidOperationException ("The referenced Mono.Android.Export.dll does not match the expected version. The required method was not found.");
}
return (Delegate) dynamic_callback_gen.Invoke (null, new object [] {method});
}
static unsafe void RegisterJniNatives (IntPtr typeName_ptr, int typeName_len, IntPtr jniClass, IntPtr methods_ptr, int methods_len)
{
string typeName = new string ((char*) typeName_ptr, 0, typeName_len);
var __start = new DateTime ();
if (Logger.LogTiming) {
__start = DateTime.UtcNow;
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.RegisterJniNatives (\"" + typeName + "\", 0x" + jniClass.ToString ("x") + ") start: " + (__start - new DateTime (1970, 1, 1)).TotalMilliseconds);
}
Type type = Type.GetType (typeName);
if (type == null) {
Logger.Log (LogLevel.Error, "MonoDroid",
"Could not load type '" + typeName + "'. Skipping JNI registration of type '" +
Java.Interop.TypeManager.GetClassName (jniClass) + "'.");
return;
}
TypeManager.RegisterType (Java.Interop.TypeManager.GetClassName (jniClass), type);
string[] methods = new string ((char*) methods_ptr, 0, methods_len).Split ('\n');
if (methods.Length == 0)
return;
JniNativeMethod[] natives = new JniNativeMethod [methods.Length-1];
for (int i = 0; i < methods.Length; ++i) {
string method = methods [i];
if (string.IsNullOrEmpty (method))
continue;
string[] toks = methods [i].Split (new[]{':'}, 4);
Delegate callback;
if (toks [2] == "__export__") {
var mname = toks [0].Substring (2);
var minfo = type.GetMethods (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Where (m => m.Name == mname && JavaNativeTypeManager.GetJniSignature (m) == toks [1]).FirstOrDefault ();
if (minfo == null)
throw new InvalidOperationException (String.Format ("Specified managed method '{0}' was not found. Signature: {1}", mname, toks [1]));
callback = CreateDynamicCallback (minfo);
} else {
GetCallbackHandler connector = (GetCallbackHandler) Delegate.CreateDelegate (typeof (GetCallbackHandler),
toks.Length == 4 ? Type.GetType (toks [3], true) : type, toks [2]);
callback = connector ();
}
natives [i] = new JniNativeMethod (toks [0], toks [1], callback);
}
#if JAVA_INTEROP
JniEnvironment.Types.RegisterNatives (new JniObjectReference (jniClass), natives, natives.Length);
#else // !JAVA_INTEROP
if (Env.RegisterNatives (Handle, jniClass, natives, natives.Length) != 0)
AndroidEnvironment.FailFast ("Unable to register JNI native methods for type: " + typeName);
#endif // !JAVA_INTEROP
if (Logger.LogTiming) {
var __end = DateTime.UtcNow;
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.RegisterJniNatives total time: " + (__end - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (__end - __start).TotalMilliseconds + " ms]");
}
}
internal static unsafe void Initialize (JnienvInitializeArgs* args)
{
Logger.Categories = (LogCategories) args->logCategories;
var __start = new DateTime ();
if (Logger.LogTiming) {
__start = DateTime.UtcNow;
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.Initialize start: " + (__start - new DateTime (1970, 1, 1)).TotalMilliseconds);
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.Initialize: Logger JIT/etc. time: " + (DateTime.UtcNow - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (DateTime.UtcNow - __start).TotalMilliseconds + " ms]");
}
gref_gc_threshold = args->grefGcThreshold;
mid_Class_getName = args->Class_getName;
java_vm = args->javaVm;
#if !JAVA_INTEROP
handle = args->env;
env = CreateNativeInterface ();
invoke_iface = (JNIInvokeInterface) Marshal.PtrToStructure (Marshal.ReadIntPtr (java_vm), typeof (JNIInvokeInterface));
#endif // !JAVA_INTEROP
version = args->version;
androidSdkVersion = args->androidSdkVersion;
java_class_loader = args->grefLoader;
load_class_id = args->Loader_loadClass;
gref_class = args->grefClass;
mid_Class_forName = args->Class_forName;
if (args->localRefsAreIndirect == 1)
IdentityHash = v => _monodroid_get_identity_hash_code (Handle, v);
else
IdentityHash = v => v;
#if JAVA_INTEROP
new AndroidRuntime (args->env, args->javaVm, androidSdkVersion > 10, args->grefLoader, args->Loader_loadClass);
#endif // JAVA_INTEROP
if (Logger.LogTiming) {
var __end = DateTime.UtcNow;
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.Initialize: time: " + (__end - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (__end - __start).TotalMilliseconds + " ms]");
__start = DateTime.UtcNow;
var _ = Java.Interop.TypeManager.jniToManaged;
__end = DateTime.UtcNow;
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.Initialize: TypeManager init time: " + (__end - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (__end - __start).TotalMilliseconds + " ms]");
}
AllocObjectSupported = androidSdkVersion > 10;
IsRunningOnDesktop = Convert.ToBoolean (args->isRunningOnDesktop);
Java.Interop.Runtime.grefIGCUserPeer_class = args->grefIGCUserPeer;
#if BROKEN_EXCEPTION_TRANSITIONS // XA < 5.0
var propagate =
Environment.GetEnvironmentVariable ("__XA_PROPAGATE_EXCEPTIONS__") ??
Environment.GetEnvironmentVariable ("__XA_PROPOGATE_EXCEPTIONS__");
if (!string.IsNullOrEmpty (propagate)) {
bool.TryParse (propagate, out PropagateExceptions);
}
if (PropagateExceptions) {
Logger.Log (LogLevel.Info,
"monodroid",
"Enabling managed-to-java exception propagation.");
}
#else
PropagateExceptions = true;
var brokenExceptionTransitions = Environment.GetEnvironmentVariable ("XA_BROKEN_EXCEPTION_TRANSITIONS");
bool brokenTransitions;
if (!string.IsNullOrEmpty (brokenExceptionTransitions) && bool.TryParse (brokenExceptionTransitions, out brokenTransitions)) {
PropagateExceptions = !brokenTransitions;
}
#endif
if (PropagateExceptions) {
defaultUncaughtExceptionHandler = new UncaughtExceptionHandler (Java.Lang.Thread.DefaultUncaughtExceptionHandler);
if (!IsRunningOnDesktop)
Java.Lang.Thread.DefaultUncaughtExceptionHandler = defaultUncaughtExceptionHandler;
}
if (Logger.LogTiming)
Logger.Log (LogLevel.Info,
"monodroid-timing",
"JNIEnv.Initialize end: " + (DateTime.UtcNow - new DateTime (1970, 1, 1)).TotalMilliseconds);
}
internal static void Exit ()
{
/* Reset uncaught exception handler so that we don't mistakenly reuse a
* now-invalid handler the next time we reinitialize JNIEnv.
*/
var uncaughtExceptionHandler = Java.Lang.Thread.DefaultUncaughtExceptionHandler as UncaughtExceptionHandler;
if (uncaughtExceptionHandler != null && uncaughtExceptionHandler == defaultUncaughtExceptionHandler)
Java.Lang.Thread.DefaultUncaughtExceptionHandler = uncaughtExceptionHandler.DefaultHandler;
#if JAVA_INTEROP
/* Manually dispose surfaced objects and close the current JniEnvironment to
* avoid ObjectDisposedException thrown on finalizer threads after shutdown
*/
foreach (var surfacedObject in Java.Interop.Runtime.GetSurfacedObjects ()) {
try {
var obj = surfacedObject.Target as IDisposable;
if (obj != null)
obj.Dispose ();
continue;
} catch (Exception e) {
Logger.Log (LogLevel.Warn,
"monodroid",
string.Format ("Couldn't dispose object: {0}", e));
}
/* If calling Dispose failed, the assumption is that user-code in
* the Dispose(bool) overload is to blame for it. In that case we
* fallback to manual deletion of the surfaced object.
*/
var jobj = surfacedObject.Target as Java.Lang.Object;
if (jobj != null)
ManualJavaObjectDispose (jobj);
}
JniEnvironment.Runtime.Dispose ();
#endif // JAVA_INTEROP
}
/* FIXME: This reproduces the minimal steps in Java.Lang.Object.Dispose
* that needs to be executed so that we don't leak any GREF and prevent
* code execution into an appdomain that we are disposing via a finalizer.
* Ideally it should be done via another more generic mechanism, likely
* from the Java.Interop.Runtime API.
*/
static void ManualJavaObjectDispose (Java.Lang.Object obj)
{
var peer = obj.PeerReference;
var handle = peer.Handle;
var keyHandle = ((IJavaObjectEx)obj).KeyHandle;
Java.Lang.Object.Dispose (obj, ref handle, keyHandle, (JObjectRefType)peer.Type);
GC.SuppressFinalize (obj);
}
internal static void PropagateUncaughtException (IntPtr env, IntPtr javaThreadPtr, IntPtr javaExceptionPtr)
{
if (defaultUncaughtExceptionHandler == null)
return;
var javaThread = JavaObject.GetObject<Java.Lang.Thread> (env, javaThreadPtr, JniHandleOwnership.DoNotTransfer);
var javaException = JavaObject.GetObject<Java.Lang.Throwable> (env, javaExceptionPtr, JniHandleOwnership.DoNotTransfer);
defaultUncaughtExceptionHandler.UncaughtException (javaThread, javaException);
}
[DllImport ("__Internal")]
extern static void _monodroid_gc_wait_for_bridge_processing ();
static volatile bool BridgeProcessing; // = false
public static void WaitForBridgeProcessing ()
{
if (!BridgeProcessing)
return;
_monodroid_gc_wait_for_bridge_processing ();
}
[DllImport ("__Internal")]
extern static IntPtr _monodroid_get_identity_hash_code (IntPtr env, IntPtr value);
internal static Func<IntPtr, IntPtr> IdentityHash;
public static IntPtr AllocObject (string jniClassName)
{
IntPtr jniClass = JNIEnv.FindClass (jniClassName);
try {
return AllocObject (jniClass);
}
finally {
JNIEnv.DeleteGlobalRef (jniClass);
}
}
public static IntPtr AllocObject (Type type)
{
IntPtr jniClass = JNIEnv.FindClass (type);
try {
return AllocObject (jniClass);
}
finally {
JNIEnv.DeleteGlobalRef (jniClass);
}
}
public static unsafe IntPtr StartCreateInstance (IntPtr jclass, IntPtr constructorId, JValue* constructorParameters)
{
if (AllocObjectSupported) {
return AllocObject (jclass);
}
return NewObject (jclass, constructorId, constructorParameters);
}
public static unsafe IntPtr StartCreateInstance (IntPtr jclass, IntPtr constructorId, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return StartCreateInstance (jclass, constructorId, cp);
}
public static unsafe void FinishCreateInstance (IntPtr instance, IntPtr jclass, IntPtr constructorId, JValue* constructorParameters)
{
if (!AllocObjectSupported)
return;
CallNonvirtualVoidMethod (instance, jclass, constructorId, constructorParameters);
}
public static unsafe void FinishCreateInstance (IntPtr instance, IntPtr jclass, IntPtr constructorId, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
FinishCreateInstance (instance, jclass, constructorId, cp);
}
public static unsafe IntPtr StartCreateInstance (Type type, string jniCtorSignature, JValue* constructorParameters)
{
if (AllocObjectSupported) {
return AllocObject (type);
}
return CreateInstance (type, jniCtorSignature, constructorParameters);
}
public static unsafe IntPtr StartCreateInstance (Type type, string jniCtorSignature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return StartCreateInstance (type, jniCtorSignature, cp);
}
public static unsafe IntPtr StartCreateInstance (string jniClassName, string jniCtorSignature, JValue* constructorParameters)
{
if (AllocObjectSupported)
return AllocObject (jniClassName);
return CreateInstance (jniClassName, jniCtorSignature, constructorParameters);
}
public static unsafe IntPtr StartCreateInstance (string jniClassName, string jniCtorSignature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return StartCreateInstance (jniClassName, jniCtorSignature, cp);
}
public static unsafe void FinishCreateInstance (IntPtr instance, string jniCtorSignature, JValue* constructorParameters)
{
if (!AllocObjectSupported)
return;
InvokeConstructor (instance, jniCtorSignature, constructorParameters);
}
public static unsafe void FinishCreateInstance (IntPtr instance, string jniCtorSignature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
FinishCreateInstance (instance, jniCtorSignature, cp);
}
public static unsafe void InvokeConstructor (IntPtr instance, string jniCtorSignature, JValue* constructorParameters)
{
IntPtr lrefClass = GetObjectClass (instance);
try {
IntPtr ctor = JNIEnv.GetMethodID (lrefClass, "<init>", jniCtorSignature);
if (ctor == IntPtr.Zero)
throw new ArgumentException (string.Format ("Could not find constructor JNI signature '{0}' on type '{1}'.",
jniCtorSignature, Java.Interop.TypeManager.GetClassName (lrefClass)));
CallNonvirtualVoidMethod (instance, lrefClass, ctor, constructorParameters);
} finally {
DeleteLocalRef (lrefClass);
}
}
public static unsafe void InvokeConstructor (IntPtr instance, string jniCtorSignature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
InvokeConstructor (instance, jniCtorSignature, cp);
}
public static unsafe IntPtr CreateInstance (IntPtr jniClass, string signature, JValue* constructorParameters)
{
IntPtr ctor = JNIEnv.GetMethodID (jniClass, "<init>", signature);
if (ctor == IntPtr.Zero)
throw new ArgumentException (string.Format ("Could not find constructor JNI signature '{0}' on type '{1}'.",
signature, Java.Interop.TypeManager.GetClassName (jniClass)));
return JNIEnv.NewObject (jniClass, ctor, constructorParameters);
}
public static unsafe IntPtr CreateInstance (IntPtr jniClass, string signature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return CreateInstance (jniClass, signature, cp);
}
public static unsafe IntPtr CreateInstance (string jniClassName, string signature, JValue* constructorParameters)
{
IntPtr jniClass = JNIEnv.FindClass (jniClassName);
try {
return CreateInstance (jniClass, signature, constructorParameters);
}
finally {
JNIEnv.DeleteGlobalRef (jniClass);
}
}
public static unsafe IntPtr CreateInstance (string jniClassName, string signature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return CreateInstance (jniClassName, signature, cp);
}
public static unsafe IntPtr CreateInstance (Type type, string signature, JValue* constructorParameters)
{
IntPtr jniClass = JNIEnv.FindClass (type);
try {
return CreateInstance (jniClass, signature, constructorParameters);
}
finally {
JNIEnv.DeleteGlobalRef (jniClass);
}
}
public static unsafe IntPtr CreateInstance (Type type, string signature, params JValue[] constructorParameters)
{
fixed (JValue* cp = constructorParameters)
return CreateInstance (type, signature, cp);
}
#if !JAVA_INTEROP
static unsafe JniNativeInterfaceInvoker CreateNativeInterface ()
{
JniNativeInterfaceStruct* p = (JniNativeInterfaceStruct*) Marshal.ReadIntPtr (Handle);
return new JniNativeInterfaceInvoker (p);
}
#endif // !JAVA_INTEROP
public static IntPtr FindClass (System.Type type)
{
int rank = JavaNativeTypeManager.GetArrayInfo (type, out type);
try {
return FindClass (JavaNativeTypeManager.ToJniName (GetJniName (type), rank));
} catch (Java.Lang.Throwable e) {
if (!((e is Java.Lang.NoClassDefFoundError) || (e is Java.Lang.ClassNotFoundException)))
throw;
Logger.Log (LogLevel.Warn, "monodroid", "JNIEnv.FindClass(Type) caught unexpected exception: " + e);
string jni = Java.Interop.TypeManager.GetJniTypeName (type);
if (jni != null) {
e.Dispose ();
return FindClass (JavaNativeTypeManager.ToJniName (jni, rank));
}
// Though it's tempting to call TypeManager.RegisterType() to avoid
// calling GetCustomAttributes() again, this isn't necessary as
// JNIEnv.FindClass() will invoke the static constructor for the type,
// which will (indirectly) call TypeManager.RegisterType().
jni = JavaNativeTypeManager.ToJniNameFromAttributes (type);
if (jni != null) {
e.Dispose ();
return FindClass (JavaNativeTypeManager.ToJniName (jni, rank));
}
throw;
}
}
static readonly int nameBufferLength = 1024;
[ThreadStatic] static char[] nameBuffer;
static unsafe IntPtr BinaryName (string classname)
{
int index = classname.IndexOf ('/');
if (index == -1)
return NewString (classname);
int length = classname.Length;
if (length > nameBufferLength)
return NewString (classname.Replace ('/', '.'));
if (nameBuffer == null)
nameBuffer = new char[nameBufferLength];
fixed (char* src = classname, dst = nameBuffer) {
char* src_ptr = src;
char* dst_ptr = dst;
char* end_ptr = src + length;
while (src_ptr < end_ptr) {
*dst_ptr = (*src_ptr == '/') ? '.' : *src_ptr;
src_ptr++;
dst_ptr++;
}
}
return NewString (nameBuffer, length);
}
public static IntPtr FindClass (string classname)
{
IntPtr local_ref;
IntPtr native_str = BinaryName (classname);
try {
local_ref = CallStaticObjectMethod (gref_class, mid_Class_forName, new JValue (native_str), new JValue (true), new JValue (java_class_loader));
} finally {
DeleteLocalRef (native_str);
}
IntPtr global_ref = NewGlobalRef (local_ref);
DeleteLocalRef (local_ref);
return global_ref;
}
public static IntPtr FindClass (string className, ref IntPtr cachedJniClassHandle)
{
if (cachedJniClassHandle != IntPtr.Zero)
return cachedJniClassHandle;
IntPtr h = FindClass (className);
if (Interlocked.CompareExchange (ref cachedJniClassHandle, h, IntPtr.Zero) != IntPtr.Zero)
DeleteGlobalRef (h);
return cachedJniClassHandle;
}
public static void Throw (IntPtr obj)
{
if (obj == IntPtr.Zero)
throw new ArgumentException ("'obj' must not be IntPtr.Zero.", "obj");
#if JAVA_INTEROP
JniEnvironment.Exceptions.Throw (new JniObjectReference (obj));
#else // !JAVA_INTEROP
if (Env.Throw (Handle, obj) != 0) {
ExceptionDescribe ();
AndroidEnvironment.FailFast ("Unable to raise a Java exception!");
}
#endif // !JAVA_INTEROP
}
public static void ThrowNew (IntPtr clazz, string message)
{
if (message == null)
throw new ArgumentNullException ("message");
#if JAVA_INTEROP
JniEnvironment.Exceptions.ThrowNew (new JniObjectReference (clazz), message);
#else // !JAVA_INTEROP
if (Env.ThrowNew (Handle, clazz, message) != 0) {
ExceptionDescribe ();
AndroidEnvironment.FailFast ("Unable to raise a Java exception!");
}
#endif // !JAVA_INTEROP
}
public static void PushLocalFrame (int capacity)
{
#if JAVA_INTEROP
JniEnvironment.References.PushLocalFrame (capacity);
#else // !JAVA_INTEROP
int rvalue = Env._PushLocalFrame (Handle, capacity);
if (rvalue != 0) {
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();
}
#endif // !JAVA_INTEROP
}
public static void EnsureLocalCapacity (int capacity)
{
#if JAVA_INTEROP
JniEnvironment.References.EnsureLocalCapacity (capacity);
#else // !JAVA_INTEROP
int rvalue = Env._EnsureLocalCapacity (Handle, capacity);
if (rvalue != 0) {
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();
}
#endif // !JAVA_INTEROP
}
internal static void DeleteRef (IntPtr handle, JniHandleOwnership transfer)
{
switch (transfer) {
case JniHandleOwnership.DoNotTransfer:
break;
case JniHandleOwnership.TransferLocalRef:
JNIEnv.DeleteLocalRef (handle);
break;
case JniHandleOwnership.TransferGlobalRef:
JNIEnv.DeleteGlobalRef (handle);
break;
}
}
[DllImport ("__Internal")]
internal static extern int _monodroid_gref_log (string message);
[DllImport ("__Internal")]
internal static extern int _monodroid_gref_log_new (IntPtr curHandle, byte curType, IntPtr newHandle, byte newType, string threadName, int threadId, [In] StringBuilder from, int from_writable);
[DllImport ("__Internal")]
internal static extern void _monodroid_gref_log_delete (IntPtr handle, byte type, string threadName, int threadId, [In] StringBuilder from, int from_writable);
[DllImport ("__Internal")]
internal static extern void _monodroid_weak_gref_new (IntPtr curHandle, byte curType, IntPtr newHandle, byte newType, string threadName, int threadId, [In] StringBuilder from, int from_writable);
[DllImport ("__Internal")]
internal static extern void _monodroid_weak_gref_delete (IntPtr handle, byte type, string threadName, int threadId, [In] StringBuilder from, int from_writable);
[DllImport ("__Internal")]
internal static extern int _monodroid_lref_log_new (int lrefc, IntPtr handle, byte type, string threadName, int threadId, [In] StringBuilder from, int from_writable);
[DllImport ("__Internal")]
internal static extern void _monodroid_lref_log_delete (int lrefc, IntPtr handle, byte type, string threadName, int threadId, [In] StringBuilder from, int from_writable);
public static IntPtr NewGlobalRef (IntPtr jobject)
{
#if JAVA_INTEROP
var r = new JniObjectReference (jobject);
return r.NewGlobalRef ().Handle;
#else // !JAVA_INTEROP
IntPtr res = Env.NewGlobalRef (Handle, jobject);
var log = Logger.LogGlobalRef;
var ctype = log ? _GetObjectRefType (jobject) : (byte) '*';
var ntype = log ? _GetObjectRefType (res) : (byte) '*';
var tname = log ? Thread.CurrentThread.Name : null;
var tid = log ? Thread.CurrentThread.ManagedThreadId : 0;
var from = log ? new StringBuilder (new StackTrace (true).ToString ()) : null;
int gc = _monodroid_gref_log_new (jobject, ctype, res, ntype, tname, tid, from, 1);
if (gc >= gref_gc_threshold) {
Logger.Log (LogLevel.Info, "monodroid-gc", gc + " outstanding GREFs. Performing a full GC!");
System.GC.Collect ();
}
return res;
#endif // !JAVA_INTEROP
}
public static void DeleteGlobalRef (IntPtr jobject)
{
#if JAVA_INTEROP
var r = new JniObjectReference (jobject, JniObjectReferenceType.Global);
JniObjectReference.Dispose (ref r);
#else // !JAVA_INTEROP
var log = Logger.LogGlobalRef;
var ctype = log ? _GetObjectRefType (jobject) : (byte) '*';
var tname = log ? Thread.CurrentThread.Name : null;
var tid = log ? Thread.CurrentThread.ManagedThreadId : 0;
var from = log ? new StringBuilder (new StackTrace (true).ToString ()) : null;
_monodroid_gref_log_delete (jobject, ctype, tname, tid, from, 1);
Env.DeleteGlobalRef (Handle, jobject);
#endif // !JAVA_INTEROP
}
#if !JAVA_INTEROP
internal static int lref_count;
static IntPtr LogCreateLocalRef (IntPtr jobject)
{
if (jobject == IntPtr.Zero)
return jobject;
if (Logger.LogLocalRef) {
var v = Interlocked.Increment (ref lref_count);
var tname = Thread.CurrentThread.Name;
var tid = Thread.CurrentThread.ManagedThreadId;;
var from = new StringBuilder (new StackTrace (true).ToString ());
_monodroid_lref_log_new (v, jobject, (byte) 'L', tname, tid, from, 1);
}
return jobject;
}
#endif // !JAVA_INTEROP
public static IntPtr NewLocalRef (IntPtr jobject)
{
#if JAVA_INTEROP
return new JniObjectReference (jobject).NewLocalRef ().Handle;
#else // !JAVA_INTEROP
return LogCreateLocalRef (Env.NewLocalRef (Handle, jobject));
#endif // !JAVA_INTEROP
}
public static void DeleteLocalRef (IntPtr jobject)
{
#if JAVA_INTEROP
var r = new JniObjectReference (jobject, JniObjectReferenceType.Local);
JniObjectReference.Dispose (ref r);
#else // !JAVA_INTEROP
Env.DeleteLocalRef (Handle, jobject);
if (jobject == IntPtr.Zero)
return;
if (Logger.LogLocalRef) {
var v = Interlocked.Decrement (ref lref_count);
var tname = Thread.CurrentThread.Name;
var tid = Thread.CurrentThread.ManagedThreadId;;
var from = new StringBuilder (new StackTrace (true).ToString ());
_monodroid_lref_log_delete (v, jobject, (byte) 'L', tname, tid, from, 1);
}
#endif // !JAVA_INTEROP
}
public static void DeleteWeakGlobalRef (IntPtr jobject)
{
#if JAVA_INTEROP
var r = new JniObjectReference (jobject, JniObjectReferenceType.WeakGlobal);
JniObjectReference.Dispose (ref r);
#else // !JAVA_INTEROP
var log = Logger.LogGlobalRef;
var ctype = log ? _GetObjectRefType (jobject) : (byte) '*';
var tname = log ? Thread.CurrentThread.Name : null;
var tid = log ? Thread.CurrentThread.ManagedThreadId : 0;
var from = log ? new StringBuilder (new StackTrace (true).ToString ()) : null;
_monodroid_weak_gref_delete (jobject, ctype, tname, tid, from, 1);
Env.DeleteWeakGlobalRef (Handle, jobject);
#endif // !JAVA_INTEROP
}
public static IntPtr NewObject (IntPtr jclass, IntPtr jmethod)
{
#if JAVA_INTEROP
var r = JniEnvironment.Object.NewObject (new JniObjectReference (jclass), new JniMethodInfo (jmethod, isStatic: false));
return r.Handle;
#else // !JAVA_INTEROP
Java.Interop.TypeManager.ActivationEnabled = false;
IntPtr rvalue = Env.NewObject (Handle, jclass, jmethod);
Java.Interop.TypeManager.ActivationEnabled = true;
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();
return LogCreateLocalRef (rvalue);
#endif // !JAVA_INTEROP
}
public static unsafe IntPtr NewObject (IntPtr jclass, IntPtr jmethod, JValue* parms)
{
#if JAVA_INTEROP
var r = JniEnvironment.Object.NewObject (new JniObjectReference (jclass), new JniMethodInfo (jmethod, isStatic: false), (JniArgumentValue*) parms);
return r.Handle;
#else // !JAVA_INTEROP
Java.Interop.TypeManager.ActivationEnabled = false;
IntPtr rvalue = Env.NewObjectA (Handle, jclass, jmethod, parms);
Java.Interop.TypeManager.ActivationEnabled = true;
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();
return LogCreateLocalRef (rvalue);
#endif // !JAVA_INTEROP
}
public static unsafe IntPtr NewObject (IntPtr jclass, IntPtr jmethod, params JValue[] parms)
{
fixed (JValue* p = parms)
return NewObject (jclass, jmethod, p);
}
public static string GetClassNameFromInstance (IntPtr jobject)
{
IntPtr jclass = GetObjectClass (jobject);
try {
return Java.Interop.TypeManager.GetClassName (jclass);
} finally {
DeleteLocalRef (jclass);
}
}
[DllImport ("__Internal")]
internal static extern IntPtr monodroid_typemap_managed_to_java (string managed);
public static string GetJniName (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
var java = monodroid_typemap_managed_to_java (type.FullName + ", " + type.Assembly.GetName ().Name);
return java == IntPtr.Zero
? JavaNativeTypeManager.ToJniName (type)
: Marshal.PtrToStringAnsi (java);
}
public static IntPtr ToJniHandle (IJavaObject value)
{
if (value == null)
return IntPtr.Zero;
return value.Handle;
}
public static IntPtr ToLocalJniHandle (IJavaObject value)
{
if (value == null)
return IntPtr.Zero;
var ex = value as IJavaObjectEx;
if (ex != null)
return ex.ToLocalJniHandle ();
return NewLocalRef (value.Handle);
}
#if !JAVA_INTEROP
static JObjectRefType GetObjectRefType (IntPtr jobject)
{
return (JObjectRefType) Env.GetObjectRefType (Handle, jobject);
}
static byte _GetObjectRefType (IntPtr jobject)
{
var value = GetObjectRefType (jobject);
switch (value) {
case JObjectRefType.Invalid: return (byte) 'I';
case JObjectRefType.Local: return (byte) 'L';
case JObjectRefType.Global: return (byte) 'G';
case JObjectRefType.WeakGlobal: return (byte) 'W';
default: return (byte) '*';
}
}
#endif // !JAVA_INTEROP
static IntPtr char_sequence_to_string_id;
public static string GetCharSequence (IntPtr jobject, JniHandleOwnership transfer)
{
if (jobject == IntPtr.Zero)
return null;
#if JAVA_INTEROP
var r = JniEnvironment.Object.ToString (new JniObjectReference (jobject));
return JniEnvironment.Strings.ToString (ref r, JniObjectReferenceOptions.CopyAndDispose);
#else // !JAVA_INTEROP
IntPtr str = LogCreateLocalRef (Env.CallObjectMethod (Handle, jobject, Java.Lang.Class.CharSequence_toString));
try {
return GetString (str, JniHandleOwnership.TransferLocalRef);
} finally {
DeleteRef (jobject, transfer);
}
#endif // !JAVA_INTEROP
}
public static unsafe string GetString (IntPtr value, JniHandleOwnership transfer)
{
if (value == IntPtr.Zero)
return null;
#if JAVA_INTEROP
var s = JniEnvironment.Strings.ToString (new JniObjectReference (value));
DeleteRef (value, transfer);
return s;
#else // !JAVA_INTEROP
int len = Env.GetStringLength (Handle, value);
IntPtr chars = Env.GetStringChars (Handle, value, IntPtr.Zero);
try {
return new string ((char*) chars, 0, len);
} finally {
Env.ReleaseStringChars (Handle, value, chars);
DeleteRef (value, transfer);
}
#endif // !JAVA_INTEROP
}
public static unsafe IntPtr NewString (string text)
{
if (text == null)
return IntPtr.Zero;
#if JAVA_INTEROP
return JniEnvironment.Strings.NewString (text).Handle;
#else // !JAVA_INTEROP
IntPtr rvalue;
fixed (char *s = text)
rvalue = LogCreateLocalRef (Env.NewString (Handle, (IntPtr) s, text.Length));
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();
return rvalue;
#endif // !JAVA_INTEROP
}
public static unsafe IntPtr NewString (char[] text, int length)
{
if (text == null)
return IntPtr.Zero;
#if JAVA_INTEROP
fixed (char *s = text)
return JniEnvironment.Strings.NewString (s, length).Handle;
#else // !JAVA_INTEROP
IntPtr rvalue;
fixed (char *s = text)
rvalue = LogCreateLocalRef (Env.NewString (Handle, (IntPtr) s, length));
Exception e = AndroidEnvironment.GetExceptionForLastThrowable ();
if (e != null)
ExceptionDispatchInfo.Capture (e).Throw ();