-
Notifications
You must be signed in to change notification settings - Fork 229
/
gumscript-runtime-java.js
3009 lines (2676 loc) · 129 KB
/
gumscript-runtime-java.js
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
/* jshint esnext: true, evil: true */
/* global console, Java, Memory, Module, NativePointer, Process, NativeCallback, NativeFunction, ptr, WeakRef, NULL */
(function () {
"use strict";
const flavor = typeof Process === 'undefined' ? 'kernel' : 'user';
if (flavor !== 'user')
return;
let _runtime = null;
let _api = null;
const pointerSize = Process.pointerSize;
/* no error */
const JNI_OK = 0;
/* generic error */
const JNI_ERR = -1;
/* thread detached from the VM */
const JNI_EDETACHED = -2;
/* JNI version error */
const JNI_VERSION = -3;
const JNI_ABORT = 2;
const JNI_VERSION_1_6 = 0x00010006;
// methods
const CONSTRUCTOR_METHOD = 1;
const STATIC_METHOD = 2;
const INSTANCE_METHOD = 3;
// fields
const STATIC_FIELD = 1;
const INSTANCE_FIELD = 2;
// ART
const ART_METHOD_SIZE = 72;
const ART_METHOD_OFFSET_INTERPRETER_CODE = 24;
const ART_METHOD_OFFSET_JNI_CODE = 32;
const ART_METHOD_OFFSET_QUICK_CODE = 40;
const ART_METHOD_OFFSET_GC_MAP = 48;
const ART_METHOD_OFFSET_ACCESS_FLAGS = 56;
const ART_METHOD_OFFSET_DEX_ITEM_INDEX = 60;
const ART_METHOD_OFFSET_DEX_METHOD_INDEX = 64;
const ART_METHOD_OFFSET_INDEX = 68;
// Dalvik
const DVM_JNI_ENV_OFFSET_SELF = 12;
const DVM_CLASS_OBJECT_SIZE = 160;
const DVM_CLASS_OBJECT_OFFSET_VTABLE_COUNT = 112;
const DVM_CLASS_OBJECT_OFFSET_VTABLE = 116;
const DVM_OBJECT_OFFSET_CLAZZ = 0;
const DVM_METHOD_SIZE = 56;
const DVM_METHOD_OFFSET_CLAZZ = 0;
const DVM_METHOD_OFFSET_ACCESS_FLAGS = 4;
const DVM_METHOD_OFFSET_METHOD_INDEX = 8;
const DVM_METHOD_OFFSET_REGISTERS_SIZE = 10;
const DVM_METHOD_OFFSET_OUTS_SIZE = 12;
const DVM_METHOD_OFFSET_INS_SIZE = 14;
const DVM_METHOD_OFFSET_INSNS = 32;
const DVM_METHOD_OFFSET_JNI_ARG_INFO = 36;
// access flags
const kAccNative = 0x0100;
// jobject reference types
const JNIInvalidRefType = 0;
const JNILocalRefType = 1;
const JNIGlobalRefType = 2;
const JNIWeakGlobalRefType = 3;
const NULL_OBJECT = NULL;
Object.defineProperty(this, 'Java', {
enumerable: true,
get: () => {
if (_runtime === null) {
_runtime = new Runtime();
}
return _runtime;
}
});
Object.defineProperty(this, 'Dalvik', {
enumerable: true,
get: () => {
return this.Java;
}
});
function Runtime() {
let api = null;
let vm = null;
let classFactory = null;
function initialize() {
api = getApi();
if (api !== null) {
vm = new VM(api);
classFactory = new ClassFactory(api, vm);
}
}
WeakRef.bind(Runtime, function dispose() {
if (api !== null) {
vm.perform(function () {
const env = vm.getEnv();
classFactory.dispose(env);
Env.dispose(env);
});
}
});
Object.defineProperty(this, 'available', {
enumerable: true,
get: function () {
return api !== null;
}
});
let androidVersion = null;
Object.defineProperty(this, 'androidVersion', {
enumerable: true,
get: function () {
if (androidVersion === null) {
assertCalledInJavaPerformCallback();
const Build = Java.use("android.os.Build$VERSION");
androidVersion = Build.RELEASE.value;
}
return androidVersion;
}
});
function assertJavaApiIsAvailable() {
if (!Java.available) {
throw new Error("Java API not available");
}
}
function assertCalledInJavaPerformCallback() {
if (classFactory.loader === null) {
throw new Error("Not allowed outside Java.perform() callback");
}
}
this.synchronized = function (obj, fn) {
assertCalledInJavaPerformCallback();
const objHandle = obj.hasOwnProperty('$handle')? obj.$handle : obj;
if (!(objHandle instanceof NativePointer)) {
throw new Error("It's neither a pointer nor a Java instance");
}
const env = vm.getEnv();
checkJniResult("VM::MonitorEnter", env.monitorEnter(objHandle));
try {
fn();
} finally {
try {
checkJniResult("VM::MonitorExit", env.monitorExit(objHandle));
} catch (e) {
env.checkForExceptionAndThrowIt();
}
}
};
function _enumerateLoadedClasses(callbacks, onlyDescription) {
assertJavaApiIsAvailable();
if (api.flavor !== 'dalvik')
throw new Error("Enumerating loaded classes is only supported on Dalvik for now");
const HASH_TOMBSTONE = ptr("0xcbcacccd");
const loadedClassesOffset = 172;
const hashEntrySize = 8;
const ptrLoadedClassesHashtable = api.gDvm.add(loadedClassesOffset);
const hashTable = Memory.readPointer(ptrLoadedClassesHashtable);
const tableSize = Memory.readS32(hashTable);
const ptrpEntries = hashTable.add(12);
const pEntries = Memory.readPointer(ptrpEntries);
const end = tableSize * hashEntrySize;
for (let offset = 0; offset < end; offset += hashEntrySize) {
const pEntriePtr = pEntries.add(offset);
const dataPtr = Memory.readPointer(pEntriePtr.add(4));
if (!(HASH_TOMBSTONE.equals(dataPtr) || NULL.equals(dataPtr))) {
const descriptionPtr = Memory.readPointer(dataPtr.add(24));
const description = Memory.readCString(descriptionPtr);
if (onlyDescription) {
callbacks.onMatch(description);
} else {
const objectSize = Memory.readU32(dataPtr.add(56));
const sourceFile = Memory.readCString(Memory.readPointer(dataPtr.add(152)));
callbacks.onMatch({
pointer: pEntriePtr,
objectSize: objectSize,
sourceFile: sourceFile,
description: description
});
}
}
}
callbacks.onComplete();
}
Object.defineProperty(this, 'enumerateLoadedClassesSync', {
enumerable: true,
value: function () {
assertJavaApiIsAvailable();
const classes = [];
Java.enumerateLoadedClasses({
onMatch: function (c) {
classes.push(c);
},
onComplete: function () {
}
});
return classes;
}
});
Object.defineProperty(this, 'enumerateLoadedClasses', {
enumerable: true,
value: function(callbacks) {
_enumerateLoadedClasses(callbacks, true);
}
});
this.scheduleOnMainThread = function (fn) {
assertCalledInJavaPerformCallback();
const ActivityThread = classFactory.use("android.app.ActivityThread");
const Handler = classFactory.use("android.os.Handler");
const Looper = classFactory.use("android.os.Looper");
const looper = Looper.getMainLooper();
const handler = Handler.$new.overload("android.os.Looper").call(Handler, looper);
const message = handler.obtainMessage();
Handler.dispatchMessage.implementation = function (msg) {
const sameHandler = this.$isSameObject(handler);
if (sameHandler) {
const app = ActivityThread.currentApplication();
if (app !== null) {
Handler.dispatchMessage.implementation = null;
fn();
}
} else {
this.dispatchMessage(msg);
}
};
message.sendToTarget();
};
this.perform = function (fn) {
assertJavaApiIsAvailable();
if (classFactory.loader === null) {
vm.perform(() => {
const ActivityThread = classFactory.use("android.app.ActivityThread");
const app = ActivityThread.currentApplication();
classFactory.loader = app.getClassLoader();
});
}
vm.perform(fn);
};
this.use = function (className) {
assertCalledInJavaPerformCallback();
return classFactory.use(className);
};
this.choose = function (className, callbacks) {
assertCalledInJavaPerformCallback();
return classFactory.choose(className, callbacks);
};
this.cast = function (obj, C) {
return classFactory.cast(obj, C);
};
// Reference: http://stackoverflow.com/questions/2848575/how-to-detect-ui-thread-on-android
this.isMainThread = function () {
assertCalledInJavaPerformCallback();
const Looper = classFactory.use("android.os.Looper");
const mainLooper = Looper.getMainLooper();
const myLooper = Looper.myLooper();
if (myLooper === null) {
return false;
}
return mainLooper.$isSameObject(myLooper);
};
initialize.call(this);
}
function ClassFactory(api, vm) {
const factory = this;
let classes = {};
let patchedClasses = {};
let loader = null;
const PENDING_CALLS = Symbol('PENDING_CALLS');
function initialize() {
api = getApi();
}
this.dispose = function (env) {
for (let entryId in patchedClasses) {
if (patchedClasses.hasOwnProperty(entryId)) {
const entry = patchedClasses[entryId];
Memory.writePointer(entry.vtablePtr, entry.vtable);
Memory.writeS32(entry.vtableCountPtr, entry.vtableCount);
for (let methodId in entry.targetMethods) {
if (entry.targetMethods.hasOwnProperty(methodId)) {
entry.targetMethods[methodId].implementation = null;
}
}
}
}
patchedClasses = {};
for (let classId in classes) {
if (classes.hasOwnProperty(classId)) {
const klass = classes[classId];
klass.__methods__.forEach(env.deleteGlobalRef, env);
klass.__fields__.forEach(env.deleteGlobalRef, env);
env.deleteGlobalRef(klass.__handle__);
}
}
classes = {};
};
Object.defineProperty(this, 'loader', {
enumerable: true,
get: function () {
return loader;
},
set: function (value) {
loader = value;
}
});
this.use = function (className) {
let C = classes[className];
if (!C) {
const env = vm.getEnv();
if (loader !== null) {
const klassObj = loader.loadClass(className);
C = ensureClass(klassObj.$handle, className);
} else {
const handle = env.findClass(className.replace(/\./g, "/"));
try {
C = ensureClass(handle, className);
} finally {
env.deleteLocalRef(handle);
}
}
}
return new C(C.__handle__, null);
};
this.choose = function (className, callbacks) {
if (api.flavor !== 'dalvik')
throw new Error("choose() is only supported on Dalvik for now");
const env = vm.getEnv();
const klass = this.use(className);
let enumerateInstances = function (className, callbacks) {
const thread = Memory.readPointer(env.handle.add(DVM_JNI_ENV_OFFSET_SELF));
const ptrClassObject = api.dvmDecodeIndirectRef(thread, klass.$classHandle);
const pattern = ptrClassObject.toMatchPattern();
const heapSourceBase = api.dvmHeapSourceGetBase();
const heapSourceLimit = api.dvmHeapSourceGetLimit();
const size = heapSourceLimit.toInt32() - heapSourceBase.toInt32();
Memory.scan(heapSourceBase, size, pattern, {
onMatch: function (address, size) {
if (api.dvmIsValidObject(address)) {
Java.perform(function () {
const env = vm.getEnv();
const thread = Memory.readPointer(env.handle.add(DVM_JNI_ENV_OFFSET_SELF));
let instance;
const localReference = api.addLocalReference(thread, address);
try {
instance = Java.cast(localReference, klass);
} finally {
env.deleteLocalRef(localReference);
}
const stopMaybe = callbacks.onMatch(instance);
if (stopMaybe === 'stop') {
return 'stop';
}
});
}
},
onError: function (reason) {
},
onComplete: function () {
callbacks.onComplete();
}
});
};
if (api.addLocalReference === null) {
const libdvm = Process.getModuleByName('libdvm.so');
let pattern;
if (Java.androidVersion.indexOf('4.2.') === 0) {
// verified with 4.2.2
pattern = 'F8 B5 06 46 0C 46 31 B3 43 68 00 F1 A8 07 22 46';
} else {
// verified with 4.3.1 and 4.4.4
pattern = '2D E9 F0 41 05 46 15 4E 0C 46 7E 44 11 B3 43 68';
}
Memory.scan(libdvm.base, libdvm.size, pattern,
{
onMatch: function (address, size) {
// Note that on 32-bit ARM this address must have its least significant bit set to 0 for ARM functions, and 1 for Thumb functions. => So set it to 1
if (Process.arch === 'arm') {
address = address.or(1);
}
api.addLocalReference = new NativeFunction(address, 'pointer', ['pointer', 'pointer']);
enumerateInstances(className, callbacks);
return 'stop';
},
onError: function (reason) {
},
onComplete: function () {
}
});
} else {
enumerateInstances(className, callbacks);
}
};
this.cast = function (obj, klass) {
const env = vm.getEnv();
const handle = obj.hasOwnProperty('$handle') ? obj.$handle : obj;
if (env.isInstanceOf(handle, klass.$classHandle)) {
const C = klass.$classWrapper;
return new C(C.__handle__, handle);
} else {
throw new Error("Cast from '" + env.getObjectClassName(handle) + "' to '" + env.getClassName(klass.$classHandle) + "' isn't possible");
}
};
function ensureClass(classHandle, cachedName) {
let env = vm.getEnv();
const name = cachedName !== null ? cachedName : env.getClassName(classHandle);
let klass = classes[name];
if (klass) {
return klass;
}
const superHandle = env.getSuperclass(classHandle);
let superKlass;
if (!superHandle.isNull()) {
try {
superKlass = ensureClass(superHandle, null);
} finally {
env.deleteLocalRef(superHandle);
}
} else {
superKlass = null;
}
eval("klass = function " + basename(name) + "(classHandle, handle) {" +
"const env = vm.getEnv();" +
"this.$classWrapper = klass;" +
"this.$classHandle = env.newGlobalRef(classHandle);" +
"this.$handle = (handle !== null) ? env.newGlobalRef(handle) : null;" +
"this.$weakRef = WeakRef.bind(this, makeHandleDestructor(this.$handle, this.$classHandle));" +
"};");
classes[name] = klass;
function initializeClass() {
klass.__name__ = name;
klass.__handle__ = env.newGlobalRef(classHandle);
klass.__methods__ = [];
klass.__fields__ = [];
let ctor = null;
Object.defineProperty(klass.prototype, "$new", {
get: function () {
if (ctor === null) {
vm.perform(function () {
ctor = makeConstructor(klass.__handle__, vm.getEnv());
});
}
return ctor;
}
});
klass.prototype.$dispose = dispose;
klass.prototype.$isSameObject = function (obj) {
const env = vm.getEnv();
return env.isSameObject(obj.$handle, this.$handle);
};
Object.defineProperty(klass.prototype, 'class', {
get: function () {
const Clazz = factory.use("java.lang.Class");
return factory.cast(this.$classHandle, Clazz);
}
});
Object.defineProperty(klass.prototype, "$className", {
get: function () {
const env = vm.getEnv();
return this.hasOwnProperty('$handle') ? env.getObjectClassName(this.$handle) : env.getClassName(this.$classHandle);
}
});
addMethodsAndFields();
}
function dispose() {
/* jshint validthis: true */
WeakRef.unbind(this.$weakRef);
}
function makeConstructor(classHandle, env) {
const Constructor = env.javaLangReflectConstructor();
const invokeObjectMethodNoArgs = env.method('pointer', []);
const jsMethods = [];
const jsRetType = getTypeFromJniTypename(name, false);
const constructors = invokeObjectMethodNoArgs(env.handle, classHandle, env.javaLangClass().getDeclaredConstructors);
try {
const numConstructors = env.getArrayLength(constructors);
for (let constructorIndex = 0; constructorIndex !== numConstructors; constructorIndex++) {
const constructor = env.getObjectArrayElement(constructors, constructorIndex);
try {
const methodId = env.fromReflectedMethod(constructor);
const jsArgTypes = [];
const types = invokeObjectMethodNoArgs(env.handle, constructor, Constructor.getGenericParameterTypes);
try {
const numTypes = env.getArrayLength(types);
for (let typeIndex = 0; typeIndex !== numTypes; typeIndex++) {
const t = env.getObjectArrayElement(types, typeIndex);
try {
const argType = getTypeFromJniTypename(env.getTypeName(t));
jsArgTypes.push(argType);
} finally {
env.deleteLocalRef(t);
}
}
} catch (e) {
continue;
} finally {
env.deleteLocalRef(types);
}
jsMethods.push(makeMethod(basename(name), CONSTRUCTOR_METHOD, methodId, jsRetType, jsArgTypes, env));
} finally {
env.deleteLocalRef(constructor);
}
}
} finally {
env.deleteLocalRef(constructors);
}
if (jsMethods.length === 0)
throw new Error("no supported overloads");
return makeMethodDispatcher("<init>", jsMethods);
}
function makeField(name, handle, env) {
const Field = env.javaLangReflectField();
const Modifier = env.javaLangReflectModifier();
const invokeObjectMethodNoArgs = env.method('pointer', []);
const invokeIntMethodNoArgs = env.method('int32', []);
const fieldId = env.fromReflectedField(handle);
const modifiers = invokeIntMethodNoArgs(env.handle, handle, Field.getModifiers);
const jsType = (modifiers & Modifier.STATIC) !== 0 ? STATIC_FIELD : INSTANCE_FIELD;
const fieldType = invokeObjectMethodNoArgs(env.handle, handle, Field.getGenericType);
let jsFieldType;
try {
jsFieldType = getTypeFromJniTypename(env.getTypeName(fieldType));
} catch (e) {
return null;
} finally {
env.deleteLocalRef(fieldType);
}
const field = createField(name, jsType, fieldId, jsFieldType, env);
if (field === null)
throw new Error("No supported field");
return field;
}
function createField(name, type, targetFieldId, fieldType, env) {
const rawFieldType = fieldType.type;
let invokeTarget = null;
if (type === STATIC_FIELD) {
invokeTarget = env.getStaticField(rawFieldType);
} else if (type === INSTANCE_FIELD) {
invokeTarget = env.getField(rawFieldType);
}
let frameCapacity = 2;
const callArgs = [
"env.handle",
type === INSTANCE_FIELD ? "this.$handle" : "this.$classHandle",
"targetFieldId"
];
let returnCapture, returnStatements;
if (fieldType.fromJni) {
frameCapacity++;
returnCapture = "rawResult = ";
returnStatements = "try {" +
"result = fieldType.fromJni.call(this, rawResult, env);" +
"} finally {" +
"env.popLocalFrame(NULL);" +
"} " +
"return result;";
} else {
returnCapture = "result = ";
returnStatements = "env.popLocalFrame(NULL);" +
"return result;";
}
let getter;
eval("getter = function get" + name + "() {" +
"const isInstance = this.$handle !== null;" +
"if (type === INSTANCE_FIELD && !isInstance) { " +
"throw new Error('" + name + ": cannot get an instance field without an instance.');" +
"}" +
"const env = vm.getEnv();" +
"if (env.pushLocalFrame(" + frameCapacity + ") !== JNI_OK) {" +
"env.exceptionClear();" +
"throw new Error(\"Out of memory\");" +
"}" +
"let result, rawResult;" +
"try {" +
returnCapture + "invokeTarget(" + callArgs.join(", ") + ");" +
"} catch (e) {" +
"env.popLocalFrame(NULL);" +
"throw e;" +
"}" +
"try {" +
"env.checkForExceptionAndThrowIt();" +
"} catch (e) {" +
"env.popLocalFrame(NULL); " +
"throw e;" +
"}" +
returnStatements +
"}");
let setFunction = null;
if (type === STATIC_FIELD) {
setFunction = env.setStaticField(rawFieldType);
} else if (type === INSTANCE_FIELD) {
setFunction = env.setField(rawFieldType);
}
let inputStatement = null;
if (fieldType.toJni) {
inputStatement = "const input = fieldType.toJni.call(this, value, env);";
} else {
inputStatement = "const input = value;";
}
let setter;
eval("setter = function set" + name + "(value) {" +
"const isInstance = this.$handle !== null;" +
"if (type === INSTANCE_FIELD && !isInstance) { " +
"throw new Error('" + name + ": cannot set an instance field without an instance');" +
"}" +
"if (!fieldType.isCompatible(value)) {" +
"throw new Error('Field \"" + name + "\" expected input value compatible with " + fieldType.className + ".');" +
"}" +
"const env = vm.getEnv();" +
"try {" +
inputStatement +
"setFunction(" + callArgs.join(", ") + ", input);" +
"} catch (e) {" +
"throw e;" +
"}" +
"try {" +
"env.checkForExceptionAndThrowIt();" +
"} catch (e) {" +
"env.popLocalFrame(NULL); " +
"throw e;" +
"}" +
"}");
const f = {};
Object.defineProperty(f, 'value', {
enumerable: true,
get: function () {
return getter.call(this.self);
},
set: function (value) {
setter.call(this.self, value);
}
});
Object.defineProperty(f, 'holder', {
enumerable: true,
value: klass
});
Object.defineProperty(f, 'fieldType', {
enumerable: true,
value: type
});
Object.defineProperty(f, 'fieldReturnType', {
enumerable: true,
value: fieldType
});
return f;
}
function myAssign(target, ...sources) {
sources.forEach(source => {
Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) => {
if (key === "holder" && target.hasOwnProperty("holder")) {
// there is already holder property
} else {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
}
return descriptors;
}, {}));
});
return target;
}
function addMethodsAndFields() {
const invokeObjectMethodNoArgs = env.method('pointer', []);
const Method_getName = env.javaLangReflectMethod().getName;
const Field_getName = env.javaLangReflectField().getName;
const fieldHandles = klass.__fields__;
const methodHandles = klass.__methods__;
const jsMethods = {};
const jsFields = {};
const methods = invokeObjectMethodNoArgs(env.handle, classHandle, env.javaLangClass().getDeclaredMethods);
try {
const numMethods = env.getArrayLength(methods);
for (let methodIndex = 0; methodIndex !== numMethods; methodIndex++) {
const method = env.getObjectArrayElement(methods, methodIndex);
try {
const methodName = invokeObjectMethodNoArgs(env.handle, method, Method_getName);
try {
const methodjsName = env.stringFromJni(methodName);
const methodHandle = env.newGlobalRef(method);
methodHandles.push(methodHandle);
let jsOverloads;
if (jsMethods.hasOwnProperty(methodjsName)) {
jsOverloads = jsMethods[methodjsName];
} else {
jsOverloads = [];
jsMethods[methodjsName] = jsOverloads;
}
jsOverloads.push(methodHandle);
} finally {
env.deleteLocalRef(methodName);
}
} finally {
env.deleteLocalRef(method);
}
}
} finally {
env.deleteLocalRef(methods);
}
const fields = invokeObjectMethodNoArgs(env.handle, classHandle, env.javaLangClass().getDeclaredFields);
try {
const numFields = env.getArrayLength(fields);
for (let fieldIndex = 0; fieldIndex < numFields; fieldIndex++) {
const field = env.getObjectArrayElement(fields, fieldIndex);
try {
const fieldName = invokeObjectMethodNoArgs(env.handle, field, Field_getName);
try {
const fieldjsName = env.stringFromJni(fieldName);
const fieldHandle = env.newGlobalRef(field);
fieldHandles.push(fieldHandle);
jsFields[fieldjsName] = fieldHandle;
} finally {
env.deleteLocalRef(fieldName);
}
} finally {
env.deleteLocalRef(field);
}
}
} finally {
env.deleteLocalRef(fields);
}
// define access to the fields in the class (klass)
const values = myAssign({}, jsFields, jsMethods);
Object.keys(values).forEach(function (name) {
let v = null;
Object.defineProperty(klass.prototype, name, {
get: function () {
if (v === null) {
vm.perform(function () {
const env = vm.getEnv();
let f = {};
if (jsFields.hasOwnProperty(name)) {
f = makeField(name, jsFields[name], env);
}
let m = {};
if (jsMethods.hasOwnProperty(name)) {
m = makeMethodFromOverloads(name, jsMethods[name], env);
}
v = myAssign(m, f);
});
}
// TODO there should be a better way to do that
// set the reference for accessing fields
v.self = this;
return v;
}
});
});
}
function makeMethodFromOverloads(name, overloads, env) {
const Method = env.javaLangReflectMethod();
const Modifier = env.javaLangReflectModifier();
const invokeObjectMethodNoArgs = env.method('pointer', []);
const invokeIntMethodNoArgs = env.method('int32', []);
const invokeUInt8MethodNoArgs = env.method('uint8', []);
const methods = overloads.map(function (handle) {
const methodId = env.fromReflectedMethod(handle);
const modifiers = invokeIntMethodNoArgs(env.handle, handle, Method.getModifiers);
const jsType = (modifiers & Modifier.STATIC) !== 0 ? STATIC_METHOD : INSTANCE_METHOD;
const isVarArgs = invokeUInt8MethodNoArgs(env.handle, handle, Method.isVarArgs) ? true : false;
let jsRetType;
const jsArgTypes = [];
try {
const retType = invokeObjectMethodNoArgs(env.handle, handle, Method.getGenericReturnType);
env.checkForExceptionAndThrowIt();
try {
jsRetType = getTypeFromJniTypename(env.getTypeName(retType));
} finally {
env.deleteLocalRef(retType);
}
const argTypes = invokeObjectMethodNoArgs(env.handle, handle, Method.getGenericParameterTypes);
env.checkForExceptionAndThrowIt();
try {
const numArgTypes = env.getArrayLength(argTypes);
for (let argTypeIndex = 0; argTypeIndex !== numArgTypes; argTypeIndex++) {
const t = env.getObjectArrayElement(argTypes, argTypeIndex);
try {
const argClassName = (isVarArgs && argTypeIndex === numArgTypes - 1) ? env.getArrayTypeName(t) : env.getTypeName(t);
const argType = getTypeFromJniTypename(argClassName);
jsArgTypes.push(argType);
} finally {
env.deleteLocalRef(t);
}
}
} finally {
env.deleteLocalRef(argTypes);
}
} catch (e) {
return null;
}
return makeMethod(name, jsType, methodId, jsRetType, jsArgTypes, env);
}).filter(function (m) {
return m !== null;
});
if (methods.length === 0)
throw new Error("no supported overloads");
if (name === "valueOf") {
const hasDefaultValueOf = methods.some(function implementsDefaultValueOf(m) {
return m.type === INSTANCE_METHOD && m.argumentTypes.length === 0;
});
if (!hasDefaultValueOf) {
const defaultValueOf = function defaultValueOf() {
return this;
};
Object.defineProperty(defaultValueOf, 'holder', {
enumerable: true,
value: klass
});
Object.defineProperty(defaultValueOf, 'type', {
enumerable: true,
value: INSTANCE_METHOD
});
Object.defineProperty(defaultValueOf, 'returnType', {
enumerable: true,
value: getTypeFromJniTypename('int')
});
Object.defineProperty(defaultValueOf, 'argumentTypes', {
enumerable: true,
value: []
});
Object.defineProperty(defaultValueOf, 'canInvokeWith', {
enumerable: true,
value: function (args) {
return args.length === 0;
}
});
methods.push(defaultValueOf);
}
}
return makeMethodDispatcher(name, methods);
}
function makeMethodDispatcher(name, methods) {
const candidates = {};
methods.forEach(function (m) {
const numArgs = m.argumentTypes.length;
let group = candidates[numArgs];
if (!group) {
group = [];
candidates[numArgs] = group;
}
group.push(m);
});
function f() {
/* jshint validthis: true */
const isInstance = this.$handle !== null;
if (methods[0].type === INSTANCE_METHOD && !isInstance) {
if (name === 'toString') {
return "<" + this.$classWrapper.__name__ + ">";
}
throw new Error(name + ": cannot call instance method without an instance");
}
const group = candidates[arguments.length];
if (!group) {
throw new Error(name + ": argument count does not match any overload");
}
for (let i = 0; i !== group.length; i++) {
const method = group[i];
if (method.canInvokeWith(arguments)) {
return method.apply(this, arguments);
}
}
throw new Error(name + ": argument types do not match any overload");
}
Object.defineProperty(f, 'overloads', {
enumerable: true,
value: methods
});
Object.defineProperty(f, 'overload', {
enumerable: true,
value: function () {
const group = candidates[arguments.length];
if (!group) {
throw new Error(name + ": argument count does not match any overload");
}
const signature = Array.prototype.join.call(arguments, ":");
for (let i = 0; i !== group.length; i++) {
const method = group[i];
const s = method.argumentTypes.map(function (t) {
return t.className;
}).join(":");
if (s === signature) {
return method;
}
}
throw new Error(name + ": specified argument types do not match any overload");
}
});
Object.defineProperty(f, 'holder', {
enumerable: true,
get: methods[0].holder
});
Object.defineProperty(f, 'type', {
enumerable: true,
value: methods[0].type