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
/
CheckJni.c
2810 lines (2518 loc) · 95.3 KB
/
CheckJni.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
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.
*/
/*
* Support for -Xcheck:jni (the "careful" version of the JNI interfaces).
*
* We want to verify types, make sure class and field IDs are valid, and
* ensure that JNI's semantic expectations are being met. JNI seems to
* be relatively lax when it comes to requirements for permission checks,
* e.g. access to private methods is generally allowed from anywhere.
*
* TODO: keep a counter on global Get/Release. Report a warning if some Gets
* were not Released. Do not count explicit Add/DeleteGlobalRef calls (or
* count them separately, so we can complain if they exceed a certain
* threshold).
*
* TODO: verify that the methodID passed into the Call functions is for
* a method in the specified class.
*/
#include "Dalvik.h"
#include "JniInternal.h"
#include <zlib.h>
static void abortMaybe(void); // fwd
/*
* ===========================================================================
* JNI call bridge wrapper
* ===========================================================================
*/
/*
* Check the result of a native method call that returns an object reference.
*
* The primary goal here is to verify that native code is returning the
* correct type of object. If it's declared to return a String but actually
* returns a byte array, things will fail in strange ways later on.
*
* This can be a fairly expensive operation, since we have to look up the
* return type class by name in method->clazz' class loader. We take a
* shortcut here and allow the call to succeed if the descriptor strings
* match. This will allow some false-positives when a class is redefined
* by a class loader, but that's rare enough that it doesn't seem worth
* testing for.
*
* At this point, pResult->l has already been converted to an object pointer.
*/
static void checkCallResultCommon(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
assert(pResult->l != NULL);
Object* resultObj = (Object*) pResult->l;
ClassObject* objClazz = resultObj->clazz;
/*
* Make sure that pResult->l is an instance of the type this
* method was expected to return.
*/
const char* declType = dexProtoGetReturnType(&method->prototype);
const char* objType = objClazz->descriptor;
if (strcmp(declType, objType) == 0) {
/* names match; ignore class loader issues and allow it */
LOGV("Check %s.%s: %s io %s (FAST-OK)\n",
method->clazz->descriptor, method->name, objType, declType);
} else {
/*
* Names didn't match. We need to resolve declType in the context
* of method->clazz->classLoader, and compare the class objects
* for equality.
*
* Since we're returning an instance of declType, it's safe to
* assume that it has been loaded and initialized (or, for the case
* of an array, generated). However, the current class loader may
* not be listed as an initiating loader, so we can't just look for
* it in the loaded-classes list.
*/
ClassObject* declClazz;
declClazz = dvmFindClassNoInit(declType, method->clazz->classLoader);
if (declClazz == NULL) {
LOGW("JNI WARNING: method declared to return '%s' returned '%s'\n",
declType, objType);
LOGW(" failed in %s.%s ('%s' not found)\n",
method->clazz->descriptor, method->name, declType);
abortMaybe();
return;
}
if (!dvmInstanceof(objClazz, declClazz)) {
LOGW("JNI WARNING: method declared to return '%s' returned '%s'\n",
declType, objType);
LOGW(" failed in %s.%s\n",
method->clazz->descriptor, method->name);
abortMaybe();
return;
} else {
LOGV("Check %s.%s: %s io %s (SLOW-OK)\n",
method->clazz->descriptor, method->name, objType, declType);
}
}
}
/*
* Determine if we need to check the return type coming out of the call.
*
* (We don't do this at the top of checkCallResultCommon() because this is on
* the critical path for native method calls.)
*/
static inline bool callNeedsCheck(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
return (method->shorty[0] == 'L' && !dvmCheckException(self) &&
pResult->l != NULL);
}
/*
* Check a call into native code.
*/
void dvmCheckCallJNIMethod_general(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
dvmCallJNIMethod_general(args, pResult, method, self);
if (callNeedsCheck(args, pResult, method, self))
checkCallResultCommon(args, pResult, method, self);
}
/*
* Check a synchronized call into native code.
*/
void dvmCheckCallJNIMethod_synchronized(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
dvmCallJNIMethod_synchronized(args, pResult, method, self);
if (callNeedsCheck(args, pResult, method, self))
checkCallResultCommon(args, pResult, method, self);
}
/*
* Check a virtual call with no reference arguments (other than "this").
*/
void dvmCheckCallJNIMethod_virtualNoRef(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
dvmCallJNIMethod_virtualNoRef(args, pResult, method, self);
if (callNeedsCheck(args, pResult, method, self))
checkCallResultCommon(args, pResult, method, self);
}
/*
* Check a static call with no reference arguments (other than "clazz").
*/
void dvmCheckCallJNIMethod_staticNoRef(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
dvmCallJNIMethod_staticNoRef(args, pResult, method, self);
if (callNeedsCheck(args, pResult, method, self))
checkCallResultCommon(args, pResult, method, self);
}
/*
* ===========================================================================
* JNI function helpers
* ===========================================================================
*/
#define JNI_ENTER() dvmChangeStatus(NULL, THREAD_RUNNING)
#define JNI_EXIT() dvmChangeStatus(NULL, THREAD_NATIVE)
#define BASE_ENV(_env) (((JNIEnvExt*)_env)->baseFuncTable)
#define BASE_VM(_vm) (((JavaVMExt*)_vm)->baseFuncTable)
#define kRedundantDirectBufferTest false
/*
* Flags passed into checkThread().
*/
#define kFlag_Default 0x0000
#define kFlag_CritBad 0x0000 /* calling while in critical is bad */
#define kFlag_CritOkay 0x0001 /* ...okay */
#define kFlag_CritGet 0x0002 /* this is a critical "get" */
#define kFlag_CritRelease 0x0003 /* this is a critical "release" */
#define kFlag_CritMask 0x0003 /* bit mask to get "crit" value */
#define kFlag_ExcepBad 0x0000 /* raised exceptions are bad */
#define kFlag_ExcepOkay 0x0004 /* ...okay */
/*
* Enter/exit macros for JNI env "check" functions. These do not change
* the thread state within the VM.
*/
#define CHECK_ENTER(_env, _flags) \
do { \
JNI_TRACE(true, true); \
checkThread(_env, _flags, __FUNCTION__); \
} while(false)
#define CHECK_EXIT(_env) \
do { JNI_TRACE(false, true); } while(false)
/*
* Enter/exit macros for JNI invocation interface "check" functions. These
* do not change the thread state within the VM.
*
* Set "_hasmeth" to true if we have a valid thread with a method pointer.
* We won't have one before attaching a thread, after detaching a thread, or
* after destroying the VM.
*/
#define CHECK_VMENTER(_vm, _hasmeth) \
do { JNI_TRACE(true, _hasmeth); } while(false)
#define CHECK_VMEXIT(_vm, _hasmeth) \
do { JNI_TRACE(false, _hasmeth); } while(false)
#define CHECK_FIELD_TYPE(_env, _obj, _fieldid, _prim, _isstatic) \
checkFieldType(_env, _obj, _fieldid, _prim, _isstatic, __FUNCTION__)
#define CHECK_INST_FIELD_ID(_env, _obj, _fieldid) \
checkInstanceFieldID(_env, _obj, _fieldid, __FUNCTION__)
#define CHECK_CLASS(_env, _clazz) \
checkClass(_env, _clazz, __FUNCTION__)
#define CHECK_STRING(_env, _str) \
checkString(_env, _str, __FUNCTION__)
#define CHECK_UTF_STRING(_env, _str, _nullok) \
checkUtfString(_env, _str, _nullok, __FUNCTION__)
#define CHECK_CLASS_NAME(_env, _str) \
checkClassName(_env, _str, __FUNCTION__)
#define CHECK_OBJECT(_env, _obj) \
checkObject(_env, _obj, __FUNCTION__)
#define CHECK_ARRAY(_env, _array) \
checkArray(_env, _array, __FUNCTION__)
#define CHECK_RELEASE_MODE(_env, _mode) \
checkReleaseMode(_env, _mode, __FUNCTION__)
#define CHECK_LENGTH_POSITIVE(_env, _length) \
checkLengthPositive(_env, _length, __FUNCTION__)
#define CHECK_NON_NULL(_env, _ptr) \
checkNonNull(_env, _ptr, __FUNCTION__)
#define CHECK_SIG(_env, _methid, _sigbyte, _isstatic) \
checkSig(_env, _methid, _sigbyte, _isstatic, __FUNCTION__)
#define CHECK_VIRTUAL_METHOD(_env, _obj, _methid) \
checkVirtualMethod(_env, _obj, _methid, __FUNCTION__)
#define CHECK_STATIC_METHOD(_env, _clazz, _methid) \
checkStaticMethod(_env, _clazz, _methid, __FUNCTION__)
#define CHECK_METHOD_ARGS_A(_env, _methid, _args) \
checkMethodArgsA(_env, _methid, _args, __FUNCTION__)
#define CHECK_METHOD_ARGS_V(_env, _methid, _args) \
checkMethodArgsV(_env, _methid, _args, __FUNCTION__)
/*
* Prints trace messages when a native method calls a JNI function such as
* NewByteArray. Enabled if both "-Xcheck:jni" and "-verbose:jni" are enabled.
*/
#define JNI_TRACE(_entry, _hasmeth) \
do { \
if (gDvm.verboseJni && (_entry)) { \
static const char* classDescriptor = "???"; \
static const char* methodName = "???"; \
if (_hasmeth) { \
const Method* meth = dvmGetCurrentJNIMethod(); \
classDescriptor = meth->clazz->descriptor; \
methodName = meth->name; \
} \
/* use +6 to drop the leading "Check_" */ \
LOGI("JNI: %s (from %s.%s)", \
(__FUNCTION__)+6, classDescriptor, methodName); \
} \
} while(false)
/*
* Log the current location.
*
* "func" looks like "Check_DeleteLocalRef"; we drop the "Check_".
*/
static void showLocation(const Method* meth, const char* func)
{
char* desc = dexProtoCopyMethodDescriptor(&meth->prototype);
LOGW(" in %s.%s %s (%s)\n",
meth->clazz->descriptor, meth->name, desc, func + 6);
free(desc);
}
/*
* Abort if we are configured to bail out on JNI warnings.
*/
static void abortMaybe(void)
{
JavaVMExt* vm = (JavaVMExt*) gDvm.vmList;
if (vm->warnError) {
dvmDumpThread(dvmThreadSelf(), false);
dvmAbort();
}
}
/*
* Verify that the current thread is (a) attached and (b) associated with
* this particular instance of JNIEnv.
*
* Verify that, if this thread previously made a critical "get" call, we
* do the corresponding "release" call before we try anything else.
*
* Verify that, if an exception has been raised, the native code doesn't
* make any JNI calls other than the Exception* methods.
*
* TODO? if we add support for non-JNI native calls, make sure that the
* method at the top of the interpreted stack is a JNI method call. (Or
* set a flag in the Thread/JNIEnv when the call is made and clear it on
* return?)
*
* NOTE: we are still in THREAD_NATIVE mode. A GC could happen at any time.
*/
static void checkThread(JNIEnv* env, int flags, const char* func)
{
JNIEnvExt* threadEnv;
bool printWarn = false;
bool printException = false;
/* get the *correct* JNIEnv by going through our TLS pointer */
threadEnv = dvmGetJNIEnvForThread();
/*
* Verify that the JNIEnv we've been handed matches what we expected
* to receive.
*/
if (threadEnv == NULL) {
LOGE("JNI ERROR: non-VM thread making JNI calls\n");
// don't set printWarn -- it'll try to call showLocation()
dvmAbort();
} else if ((JNIEnvExt*) env != threadEnv) {
if (dvmThreadSelf()->threadId != threadEnv->envThreadId) {
LOGE("JNI: threadEnv != thread->env?\n");
dvmAbort();
}
LOGW("JNI WARNING: threadid=%d using env from threadid=%d\n",
threadEnv->envThreadId, ((JNIEnvExt*)env)->envThreadId);
printWarn = true;
/* this is a bad idea -- need to throw as we exit, or abort func */
//dvmThrowException("Ljava/lang/RuntimeException;",
// "invalid use of JNI env ptr");
} else if (((JNIEnvExt*) env)->self != dvmThreadSelf()) {
/* correct JNIEnv*; make sure the "self" pointer is correct */
LOGE("JNI ERROR: env->self != thread-self (%p vs. %p)\n",
((JNIEnvExt*) env)->self, dvmThreadSelf());
dvmAbort();
}
/*
* Check for critical resource misuse.
*/
switch (flags & kFlag_CritMask) {
case kFlag_CritOkay: // okay to call this method
break;
case kFlag_CritBad: // not okay to call
if (threadEnv->critical) {
LOGW("JNI WARNING: threadid=%d using JNI after critical get\n",
threadEnv->envThreadId);
printWarn = true;
}
break;
case kFlag_CritGet: // this is a "get" call
/* don't check here; we allow nested gets */
threadEnv->critical++;
break;
case kFlag_CritRelease: // this is a "release" call
threadEnv->critical--;
if (threadEnv->critical < 0) {
LOGW("JNI WARNING: threadid=%d called too many crit releases\n",
threadEnv->envThreadId);
printWarn = true;
}
break;
default:
assert(false);
}
/*
* Check for raised exceptions.
*/
if ((flags & kFlag_ExcepOkay) == 0 && dvmCheckException(dvmThreadSelf())) {
LOGW("JNI WARNING: JNI method called with exception raised\n");
printWarn = true;
printException = true;
}
if (printWarn)
showLocation(dvmGetCurrentJNIMethod(), func);
if (printException) {
LOGW("Pending exception is:\n");
dvmLogExceptionStackTrace();
}
if (printWarn)
abortMaybe();
}
/*
* Verify that the field is of the appropriate type. If the field has an
* object type, "obj" is the object we're trying to assign into it.
*
* Works for both static and instance fields.
*/
static void checkFieldType(JNIEnv* env, jobject jobj, jfieldID fieldID,
PrimitiveType prim, bool isStatic, const char* func)
{
static const char* primNameList[] = {
"Object/Array", "boolean", "char", "float", "double",
"byte", "short", "int", "long", "void"
};
const char** primNames = &primNameList[1]; // shift up for PRIM_NOT
Field* field = (Field*) fieldID;
bool printWarn = false;
if (fieldID == NULL) {
LOGE("JNI ERROR: null field ID\n");
abortMaybe();
}
if (field->signature[0] == 'L' || field->signature[0] == '[') {
Object* obj = dvmDecodeIndirectRef(env, jobj);
if (obj != NULL) {
ClassObject* fieldClass =
dvmFindLoadedClass(field->signature);
ClassObject* objClass = obj->clazz;
assert(fieldClass != NULL);
assert(objClass != NULL);
if (!dvmInstanceof(objClass, fieldClass)) {
LOGW("JNI WARNING: field '%s' with type '%s' set with wrong type (%s)\n",
field->name, field->signature, objClass->descriptor);
printWarn = true;
}
}
} else if (field->signature[0] != PRIM_TYPE_TO_LETTER[prim]) {
LOGW("JNI WARNING: field '%s' with type '%s' set with wrong type (%s)\n",
field->name, field->signature, primNames[prim]);
printWarn = true;
} else if (isStatic && !dvmIsStaticField(field)) {
if (isStatic)
LOGW("JNI WARNING: accessing non-static field %s as static\n",
field->name);
else
LOGW("JNI WARNING: accessing static field %s as non-static\n",
field->name);
printWarn = true;
}
if (printWarn) {
showLocation(dvmGetCurrentJNIMethod(), func);
abortMaybe();
}
}
/*
* Verify that "jobj" is a valid object, and that it's an object that JNI
* is allowed to know about. We allow NULL references.
*
* Must be in "running" mode before calling here.
*/
static void checkObject0(JNIEnv* env, jobject jobj, const char* func)
{
UNUSED_PARAMETER(env);
bool printWarn = false;
if (jobj == NULL)
return;
if (dvmIsWeakGlobalRef(jobj)) {
/*
* Normalize and continue. This will tell us if the PhantomReference
* object is valid.
*/
jobj = dvmNormalizeWeakGlobalRef((jweak) jobj);
}
if (dvmGetJNIRefType(env, jobj) == JNIInvalidRefType) {
LOGW("JNI WARNING: %p is not a valid JNI reference\n", jobj);
printWarn = true;
} else {
Object* obj = dvmDecodeIndirectRef(env, jobj);
if (obj == NULL || !dvmIsValidObject(obj)) {
LOGW("JNI WARNING: native code passing in bad object %p %p (%s)\n",
jobj, obj, func);
printWarn = true;
}
}
if (printWarn) {
showLocation(dvmGetCurrentJNIMethod(), func);
abortMaybe();
}
}
/*
* Verify that "jobj" is a valid object, and that it's an object that JNI
* is allowed to know about. We allow NULL references.
*
* Switches to "running" mode before performing checks.
*/
static void checkObject(JNIEnv* env, jobject jobj, const char* func)
{
JNI_ENTER();
checkObject0(env, jobj, func);
JNI_EXIT();
}
/*
* Verify that "clazz" actually points to a class object. (Also performs
* checkObject.)
*
* We probably don't need to identify where we're being called from,
* because the VM is most likely about to crash and leave a core dump
* if something is wrong.
*
* Because we're looking at an object on the GC heap, we have to switch
* to "running" mode before doing the checks.
*/
static void checkClass(JNIEnv* env, jclass jclazz, const char* func)
{
JNI_ENTER();
bool printWarn = false;
Object* obj = dvmDecodeIndirectRef(env, jclazz);
if (obj == NULL) {
LOGW("JNI WARNING: received null jclass\n");
printWarn = true;
} else if (!dvmIsValidObject(obj)) {
LOGW("JNI WARNING: jclass points to invalid object %p\n", obj);
printWarn = true;
} else if (obj->clazz != gDvm.classJavaLangClass) {
LOGW("JNI WARNING: jclass arg is not a Class reference "
"(%p is instance of %s)\n",
jclazz, obj->clazz->descriptor);
printWarn = true;
}
JNI_EXIT();
if (printWarn)
abortMaybe();
else
checkObject(env, jclazz, func);
}
/*
* Verify that "str" is non-NULL and points to a String object.
*
* Since we're dealing with objects, switch to "running" mode.
*/
static void checkString(JNIEnv* env, jstring jstr, const char* func)
{
JNI_ENTER();
bool printWarn = false;
Object* obj = dvmDecodeIndirectRef(env, jstr);
if (obj == NULL) {
LOGW("JNI WARNING: received null jstring (%s)\n", func);
printWarn = true;
} else if (obj->clazz != gDvm.classJavaLangString) {
/*
* TODO: we probably should test dvmIsValidObject first, because
* this will crash if "obj" is non-null but pointing to an invalid
* memory region. However, the "is valid" test is a little slow,
* we're doing it again over in checkObject().
*/
if (dvmIsValidObject(obj))
LOGW("JNI WARNING: jstring %p points to non-string object (%s)\n",
jstr, func);
else
LOGW("JNI WARNING: jstring %p is bogus (%s)\n", jstr, func);
printWarn = true;
}
JNI_EXIT();
if (printWarn)
abortMaybe();
else
checkObject(env, jstr, func);
}
/*
* Verify that "bytes" points to valid "modified UTF-8" data.
*/
static void checkUtfString(JNIEnv* env, const char* bytes, bool nullOk,
const char* func)
{
const char* origBytes = bytes;
if (bytes == NULL) {
if (!nullOk) {
LOGW("JNI WARNING: unexpectedly null UTF string\n");
goto fail;
}
return;
}
while (*bytes != '\0') {
u1 utf8 = *(bytes++);
// Switch on the high four bits.
switch (utf8 >> 4) {
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07: {
// Bit pattern 0xxx. No need for any extra bytes.
break;
}
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0f: {
/*
* Bit pattern 10xx or 1111, which are illegal start bytes.
* Note: 1111 is valid for normal UTF-8, but not the
* modified UTF-8 used here.
*/
LOGW("JNI WARNING: illegal start byte 0x%x\n", utf8);
goto fail;
}
case 0x0e: {
// Bit pattern 1110, so there are two additional bytes.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
LOGW("JNI WARNING: illegal continuation byte 0x%x\n", utf8);
goto fail;
}
// Fall through to take care of the final byte.
}
case 0x0c:
case 0x0d: {
// Bit pattern 110x, so there is one additional byte.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
LOGW("JNI WARNING: illegal continuation byte 0x%x\n", utf8);
goto fail;
}
break;
}
}
}
return;
fail:
LOGW(" string: '%s'\n", origBytes);
showLocation(dvmGetCurrentJNIMethod(), func);
abortMaybe();
}
/*
* In some circumstances the VM will screen class names, but it doesn't
* for class lookup. When things get bounced through a class loader, they
* can actually get normalized a couple of times; as a result, passing in
* a class name like "java.lang.Thread" instead of "java/lang/Thread" will
* work in some circumstances.
*
* This is incorrect and could cause strange behavior or compatibility
* problems, so we want to screen that out here.
*
* We expect "full-qualified" class names, like "java/lang/Thread" or
* "[Ljava/lang/Object;".
*/
static void checkClassName(JNIEnv* env, const char* className, const char* func)
{
const char* cp;
/* quick check for illegal chars */
cp = className;
while (*cp != '\0') {
if (*cp == '.') /* catch "java.lang.String" */
goto fail;
cp++;
}
if (*(cp-1) == ';' && *className == 'L')
goto fail; /* catch "Ljava/lang/String;" */
// TODO: need a more rigorous check here
return;
fail:
LOGW("JNI WARNING: illegal class name '%s' (%s)\n", className, func);
LOGW(" (should be formed like 'java/lang/String')\n");
abortMaybe();
}
/*
* Verify that "array" is non-NULL and points to an Array object.
*
* Since we're dealing with objects, switch to "running" mode.
*/
static void checkArray(JNIEnv* env, jarray jarr, const char* func)
{
JNI_ENTER();
bool printWarn = false;
Object* obj = dvmDecodeIndirectRef(env, jarr);
if (obj == NULL) {
LOGW("JNI WARNING: received null array (%s)\n", func);
printWarn = true;
} else if (obj->clazz->descriptor[0] != '[') {
if (dvmIsValidObject(obj))
LOGW("JNI WARNING: jarray %p points to non-array object (%s)\n",
jarr, obj->clazz->descriptor);
else
LOGW("JNI WARNING: jarray %p is bogus\n", jarr);
printWarn = true;
}
JNI_EXIT();
if (printWarn)
abortMaybe();
else
checkObject(env, jarr, func);
}
/*
* Verify that the "mode" argument passed to a primitive array Release
* function is one of the valid values.
*/
static void checkReleaseMode(JNIEnv* env, jint mode, const char* func)
{
if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
LOGW("JNI WARNING: bad value for mode (%d) (%s)\n", mode, func);
abortMaybe();
}
}
/*
* Verify that the length argument to array-creation calls is >= 0.
*/
static void checkLengthPositive(JNIEnv* env, jsize length, const char* func)
{
if (length < 0) {
LOGW("JNI WARNING: negative length for array allocation (%s)\n", func);
abortMaybe();
}
}
/*
* Verify that the pointer value is non-NULL.
*/
static void checkNonNull(JNIEnv* env, const void* ptr, const char* func)
{
if (ptr == NULL) {
LOGW("JNI WARNING: invalid null pointer (%s)\n", func);
abortMaybe();
}
}
/*
* Verify that the method's return type matches the type of call.
*
* "expectedSigByte" will be 'L' for all objects, including arrays.
*/
static void checkSig(JNIEnv* env, jmethodID methodID, char expectedSigByte,
bool isStatic, const char* func)
{
const Method* meth = (const Method*) methodID;
bool printWarn = false;
if (expectedSigByte != meth->shorty[0]) {
LOGW("JNI WARNING: expected return type '%c'\n", expectedSigByte);
printWarn = true;
} else if (isStatic && !dvmIsStaticMethod(meth)) {
if (isStatic)
LOGW("JNI WARNING: calling non-static method with static call\n");
else
LOGW("JNI WARNING: calling static method with non-static call\n");
printWarn = true;
}
if (printWarn) {
char* desc = dexProtoCopyMethodDescriptor(&meth->prototype);
LOGW(" calling %s.%s %s\n",
meth->clazz->descriptor, meth->name, desc);
free(desc);
showLocation(dvmGetCurrentJNIMethod(), func);
abortMaybe();
}
}
/*
* Verify that this static field ID is valid for this class.
*/
static void checkStaticFieldID(JNIEnv* env, jclass jclazz, jfieldID fieldID)
{
ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(env, jclazz);
StaticField* base = &clazz->sfields[0];
int fieldCount = clazz->sfieldCount;
if ((StaticField*) fieldID < base ||
(StaticField*) fieldID >= base + fieldCount)
{
LOGW("JNI WARNING: static fieldID %p not valid for class %s\n",
fieldID, clazz->descriptor);
LOGW(" base=%p count=%d\n", base, fieldCount);
abortMaybe();
}
}
/*
* Verify that this instance field ID is valid for this object.
*/
static void checkInstanceFieldID(JNIEnv* env, jobject jobj, jfieldID fieldID,
const char* func)
{
JNI_ENTER();
if (jobj == NULL) {
LOGW("JNI WARNING: invalid null object (%s)\n", func);
abortMaybe();
goto bail;
}
Object* obj = dvmDecodeIndirectRef(env, jobj);
ClassObject* clazz = obj->clazz;
/*
* Check this class and all of its superclasses for a matching field.
* Don't need to scan interfaces.
*/
while (clazz != NULL) {
if ((InstField*) fieldID >= clazz->ifields &&
(InstField*) fieldID < clazz->ifields + clazz->ifieldCount)
{
goto bail;
}
clazz = clazz->super;
}
LOGW("JNI WARNING: inst fieldID %p not valid for class %s\n",
fieldID, obj->clazz->descriptor);
abortMaybe();
bail:
JNI_EXIT();
}
/*
* Verify that "methodID" is appropriate for "jobj".
*
* Make sure the object is an instance of the method's declaring class.
* (Note the methodID might point to a declaration in an interface; this
* will be handled automatically by the instanceof check.)
*/
static void checkVirtualMethod(JNIEnv* env, jobject jobj, jmethodID methodID,
const char* func)
{
JNI_ENTER();
Object* obj = dvmDecodeIndirectRef(env, jobj);
const Method* meth = (const Method*) methodID;
if (!dvmInstanceof(obj->clazz, meth->clazz)) {
LOGW("JNI WARNING: can't call %s.%s on instance of %s\n",
meth->clazz->descriptor, meth->name, obj->clazz->descriptor);
abortMaybe();
}
JNI_EXIT();
}
/*
* Verify that "methodID" is appropriate for "clazz".
*
* A mismatch isn't dangerous, because the method defines the class. In
* fact, jclazz is unused in the implementation. It's best if we don't
* allow bad code in the system though.
*
* Instances of "jclazz" must be instances of the method's declaring class.
*/
static void checkStaticMethod(JNIEnv* env, jclass jclazz, jmethodID methodID,
const char* func)
{
JNI_ENTER();
ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(env, jclazz);
const Method* meth = (const Method*) methodID;
if (!dvmInstanceof(clazz, meth->clazz)) {
LOGW("JNI WARNING: can't call static %s.%s on class %s\n",
meth->clazz->descriptor, meth->name, clazz->descriptor);
// no abort
}
JNI_EXIT();
}
/*
* Verify that the reference arguments being passed in are appropriate for
* this method.
*
* At a minimum we want to make sure that the argument is a valid
* reference. We can also do a class lookup on the method signature
* and verify that the object is an instance of the appropriate class,
* but that's more expensive.
*
* The basic tests are redundant when indirect references are enabled,
* since reference arguments must always be converted explicitly. An
* instanceof test would not be redundant, but we're not doing that at
* this time.
*/
static void checkMethodArgsV(JNIEnv* env, jmethodID methodID, va_list args,
const char* func)
{
#ifndef USE_INDIRECT_REF
JNI_ENTER();
const Method* meth = (const Method*) methodID;
const char* desc = meth->shorty;
LOGV("V-checking %s.%s:%s...\n", meth->clazz->descriptor, meth->name, desc);
while (*++desc != '\0') { /* pre-incr to skip return type */
switch (*desc) {
case 'L':
{ /* 'shorty' descr uses L for all refs, incl array */
jobject argObj = va_arg(args, jobject);
checkObject0(env, argObj, func);
}
break;
case 'D': /* 8-byte double */
case 'J': /* 8-byte long */
case 'F': /* floats normalized to doubles */
(void) va_arg(args, u8);
break;
default: /* Z B C S I -- all passed as 32-bit integers */
(void) va_arg(args, u4);
break;
}
}
JNI_EXIT();
#endif
}
/*
* Same purpose as checkMethodArgsV, but with arguments in an array of
* jvalue structs.
*/
static void checkMethodArgsA(JNIEnv* env, jmethodID methodID, jvalue* args,
const char* func)
{
#ifndef USE_INDIRECT_REF
JNI_ENTER();
const Method* meth = (const Method*) methodID;
const char* desc = meth->shorty;
int idx = 0;
LOGV("A-checking %s.%s:%s...\n", meth->clazz->descriptor, meth->name, desc);
while (*++desc != '\0') { /* pre-incr to skip return type */
if (*desc == 'L') {
jobject argObj = args[idx].l;
checkObject0(env, argObj, func);
}
idx++;
}
JNI_EXIT();
#endif
}
/*
* ===========================================================================
* Guarded arrays
* ===========================================================================
*/
#define kGuardLen 512 /* must be multiple of 2 */
#define kGuardPattern 0xd5e3 /* uncommon values; d5e3d5e3 invalid addr */