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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
|
/*
* 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.
*/
/*
* Implementation of java.lang.reflect.Proxy.
*
* Traditionally this is implemented entirely in interpreted code,
* generating bytecode that defines the proxy class. Dalvik doesn't
* currently support this approach, so we generate the class directly. If
* we add support for DefineClass with standard classfiles we can
* eliminate this.
*/
#include "Dalvik.h"
#include <stdlib.h>
// fwd
static bool returnTypesAreCompatible(Method* baseMethod, Method* subMethod);
static bool gatherMethods(ArrayObject* interfaces, Method*** pMethods,\
ArrayObject** pThrows, int* pMethodCount);
static int copyWithoutDuplicates(Method** allMethods, int allCount,
Method** outMethods, ArrayObject* throws);
static bool createExceptionClassList(const Method* method,
PointerSet** pThrows);
static void updateExceptionClassList(const Method* method, PointerSet* throws);
static void createConstructor(ClassObject* clazz, Method* meth);
static void createHandlerMethod(ClassObject* clazz, Method* dstMeth,
const Method* srcMeth);
static void proxyConstructor(const u4* args, JValue* pResult,
const Method* method, Thread* self);
static void proxyInvoker(const u4* args, JValue* pResult,
const Method* method, Thread* self);
static bool mustWrapException(const Method* method, const Object* throwable);
/* private static fields in the Proxy class */
#define kThrowsField 0
#define kProxySFieldCount 1
/*
* Generate a proxy class with the specified name, interfaces, and loader.
* "interfaces" is an array of class objects.
*
* The Proxy.getProxyClass() code has done the following:
* - Verified that "interfaces" contains only interfaces
* - Verified that no interface appears twice
* - Prepended the package name to the class name if one or more
* interfaces are non-public
* - Searched for an existing instance of an appropriate Proxy class
*
* On failure we leave a partially-created class object sitting around,
* but the garbage collector will take care of it.
*/
ClassObject* dvmGenerateProxyClass(StringObject* str, ArrayObject* interfaces,
Object* loader)
{
int result = -1;
ArrayObject* throws = NULL;
char* nameStr = dvmCreateCstrFromString(str);
if (nameStr == NULL) {
dvmThrowIllegalArgumentException("missing name");
return NULL;
}
ALOGV("+++ Generate proxy class '%s' %p from %d interface classes",
nameStr, loader, interfaces->length);
/*
* Characteristics of a Proxy class:
* - concrete class, public and final
* - superclass is java.lang.reflect.Proxy
* - implements all listed interfaces (req'd for instanceof)
* - has one method for each method in the interfaces (for duplicates,
* the method in the earliest interface wins)
* - has one constructor (takes an InvocationHandler arg)
* - has overrides for hashCode, equals, and toString (these come first)
* - has one field, a reference to the InvocationHandler object, inherited
* from Proxy
*
* TODO: set protection domain so it matches bootstrap classes.
*
* The idea here is to create a class object and fill in the details
* as we would in loadClassFromDex(), and then call dvmLinkClass() to do
* all the heavy lifting (notably populating the virtual and interface
* method tables).
*/
/*
* Allocate storage for the class object and set some basic fields.
*/
size_t newClassSize =
sizeof(ClassObject) + kProxySFieldCount * sizeof(StaticField);
ClassObject* newClass =
(ClassObject*) dvmMalloc(newClassSize, ALLOC_NON_MOVING);
if (newClass == NULL)
goto bail;
DVM_OBJECT_INIT(newClass, gDvm.classJavaLangClass);
dvmSetClassSerialNumber(newClass);
newClass->descriptorAlloc = dvmNameToDescriptor(nameStr);
newClass->descriptor = newClass->descriptorAlloc;
SET_CLASS_FLAG(newClass, ACC_PUBLIC | ACC_FINAL);
dvmSetFieldObject((Object *)newClass,
OFFSETOF_MEMBER(ClassObject, super),
(Object *)gDvm.classJavaLangReflectProxy);
newClass->primitiveType = PRIM_NOT;
dvmSetFieldObject((Object *)newClass,
OFFSETOF_MEMBER(ClassObject, classLoader),
(Object *)loader);
/*
* Add direct method definitions. We have one (the constructor).
*/
newClass->directMethodCount = 1;
newClass->directMethods = (Method*) dvmLinearAlloc(newClass->classLoader,
1 * sizeof(Method));
createConstructor(newClass, &newClass->directMethods[0]);
dvmLinearReadOnly(newClass->classLoader, newClass->directMethods);
/*
* Add virtual method definitions.
*/
{
/*
* Generate a temporary list of virtual methods.
*/
int methodCount;
Method **methods;
if (!gatherMethods(interfaces, &methods, &throws, &methodCount)) {
goto bail;
}
newClass->virtualMethodCount = methodCount;
size_t virtualMethodsSize = methodCount * sizeof(Method);
newClass->virtualMethods =
(Method*)dvmLinearAlloc(newClass->classLoader, virtualMethodsSize);
for (int i = 0; i < newClass->virtualMethodCount; i++) {
createHandlerMethod(newClass, &newClass->virtualMethods[i], methods[i]);
}
free(methods);
dvmLinearReadOnly(newClass->classLoader, newClass->virtualMethods);
}
/*
* Add interface list.
*/
{
size_t interfaceCount = interfaces->length;
ClassObject** ifArray = (ClassObject**)(void*)interfaces->contents;
newClass->interfaceCount = interfaceCount;
size_t interfacesSize = sizeof(ClassObject*) * interfaceCount;
newClass->interfaces =
(ClassObject**)dvmLinearAlloc(newClass->classLoader, interfacesSize);
for (size_t i = 0; i < interfaceCount; i++)
newClass->interfaces[i] = ifArray[i];
dvmLinearReadOnly(newClass->classLoader, newClass->interfaces);
}
/*
* Static field list. We have one private field, for our list of
* exceptions declared for each method.
*/
assert(kProxySFieldCount == 1);
newClass->sfieldCount = kProxySFieldCount;
{
StaticField* sfield = &newClass->sfields[kThrowsField];
sfield->clazz = newClass;
sfield->name = "throws";
sfield->signature = "[[Ljava/lang/Throwable;";
sfield->accessFlags = ACC_STATIC | ACC_PRIVATE;
dvmSetStaticFieldObject(sfield, (Object*)throws);
}
/*
* Everything is ready. This class didn't come out of a DEX file
* so we didn't tuck any indexes into the class object. We can
* advance to LOADED state immediately.
*/
newClass->status = CLASS_LOADED;
if (!dvmLinkClass(newClass)) {
ALOGD("Proxy class link failed");
goto bail;
}
/*
* All good. Add it to the hash table. We should NOT see a collision
* here; if we do, it means the caller has screwed up and provided us
* with a duplicate name.
*/
if (!dvmAddClassToHash(newClass)) {
LOGE("ERROR: attempted to generate %s more than once",
newClass->descriptor);
goto bail;
}
result = 0;
bail:
free(nameStr);
if (result != 0) {
/* must free innards explicitly if we didn't finish linking */
dvmFreeClassInnards(newClass);
newClass = NULL;
if (!dvmCheckException(dvmThreadSelf())) {
/* throw something */
dvmThrowRuntimeException(NULL);
}
}
/* allow the GC to free these when nothing else has a reference */
dvmReleaseTrackedAlloc((Object*) throws, NULL);
dvmReleaseTrackedAlloc((Object*) newClass, NULL);
return newClass;
}
/*
* Generate a list of methods. The Method pointers returned point to the
* abstract method definition from the appropriate interface, or to the
* virtual method definition in java.lang.Object.
*
* We also allocate an array of arrays of throwable classes, one for each
* method,so we can do some special handling of checked exceptions. The
* caller must call ReleaseTrackedAlloc() on *pThrows.
*/
static bool gatherMethods(ArrayObject* interfaces, Method*** pMethods,
ArrayObject** pThrows, int* pMethodCount)
{
ClassObject** classes;
ArrayObject* throws = NULL;
Method** methods = NULL;
Method** allMethods = NULL;
int numInterfaces, maxCount, actualCount, allCount;
bool result = false;
int i;
/*
* Get a maximum count so we can allocate storage. We need the
* methods declared by each interface and all of its superinterfaces.
*/
maxCount = 3; // 3 methods in java.lang.Object
numInterfaces = interfaces->length;
classes = (ClassObject**)(void*)interfaces->contents;
for (i = 0; i < numInterfaces; i++, classes++) {
ClassObject* clazz = *classes;
LOGVV("--- %s virtualMethodCount=%d",
clazz->descriptor, clazz->virtualMethodCount);
maxCount += clazz->virtualMethodCount;
int j;
for (j = 0; j < clazz->iftableCount; j++) {
ClassObject* iclass = clazz->iftable[j].clazz;
LOGVV("--- +%s %d",
iclass->descriptor, iclass->virtualMethodCount);
maxCount += iclass->virtualMethodCount;
}
}
methods = (Method**) malloc(maxCount * sizeof(*methods));
allMethods = (Method**) malloc(maxCount * sizeof(*methods));
if (methods == NULL || allMethods == NULL)
goto bail;
/*
* First three entries are the java.lang.Object methods.
*/
{
ClassObject* obj = gDvm.classJavaLangObject;
allMethods[0] = obj->vtable[gDvm.voffJavaLangObject_equals];
allMethods[1] = obj->vtable[gDvm.voffJavaLangObject_hashCode];
allMethods[2] = obj->vtable[gDvm.voffJavaLangObject_toString];
allCount = 3;
}
/*
* Add the methods from each interface, in order.
*/
classes = (ClassObject**)(void*)interfaces->contents;
for (i = 0; i < numInterfaces; i++, classes++) {
ClassObject* clazz = *classes;
int j;
for (j = 0; j < clazz->virtualMethodCount; j++) {
allMethods[allCount++] = &clazz->virtualMethods[j];
}
for (j = 0; j < clazz->iftableCount; j++) {
ClassObject* iclass = clazz->iftable[j].clazz;
int k;
for (k = 0; k < iclass->virtualMethodCount; k++) {
allMethods[allCount++] = &iclass->virtualMethods[k];
}
}
}
assert(allCount == maxCount);
/*
* Allocate some storage to hold the lists of throwables. We need
* one entry per unique method, but it's convenient to allocate it
* ahead of the duplicate processing.
*/
ClassObject* arrArrClass;
arrArrClass = dvmFindArrayClass("[[Ljava/lang/Throwable;", NULL);
if (arrArrClass == NULL)
goto bail;
throws = dvmAllocArrayByClass(arrArrClass, allCount, ALLOC_DEFAULT);
/*
* Identify and remove duplicates.
*/
actualCount = copyWithoutDuplicates(allMethods, allCount, methods, throws);
if (actualCount < 0)
goto bail;
//LOGI("gathered methods:");
//for (i = 0; i < actualCount; i++) {
// LOGI(" %d: %s.%s",
// i, methods[i]->clazz->descriptor, methods[i]->name);
//}
*pMethods = methods;
*pMethodCount = actualCount;
*pThrows = throws;
result = true;
bail:
free(allMethods);
if (!result) {
free(methods);
dvmReleaseTrackedAlloc((Object*)throws, NULL);
}
return result;
}
/*
* Identify and remove duplicates, where "duplicate" means it has the
* same name and arguments, but not necessarily the same return type.
*
* If duplicate methods have different return types, we want to use the
* first method whose return type is assignable from all other duplicate
* methods. That is, if we have:
* class base {...}
* class sub extends base {...}
* class subsub extends sub {...}
* Then we want to return the method that returns subsub, since callers
* to any form of the method will get a usable object back.
*
* All other duplicate methods are stripped out.
*
* This also populates the "throwLists" array with arrays of Class objects,
* one entry per method in "outMethods". Methods that don't declare any
* throwables (or have no common throwables with duplicate methods) will
* have NULL entries.
*
* Returns the number of methods copied into "methods", or -1 on failure.
*/
static int copyWithoutDuplicates(Method** allMethods, int allCount,
Method** outMethods, ArrayObject* throwLists)
{
int outCount = 0;
int i, j;
/*
* The plan is to run through all methods, checking all other methods
* for a duplicate. If we find a match, we see if the other methods'
* return type is compatible/assignable with ours. If the current
* method is assignable from all others, we copy it to the new list,
* and NULL out all other entries. If not, we keep looking for a
* better version.
*
* If there are no duplicates, we copy the method and NULL the entry.
*
* At the end of processing, if we have any non-NULL entries, then we
* have bad duplicates and must exit with an exception.
*/
for (i = 0; i < allCount; i++) {
bool best, dupe;
if (allMethods[i] == NULL)
continue;
/*
* Find all duplicates. If any of the return types is not
* assignable to our return type, then we're not the best.
*
* We start from 0, not i, because we need to compare assignability
* the other direction even if we've compared these before.
*/
dupe = false;
best = true;
for (j = 0; j < allCount; j++) {
if (i == j)
continue;
if (allMethods[j] == NULL)
continue;
if (dvmCompareMethodNamesAndParameterProtos(allMethods[i],
allMethods[j]) == 0)
{
/*
* Duplicate method, check return type. If it's a primitive
* type or void, the types must match exactly, or we throw
* an exception now.
*/
ALOGV("MATCH on %s.%s and %s.%s",
allMethods[i]->clazz->descriptor, allMethods[i]->name,
allMethods[j]->clazz->descriptor, allMethods[j]->name);
dupe = true;
if (!returnTypesAreCompatible(allMethods[i], allMethods[j]))
best = false;
}
}
/*
* If this is the best of a set of duplicates, copy it over and
* nuke all duplicates.
*
* While we do this, we create the set of exceptions declared to
* be thrown by all occurrences of the method.
*/
if (dupe) {
if (best) {
ALOGV("BEST %d %s.%s -> %d", i,
allMethods[i]->clazz->descriptor, allMethods[i]->name,
outCount);
/* if we have exceptions, make a local copy */
PointerSet* commonThrows = NULL;
if (!createExceptionClassList(allMethods[i], &commonThrows))
return -1;
/*
* Run through one more time, erasing the duplicates. (This
* would go faster if we had marked them somehow.)
*/
for (j = 0; j < allCount; j++) {
if (i == j)
continue;
if (allMethods[j] == NULL)
continue;
if (dvmCompareMethodNamesAndParameterProtos(allMethods[i],
allMethods[j]) == 0)
{
ALOGV("DEL %d %s.%s", j,
allMethods[j]->clazz->descriptor,
allMethods[j]->name);
/*
* Update set to hold the intersection of method[i]'s
* and method[j]'s throws.
*/
if (commonThrows != NULL) {
updateExceptionClassList(allMethods[j],
commonThrows);
}
allMethods[j] = NULL;
}
}
/*
* If the set of Throwable classes isn't empty, create an
* array of Class, copy them into it, and put the result
* into the "throwLists" array.
*/
if (commonThrows != NULL &&
dvmPointerSetGetCount(commonThrows) > 0)
{
int commonCount = dvmPointerSetGetCount(commonThrows);
ArrayObject* throwArray;
Object** contents;
int ent;
throwArray = dvmAllocArrayByClass(
gDvm.classJavaLangClassArray, commonCount,
ALLOC_DEFAULT);
if (throwArray == NULL) {
LOGE("common-throw array alloc failed");
return -1;
}
contents = (Object**)(void*)throwArray->contents;
for (ent = 0; ent < commonCount; ent++) {
contents[ent] = (Object*)
dvmPointerSetGetEntry(commonThrows, ent);
}
/* add it to the array of arrays */
contents = (Object**)(void*)throwLists->contents;
contents[outCount] = (Object*) throwArray;
dvmReleaseTrackedAlloc((Object*) throwArray, NULL);
}
/* copy the winner and NULL it out */
outMethods[outCount++] = allMethods[i];
allMethods[i] = NULL;
dvmPointerSetFree(commonThrows);
} else {
ALOGV("BEST not %d", i);
}
} else {
/*
* Singleton. Copy the entry and NULL it out.
*/
ALOGV("COPY singleton %d %s.%s -> %d", i,
allMethods[i]->clazz->descriptor, allMethods[i]->name,
outCount);
/* keep track of our throwables */
ArrayObject* exceptionArray = dvmGetMethodThrows(allMethods[i]);
if (exceptionArray != NULL) {
Object** contents;
contents = (Object**)(void*)throwLists->contents;
contents[outCount] = (Object*) exceptionArray;
dvmReleaseTrackedAlloc((Object*) exceptionArray, NULL);
}
outMethods[outCount++] = allMethods[i];
allMethods[i] = NULL;
}
}
/*
* Check for stragglers. If we find any, throw an exception.
*/
for (i = 0; i < allCount; i++) {
if (allMethods[i] != NULL) {
ALOGV("BAD DUPE: %d %s.%s", i,
allMethods[i]->clazz->descriptor, allMethods[i]->name);
dvmThrowIllegalArgumentException(
"incompatible return types in proxied interfaces");
return -1;
}
}
return outCount;
}
/*
* Classes can declare to throw multiple exceptions in a hierarchy, e.g.
* IOException and FileNotFoundException. Since we're only interested in
* knowing the set that can be thrown without requiring an extra wrapper,
* we can remove anything that is a subclass of something else in the list.
*
* The "mix" step we do next reduces things toward the most-derived class,
* so it's important that we start with the least-derived classes.
*/
static void reduceExceptionClassList(ArrayObject* exceptionArray)
{
const ClassObject** classes =
(const ClassObject**)(void*)exceptionArray->contents;
/*
* Consider all pairs of classes. If one is the subclass of the other,
* null out the subclass.
*/
size_t len = exceptionArray->length;
for (size_t i = 0; i < len - 1; i++) {
if (classes[i] == NULL)
continue;
for (size_t j = i + 1; j < len; j++) {
if (classes[j] == NULL)
continue;
if (dvmInstanceof(classes[i], classes[j])) {
classes[i] = NULL;
break; /* no more comparisons against classes[i] */
} else if (dvmInstanceof(classes[j], classes[i])) {
classes[j] = NULL;
}
}
}
}
/*
* Create a local array with a copy of the throwable classes declared by
* "method". If no throws are declared, "*pSet" will be NULL.
*
* Returns "false" on allocation failure.
*/
static bool createExceptionClassList(const Method* method, PointerSet** pThrows)
{
ArrayObject* exceptionArray = NULL;
bool result = false;
exceptionArray = dvmGetMethodThrows(method);
if (exceptionArray != NULL && exceptionArray->length > 0) {
/* reduce list, nulling out redundant entries */
reduceExceptionClassList(exceptionArray);
*pThrows = dvmPointerSetAlloc(exceptionArray->length);
if (*pThrows == NULL)
goto bail;
const ClassObject** contents;
contents = (const ClassObject**)(void*)exceptionArray->contents;
for (size_t i = 0; i < exceptionArray->length; i++) {
if (contents[i] != NULL)
dvmPointerSetAddEntry(*pThrows, contents[i]);
}
} else {
*pThrows = NULL;
}
result = true;
bail:
dvmReleaseTrackedAlloc((Object*) exceptionArray, NULL);
return result;
}
/*
* We need to compute the intersection of the arguments, i.e. remove
* anything from "throws" that isn't in the method's list of throws.
*
* If one class is a subclass of another, we want to keep just the subclass,
* moving toward the most-restrictive set.
*
* We assume these are all classes, and don't try to filter out interfaces.
*/
static void updateExceptionClassList(const Method* method, PointerSet* throws)
{
int setSize = dvmPointerSetGetCount(throws);
if (setSize == 0)
return;
ArrayObject* exceptionArray = dvmGetMethodThrows(method);
if (exceptionArray == NULL) {
/* nothing declared, so intersection is empty */
dvmPointerSetClear(throws);
return;
}
/* reduce list, nulling out redundant entries */
reduceExceptionClassList(exceptionArray);
size_t mixLen = dvmPointerSetGetCount(throws);
const ClassObject* mixSet[mixLen];
size_t declLen = exceptionArray->length;
const ClassObject** declSet = (const ClassObject**)(void*)exceptionArray->contents;
/* grab a local copy to work on */
for (size_t i = 0; i < mixLen; i++) {
mixSet[i] = (ClassObject*)dvmPointerSetGetEntry(throws, i);
}
for (size_t i = 0; i < mixLen; i++) {
size_t j;
for (j = 0; j < declLen; j++) {
if (declSet[j] == NULL)
continue;
if (mixSet[i] == declSet[j]) {
/* match, keep this one */
break;
} else if (dvmInstanceof(mixSet[i], declSet[j])) {
/* mix is a subclass of a declared throwable, keep it */
break;
} else if (dvmInstanceof(declSet[j], mixSet[i])) {
/* mix is a superclass, replace it */
mixSet[i] = declSet[j];
break;
}
}
if (j == declLen) {
/* no match, remove entry by nulling it out */
mixSet[i] = NULL;
}
}
/* copy results back out; this eliminates duplicates as we go */
dvmPointerSetClear(throws);
for (size_t i = 0; i < mixLen; i++) {
if (mixSet[i] != NULL)
dvmPointerSetAddEntry(throws, mixSet[i]);
}
dvmReleaseTrackedAlloc((Object*) exceptionArray, NULL);
}
/*
* Check to see if the return types are compatible.
*
* If the return type is primitive or void, it must match exactly.
*
* If not, the type in "subMethod" must be assignable to the type in
* "baseMethod".
*/
static bool returnTypesAreCompatible(Method* subMethod, Method* baseMethod)
{
const char* baseSig = dexProtoGetReturnType(&baseMethod->prototype);
const char* subSig = dexProtoGetReturnType(&subMethod->prototype);
ClassObject* baseClass;
ClassObject* subClass;
if (baseSig[1] == '\0' || subSig[1] == '\0') {
/* at least one is primitive type */
return (baseSig[0] == subSig[0] && baseSig[1] == subSig[1]);
}
baseClass = dvmFindClass(baseSig, baseMethod->clazz->classLoader);
subClass = dvmFindClass(subSig, subMethod->clazz->classLoader);
bool result = dvmInstanceof(subClass, baseClass);
return result;
}
/*
* Create a constructor for our Proxy class. The constructor takes one
* argument, a java.lang.reflect.InvocationHandler.
*/
static void createConstructor(ClassObject* clazz, Method* meth)
{
/*
* The constructor signatures (->prototype and ->shorty) need to
* be cloned from a method in a "real" DEX file. We declared the
* otherwise unused method Proxy.constructorPrototype() just for
* this purpose.
*/
meth->clazz = clazz;
meth->accessFlags = ACC_PUBLIC | ACC_NATIVE;
meth->name = "<init>";
meth->prototype =
gDvm.methJavaLangReflectProxy_constructorPrototype->prototype;
meth->shorty =
gDvm.methJavaLangReflectProxy_constructorPrototype->shorty;
// no pDexCode or pDexMethod
int argsSize = dvmComputeMethodArgsSize(meth) + 1;
meth->registersSize = meth->insSize = argsSize;
meth->nativeFunc = proxyConstructor;
}
/*
* Create a method in our Proxy class with the name and signature of
* the interface method it implements.
*/
static void createHandlerMethod(ClassObject* clazz, Method* dstMeth,
const Method* srcMeth)
{
dstMeth->clazz = clazz;
dstMeth->insns = (u2*) srcMeth;
dstMeth->accessFlags = ACC_PUBLIC | ACC_NATIVE;
dstMeth->name = srcMeth->name;
dstMeth->prototype = srcMeth->prototype;
dstMeth->shorty = srcMeth->shorty;
// no pDexCode or pDexMethod
int argsSize = dvmComputeMethodArgsSize(dstMeth) + 1;
dstMeth->registersSize = dstMeth->insSize = argsSize;
dstMeth->nativeFunc = proxyInvoker;
}
/*
* Return a new Object[] array with the contents of "args". We determine
* the number and types of values in "args" based on the method signature.
* Primitive types are boxed.
*
* Returns NULL if the method takes no arguments.
*
* The caller must call dvmReleaseTrackedAlloc() on the return value.
*
* On failure, returns with an appropriate exception raised.
*/
static ArrayObject* boxMethodArgs(const Method* method, const u4* args)
{
const char* desc = &method->shorty[1]; // [0] is the return type.
/* count args */
size_t argCount = dexProtoGetParameterCount(&method->prototype);
/* allocate storage */
ArrayObject* argArray = dvmAllocArrayByClass(gDvm.classJavaLangObjectArray,
argCount, ALLOC_DEFAULT);
if (argArray == NULL)
return NULL;
Object** argObjects = (Object**)(void*)argArray->contents;
/*
* Fill in the array.
*/
size_t srcIndex = 0;
size_t dstIndex = 0;
while (*desc != '\0') {
char descChar = *(desc++);
JValue value;
switch (descChar) {
case 'Z':
case 'C':
case 'F':
case 'B':
case 'S':
case 'I':
value.i = args[srcIndex++];
argObjects[dstIndex] = (Object*) dvmBoxPrimitive(value,
dvmFindPrimitiveClass(descChar));
/* argObjects is tracked, don't need to hold this too */
dvmReleaseTrackedAlloc(argObjects[dstIndex], NULL);
dstIndex++;
break;
case 'D':
case 'J':
value.j = dvmGetArgLong(args, srcIndex);
srcIndex += 2;
argObjects[dstIndex] = (Object*) dvmBoxPrimitive(value,
dvmFindPrimitiveClass(descChar));
dvmReleaseTrackedAlloc(argObjects[dstIndex], NULL);
dstIndex++;
break;
case '[':
case 'L':
argObjects[dstIndex++] = (Object*) args[srcIndex++];
break;
}
}
return argArray;
}
/*
* This is the constructor for a generated proxy object. All we need to
* do is stuff "handler" into "h".
*/
static void proxyConstructor(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
Object* obj = (Object*) args[0];
Object* handler = (Object*) args[1];
dvmSetFieldObject(obj, gDvm.offJavaLangReflectProxy_h, handler);
}
/*
* This is the common message body for proxy methods.
*
* The method we're calling looks like:
* public Object invoke(Object proxy, Method method, Object[] args)
*
* This means we have to create a Method object, box our arguments into
* a new Object[] array, make the call, and unbox the return value if
* necessary.
*/
static void proxyInvoker(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
Object* thisObj = (Object*) args[0];
Object* methodObj = NULL;
ArrayObject* argArray = NULL;
Object* handler;
Method* invoke;
ClassObject* returnType;
JValue invokeResult;
/*
* Retrieve handler object for this proxy instance. The field is
* defined in the superclass (Proxy).
*/
handler = dvmGetFieldObject(thisObj, gDvm.offJavaLangReflectProxy_h);
/*
* Find the invoke() method, looking in "this"s class. (Because we
* start here we don't have to convert it to a vtable index and then
* index into this' vtable.)
*/
invoke = dvmFindVirtualMethodHierByDescriptor(handler->clazz, "invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;");
if (invoke == NULL) {
LOGE("Unable to find invoke()");
dvmAbort();
}
ALOGV("invoke: %s.%s, this=%p, handler=%s",
method->clazz->descriptor, method->name,
thisObj, handler->clazz->descriptor);
/*
* Create a java.lang.reflect.Method object for this method.
*
* We don't want to use "method", because that's the concrete
* implementation in the proxy class. We want the abstract Method
* from the declaring interface. We have a pointer to it tucked
* away in the "insns" field.
*
* TODO: this could be cached for performance.
*/
methodObj = dvmCreateReflectMethodObject((Method*) method->insns);
if (methodObj == NULL) {
assert(dvmCheckException(self));
goto bail;
}
/*
* Determine the return type from the signature.
*
* TODO: this could be cached for performance.
*/
returnType = dvmGetBoxedReturnType(method);
if (returnType == NULL) {
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
LOGE("Could not determine return type for '%s'", desc);
free(desc);
assert(dvmCheckException(self));
goto bail;
}
ALOGV(" return type will be %s", returnType->descriptor);
/*
* Convert "args" array into Object[] array, using the method
* signature to determine types. If the method takes no arguments,
* we must pass null.
*/
argArray = boxMethodArgs(method, args+1);
if (dvmCheckException(self))
goto bail;
/*
* Call h.invoke(proxy, method, args).
*
* We don't need to repackage exceptions, so if one has been thrown
* just jump to the end.
*
* We're not adding invokeResult.l to the tracked allocation list, but
* since we're just unboxing it or returning it to interpreted code
* that shouldn't be a problem.
*/
dvmCallMethod(self, invoke, handler, &invokeResult,
thisObj, methodObj, argArray);
if (dvmCheckException(self)) {
Object* excep = dvmGetException(self);
if (mustWrapException(method, excep)) {
/* wrap with UndeclaredThrowableException */
dvmWrapException("Ljava/lang/reflect/UndeclaredThrowableException;");
}
goto bail;
}
/*
* Unbox the return value. If it's the wrong type, throw a
* ClassCastException. If it's a null pointer and we need a
* primitive type, throw a NullPointerException.
*/
if (returnType->primitiveType == PRIM_VOID) {
LOGVV("+++ ignoring return to void");
} else if (invokeResult.l == NULL) {
if (dvmIsPrimitiveClass(returnType)) {
dvmThrowNullPointerException(
"null result when primitive expected");
goto bail;
}
pResult->l = NULL;
} else {
if (!dvmUnboxPrimitive((Object*)invokeResult.l, returnType, pResult)) {
dvmThrowClassCastException(((Object*)invokeResult.l)->clazz,
returnType);
goto bail;
}
}
bail:
dvmReleaseTrackedAlloc(methodObj, self);
dvmReleaseTrackedAlloc((Object*)argArray, self);
}
/*
* Determine if it's okay for this method to throw this exception. If
* an unchecked exception was thrown we immediately return false. If
* checked, we have to ensure that this method and all of its duplicates
* have declared that they throw it.
*/
static bool mustWrapException(const Method* method, const Object* throwable)
{
if (!dvmIsCheckedException(throwable))
return false;
const StaticField* sfield = &method->clazz->sfields[kThrowsField];
const ArrayObject* throws = (ArrayObject*) dvmGetStaticFieldObject(sfield);
int methodIndex = method - method->clazz->virtualMethods;
assert(methodIndex >= 0 && methodIndex < method->clazz->virtualMethodCount);
const Object** contents = (const Object**)(void*)throws->contents;
const ArrayObject* methodThrows = (ArrayObject*) contents[methodIndex];
if (methodThrows == NULL) {
/* no throws declared, must wrap all checked exceptions */
return true;
}
size_t throwCount = methodThrows->length;
const ClassObject** classes =
(const ClassObject**)(void*)methodThrows->contents;
for (size_t i = 0; i < throwCount; i++) {
if (dvmInstanceof(throwable->clazz, classes[i])) {
/* this was declared, okay to throw */
return false;
}
}
/* no match in declared throws */
return true;
}
|