This repository has been archived by the owner on Nov 15, 2022. It is now read-only.
mirrored from https://android.googlesource.com/platform/dalvik.git
-
Notifications
You must be signed in to change notification settings - Fork 263
/
Jni.cpp
3512 lines (3135 loc) · 122 KB
/
Jni.cpp
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
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Dalvik implementation of JNI interfaces.
*/
#include "Dalvik.h"
#include "JniInternal.h"
#include "ScopedPthreadMutexLock.h"
#include "UniquePtr.h"
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
/*
Native methods and interaction with the GC
All JNI methods must start by changing their thread status to
THREAD_RUNNING, and finish by changing it back to THREAD_NATIVE before
returning to native code. The switch to "running" triggers a thread
suspension check.
With a rudimentary GC we should be able to skip the status change for
simple functions, e.g. IsSameObject, GetJavaVM, GetStringLength, maybe
even access to fields with primitive types. Our options are more limited
with a compacting GC.
For performance reasons we do as little error-checking as possible here.
For example, we don't check to make sure the correct type of Object is
passed in when setting a field, and we don't prevent you from storing
new values in a "final" field. Such things are best handled in the
"check" version. For actions that are common, dangerous, and must be
checked at runtime, such as array bounds checks, we do the tests here.
General notes on local/global reference tracking
JNI provides explicit control over natively-held references that the GC
needs to know about. These can be local, in which case they're released
when the native method returns into the VM, or global, which are held
until explicitly released. (There are also weak-global references,
which have the lifespan and visibility of global references, but the
object they refer to may be collected.)
The references can be created with explicit JNI NewLocalRef / NewGlobalRef
calls. The former is very unusual, the latter is reasonably common
(e.g. for caching references to class objects).
Local references are most often created as a side-effect of JNI functions.
For example, the AllocObject/NewObject functions must create local
references to the objects returned, because nothing else in the GC root
set has a reference to the new objects.
The most common mode of operation is for a method to create zero or
more local references and return. Explicit "local delete" operations
are expected to be exceedingly rare, except when walking through an
object array, and the Push/PopLocalFrame calls are expected to be used
infrequently. For efficient operation, we want to add new local refs
with a simple store/increment operation; to avoid infinite growth in
pathological situations, we need to reclaim the space used by deleted
entries.
If we just want to maintain a list for the GC root set, we can use an
expanding append-only array that compacts when objects are deleted.
In typical situations, e.g. running through an array of objects, we will
be deleting one of the most recently added entries, so we can minimize
the number of elements moved (or avoid having to move any).
If we want to conceal the pointer values from native code, which is
necessary to allow the GC to move JNI-referenced objects around, then we
have to use a more complicated indirection mechanism.
The spec says, "Local references are only valid in the thread in which
they are created. The native code must not pass local references from
one thread to another."
Pinned objects
For some large chunks of data, notably primitive arrays and String data,
JNI allows the VM to choose whether it wants to pin the array object or
make a copy. We currently pin the memory for better execution performance.
TODO: we're using simple root set references to pin primitive array data,
because they have the property we need (i.e. the pointer we return is
guaranteed valid until we explicitly release it). However, if we have a
compacting GC and don't want to pin all memory held by all global refs,
we need to treat these differently.
Global reference tracking
There should be a small "active" set centered around the most-recently
added items.
Because it's global, access to it has to be synchronized. Additions and
removals require grabbing a mutex. If the table serves as an indirection
mechanism (i.e. it's not just a list for the benefit of the garbage
collector), reference lookups may also require grabbing a mutex.
The JNI spec does not define any sort of limit, so the list must be able
to expand to a reasonable size. It may be useful to log significant
increases in usage to help identify resource leaks.
Weak-global reference tracking
[TBD]
Local reference tracking
Each Thread/JNIEnv points to an IndirectRefTable.
We implement Push/PopLocalFrame with actual stack frames. Before a JNI
frame gets popped, we set "nextEntry" to the "top" pointer of the current
frame, effectively releasing the references.
The GC will scan all references in the table.
*/
#ifdef WITH_JNI_STACK_CHECK
# define COMPUTE_STACK_SUM(_self) computeStackSum(_self);
# define CHECK_STACK_SUM(_self) checkStackSum(_self);
/*
* Compute a CRC on the entire interpreted stack.
*
* Would be nice to compute it on "self" as well, but there are parts of
* the Thread that can be altered by other threads (e.g. prev/next pointers).
*/
static void computeStackSum(Thread* self) {
const u1* low = (const u1*)SAVEAREA_FROM_FP(self->interpSave.curFrame);
u4 crc = dvmInitCrc32();
self->stackCrc = 0;
crc = dvmComputeCrc32(crc, low, self->interpStackStart - low);
self->stackCrc = crc;
}
/*
* Compute a CRC on the entire interpreted stack, and compare it to what
* we previously computed.
*
* We can execute JNI directly from native code without calling in from
* interpreted code during VM initialization and immediately after JNI
* thread attachment. Another opportunity exists during JNI_OnLoad. Rather
* than catching these cases we just ignore them here, which is marginally
* less accurate but reduces the amount of code we have to touch with #ifdefs.
*/
static void checkStackSum(Thread* self) {
const u1* low = (const u1*)SAVEAREA_FROM_FP(self->interpSave.curFrame);
u4 stackCrc = self->stackCrc;
self->stackCrc = 0;
u4 crc = dvmInitCrc32();
crc = dvmComputeCrc32(crc, low, self->interpStackStart - low);
if (crc != stackCrc) {
const Method* meth = dvmGetCurrentJNIMethod();
if (dvmComputeExactFrameDepth(self->interpSave.curFrame) == 1) {
LOGD("JNI: bad stack CRC (0x%08x) -- okay during init", stackCrc);
} else if (strcmp(meth->name, "nativeLoad") == 0 &&
(strcmp(meth->clazz->descriptor, "Ljava/lang/Runtime;") == 0)) {
LOGD("JNI: bad stack CRC (0x%08x) -- okay during JNI_OnLoad", stackCrc);
} else {
LOGW("JNI: bad stack CRC (%08x vs %08x)", crc, stackCrc);
dvmAbort();
}
}
self->stackCrc = (u4) -1; /* make logic errors more noticeable */
}
#else
# define COMPUTE_STACK_SUM(_self) ((void)0)
# define CHECK_STACK_SUM(_self) ((void)0)
#endif
/*
* ===========================================================================
* Utility functions
* ===========================================================================
*/
/*
* Entry/exit processing for all JNI calls.
*
* We skip the (curiously expensive) thread-local storage lookup on our Thread*.
* If the caller has passed the wrong JNIEnv in, we're going to be accessing unsynchronized
* structures from more than one thread, and things are going to fail
* in bizarre ways. This is only sensible if the native code has been
* fully exercised with CheckJNI enabled.
*/
class ScopedJniThreadState {
public:
explicit ScopedJniThreadState(JNIEnv* env) {
mSelf = ((JNIEnvExt*) env)->self;
if (UNLIKELY(gDvmJni.workAroundAppJniBugs)) {
// When emulating direct pointers with indirect references, it's critical
// that we use the correct per-thread indirect reference table.
Thread* self = gDvmJni.workAroundAppJniBugs ? dvmThreadSelf() : mSelf;
if (self != mSelf) {
LOGE("JNI ERROR: env->self != thread-self (%p vs. %p); auto-correcting", mSelf, self);
mSelf = self;
}
}
CHECK_STACK_SUM(mSelf);
dvmChangeStatus(mSelf, THREAD_RUNNING);
}
~ScopedJniThreadState() {
dvmChangeStatus(mSelf, THREAD_NATIVE);
COMPUTE_STACK_SUM(mSelf);
}
inline Thread* self() {
return mSelf;
}
private:
Thread* mSelf;
// Disallow copy and assignment.
ScopedJniThreadState(const ScopedJniThreadState&);
void operator=(const ScopedJniThreadState&);
};
#define kGlobalRefsTableInitialSize 512
#define kGlobalRefsTableMaxSize 51200 /* arbitrary, must be < 64K */
#define kGrefWaterInterval 100
#define kTrackGrefUsage true
#define kWeakGlobalRefsTableInitialSize 16
#define kPinTableInitialSize 16
#define kPinTableMaxSize 1024
#define kPinComplainThreshold 10
bool dvmJniStartup() {
if (!gDvm.jniGlobalRefTable.init(kGlobalRefsTableInitialSize,
kGlobalRefsTableMaxSize,
kIndirectKindGlobal)) {
return false;
}
if (!gDvm.jniWeakGlobalRefTable.init(kWeakGlobalRefsTableInitialSize,
kGlobalRefsTableMaxSize,
kIndirectKindWeakGlobal)) {
return false;
}
dvmInitMutex(&gDvm.jniGlobalRefLock);
dvmInitMutex(&gDvm.jniWeakGlobalRefLock);
gDvm.jniGlobalRefLoMark = 0;
gDvm.jniGlobalRefHiMark = kGrefWaterInterval * 2;
if (!dvmInitReferenceTable(&gDvm.jniPinRefTable, kPinTableInitialSize, kPinTableMaxSize)) {
return false;
}
dvmInitMutex(&gDvm.jniPinRefLock);
return true;
}
void dvmJniShutdown() {
gDvm.jniGlobalRefTable.destroy();
gDvm.jniWeakGlobalRefTable.destroy();
dvmClearReferenceTable(&gDvm.jniPinRefTable);
}
/*
* Find the JNIEnv associated with the current thread.
*
* Currently stored in the Thread struct. Could also just drop this into
* thread-local storage.
*/
JNIEnvExt* dvmGetJNIEnvForThread() {
Thread* self = dvmThreadSelf();
if (self == NULL) {
return NULL;
}
return (JNIEnvExt*) dvmGetThreadJNIEnv(self);
}
/*
* Convert an indirect reference to an Object reference. The indirect
* reference may be local, global, or weak-global.
*
* If "jobj" is NULL, or is a weak global reference whose reference has
* been cleared, this returns NULL. If jobj is an invalid indirect
* reference, kInvalidIndirectRefObject is returned.
*
* Note "env" may be NULL when decoding global references.
*/
Object* dvmDecodeIndirectRef(Thread* self, jobject jobj) {
if (jobj == NULL) {
return NULL;
}
switch (indirectRefKind(jobj)) {
case kIndirectKindLocal:
{
Object* result = self->jniLocalRefTable.get(jobj);
if (UNLIKELY(result == NULL)) {
LOGE("JNI ERROR (app bug): use of deleted local reference (%p)", jobj);
dvmAbort();
}
return result;
}
case kIndirectKindGlobal:
{
// TODO: find a way to avoid the mutex activity here
IndirectRefTable* pRefTable = &gDvm.jniGlobalRefTable;
ScopedPthreadMutexLock lock(&gDvm.jniGlobalRefLock);
Object* result = pRefTable->get(jobj);
if (UNLIKELY(result == NULL)) {
LOGE("JNI ERROR (app bug): use of deleted global reference (%p)", jobj);
dvmAbort();
}
return result;
}
case kIndirectKindWeakGlobal:
{
// TODO: find a way to avoid the mutex activity here
IndirectRefTable* pRefTable = &gDvm.jniWeakGlobalRefTable;
ScopedPthreadMutexLock lock(&gDvm.jniWeakGlobalRefLock);
Object* result = pRefTable->get(jobj);
if (result == kClearedJniWeakGlobal) {
result = NULL;
} else if (UNLIKELY(result == NULL)) {
LOGE("JNI ERROR (app bug): use of deleted weak global reference (%p)", jobj);
dvmAbort();
}
return result;
}
case kIndirectKindInvalid:
default:
if (UNLIKELY(gDvmJni.workAroundAppJniBugs)) {
// Assume an invalid local reference is actually a direct pointer.
return reinterpret_cast<Object*>(jobj);
}
LOGW("Invalid indirect reference %p in decodeIndirectRef", jobj);
dvmAbort();
return kInvalidIndirectRefObject;
}
}
static void AddLocalReferenceFailure(IndirectRefTable* pRefTable) {
pRefTable->dump("JNI local");
LOGE("Failed adding to JNI local ref table (has %zd entries)", pRefTable->capacity());
dvmDumpThread(dvmThreadSelf(), false);
dvmAbort(); // spec says call FatalError; this is equivalent
}
/*
* Add a local reference for an object to the current stack frame. When
* the native function returns, the reference will be discarded.
*
* We need to allow the same reference to be added multiple times.
*
* This will be called on otherwise unreferenced objects. We cannot do
* GC allocations here, and it's best if we don't grab a mutex.
*/
static inline jobject addLocalReference(Thread* self, Object* obj) {
if (obj == NULL) {
return NULL;
}
IndirectRefTable* pRefTable = &self->jniLocalRefTable;
void* curFrame = self->interpSave.curFrame;
u4 cookie = SAVEAREA_FROM_FP(curFrame)->xtra.localRefCookie;
jobject jobj = (jobject) pRefTable->add(cookie, obj);
if (UNLIKELY(jobj == NULL)) {
AddLocalReferenceFailure(pRefTable);
}
if (UNLIKELY(gDvmJni.workAroundAppJniBugs)) {
// Hand out direct pointers to support broken old apps.
return reinterpret_cast<jobject>(obj);
}
return jobj;
}
/*
* Ensure that at least "capacity" references can be held in the local
* refs table of the current thread.
*/
static bool ensureLocalCapacity(Thread* self, int capacity) {
int numEntries = self->jniLocalRefTable.capacity();
// TODO: this isn't quite right, since "numEntries" includes holes
return ((kJniLocalRefMax - numEntries) >= capacity);
}
/*
* Explicitly delete a reference from the local list.
*/
static void deleteLocalReference(Thread* self, jobject jobj) {
if (jobj == NULL) {
return;
}
IndirectRefTable* pRefTable = &self->jniLocalRefTable;
void* curFrame = self->interpSave.curFrame;
u4 cookie = SAVEAREA_FROM_FP(curFrame)->xtra.localRefCookie;
if (!pRefTable->remove(cookie, jobj)) {
/*
* Attempting to delete a local reference that is not in the
* topmost local reference frame is a no-op. DeleteLocalRef returns
* void and doesn't throw any exceptions, but we should probably
* complain about it so the user will notice that things aren't
* going quite the way they expect.
*/
LOGW("JNI WARNING: DeleteLocalRef(%p) failed to find entry", jobj);
}
}
/*
* Add a global reference for an object.
*
* We may add the same object more than once. Add/remove calls are paired,
* so it needs to appear on the list multiple times.
*/
static jobject addGlobalReference(Object* obj) {
if (obj == NULL) {
return NULL;
}
//LOGI("adding obj=%p", obj);
//dvmDumpThread(dvmThreadSelf(), false);
if (false && dvmIsClassObject((Object*)obj)) {
ClassObject* clazz = (ClassObject*) obj;
LOGI("-------");
LOGI("Adding global ref on class %s", clazz->descriptor);
dvmDumpThread(dvmThreadSelf(), false);
}
if (false && ((Object*)obj)->clazz == gDvm.classJavaLangString) {
StringObject* strObj = (StringObject*) obj;
char* str = dvmCreateCstrFromString(strObj);
if (strcmp(str, "sync-response") == 0) {
LOGI("-------");
LOGI("Adding global ref on string '%s'", str);
dvmDumpThread(dvmThreadSelf(), false);
//dvmAbort();
}
free(str);
}
if (false && ((Object*)obj)->clazz == gDvm.classArrayByte) {
ArrayObject* arrayObj = (ArrayObject*) obj;
if (arrayObj->length == 8192 /*&&
dvmReferenceTableEntries(&gDvm.jniGlobalRefTable) > 400*/)
{
LOGI("Adding global ref on byte array %p (len=%d)",
arrayObj, arrayObj->length);
dvmDumpThread(dvmThreadSelf(), false);
}
}
ScopedPthreadMutexLock lock(&gDvm.jniGlobalRefLock);
/*
* Throwing an exception on failure is problematic, because JNI code
* may not be expecting an exception, and things sort of cascade. We
* want to have a hard limit to catch leaks during debugging, but this
* otherwise needs to expand until memory is consumed. As a practical
* matter, if we have many thousands of global references, chances are
* we're either leaking global ref table entries or we're going to
* run out of space in the GC heap.
*/
jobject jobj = (jobject) gDvm.jniGlobalRefTable.add(IRT_FIRST_SEGMENT, obj);
if (jobj == NULL) {
gDvm.jniGlobalRefTable.dump("JNI global");
LOGE("Failed adding to JNI global ref table (%zd entries)",
gDvm.jniGlobalRefTable.capacity());
dvmAbort();
}
LOGVV("GREF add %p (%s.%s)", obj,
dvmGetCurrentJNIMethod()->clazz->descriptor,
dvmGetCurrentJNIMethod()->name);
/* GREF usage tracking; should probably be disabled for production env */
if (kTrackGrefUsage && gDvm.jniGrefLimit != 0) {
int count = gDvm.jniGlobalRefTable.capacity();
// TODO: adjust for "holes"
if (count > gDvm.jniGlobalRefHiMark) {
LOGD("GREF has increased to %d", count);
gDvm.jniGlobalRefHiMark += kGrefWaterInterval;
gDvm.jniGlobalRefLoMark += kGrefWaterInterval;
/* watch for "excessive" use; not generally appropriate */
if (count >= gDvm.jniGrefLimit) {
if (gDvmJni.warnOnly) {
LOGW("Excessive JNI global references (%d)", count);
} else {
gDvm.jniGlobalRefTable.dump("JNI global");
LOGE("Excessive JNI global references (%d)", count);
dvmAbort();
}
}
}
}
return jobj;
}
static jobject addWeakGlobalReference(Object* obj) {
if (obj == NULL) {
return NULL;
}
ScopedPthreadMutexLock lock(&gDvm.jniWeakGlobalRefLock);
IndirectRefTable *table = &gDvm.jniWeakGlobalRefTable;
jobject jobj = (jobject) table->add(IRT_FIRST_SEGMENT, obj);
if (jobj == NULL) {
gDvm.jniWeakGlobalRefTable.dump("JNI weak global");
LOGE("Failed adding to JNI weak global ref table (%zd entries)", table->capacity());
dvmAbort();
}
return jobj;
}
static void deleteWeakGlobalReference(jobject jobj) {
if (jobj == NULL) {
return;
}
ScopedPthreadMutexLock lock(&gDvm.jniWeakGlobalRefLock);
IndirectRefTable *table = &gDvm.jniWeakGlobalRefTable;
if (!table->remove(IRT_FIRST_SEGMENT, jobj)) {
LOGW("JNI: DeleteWeakGlobalRef(%p) failed to find entry", jobj);
}
}
/*
* Remove a global reference. In most cases it's the entry most recently
* added, which makes this pretty quick.
*
* Thought: if it's not the most recent entry, just null it out. When we
* fill up, do a compaction pass before we expand the list.
*/
static void deleteGlobalReference(jobject jobj) {
if (jobj == NULL) {
return;
}
ScopedPthreadMutexLock lock(&gDvm.jniGlobalRefLock);
if (!gDvm.jniGlobalRefTable.remove(IRT_FIRST_SEGMENT, jobj)) {
LOGW("JNI: DeleteGlobalRef(%p) failed to find entry", jobj);
return;
}
if (kTrackGrefUsage && gDvm.jniGrefLimit != 0) {
int count = gDvm.jniGlobalRefTable.capacity();
// TODO: not quite right, need to subtract holes
if (count < gDvm.jniGlobalRefLoMark) {
LOGD("GREF has decreased to %d", count);
gDvm.jniGlobalRefHiMark -= kGrefWaterInterval;
gDvm.jniGlobalRefLoMark -= kGrefWaterInterval;
}
}
}
/*
* Objects don't currently move, so we just need to create a reference
* that will ensure the array object isn't collected.
*
* We use a separate reference table, which is part of the GC root set.
*/
static void pinPrimitiveArray(ArrayObject* arrayObj) {
if (arrayObj == NULL) {
return;
}
ScopedPthreadMutexLock lock(&gDvm.jniPinRefLock);
if (!dvmAddToReferenceTable(&gDvm.jniPinRefTable, (Object*)arrayObj)) {
dvmDumpReferenceTable(&gDvm.jniPinRefTable, "JNI pinned array");
LOGE("Failed adding to JNI pinned array ref table (%d entries)",
(int) dvmReferenceTableEntries(&gDvm.jniPinRefTable));
dvmDumpThread(dvmThreadSelf(), false);
dvmAbort();
}
/*
* If we're watching global ref usage, also keep an eye on these.
*
* The total number of pinned primitive arrays should be pretty small.
* A single array should not be pinned more than once or twice; any
* more than that is a strong indicator that a Release function is
* not being called.
*/
if (kTrackGrefUsage && gDvm.jniGrefLimit != 0) {
int count = 0;
Object** ppObj = gDvm.jniPinRefTable.table;
while (ppObj < gDvm.jniPinRefTable.nextEntry) {
if (*ppObj++ == (Object*) arrayObj)
count++;
}
if (count > kPinComplainThreshold) {
LOGW("JNI: pin count on array %p (%s) is now %d",
arrayObj, arrayObj->clazz->descriptor, count);
/* keep going */
}
}
}
/*
* Un-pin the array object. If an object was pinned twice, it must be
* unpinned twice before it's free to move.
*/
static void unpinPrimitiveArray(ArrayObject* arrayObj) {
if (arrayObj == NULL) {
return;
}
ScopedPthreadMutexLock lock(&gDvm.jniPinRefLock);
if (!dvmRemoveFromReferenceTable(&gDvm.jniPinRefTable,
gDvm.jniPinRefTable.table, (Object*) arrayObj))
{
LOGW("JNI: unpinPrimitiveArray(%p) failed to find entry (valid=%d)",
arrayObj, dvmIsHeapAddress((Object*) arrayObj));
return;
}
}
/*
* Dump the contents of the JNI reference tables to the log file.
*
* We only dump the local refs associated with the current thread.
*/
void dvmDumpJniReferenceTables() {
Thread* self = dvmThreadSelf();
self->jniLocalRefTable.dump("JNI local");
gDvm.jniGlobalRefTable.dump("JNI global");
dvmDumpReferenceTable(&gDvm.jniPinRefTable, "JNI pinned array");
}
/*
* Verify that a reference passed in from native code is one that the
* code is allowed to have.
*
* It's okay for native code to pass us a reference that:
* - was passed in as an argument when invoked by native code (and hence
* is in the JNI local refs table)
* - was returned to it from JNI (and is now in the local refs table)
* - is present in the JNI global refs table
*
* Used by -Xcheck:jni and GetObjectRefType.
*/
jobjectRefType dvmGetJNIRefType(Thread* self, jobject jobj) {
/*
* IndirectRefKind is currently defined as an exact match of
* jobjectRefType, so this is easy. We have to decode it to determine
* if it's a valid reference and not merely valid-looking.
*/
assert(jobj != NULL);
Object* obj = dvmDecodeIndirectRef(self, jobj);
if (obj == reinterpret_cast<Object*>(jobj) && gDvmJni.workAroundAppJniBugs) {
// If we're handing out direct pointers, check whether 'jobj' is a direct reference
// to a local reference.
return self->jniLocalRefTable.contains(obj) ? JNILocalRefType : JNIInvalidRefType;
} else if (obj == kInvalidIndirectRefObject) {
return JNIInvalidRefType;
} else {
return (jobjectRefType) indirectRefKind(jobj);
}
}
static void dumpMethods(Method* methods, size_t methodCount, const char* name) {
size_t i;
for (i = 0; i < methodCount; ++i) {
Method* method = &methods[i];
if (strcmp(name, method->name) == 0) {
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
LOGE("Candidate: %s.%s:%s", method->clazz->descriptor, name, desc);
free(desc);
}
}
}
static void dumpCandidateMethods(ClassObject* clazz, const char* methodName, const char* signature) {
LOGE("ERROR: couldn't find native method");
LOGE("Requested: %s.%s:%s", clazz->descriptor, methodName, signature);
dumpMethods(clazz->virtualMethods, clazz->virtualMethodCount, methodName);
dumpMethods(clazz->directMethods, clazz->directMethodCount, methodName);
}
/*
* Register a method that uses JNI calling conventions.
*/
static bool dvmRegisterJNIMethod(ClassObject* clazz, const char* methodName,
const char* signature, void* fnPtr)
{
if (fnPtr == NULL) {
return false;
}
// If a signature starts with a '!', we take that as a sign that the native code doesn't
// need the extra JNI arguments (the JNIEnv* and the jclass).
bool fastJni = false;
if (*signature == '!') {
fastJni = true;
++signature;
LOGV("fast JNI method %s.%s:%s detected", clazz->descriptor, methodName, signature);
}
Method* method = dvmFindDirectMethodByDescriptor(clazz, methodName, signature);
if (method == NULL) {
method = dvmFindVirtualMethodByDescriptor(clazz, methodName, signature);
}
if (method == NULL) {
dumpCandidateMethods(clazz, methodName, signature);
return false;
}
if (!dvmIsNativeMethod(method)) {
LOGW("Unable to register: not native: %s.%s:%s", clazz->descriptor, methodName, signature);
return false;
}
if (fastJni) {
// In this case, we have extra constraints to check...
if (dvmIsSynchronizedMethod(method)) {
// Synchronization is usually provided by the JNI bridge,
// but we won't have one.
LOGE("fast JNI method %s.%s:%s cannot be synchronized",
clazz->descriptor, methodName, signature);
return false;
}
if (!dvmIsStaticMethod(method)) {
// There's no real reason for this constraint, but since we won't
// be supplying a JNIEnv* or a jobject 'this', you're effectively
// static anyway, so it seems clearer to say so.
LOGE("fast JNI method %s.%s:%s cannot be non-static",
clazz->descriptor, methodName, signature);
return false;
}
}
if (method->nativeFunc != dvmResolveNativeMethod) {
/* this is allowed, but unusual */
LOGV("Note: %s.%s:%s was already registered", clazz->descriptor, methodName, signature);
}
method->fastJni = fastJni;
dvmUseJNIBridge(method, fnPtr);
LOGV("JNI-registered %s.%s:%s", clazz->descriptor, methodName, signature);
return true;
}
static const char* builtInPrefixes[] = {
"Landroid/",
"Lcom/android/",
"Lcom/google/android/",
"Ldalvik/",
"Ljava/",
"Ljavax/",
"Llibcore/",
"Lorg/apache/harmony/",
};
static bool shouldTrace(Method* method) {
const char* className = method->clazz->descriptor;
// Return true if the -Xjnitrace setting implies we should trace 'method'.
if (gDvm.jniTrace && strstr(className, gDvm.jniTrace)) {
return true;
}
// Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
// like part of Android.
if (gDvmJni.logThirdPartyJni) {
for (size_t i = 0; i < NELEM(builtInPrefixes); ++i) {
if (strstr(className, builtInPrefixes[i]) == className) {
return false;
}
}
return true;
}
return false;
}
/*
* Point "method->nativeFunc" at the JNI bridge, and overload "method->insns"
* to point at the actual function.
*/
void dvmUseJNIBridge(Method* method, void* func) {
method->shouldTrace = shouldTrace(method);
// Does the method take any reference arguments?
method->noRef = true;
const char* cp = method->shorty;
while (*++cp != '\0') { // Pre-increment to skip return type.
if (*cp == 'L') {
method->noRef = false;
break;
}
}
DalvikBridgeFunc bridge = gDvmJni.useCheckJni ? dvmCheckCallJNIMethod : dvmCallJNIMethod;
dvmSetNativeFunc(method, bridge, (const u2*) func);
}
// TODO: rewrite this to share code with CheckJNI's tracing...
static void appendValue(char type, const JValue value, char* buf, size_t n, bool appendComma)
{
size_t len = strlen(buf);
if (len >= n - 32) { // 32 should be longer than anything we could append.
buf[len - 1] = '.';
buf[len - 2] = '.';
buf[len - 3] = '.';
return;
}
char* p = buf + len;
switch (type) {
case 'B':
if (value.b >= 0 && value.b < 10) {
sprintf(p, "%d", value.b);
} else {
sprintf(p, "%#x (%d)", value.b, value.b);
}
break;
case 'C':
if (value.c < 0x7f && value.c >= ' ') {
sprintf(p, "U+%x ('%c')", value.c, value.c);
} else {
sprintf(p, "U+%x", value.c);
}
break;
case 'D':
sprintf(p, "%g", value.d);
break;
case 'F':
sprintf(p, "%g", value.f);
break;
case 'I':
sprintf(p, "%d", value.i);
break;
case 'L':
sprintf(p, "%#x", value.i);
break;
case 'J':
sprintf(p, "%lld", value.j);
break;
case 'S':
sprintf(p, "%d", value.s);
break;
case 'V':
strcpy(p, "void");
break;
case 'Z':
strcpy(p, value.z ? "true" : "false");
break;
default:
sprintf(p, "unknown type '%c'", type);
break;
}
if (appendComma) {
strcat(p, ", ");
}
}
static void logNativeMethodEntry(const Method* method, const u4* args)
{
char thisString[32] = { 0 };
const u4* sp = args;
if (!dvmIsStaticMethod(method)) {
sprintf(thisString, "this=0x%08x ", *sp++);
}
char argsString[128]= { 0 };
const char* desc = &method->shorty[1];
while (*desc != '\0') {
char argType = *desc++;
JValue value;
if (argType == 'D' || argType == 'J') {
value.j = dvmGetArgLong(sp, 0);
sp += 2;
} else {
value.i = *sp++;
}
appendValue(argType, value, argsString, sizeof(argsString),
*desc != '\0');
}
std::string className(dvmHumanReadableDescriptor(method->clazz->descriptor));
char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
LOGI("-> %s %s%s %s(%s)", className.c_str(), method->name, signature, thisString, argsString);
free(signature);
}
static void logNativeMethodExit(const Method* method, Thread* self, const JValue returnValue)
{
std::string className(dvmHumanReadableDescriptor(method->clazz->descriptor));
char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
if (dvmCheckException(self)) {
Object* exception = dvmGetException(self);
std::string exceptionClassName(dvmHumanReadableDescriptor(exception->clazz->descriptor));
LOGI("<- %s %s%s threw %s", className.c_str(),
method->name, signature, exceptionClassName.c_str());
} else {
char returnValueString[128] = { 0 };
char returnType = method->shorty[0];
appendValue(returnType, returnValue, returnValueString, sizeof(returnValueString), false);
LOGI("<- %s %s%s returned %s", className.c_str(),
method->name, signature, returnValueString);
}
free(signature);
}
/*
* Get the method currently being executed by examining the interp stack.
*/
const Method* dvmGetCurrentJNIMethod() {
assert(dvmThreadSelf() != NULL);
void* fp = dvmThreadSelf()->interpSave.curFrame;
const Method* meth = SAVEAREA_FROM_FP(fp)->method;
assert(meth != NULL);
assert(dvmIsNativeMethod(meth));
return meth;
}
/*
* Track a JNI MonitorEnter in the current thread.
*
* The goal is to be able to "implicitly" release all JNI-held monitors
* when the thread detaches.
*
* Monitors may be entered multiple times, so we add a new entry for each
* enter call. It would be more efficient to keep a counter. At present
* there's no real motivation to improve this however.
*/
static void trackMonitorEnter(Thread* self, Object* obj) {
static const int kInitialSize = 16;
ReferenceTable* refTable = &self->jniMonitorRefTable;
/* init table on first use */
if (refTable->table == NULL) {
assert(refTable->maxEntries == 0);
if (!dvmInitReferenceTable(refTable, kInitialSize, INT_MAX)) {
LOGE("Unable to initialize monitor tracking table");
dvmAbort();
}
}
if (!dvmAddToReferenceTable(refTable, obj)) {
/* ran out of memory? could throw exception instead */
LOGE("Unable to add entry to monitor tracking table");
dvmAbort();
} else {
LOGVV("--- added monitor %p", obj);
}
}
/*
* Track a JNI MonitorExit in the current thread.
*/
static void trackMonitorExit(Thread* self, Object* obj) {
ReferenceTable* pRefTable = &self->jniMonitorRefTable;
if (!dvmRemoveFromReferenceTable(pRefTable, pRefTable->table, obj)) {
LOGE("JNI monitor %p not found in tracking list", obj);
/* keep going? */
} else {
LOGVV("--- removed monitor %p", obj);
}
}
/*
* Release all monitors held by the jniMonitorRefTable list.
*/
void dvmReleaseJniMonitors(Thread* self) {
ReferenceTable* pRefTable = &self->jniMonitorRefTable;
Object** top = pRefTable->table;
if (top == NULL) {
return;
}
Object** ptr = pRefTable->nextEntry;
while (--ptr >= top) {
if (!dvmUnlockObject(self, *ptr)) {