blob: cc461e7e2de3da443e80376d30963db311c28742 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Class loading, including bootstrap class loader, linking, and
19 * initialization.
20 */
21
22#define LOG_CLASS_LOADING 0
23
24#include "Dalvik.h"
25#include "libdex/DexClass.h"
26
27#include <stdlib.h>
28#include <stddef.h>
29#include <sys/stat.h>
30
31#if LOG_CLASS_LOADING
32#include <unistd.h>
33#include <pthread.h>
34#include <cutils/process_name.h>
35#include <sys/types.h>
36#endif
37
38/*
39Notes on Linking and Verification
40
41The basic way to retrieve a class is to load it, make sure its superclass
42and interfaces are available, prepare its fields, and return it. This gets
43a little more complicated when multiple threads can be trying to retrieve
44the class simultaneously, requiring that we use the class object's monitor
45to keep things orderly.
46
47The linking (preparing, resolving) of a class can cause us to recursively
48load superclasses and interfaces. Barring circular references (e.g. two
49classes that are superclasses of each other), this will complete without
50the loader attempting to access the partially-linked class.
51
52With verification, the situation is different. If we try to verify
53every class as we load it, we quickly run into trouble. Even the lowly
54java.lang.Object requires CloneNotSupportedException; follow the list
55of referenced classes and you can head down quite a trail. The trail
56eventually leads back to Object, which is officially not fully-formed yet.
57
58The VM spec (specifically, v2 5.4.1) notes that classes pulled in during
59verification do not need to be prepared or verified. This means that we
60are allowed to have loaded but unverified classes. It further notes that
61the class must be verified before it is initialized, which allows us to
62defer verification for all classes until class init. You can't execute
63code or access fields in an uninitialized class, so this is safe.
64
65It also allows a more peaceful coexistence between verified and
66unverifiable code. If class A refers to B, and B has a method that
67refers to a bogus class C, should we allow class A to be verified?
68If A only exercises parts of B that don't use class C, then there is
69nothing wrong with running code in A. We can fully verify both A and B,
70and allow execution to continue until B causes initialization of C. The
71VerifyError is thrown close to the point of use.
72
73This gets a little weird with java.lang.Class, which is the only class
74that can be instantiated before it is initialized. We have to force
75initialization right after the class is created, because by definition we
76have instances of it on the heap, and somebody might get a class object and
77start making virtual calls on it. We can end up going recursive during
78verification of java.lang.Class, but we avoid that by checking to see if
79verification is already in progress before we try to initialize it.
80*/
81
82/*
83Notes on class loaders and interaction with optimization / verification
84
85In what follows, "pre-verification" and "optimization" are the steps
86performed by the dexopt command, which attempts to verify and optimize
87classes as part of unpacking jar files and storing the DEX data in the
88dalvik-cache directory. These steps are performed by loading the DEX
89files directly, without any assistance from ClassLoader instances.
90
91When we pre-verify and optimize a class in a DEX file, we make some
92assumptions about where the class loader will go to look for classes.
93If we can't guarantee those assumptions, e.g. because a class ("AppClass")
94references something not defined in the bootstrap jars or the AppClass jar,
95we can't pre-verify or optimize the class.
96
97The VM doesn't define the behavior of user-defined class loaders.
98For example, suppose application class AppClass, loaded by UserLoader,
99has a method that creates a java.lang.String. The first time
100AppClass.stringyMethod tries to do something with java.lang.String, it
101asks UserLoader to find it. UserLoader is expected to defer to its parent
102loader, but isn't required to. UserLoader might provide a replacement
103for String.
104
105We can run into trouble if we pre-verify AppClass with the assumption that
106java.lang.String will come from core.jar, and don't verify this assumption
107at runtime. There are two places that an alternate implementation of
108java.lang.String can come from: the AppClass jar, or from some other jar
109that UserLoader knows about. (Someday UserLoader will be able to generate
110some bytecode and call DefineClass, but not yet.)
111
112To handle the first situation, the pre-verifier will explicitly check for
113conflicts between the class being optimized/verified and the bootstrap
114classes. If an app jar contains a class that has the same package and
115class name as a class in a bootstrap jar, the verification resolver refuses
116to find either, which will block pre-verification and optimization on
117classes that reference ambiguity. The VM will postpone verification of
118the app class until first load.
119
120For the second situation, we need to ensure that all references from a
121pre-verified class are satisified by the class' jar or earlier bootstrap
122jars. In concrete terms: when resolving a reference to NewClass,
123which was caused by a reference in class AppClass, we check to see if
124AppClass was pre-verified. If so, we require that NewClass comes out
125of either the AppClass jar or one of the jars in the bootstrap path.
126(We may not control the class loaders, but we do manage the DEX files.
127We can verify that it's either (loader==null && dexFile==a_boot_dex)
128or (loader==UserLoader && dexFile==AppClass.dexFile). Classes from
129DefineClass can't be pre-verified, so this doesn't apply.)
130
131This should ensure that you can't "fake out" the pre-verifier by creating
132a user-defined class loader that replaces system classes. It should
133also ensure that you can write such a loader and have it work in the
134expected fashion; all you lose is some performance due to "just-in-time
135verification" and the lack of DEX optimizations.
136
137There is a "back door" of sorts in the class resolution check, due to
138the fact that the "class ref" entries are shared between the bytecode
139and meta-data references (e.g. annotations and exception handler lists).
140The class references in annotations have no bearing on class verification,
141so when a class does an annotation query that causes a class reference
142index to be resolved, we don't want to fail just because the calling
143class was pre-verified and the resolved class is in some random DEX file.
144The successful resolution adds the class to the "resolved classes" table,
145so when optimized bytecode references it we don't repeat the resolve-time
146check. We can avoid this by not updating the "resolved classes" table
147when the class reference doesn't come out of something that has been
148checked by the verifier, but that has a nonzero performance impact.
149Since the ultimate goal of this test is to catch an unusual situation
150(user-defined class loaders redefining core classes), the added caution
151may not be worth the performance hit.
152*/
153
Andy McFadden7ccb7a62009-05-15 13:44:29 -0700154/*
155 * Class serial numbers start at this value. We use a nonzero initial
156 * value so they stand out in binary dumps (e.g. hprof output).
157 */
Barry Hayes2c987472009-04-06 10:03:48 -0700158#define INITIAL_CLASS_SERIAL_NUMBER 0x50000000
Andy McFadden7ccb7a62009-05-15 13:44:29 -0700159
160/*
161 * Constant used to size an auxillary class object data structure.
162 * For optimum memory use this should be equal to or slightly larger than
163 * the number of classes loaded when the zygote finishes initializing.
164 */
165#define ZYGOTE_CLASS_CUTOFF 2304
Barry Hayes2c987472009-04-06 10:03:48 -0700166
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800167static ClassPathEntry* processClassPath(const char* pathStr, bool isBootstrap);
168static void freeCpeArray(ClassPathEntry* cpe);
169
170static ClassObject* findClassFromLoaderNoInit(
171 const char* descriptor, Object* loader);
172static ClassObject* findClassNoInit(const char* descriptor, Object* loader,\
173 DvmDex* pDvmDex);
174static ClassObject* loadClassFromDex(DvmDex* pDvmDex,
175 const DexClassDef* pClassDef, Object* loader);
176static void loadMethodFromDex(ClassObject* clazz, const DexMethod* pDexMethod,\
177 Method* meth);
178static int computeJniArgInfo(const DexProto* proto);
179static void loadSFieldFromDex(ClassObject* clazz,
180 const DexField* pDexSField, StaticField* sfield);
181static void loadIFieldFromDex(ClassObject* clazz,
182 const DexField* pDexIField, InstField* field);
Barry Hayes6daaac12009-07-08 10:01:56 -0700183static bool precacheReferenceOffsets(ClassObject* clazz);
184static void computeRefOffsets(ClassObject* clazz);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800185static void freeMethodInnards(Method* meth);
186static bool createVtable(ClassObject* clazz);
187static bool createIftable(ClassObject* clazz);
188static bool insertMethodStubs(ClassObject* clazz);
189static bool computeFieldOffsets(ClassObject* clazz);
190static void throwEarlierClassFailure(ClassObject* clazz);
191
192#if LOG_CLASS_LOADING
193/*
194 * Logs information about a class loading with given timestamp.
195 *
196 * TODO: In the case where we fail in dvmLinkClass() and log the class as closing (type='<'),
197 * it would probably be better to use a new type code to indicate the failure. This change would
198 * require a matching change in the parser and analysis code in frameworks/base/tools/preload.
199 */
200static void logClassLoadWithTime(char type, ClassObject* clazz, u8 time) {
201 pid_t ppid = getppid();
202 pid_t pid = getpid();
203 unsigned int tid = (unsigned int) pthread_self();
204
205 LOG(LOG_INFO, "PRELOAD", "%c%d:%d:%d:%s:%d:%s:%lld\n", type, ppid, pid, tid,
206 get_process_name(), (int) clazz->classLoader, clazz->descriptor,
207 time);
208}
209
210/*
211 * Logs information about a class loading.
212 */
213static void logClassLoad(char type, ClassObject* clazz) {
214 logClassLoadWithTime(type, clazz, dvmGetThreadCpuTimeNsec());
215}
216#endif
217
218/*
219 * Some LinearAlloc unit tests.
220 */
221static void linearAllocTests()
222{
223 char* fiddle;
224 int try = 1;
225
226 switch (try) {
227 case 0:
228 fiddle = dvmLinearAlloc(NULL, 3200-28);
229 dvmLinearReadOnly(NULL, fiddle);
230 break;
231 case 1:
232 fiddle = dvmLinearAlloc(NULL, 3200-24);
233 dvmLinearReadOnly(NULL, fiddle);
234 break;
235 case 2:
236 fiddle = dvmLinearAlloc(NULL, 3200-20);
237 dvmLinearReadOnly(NULL, fiddle);
238 break;
239 case 3:
240 fiddle = dvmLinearAlloc(NULL, 3200-16);
241 dvmLinearReadOnly(NULL, fiddle);
242 break;
243 case 4:
244 fiddle = dvmLinearAlloc(NULL, 3200-12);
245 dvmLinearReadOnly(NULL, fiddle);
246 break;
247 }
248 fiddle = dvmLinearAlloc(NULL, 896);
249 dvmLinearReadOnly(NULL, fiddle);
250 fiddle = dvmLinearAlloc(NULL, 20); // watch addr of this alloc
251 dvmLinearReadOnly(NULL, fiddle);
252
253 fiddle = dvmLinearAlloc(NULL, 1);
254 fiddle[0] = 'q';
255 dvmLinearReadOnly(NULL, fiddle);
256 fiddle = dvmLinearAlloc(NULL, 4096);
257 fiddle[0] = 'x';
258 fiddle[4095] = 'y';
259 dvmLinearReadOnly(NULL, fiddle);
260 dvmLinearFree(NULL, fiddle);
261 fiddle = dvmLinearAlloc(NULL, 0);
262 dvmLinearReadOnly(NULL, fiddle);
263 fiddle = dvmLinearRealloc(NULL, fiddle, 12);
264 fiddle[11] = 'z';
265 dvmLinearReadOnly(NULL, fiddle);
266 fiddle = dvmLinearRealloc(NULL, fiddle, 5);
267 dvmLinearReadOnly(NULL, fiddle);
268 fiddle = dvmLinearAlloc(NULL, 17001);
269 fiddle[0] = 'x';
270 fiddle[17000] = 'y';
271 dvmLinearReadOnly(NULL, fiddle);
272
273 char* str = dvmLinearStrdup(NULL, "This is a test!");
274 LOGI("GOT: '%s'\n", str);
275
Andy McFadden7605a842009-07-27 14:44:22 -0700276 /* try to check the bounds; allocator may round allocation size up */
277 fiddle = dvmLinearAlloc(NULL, 12);
278 LOGI("Should be 1: %d\n", dvmLinearAllocContains(fiddle, 12));
279 LOGI("Should be 0: %d\n", dvmLinearAllocContains(fiddle, 13));
280 LOGI("Should be 0: %d\n", dvmLinearAllocContains(fiddle - 128*1024, 1));
281
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800282 dvmLinearAllocDump(NULL);
283 dvmLinearFree(NULL, str);
284}
285
286/*
287 * Initialize the bootstrap class loader.
288 *
289 * Call this after the bootclasspath string has been finalized.
290 */
291bool dvmClassStartup(void)
292{
293 ClassObject* unlinkedClass;
294
295 /* make this a requirement -- don't currently support dirs in path */
296 if (strcmp(gDvm.bootClassPathStr, ".") == 0) {
297 LOGE("ERROR: must specify non-'.' bootclasspath\n");
298 return false;
299 }
300
301 gDvm.loadedClasses =
302 dvmHashTableCreate(256, (HashFreeFunc) dvmFreeClassInnards);
303
304 gDvm.pBootLoaderAlloc = dvmLinearAllocCreate(NULL);
305 if (gDvm.pBootLoaderAlloc == NULL)
306 return false;
307
308 if (false) {
309 linearAllocTests();
310 exit(0);
311 }
312
313 /*
314 * Class serial number. We start with a high value to make it distinct
315 * in binary dumps (e.g. hprof).
316 */
Barry Hayes2c987472009-04-06 10:03:48 -0700317 gDvm.classSerialNumber = INITIAL_CLASS_SERIAL_NUMBER;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800318
Barry Hayes2c987472009-04-06 10:03:48 -0700319 /* Set up the table we'll use for tracking initiating loaders for
320 * early classes.
321 * If it's NULL, we just fall back to the InitiatingLoaderList in the
322 * ClassObject, so it's not fatal to fail this allocation.
323 */
324 gDvm.initiatingLoaderList =
325 calloc(ZYGOTE_CLASS_CUTOFF, sizeof(InitiatingLoaderList));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800326
327 /* This placeholder class is used while a ClassObject is
328 * loading/linking so those not in the know can still say
329 * "obj->clazz->...".
330 */
331 unlinkedClass = &gDvm.unlinkedJavaLangClassObject;
332
333 memset(unlinkedClass, 0, sizeof(*unlinkedClass));
334
335 /* Set obj->clazz to NULL so anyone who gets too interested
336 * in the fake class will crash.
337 */
338 DVM_OBJECT_INIT(&unlinkedClass->obj, NULL);
339 unlinkedClass->descriptor = "!unlinkedClass";
340 dvmSetClassSerialNumber(unlinkedClass);
341
342 gDvm.unlinkedJavaLangClass = unlinkedClass;
343
344 /*
345 * Process the bootstrap class path. This means opening the specified
346 * DEX or Jar files and possibly running them through the optimizer.
347 */
348 assert(gDvm.bootClassPath == NULL);
349 processClassPath(gDvm.bootClassPathStr, true);
350
351 if (gDvm.bootClassPath == NULL)
352 return false;
353
354 return true;
355}
356
357/*
358 * Clean up.
359 */
360void dvmClassShutdown(void)
361{
362 int i;
363
364 /* discard all system-loaded classes */
365 dvmHashTableFree(gDvm.loadedClasses);
366 gDvm.loadedClasses = NULL;
367
368 /* discard primitive classes created for arrays */
369 for (i = 0; i < PRIM_MAX; i++)
370 dvmFreeClassInnards(gDvm.primitiveClass[i]);
371
372 /* this closes DEX files, JAR files, etc. */
373 freeCpeArray(gDvm.bootClassPath);
374 gDvm.bootClassPath = NULL;
375
376 dvmLinearAllocDestroy(NULL);
Barry Hayes2c987472009-04-06 10:03:48 -0700377
378 free(gDvm.initiatingLoaderList);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800379}
380
381
382/*
383 * ===========================================================================
384 * Bootstrap class loader
385 * ===========================================================================
386 */
387
388/*
389 * Dump the contents of a ClassPathEntry array.
390 */
391static void dumpClassPath(const ClassPathEntry* cpe)
392{
393 int idx = 0;
394
395 while (cpe->kind != kCpeLastEntry) {
396 const char* kindStr;
397
398 switch (cpe->kind) {
399 case kCpeDir: kindStr = "dir"; break;
400 case kCpeJar: kindStr = "jar"; break;
401 case kCpeDex: kindStr = "dex"; break;
402 default: kindStr = "???"; break;
403 }
404
405 LOGI(" %2d: type=%s %s %p\n", idx, kindStr, cpe->fileName, cpe->ptr);
406 if (CALC_CACHE_STATS && cpe->kind == kCpeJar) {
407 JarFile* pJarFile = (JarFile*) cpe->ptr;
408 DvmDex* pDvmDex = dvmGetJarFileDex(pJarFile);
409 dvmDumpAtomicCacheStats(pDvmDex->pInterfaceCache);
410 }
411
412 cpe++;
413 idx++;
414 }
415}
416
417/*
418 * Dump the contents of the bootstrap class path.
419 */
420void dvmDumpBootClassPath(void)
421{
422 dumpClassPath(gDvm.bootClassPath);
423}
424
425/*
426 * Returns "true" if the class path contains the specified path.
427 */
428bool dvmClassPathContains(const ClassPathEntry* cpe, const char* path)
429{
430 while (cpe->kind != kCpeLastEntry) {
431 if (strcmp(cpe->fileName, path) == 0)
432 return true;
433
434 cpe++;
435 }
436 return false;
437}
438
439/*
440 * Free an array of ClassPathEntry structs.
441 *
442 * We release the contents of each entry, then free the array itself.
443 */
444static void freeCpeArray(ClassPathEntry* cpe)
445{
446 ClassPathEntry* cpeStart = cpe;
447
448 if (cpe == NULL)
449 return;
450
451 while (cpe->kind != kCpeLastEntry) {
452 switch (cpe->kind) {
453 case kCpeJar:
454 /* free JarFile */
455 dvmJarFileFree((JarFile*) cpe->ptr);
456 break;
457 case kCpeDex:
458 /* free RawDexFile */
459 dvmRawDexFileFree((RawDexFile*) cpe->ptr);
460 break;
461 default:
462 /* e.g. kCpeDir */
463 assert(cpe->ptr == NULL);
464 break;
465 }
466
467 free(cpe->fileName);
468 cpe++;
469 }
470
471 free(cpeStart);
472}
473
474/*
475 * Prepare a ClassPathEntry struct, which at this point only has a valid
476 * filename. We need to figure out what kind of file it is, and for
477 * everything other than directories we need to open it up and see
478 * what's inside.
479 */
480static bool prepareCpe(ClassPathEntry* cpe, bool isBootstrap)
481{
482 JarFile* pJarFile = NULL;
483 RawDexFile* pRawDexFile = NULL;
484 struct stat sb;
485 int cc;
486
487 cc = stat(cpe->fileName, &sb);
488 if (cc < 0) {
Andy McFadden1b589582009-05-22 12:27:20 -0700489 LOGD("Unable to stat classpath element '%s'\n", cpe->fileName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800490 return false;
491 }
492 if (S_ISDIR(sb.st_mode)) {
493 /*
494 * The directory will usually have .class files in subdirectories,
495 * which may be a few levels down. Doing a recursive scan and
496 * caching the results would help us avoid hitting the filesystem
497 * on misses. Whether or not this is of measureable benefit
498 * depends on a number of factors, but most likely it is not
499 * worth the effort (especially since most of our stuff will be
500 * in DEX or JAR).
501 */
502 cpe->kind = kCpeDir;
503 assert(cpe->ptr == NULL);
504 return true;
505 }
506
507 if (dvmJarFileOpen(cpe->fileName, NULL, &pJarFile, isBootstrap) == 0) {
508 cpe->kind = kCpeJar;
509 cpe->ptr = pJarFile;
510 return true;
511 }
512
513 // TODO: do we still want to support "raw" DEX files in the classpath?
514 if (dvmRawDexFileOpen(cpe->fileName, NULL, &pRawDexFile, isBootstrap) == 0)
515 {
516 cpe->kind = kCpeDex;
517 cpe->ptr = pRawDexFile;
518 return true;
519 }
520
Andy McFadden1b589582009-05-22 12:27:20 -0700521 LOGD("Unable to process classpath element '%s'\n", cpe->fileName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800522 return false;
523}
524
525/*
526 * Convert a colon-separated list of directories, Zip files, and DEX files
527 * into an array of ClassPathEntry structs.
528 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800529 * During normal startup we fail if there are no entries, because we won't
530 * get very far without the basic language support classes, but if we're
531 * optimizing a DEX file we allow it.
Andy McFadden1b589582009-05-22 12:27:20 -0700532 *
533 * If entries are added or removed from the bootstrap class path, the
534 * dependencies in the DEX files will break, and everything except the
535 * very first entry will need to be regenerated.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800536 */
537static ClassPathEntry* processClassPath(const char* pathStr, bool isBootstrap)
538{
539 ClassPathEntry* cpe = NULL;
540 char* mangle;
541 char* cp;
542 const char* end;
543 int idx, count;
544
545 assert(pathStr != NULL);
546
547 mangle = strdup(pathStr);
548
549 /*
550 * Run through and essentially strtok() the string. Get a count of
551 * the #of elements while we're at it.
552 *
553 * If the path was constructed strangely (e.g. ":foo::bar:") this will
554 * over-allocate, which isn't ideal but is mostly harmless.
555 */
556 count = 1;
557 for (cp = mangle; *cp != '\0'; cp++) {
558 if (*cp == ':') { /* separates two entries */
559 count++;
560 *cp = '\0';
561 }
562 }
563 end = cp;
564
565 /*
566 * Allocate storage. We over-alloc by one so we can set an "end" marker.
567 */
568 cpe = (ClassPathEntry*) calloc(count+1, sizeof(ClassPathEntry));
569
570 /*
571 * Set the global pointer so the DEX file dependency stuff can find it.
572 */
573 gDvm.bootClassPath = cpe;
574
575 /*
576 * Go through a second time, pulling stuff out.
577 */
578 cp = mangle;
579 idx = 0;
580 while (cp < end) {
581 if (*cp == '\0') {
582 /* leading, trailing, or doubled ':'; ignore it */
583 } else {
584 ClassPathEntry tmp;
585 tmp.kind = kCpeUnknown;
586 tmp.fileName = strdup(cp);
587 tmp.ptr = NULL;
588
589 /* drop an end marker here so DEX loader can walk unfinished list */
590 cpe[idx].kind = kCpeLastEntry;
591 cpe[idx].fileName = NULL;
592 cpe[idx].ptr = NULL;
593
594 if (!prepareCpe(&tmp, isBootstrap)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800595 /* drop from list and continue on */
596 free(tmp.fileName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800597 } else {
598 /* copy over, pointers and all */
599 if (tmp.fileName[0] != '/')
600 LOGW("Non-absolute bootclasspath entry '%s'\n",
601 tmp.fileName);
602 cpe[idx] = tmp;
603 idx++;
604 }
605 }
606
607 cp += strlen(cp) +1;
608 }
609 assert(idx <= count);
610 if (idx == 0 && !gDvm.optimizing) {
611 LOGE("ERROR: no valid entries found in bootclasspath '%s'\n", pathStr);
612 free(cpe);
613 cpe = NULL;
614 goto bail;
615 }
616
617 LOGVV(" (filled %d of %d slots)\n", idx, count);
618
619 /* put end marker in over-alloc slot */
620 cpe[idx].kind = kCpeLastEntry;
621 cpe[idx].fileName = NULL;
622 cpe[idx].ptr = NULL;
623
624 //dumpClassPath(cpe);
625
626bail:
627 free(mangle);
628 gDvm.bootClassPath = cpe;
629 return cpe;
630}
631
632/*
633 * Search the DEX files we loaded from the bootstrap class path for a DEX
634 * file that has the class with the matching descriptor.
635 *
636 * Returns the matching DEX file and DexClassDef entry if found, otherwise
637 * returns NULL.
638 */
639static DvmDex* searchBootPathForClass(const char* descriptor,
640 const DexClassDef** ppClassDef)
641{
642 const ClassPathEntry* cpe = gDvm.bootClassPath;
643 const DexClassDef* pFoundDef = NULL;
644 DvmDex* pFoundFile = NULL;
645
646 LOGVV("+++ class '%s' not yet loaded, scanning bootclasspath...\n",
647 descriptor);
648
649 while (cpe->kind != kCpeLastEntry) {
650 //LOGV("+++ checking '%s' (%d)\n", cpe->fileName, cpe->kind);
651
652 switch (cpe->kind) {
653 case kCpeDir:
654 LOGW("Directory entries ('%s') not supported in bootclasspath\n",
655 cpe->fileName);
656 break;
657 case kCpeJar:
658 {
659 JarFile* pJarFile = (JarFile*) cpe->ptr;
660 const DexClassDef* pClassDef;
661 DvmDex* pDvmDex;
662
663 pDvmDex = dvmGetJarFileDex(pJarFile);
664 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
665 if (pClassDef != NULL) {
666 /* found */
667 pFoundDef = pClassDef;
668 pFoundFile = pDvmDex;
669 goto found;
670 }
671 }
672 break;
673 case kCpeDex:
674 {
675 RawDexFile* pRawDexFile = (RawDexFile*) cpe->ptr;
676 const DexClassDef* pClassDef;
677 DvmDex* pDvmDex;
678
679 pDvmDex = dvmGetRawDexFileDex(pRawDexFile);
680 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
681 if (pClassDef != NULL) {
682 /* found */
683 pFoundDef = pClassDef;
684 pFoundFile = pDvmDex;
685 goto found;
686 }
687 }
688 break;
689 default:
690 LOGE("Unknown kind %d\n", cpe->kind);
691 assert(false);
692 break;
693 }
694
695 cpe++;
696 }
697
698 /*
699 * Special handling during verification + optimization.
700 *
701 * The DEX optimizer needs to load classes from the DEX file it's working
702 * on. Rather than trying to insert it into the bootstrap class path
703 * or synthesizing a class loader to manage it, we just make it available
704 * here. It logically comes after all existing entries in the bootstrap
705 * class path.
706 */
707 if (gDvm.bootClassPathOptExtra != NULL) {
708 const DexClassDef* pClassDef;
709
710 pClassDef =
711 dexFindClass(gDvm.bootClassPathOptExtra->pDexFile, descriptor);
712 if (pClassDef != NULL) {
713 /* found */
714 pFoundDef = pClassDef;
715 pFoundFile = gDvm.bootClassPathOptExtra;
716 }
717 }
718
719found:
720 *ppClassDef = pFoundDef;
721 return pFoundFile;
722}
723
724/*
725 * Set the "extra" DEX, which becomes a de facto member of the bootstrap
726 * class set.
727 */
728void dvmSetBootPathExtraDex(DvmDex* pDvmDex)
729{
730 gDvm.bootClassPathOptExtra = pDvmDex;
731}
732
733
734/*
735 * Return the #of entries in the bootstrap class path.
736 *
737 * (Used for ClassLoader.getResources().)
738 */
739int dvmGetBootPathSize(void)
740{
741 const ClassPathEntry* cpe = gDvm.bootClassPath;
742
743 while (cpe->kind != kCpeLastEntry)
744 cpe++;
745
746 return cpe - gDvm.bootClassPath;
747}
748
749/*
750 * Find a resource with the specified name in entry N of the boot class path.
751 *
752 * We return a newly-allocated String of one of these forms:
753 * file://path/name
754 * jar:file://path!/name
755 * Where "path" is the bootstrap class path entry and "name" is the string
756 * passed into this method. "path" needs to be an absolute path (starting
757 * with '/'); if it's not we'd need to "absolutify" it as part of forming
758 * the URL string.
759 */
760StringObject* dvmGetBootPathResource(const char* name, int idx)
761{
762 const int kUrlOverhead = 13; // worst case for Jar URL
763 const ClassPathEntry* cpe = gDvm.bootClassPath;
764 StringObject* urlObj = NULL;
765
766 LOGV("+++ searching for resource '%s' in %d(%s)\n",
767 name, idx, cpe[idx].fileName);
768
769 /* we could use direct array index, but I don't entirely trust "idx" */
770 while (idx-- && cpe->kind != kCpeLastEntry)
771 cpe++;
772 if (cpe->kind == kCpeLastEntry) {
773 assert(false);
774 return NULL;
775 }
776
777 char urlBuf[strlen(name) + strlen(cpe->fileName) + kUrlOverhead +1];
778
779 switch (cpe->kind) {
780 case kCpeDir:
781 sprintf(urlBuf, "file://%s/%s", cpe->fileName, name);
782 if (access(urlBuf+7, F_OK) != 0)
783 goto bail;
784 break;
785 case kCpeJar:
786 {
787 JarFile* pJarFile = (JarFile*) cpe->ptr;
788 if (dexZipFindEntry(&pJarFile->archive, name) == NULL)
789 goto bail;
790 sprintf(urlBuf, "jar:file://%s!/%s", cpe->fileName, name);
791 }
792 break;
793 case kCpeDex:
794 LOGV("No resources in DEX files\n");
795 goto bail;
796 default:
797 assert(false);
798 goto bail;
799 }
800
801 LOGV("+++ using URL='%s'\n", urlBuf);
802 urlObj = dvmCreateStringFromCstr(urlBuf, ALLOC_DEFAULT);
803
804bail:
805 return urlObj;
806}
807
808
809/*
810 * ===========================================================================
811 * Class list management
812 * ===========================================================================
813 */
814
815/* search for these criteria in the Class hash table */
816typedef struct ClassMatchCriteria {
817 const char* descriptor;
818 Object* loader;
819} ClassMatchCriteria;
820
821#define kInitLoaderInc 4 /* must be power of 2 */
822
Barry Hayes2c987472009-04-06 10:03:48 -0700823static InitiatingLoaderList *dvmGetInitiatingLoaderList(ClassObject* clazz)
824{
825 assert(clazz->serialNumber > INITIAL_CLASS_SERIAL_NUMBER);
826 int classIndex = clazz->serialNumber-INITIAL_CLASS_SERIAL_NUMBER;
827 if (gDvm.initiatingLoaderList != NULL &&
828 classIndex < ZYGOTE_CLASS_CUTOFF) {
829 return &(gDvm.initiatingLoaderList[classIndex]);
830 } else {
831 return &(clazz->initiatingLoaderList);
832 }
833}
834
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800835/*
836 * Determine if "loader" appears in clazz' initiating loader list.
837 *
838 * The class hash table lock must be held when calling here, since
839 * it's also used when updating a class' initiating loader list.
840 *
841 * TODO: switch to some sort of lock-free data structure so we don't have
842 * to grab the lock to do a lookup. Among other things, this would improve
843 * the speed of compareDescriptorClasses().
844 */
845bool dvmLoaderInInitiatingList(const ClassObject* clazz, const Object* loader)
846{
847 /*
848 * The bootstrap class loader can't be just an initiating loader for
849 * anything (it's always the defining loader if the class is visible
850 * to it). We don't put defining loaders in the initiating list.
851 */
852 if (loader == NULL)
853 return false;
854
855 /*
856 * Scan the list for a match. The list is expected to be short.
857 */
Barry Hayes2c987472009-04-06 10:03:48 -0700858 /* Cast to remove the const from clazz, but use const loaderList */
859 ClassObject* nonConstClazz = (ClassObject*) clazz;
860 const InitiatingLoaderList *loaderList =
861 dvmGetInitiatingLoaderList(nonConstClazz);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800862 int i;
Barry Hayes2c987472009-04-06 10:03:48 -0700863 for (i = loaderList->initiatingLoaderCount-1; i >= 0; --i) {
864 if (loaderList->initiatingLoaders[i] == loader) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800865 //LOGI("+++ found initiating match %p in %s\n",
866 // loader, clazz->descriptor);
867 return true;
868 }
869 }
870 return false;
871}
872
873/*
874 * Add "loader" to clazz's initiating loader set, unless it's the defining
875 * class loader.
876 *
877 * In the common case this will be a short list, so we don't need to do
878 * anything too fancy here.
879 *
880 * This locks gDvm.loadedClasses for synchronization, so don't hold it
881 * when calling here.
882 */
883void dvmAddInitiatingLoader(ClassObject* clazz, Object* loader)
884{
885 if (loader != clazz->classLoader) {
886 assert(loader != NULL);
887
888 LOGVV("Adding %p to '%s' init list\n", loader, clazz->descriptor);
889 dvmHashTableLock(gDvm.loadedClasses);
890
891 /*
892 * Make sure nobody snuck in. The penalty for adding twice is
893 * pretty minor, and probably outweighs the O(n^2) hit for
894 * checking before every add, so we may not want to do this.
895 */
Barry Hayes2c987472009-04-06 10:03:48 -0700896 //if (dvmLoaderInInitiatingList(clazz, loader)) {
897 // LOGW("WOW: simultaneous add of initiating class loader\n");
898 // goto bail_unlock;
899 //}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800900
901 /*
902 * The list never shrinks, so we just keep a count of the
903 * number of elements in it, and reallocate the buffer when
904 * we run off the end.
905 *
906 * The pointer is initially NULL, so we *do* want to call realloc
907 * when count==0.
908 */
Barry Hayes2c987472009-04-06 10:03:48 -0700909 InitiatingLoaderList *loaderList = dvmGetInitiatingLoaderList(clazz);
910 if ((loaderList->initiatingLoaderCount & (kInitLoaderInc-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800911 Object** newList;
912
Barry Hayes2c987472009-04-06 10:03:48 -0700913 newList = (Object**) realloc(loaderList->initiatingLoaders,
914 (loaderList->initiatingLoaderCount + kInitLoaderInc)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800915 * sizeof(Object*));
916 if (newList == NULL) {
917 /* this is mainly a cache, so it's not the EotW */
918 assert(false);
919 goto bail_unlock;
920 }
Barry Hayes2c987472009-04-06 10:03:48 -0700921 loaderList->initiatingLoaders = newList;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800922
923 //LOGI("Expanded init list to %d (%s)\n",
Barry Hayes2c987472009-04-06 10:03:48 -0700924 // loaderList->initiatingLoaderCount+kInitLoaderInc,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800925 // clazz->descriptor);
926 }
Barry Hayes2c987472009-04-06 10:03:48 -0700927 loaderList->initiatingLoaders[loaderList->initiatingLoaderCount++] =
928 loader;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800929
930bail_unlock:
931 dvmHashTableUnlock(gDvm.loadedClasses);
932 }
933}
934
935/*
936 * (This is a dvmHashTableLookup callback.)
937 *
938 * Entries in the class hash table are stored as { descriptor, d-loader }
939 * tuples. If the hashed class descriptor matches the requested descriptor,
940 * and the hashed defining class loader matches the requested class
941 * loader, we're good. If only the descriptor matches, we check to see if the
942 * loader is in the hashed class' initiating loader list. If so, we
943 * can return "true" immediately and skip some of the loadClass melodrama.
944 *
945 * The caller must lock the hash table before calling here.
946 *
947 * Returns 0 if a matching entry is found, nonzero otherwise.
948 */
949static int hashcmpClassByCrit(const void* vclazz, const void* vcrit)
950{
951 const ClassObject* clazz = (const ClassObject*) vclazz;
952 const ClassMatchCriteria* pCrit = (const ClassMatchCriteria*) vcrit;
953 bool match;
954
955 match = (strcmp(clazz->descriptor, pCrit->descriptor) == 0 &&
956 (clazz->classLoader == pCrit->loader ||
957 (pCrit->loader != NULL &&
958 dvmLoaderInInitiatingList(clazz, pCrit->loader)) ));
959 //if (match)
960 // LOGI("+++ %s %p matches existing %s %p\n",
961 // pCrit->descriptor, pCrit->loader,
962 // clazz->descriptor, clazz->classLoader);
963 return !match;
964}
965
966/*
967 * Like hashcmpClassByCrit, but passing in a fully-formed ClassObject
968 * instead of a ClassMatchCriteria.
969 */
970static int hashcmpClassByClass(const void* vclazz, const void* vaddclazz)
971{
972 const ClassObject* clazz = (const ClassObject*) vclazz;
973 const ClassObject* addClazz = (const ClassObject*) vaddclazz;
974 bool match;
975
976 match = (strcmp(clazz->descriptor, addClazz->descriptor) == 0 &&
977 (clazz->classLoader == addClazz->classLoader ||
978 (addClazz->classLoader != NULL &&
979 dvmLoaderInInitiatingList(clazz, addClazz->classLoader)) ));
980 return !match;
981}
982
983/*
984 * Search through the hash table to find an entry with a matching descriptor
985 * and an initiating class loader that matches "loader".
986 *
987 * The table entries are hashed on descriptor only, because they're unique
988 * on *defining* class loader, not *initiating* class loader. This isn't
989 * great, because it guarantees we will have to probe when multiple
990 * class loaders are used.
991 *
992 * Note this does NOT try to load a class; it just finds a class that
993 * has already been loaded.
994 *
995 * If "unprepOkay" is set, this will return classes that have been added
996 * to the hash table but are not yet fully loaded and linked. Otherwise,
997 * such classes are ignored. (The only place that should set "unprepOkay"
998 * is findClassNoInit(), which will wait for the prep to finish.)
999 *
1000 * Returns NULL if not found.
1001 */
1002ClassObject* dvmLookupClass(const char* descriptor, Object* loader,
1003 bool unprepOkay)
1004{
1005 ClassMatchCriteria crit;
1006 void* found;
1007 u4 hash;
1008
1009 crit.descriptor = descriptor;
1010 crit.loader = loader;
1011 hash = dvmComputeUtf8Hash(descriptor);
1012
1013 LOGVV("threadid=%d: dvmLookupClass searching for '%s' %p\n",
1014 dvmThreadSelf()->threadId, descriptor, loader);
1015
1016 dvmHashTableLock(gDvm.loadedClasses);
1017 found = dvmHashTableLookup(gDvm.loadedClasses, hash, &crit,
1018 hashcmpClassByCrit, false);
1019 dvmHashTableUnlock(gDvm.loadedClasses);
1020
1021 /*
1022 * The class has been added to the hash table but isn't ready for use.
1023 * We're going to act like we didn't see it, so that the caller will
1024 * go through the full "find class" path, which includes locking the
1025 * object and waiting until it's ready. We could do that lock/wait
1026 * here, but this is an extremely rare case, and it's simpler to have
1027 * the wait-for-class code centralized.
1028 */
1029 if (found != NULL && !unprepOkay && !dvmIsClassLinked(found)) {
1030 LOGV("Ignoring not-yet-ready %s, using slow path\n",
1031 ((ClassObject*)found)->descriptor);
1032 found = NULL;
1033 }
1034
1035 return (ClassObject*) found;
1036}
1037
1038/*
1039 * Add a new class to the hash table.
1040 *
1041 * The class is considered "new" if it doesn't match on both the class
1042 * descriptor and the defining class loader.
1043 *
1044 * TODO: we should probably have separate hash tables for each
1045 * ClassLoader. This could speed up dvmLookupClass and
1046 * other common operations. It does imply a VM-visible data structure
1047 * for each ClassLoader object with loaded classes, which we don't
1048 * have yet.
1049 */
1050bool dvmAddClassToHash(ClassObject* clazz)
1051{
1052 void* found;
1053 u4 hash;
1054
1055 hash = dvmComputeUtf8Hash(clazz->descriptor);
1056
1057 dvmHashTableLock(gDvm.loadedClasses);
1058 found = dvmHashTableLookup(gDvm.loadedClasses, hash, clazz,
1059 hashcmpClassByClass, true);
1060 dvmHashTableUnlock(gDvm.loadedClasses);
1061
1062 LOGV("+++ dvmAddClassToHash '%s' %p (isnew=%d) --> %p\n",
1063 clazz->descriptor, clazz->classLoader,
1064 (found == (void*) clazz), clazz);
1065
1066 //dvmCheckClassTablePerf();
1067
1068 /* can happen if two threads load the same class simultaneously */
1069 return (found == (void*) clazz);
1070}
1071
1072#if 0
1073/*
1074 * Compute hash value for a class.
1075 */
1076u4 hashcalcClass(const void* item)
1077{
1078 return dvmComputeUtf8Hash(((const ClassObject*) item)->descriptor);
1079}
1080
1081/*
1082 * Check the performance of the "loadedClasses" hash table.
1083 */
1084void dvmCheckClassTablePerf(void)
1085{
1086 dvmHashTableLock(gDvm.loadedClasses);
1087 dvmHashTableProbeCount(gDvm.loadedClasses, hashcalcClass,
1088 hashcmpClassByClass);
1089 dvmHashTableUnlock(gDvm.loadedClasses);
1090}
1091#endif
1092
1093/*
1094 * Remove a class object from the hash table.
1095 */
1096static void removeClassFromHash(ClassObject* clazz)
1097{
1098 LOGV("+++ removeClassFromHash '%s'\n", clazz->descriptor);
1099
1100 u4 hash = dvmComputeUtf8Hash(clazz->descriptor);
1101
1102 dvmHashTableLock(gDvm.loadedClasses);
1103 if (!dvmHashTableRemove(gDvm.loadedClasses, hash, clazz))
1104 LOGW("Hash table remove failed on class '%s'\n", clazz->descriptor);
1105 dvmHashTableUnlock(gDvm.loadedClasses);
1106}
1107
1108
1109/*
1110 * ===========================================================================
1111 * Class creation
1112 * ===========================================================================
1113 */
1114
1115/*
1116 * Set clazz->serialNumber to the next available value.
1117 *
1118 * This usually happens *very* early in class creation, so don't expect
1119 * anything else in the class to be ready.
1120 */
1121void dvmSetClassSerialNumber(ClassObject* clazz)
1122{
1123 u4 oldValue, newValue;
1124
1125 assert(clazz->serialNumber == 0);
1126
1127 do {
1128 oldValue = gDvm.classSerialNumber;
1129 newValue = oldValue + 1;
1130 } while (!ATOMIC_CMP_SWAP(&gDvm.classSerialNumber, oldValue, newValue));
1131
1132 clazz->serialNumber = (u4) oldValue;
1133}
1134
1135
1136/*
1137 * Find the named class (by descriptor), using the specified
1138 * initiating ClassLoader.
1139 *
1140 * The class will be loaded and initialized if it has not already been.
1141 * If necessary, the superclass will be loaded.
1142 *
1143 * If the class can't be found, returns NULL with an appropriate exception
1144 * raised.
1145 */
1146ClassObject* dvmFindClass(const char* descriptor, Object* loader)
1147{
1148 ClassObject* clazz;
1149
1150 clazz = dvmFindClassNoInit(descriptor, loader);
1151 if (clazz != NULL && clazz->status < CLASS_INITIALIZED) {
1152 /* initialize class */
1153 if (!dvmInitClass(clazz)) {
1154 /* init failed; leave it in the list, marked as bad */
1155 assert(dvmCheckException(dvmThreadSelf()));
1156 assert(clazz->status == CLASS_ERROR);
1157 return NULL;
1158 }
1159 }
1160
1161 return clazz;
1162}
1163
1164/*
1165 * Find the named class (by descriptor), using the specified
1166 * initiating ClassLoader.
1167 *
1168 * The class will be loaded if it has not already been, as will its
1169 * superclass. It will not be initialized.
1170 *
1171 * If the class can't be found, returns NULL with an appropriate exception
1172 * raised.
1173 */
1174ClassObject* dvmFindClassNoInit(const char* descriptor,
1175 Object* loader)
1176{
1177 assert(descriptor != NULL);
1178 //assert(loader != NULL);
1179
1180 LOGVV("FindClassNoInit '%s' %p\n", descriptor, loader);
1181
1182 if (*descriptor == '[') {
1183 /*
1184 * Array class. Find in table, generate if not found.
1185 */
1186 return dvmFindArrayClass(descriptor, loader);
1187 } else {
1188 /*
1189 * Regular class. Find in table, load if not found.
1190 */
1191 if (loader != NULL) {
1192 return findClassFromLoaderNoInit(descriptor, loader);
1193 } else {
1194 return dvmFindSystemClassNoInit(descriptor);
1195 }
1196 }
1197}
1198
1199/*
1200 * Load the named class (by descriptor) from the specified class
1201 * loader. This calls out to let the ClassLoader object do its thing.
1202 *
1203 * Returns with NULL and an exception raised on error.
1204 */
1205static ClassObject* findClassFromLoaderNoInit(const char* descriptor,
1206 Object* loader)
1207{
1208 //LOGI("##### findClassFromLoaderNoInit (%s,%p)\n",
1209 // descriptor, loader);
1210
1211 Thread* self = dvmThreadSelf();
1212 ClassObject* clazz;
1213
1214 assert(loader != NULL);
1215
1216 /*
1217 * Do we already have it?
1218 *
1219 * The class loader code does the "is it already loaded" check as
1220 * well. However, this call is much faster than calling through
1221 * interpreted code. Doing this does mean that in the common case
1222 * (365 out of 420 calls booting the sim) we're doing the
1223 * lookup-by-descriptor twice. It appears this is still a win, so
1224 * I'm keeping it in.
1225 */
1226 clazz = dvmLookupClass(descriptor, loader, false);
1227 if (clazz != NULL) {
1228 LOGVV("Already loaded: %s %p\n", descriptor, loader);
1229 return clazz;
1230 } else {
1231 LOGVV("Not already loaded: %s %p\n", descriptor, loader);
1232 }
1233
1234 char* dotName = NULL;
1235 StringObject* nameObj = NULL;
1236 Object* excep;
1237 Method* loadClass;
1238
1239 /* convert "Landroid/debug/Stuff;" to "android.debug.Stuff" */
1240 dotName = dvmDescriptorToDot(descriptor);
1241 if (dotName == NULL) {
1242 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
1243 goto bail;
1244 }
1245 nameObj = dvmCreateStringFromCstr(dotName, ALLOC_DEFAULT);
1246 if (nameObj == NULL) {
1247 assert(dvmCheckException(self));
1248 goto bail;
1249 }
1250
1251 // TODO: cache the vtable offset
1252 loadClass = dvmFindVirtualMethodHierByDescriptor(loader->clazz, "loadClass",
1253 "(Ljava/lang/String;)Ljava/lang/Class;");
1254 if (loadClass == NULL) {
1255 LOGW("Couldn't find loadClass in ClassLoader\n");
1256 goto bail;
1257 }
1258
1259#ifdef WITH_PROFILER
1260 dvmMethodTraceClassPrepBegin();
1261#endif
1262
1263 /*
1264 * Invoke loadClass(). This will probably result in a couple of
1265 * exceptions being thrown, because the ClassLoader.loadClass()
1266 * implementation eventually calls VMClassLoader.loadClass to see if
1267 * the bootstrap class loader can find it before doing its own load.
1268 */
1269 LOGVV("--- Invoking loadClass(%s, %p)\n", dotName, loader);
1270 JValue result;
1271 dvmCallMethod(self, loadClass, loader, &result, nameObj);
1272 clazz = (ClassObject*) result.l;
1273
1274#ifdef WITH_PROFILER
1275 dvmMethodTraceClassPrepEnd();
1276#endif
1277
1278 excep = dvmGetException(self);
1279 if (excep != NULL) {
1280#if DVM_SHOW_EXCEPTION >= 2
1281 LOGD("NOTE: loadClass '%s' %p threw exception %s\n",
1282 dotName, loader, excep->clazz->descriptor);
1283#endif
1284 dvmAddTrackedAlloc(excep, self);
1285 dvmClearException(self);
1286 dvmThrowChainedExceptionWithClassMessage(
1287 "Ljava/lang/NoClassDefFoundError;", descriptor, excep);
1288 dvmReleaseTrackedAlloc(excep, self);
1289 clazz = NULL;
1290 goto bail;
1291 } else {
1292 assert(clazz != NULL);
1293 }
1294
1295 dvmAddInitiatingLoader(clazz, loader);
1296
1297 LOGVV("--- Successfully loaded %s %p (thisldr=%p clazz=%p)\n",
1298 descriptor, clazz->classLoader, loader, clazz);
1299
1300bail:
1301 dvmReleaseTrackedAlloc((Object*)nameObj, NULL);
1302 free(dotName);
1303 return clazz;
1304}
1305
1306/*
1307 * Load the named class (by descriptor) from the specified DEX file.
1308 * Used by class loaders to instantiate a class object from a
1309 * VM-managed DEX.
1310 */
1311ClassObject* dvmDefineClass(DvmDex* pDvmDex, const char* descriptor,
1312 Object* classLoader)
1313{
1314 assert(pDvmDex != NULL);
1315
1316 return findClassNoInit(descriptor, classLoader, pDvmDex);
1317}
1318
1319
1320/*
1321 * Find the named class (by descriptor), scanning through the
1322 * bootclasspath if it hasn't already been loaded.
1323 *
1324 * "descriptor" looks like "Landroid/debug/Stuff;".
1325 *
1326 * Uses NULL as the defining class loader.
1327 */
1328ClassObject* dvmFindSystemClass(const char* descriptor)
1329{
1330 ClassObject* clazz;
1331
1332 clazz = dvmFindSystemClassNoInit(descriptor);
1333 if (clazz != NULL && clazz->status < CLASS_INITIALIZED) {
1334 /* initialize class */
1335 if (!dvmInitClass(clazz)) {
1336 /* init failed; leave it in the list, marked as bad */
1337 assert(dvmCheckException(dvmThreadSelf()));
1338 assert(clazz->status == CLASS_ERROR);
1339 return NULL;
1340 }
1341 }
1342
1343 return clazz;
1344}
1345
1346/*
1347 * Find the named class (by descriptor), searching for it in the
1348 * bootclasspath.
1349 *
1350 * On failure, this returns NULL with an exception raised.
1351 */
1352ClassObject* dvmFindSystemClassNoInit(const char* descriptor)
1353{
1354 return findClassNoInit(descriptor, NULL, NULL);
1355}
1356
1357/*
1358 * Find the named class (by descriptor). If it's not already loaded,
1359 * we load it and link it, but don't execute <clinit>. (The VM has
1360 * specific limitations on which events can cause initialization.)
1361 *
1362 * If "pDexFile" is NULL, we will search the bootclasspath for an entry.
1363 *
1364 * On failure, this returns NULL with an exception raised.
1365 *
1366 * TODO: we need to return an indication of whether we loaded the class or
1367 * used an existing definition. If somebody deliberately tries to load a
1368 * class twice in the same class loader, they should get a LinkageError,
1369 * but inadvertent simultaneous class references should "just work".
1370 */
1371static ClassObject* findClassNoInit(const char* descriptor, Object* loader,
1372 DvmDex* pDvmDex)
1373{
1374 Thread* self = dvmThreadSelf();
1375 ClassObject* clazz;
1376#ifdef WITH_PROFILER
1377 bool profilerNotified = false;
1378#endif
1379
1380 if (loader != NULL) {
1381 LOGVV("#### findClassNoInit(%s,%p,%p)\n", descriptor, loader,
1382 pDvmDex->pDexFile);
1383 }
1384
1385 /*
1386 * We don't expect an exception to be raised at this point. The
1387 * exception handling code is good about managing this. This *can*
1388 * happen if a JNI lookup fails and the JNI code doesn't do any
1389 * error checking before doing another class lookup, so we may just
1390 * want to clear this and restore it on exit. If we don't, some kinds
1391 * of failures can't be detected without rearranging other stuff.
1392 *
1393 * Most often when we hit this situation it means that something is
1394 * broken in the VM or in JNI code, so I'm keeping it in place (and
1395 * making it an informative abort rather than an assert).
1396 */
1397 if (dvmCheckException(self)) {
Andy McFadden504e9f42009-09-15 20:01:40 -07001398 LOGE("Class lookup %s attempted while exception %s pending\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001399 descriptor, dvmGetException(self)->clazz->descriptor);
1400 dvmDumpAllThreads(false);
1401 dvmAbort();
1402 }
1403
1404 clazz = dvmLookupClass(descriptor, loader, true);
1405 if (clazz == NULL) {
1406 const DexClassDef* pClassDef;
1407
1408#ifdef WITH_PROFILER
1409 dvmMethodTraceClassPrepBegin();
1410 profilerNotified = true;
1411#endif
1412
1413#if LOG_CLASS_LOADING
1414 u8 startTime = dvmGetThreadCpuTimeNsec();
1415#endif
1416
1417 if (pDvmDex == NULL) {
1418 assert(loader == NULL); /* shouldn't be here otherwise */
1419 pDvmDex = searchBootPathForClass(descriptor, &pClassDef);
1420 } else {
1421 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
1422 }
1423
1424 if (pDvmDex == NULL || pClassDef == NULL) {
Andy McFadden7fc3ce82009-07-14 15:57:23 -07001425 if (gDvm.noClassDefFoundErrorObj != NULL) {
1426 /* usual case -- use prefabricated object */
1427 dvmSetException(self, gDvm.noClassDefFoundErrorObj);
1428 } else {
1429 /* dexopt case -- can't guarantee prefab (core.jar) */
1430 dvmThrowExceptionWithClassMessage(
1431 "Ljava/lang/NoClassDefFoundError;", descriptor);
1432 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001433 goto bail;
1434 }
1435
1436 /* found a match, try to load it */
1437 clazz = loadClassFromDex(pDvmDex, pClassDef, loader);
1438 if (dvmCheckException(self)) {
1439 /* class was found but had issues */
1440 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1441 goto bail;
1442 }
1443
1444 /*
1445 * Lock the class while we link it so other threads must wait for us
1446 * to finish. Set the "initThreadId" so we can identify recursive
1447 * invocation.
1448 */
1449 dvmLockObject(self, (Object*) clazz);
1450 clazz->initThreadId = self->threadId;
1451
1452 /*
1453 * Add to hash table so lookups succeed.
1454 *
1455 * [Are circular references possible when linking a class?]
1456 */
1457 assert(clazz->classLoader == loader);
1458 if (!dvmAddClassToHash(clazz)) {
1459 /*
1460 * Another thread must have loaded the class after we
1461 * started but before we finished. Discard what we've
1462 * done and leave some hints for the GC.
1463 *
1464 * (Yes, this happens.)
1465 */
1466 //LOGW("WOW: somebody loaded %s simultaneously\n", descriptor);
1467 clazz->initThreadId = 0;
1468 dvmUnlockObject(self, (Object*) clazz);
1469
1470 /* Let the GC free the class.
1471 */
1472 assert(clazz->obj.clazz == gDvm.unlinkedJavaLangClass);
1473 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1474
1475 /* Grab the winning class.
1476 */
1477 clazz = dvmLookupClass(descriptor, loader, true);
1478 assert(clazz != NULL);
1479 goto got_class;
1480 }
1481 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1482
1483#if LOG_CLASS_LOADING
1484 logClassLoadWithTime('>', clazz, startTime);
1485#endif
1486 /*
1487 * Prepare and resolve.
1488 */
1489 if (!dvmLinkClass(clazz, false)) {
1490 assert(dvmCheckException(self));
1491
1492 /* Make note of the error and clean up the class.
1493 */
1494 removeClassFromHash(clazz);
1495 clazz->status = CLASS_ERROR;
1496 dvmFreeClassInnards(clazz);
1497
1498 /* Let any waiters know.
1499 */
1500 clazz->initThreadId = 0;
1501 dvmObjectNotifyAll(self, (Object*) clazz);
1502 dvmUnlockObject(self, (Object*) clazz);
1503
1504#if LOG_CLASS_LOADING
1505 LOG(LOG_INFO, "DVMLINK FAILED FOR CLASS ", "%s in %s\n",
1506 clazz->descriptor, get_process_name());
1507
1508 /*
1509 * TODO: It would probably be better to use a new type code here (instead of '<') to
1510 * indicate the failure. This change would require a matching change in the parser
1511 * and analysis code in frameworks/base/tools/preload.
1512 */
1513 logClassLoad('<', clazz);
1514#endif
1515 clazz = NULL;
1516 if (gDvm.optimizing) {
1517 /* happens with "external" libs */
1518 LOGV("Link of class '%s' failed\n", descriptor);
1519 } else {
1520 LOGW("Link of class '%s' failed\n", descriptor);
1521 }
1522 goto bail;
1523 }
1524 dvmObjectNotifyAll(self, (Object*) clazz);
1525 dvmUnlockObject(self, (Object*) clazz);
1526
1527 /*
1528 * Add class stats to global counters.
1529 *
1530 * TODO: these should probably be atomic ops.
1531 */
1532 gDvm.numLoadedClasses++;
1533 gDvm.numDeclaredMethods +=
1534 clazz->virtualMethodCount + clazz->directMethodCount;
1535 gDvm.numDeclaredInstFields += clazz->ifieldCount;
1536 gDvm.numDeclaredStaticFields += clazz->sfieldCount;
1537
1538 /*
1539 * Cache pointers to basic classes. We want to use these in
1540 * various places, and it's easiest to initialize them on first
1541 * use rather than trying to force them to initialize (startup
1542 * ordering makes it weird).
1543 */
1544 if (gDvm.classJavaLangObject == NULL &&
1545 strcmp(descriptor, "Ljava/lang/Object;") == 0)
1546 {
1547 /* It should be impossible to get here with anything
1548 * but the bootclasspath loader.
1549 */
1550 assert(loader == NULL);
1551 gDvm.classJavaLangObject = clazz;
1552 }
1553
1554#if LOG_CLASS_LOADING
1555 logClassLoad('<', clazz);
1556#endif
1557
1558 } else {
1559got_class:
1560 if (!dvmIsClassLinked(clazz) && clazz->status != CLASS_ERROR) {
1561 /*
1562 * We can race with other threads for class linking. We should
1563 * never get here recursively; doing so indicates that two
1564 * classes have circular dependencies.
1565 *
1566 * One exception: we force discovery of java.lang.Class in
1567 * dvmLinkClass(), and Class has Object as its superclass. So
1568 * if the first thing we ever load is Object, we will init
1569 * Object->Class->Object. The easiest way to avoid this is to
1570 * ensure that Object is never the first thing we look up, so
1571 * we get Foo->Class->Object instead.
1572 */
1573 dvmLockObject(self, (Object*) clazz);
1574 if (!dvmIsClassLinked(clazz) &&
1575 clazz->initThreadId == self->threadId)
1576 {
1577 LOGW("Recursive link on class %s\n", clazz->descriptor);
1578 dvmUnlockObject(self, (Object*) clazz);
1579 dvmThrowExceptionWithClassMessage(
1580 "Ljava/lang/ClassCircularityError;", clazz->descriptor);
1581 clazz = NULL;
1582 goto bail;
1583 }
1584 //LOGI("WAITING for '%s' (owner=%d)\n",
1585 // clazz->descriptor, clazz->initThreadId);
1586 while (!dvmIsClassLinked(clazz) && clazz->status != CLASS_ERROR) {
1587 dvmObjectWait(self, (Object*) clazz, 0, 0, false);
1588 }
1589 dvmUnlockObject(self, (Object*) clazz);
1590 }
1591 if (clazz->status == CLASS_ERROR) {
1592 /*
1593 * Somebody else tried to load this and failed. We need to raise
1594 * an exception and report failure.
1595 */
1596 throwEarlierClassFailure(clazz);
1597 clazz = NULL;
1598 goto bail;
1599 }
1600 }
1601
1602 /* check some invariants */
1603 assert(dvmIsClassLinked(clazz));
1604 assert(gDvm.classJavaLangClass != NULL);
1605 assert(clazz->obj.clazz == gDvm.classJavaLangClass);
1606 if (clazz != gDvm.classJavaLangObject) {
1607 if (clazz->super == NULL) {
1608 LOGE("Non-Object has no superclass (gDvm.classJavaLangObject=%p)\n",
1609 gDvm.classJavaLangObject);
1610 dvmAbort();
1611 }
1612 }
1613 if (!dvmIsInterfaceClass(clazz)) {
1614 //LOGI("class=%s vtableCount=%d, virtualMeth=%d\n",
1615 // clazz->descriptor, clazz->vtableCount,
1616 // clazz->virtualMethodCount);
1617 assert(clazz->vtableCount >= clazz->virtualMethodCount);
1618 }
1619
1620 /*
1621 * Normally class objects are initialized before we instantiate them,
1622 * but we can't do that with java.lang.Class (chicken, meet egg). We
1623 * do it explicitly here.
1624 *
1625 * The verifier could call here to find Class while verifying Class,
1626 * so we need to check for CLASS_VERIFYING as well as !initialized.
1627 */
1628 if (clazz == gDvm.classJavaLangClass && !dvmIsClassInitialized(clazz) &&
1629 !(clazz->status == CLASS_VERIFYING))
1630 {
1631 LOGV("+++ explicitly initializing %s\n", clazz->descriptor);
1632 dvmInitClass(clazz);
1633 }
1634
1635bail:
1636#ifdef WITH_PROFILER
1637 if (profilerNotified)
1638 dvmMethodTraceClassPrepEnd();
1639#endif
1640 assert(clazz != NULL || dvmCheckException(self));
1641 return clazz;
1642}
1643
1644/*
1645 * Helper for loadClassFromDex, which takes a DexClassDataHeader and
1646 * encoded data pointer in addition to the other arguments.
1647 */
1648static ClassObject* loadClassFromDex0(DvmDex* pDvmDex,
1649 const DexClassDef* pClassDef, const DexClassDataHeader* pHeader,
1650 const u1* pEncodedData, Object* classLoader)
1651{
1652 ClassObject* newClass = NULL;
1653 const DexFile* pDexFile;
1654 const char* descriptor;
1655 int i;
1656
1657 pDexFile = pDvmDex->pDexFile;
1658 descriptor = dexGetClassDescriptor(pDexFile, pClassDef);
1659
1660 /*
1661 * Make sure the aren't any "bonus" flags set, since we use them for
1662 * runtime state.
1663 */
1664 if ((pClassDef->accessFlags & ~EXPECTED_FILE_FLAGS) != 0) {
1665 LOGW("Invalid file flags in class %s: %04x\n",
1666 descriptor, pClassDef->accessFlags);
1667 return NULL;
1668 }
1669
1670 /*
1671 * Allocate storage for the class object on the GC heap, so that other
1672 * objects can have references to it. We bypass the usual mechanism
1673 * (allocObject), because we don't have all the bits and pieces yet.
1674 *
1675 * Note that we assume that java.lang.Class does not override
1676 * finalize().
1677 */
1678 newClass = (ClassObject*) dvmMalloc(sizeof(*newClass), ALLOC_DEFAULT);
1679 if (newClass == NULL)
1680 return NULL;
1681
1682 /* Until the class is loaded and linked, use a placeholder
1683 * obj->clazz value as a hint to the GC. We don't want
1684 * the GC trying to scan the object while it's full of Idx
1685 * values. Also, the real java.lang.Class may not exist
1686 * yet.
1687 */
1688 DVM_OBJECT_INIT(&newClass->obj, gDvm.unlinkedJavaLangClass);
1689
1690 dvmSetClassSerialNumber(newClass);
1691 newClass->descriptor = descriptor;
1692 assert(newClass->descriptorAlloc == NULL);
1693 newClass->accessFlags = pClassDef->accessFlags;
1694 newClass->classLoader = classLoader;
1695 newClass->pDvmDex = pDvmDex;
1696 newClass->primitiveType = PRIM_NOT;
1697
1698 /*
1699 * Stuff the superclass index into the object pointer field. The linker
1700 * pulls it out and replaces it with a resolved ClassObject pointer.
1701 * I'm doing it this way (rather than having a dedicated superclassIdx
1702 * field) to save a few bytes of overhead per class.
1703 *
1704 * newClass->super is not traversed or freed by dvmFreeClassInnards, so
1705 * this is safe.
1706 */
1707 assert(sizeof(u4) == sizeof(ClassObject*));
1708 newClass->super = (ClassObject*) pClassDef->superclassIdx;
1709
1710 /*
1711 * Stuff class reference indices into the pointer fields.
1712 *
1713 * The elements of newClass->interfaces are not traversed or freed by
1714 * dvmFreeClassInnards, so this is GC-safe.
1715 */
1716 const DexTypeList* pInterfacesList;
1717 pInterfacesList = dexGetInterfacesList(pDexFile, pClassDef);
1718 if (pInterfacesList != NULL) {
1719 newClass->interfaceCount = pInterfacesList->size;
1720 newClass->interfaces = (ClassObject**) dvmLinearAlloc(classLoader,
1721 newClass->interfaceCount * sizeof(ClassObject*));
1722
1723 for (i = 0; i < newClass->interfaceCount; i++) {
1724 const DexTypeItem* pType = dexGetTypeItem(pInterfacesList, i);
1725 newClass->interfaces[i] = (ClassObject*)(u4) pType->typeIdx;
1726 }
1727 dvmLinearReadOnly(classLoader, newClass->interfaces);
1728 }
1729
1730 /* load field definitions */
1731
1732 /*
1733 * TODO: consider over-allocating the class object and appending the
1734 * static field info onto the end. It's fixed-size and known at alloc
1735 * time. This would save a couple of native heap allocations, but it
1736 * would also make heap compaction more difficult because we pass Field
1737 * pointers around internally.
1738 */
1739
1740 if (pHeader->staticFieldsSize != 0) {
1741 /* static fields stay on system heap; field data isn't "write once" */
1742 int count = (int) pHeader->staticFieldsSize;
1743 u4 lastIndex = 0;
1744 DexField field;
1745
1746 newClass->sfieldCount = count;
1747 newClass->sfields =
1748 (StaticField*) calloc(count, sizeof(StaticField));
1749 for (i = 0; i < count; i++) {
1750 dexReadClassDataField(&pEncodedData, &field, &lastIndex);
1751 loadSFieldFromDex(newClass, &field, &newClass->sfields[i]);
1752 }
1753 }
1754
1755 if (pHeader->instanceFieldsSize != 0) {
1756 int count = (int) pHeader->instanceFieldsSize;
1757 u4 lastIndex = 0;
1758 DexField field;
1759
1760 newClass->ifieldCount = count;
1761 newClass->ifields = (InstField*) dvmLinearAlloc(classLoader,
1762 count * sizeof(InstField));
1763 for (i = 0; i < count; i++) {
1764 dexReadClassDataField(&pEncodedData, &field, &lastIndex);
1765 loadIFieldFromDex(newClass, &field, &newClass->ifields[i]);
1766 }
1767 dvmLinearReadOnly(classLoader, newClass->ifields);
1768 }
1769
The Android Open Source Project99409882009-03-18 22:20:24 -07001770 /*
1771 * Load method definitions. We do this in two batches, direct then
1772 * virtual.
1773 *
1774 * If register maps have already been generated for this class, and
1775 * precise GC is enabled, we pull out pointers to them. We know that
1776 * they were streamed to the DEX file in the same order in which the
1777 * methods appear.
1778 *
1779 * If the class wasn't pre-verified, the maps will be generated when
1780 * the class is verified during class initialization.
1781 */
1782 u4 classDefIdx = dexGetIndexForClassDef(pDexFile, pClassDef);
1783 const void* classMapData;
1784 u4 numMethods;
1785
1786 if (gDvm.preciseGc) {
1787 classMapData =
Andy McFaddend45a8872009-03-24 20:41:52 -07001788 dvmRegisterMapGetClassData(pDexFile, classDefIdx, &numMethods);
The Android Open Source Project99409882009-03-18 22:20:24 -07001789
1790 /* sanity check */
1791 if (classMapData != NULL &&
1792 pHeader->directMethodsSize + pHeader->virtualMethodsSize != numMethods)
1793 {
1794 LOGE("ERROR: in %s, direct=%d virtual=%d, maps have %d\n",
1795 newClass->descriptor, pHeader->directMethodsSize,
1796 pHeader->virtualMethodsSize, numMethods);
1797 assert(false);
1798 classMapData = NULL; /* abandon */
1799 }
1800 } else {
1801 classMapData = NULL;
1802 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001803
1804 if (pHeader->directMethodsSize != 0) {
1805 int count = (int) pHeader->directMethodsSize;
1806 u4 lastIndex = 0;
1807 DexMethod method;
1808
1809 newClass->directMethodCount = count;
1810 newClass->directMethods = (Method*) dvmLinearAlloc(classLoader,
1811 count * sizeof(Method));
1812 for (i = 0; i < count; i++) {
1813 dexReadClassDataMethod(&pEncodedData, &method, &lastIndex);
1814 loadMethodFromDex(newClass, &method, &newClass->directMethods[i]);
The Android Open Source Project99409882009-03-18 22:20:24 -07001815 if (classMapData != NULL) {
Andy McFaddend45a8872009-03-24 20:41:52 -07001816 const RegisterMap* pMap = dvmRegisterMapGetNext(&classMapData);
1817 if (dvmRegisterMapGetFormat(pMap) != kRegMapFormatNone) {
The Android Open Source Project99409882009-03-18 22:20:24 -07001818 newClass->directMethods[i].registerMap = pMap;
1819 /* TODO: add rigorous checks */
1820 assert((newClass->directMethods[i].registersSize+7) / 8 ==
1821 newClass->directMethods[i].registerMap->regWidth);
1822 }
1823 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001824 }
1825 dvmLinearReadOnly(classLoader, newClass->directMethods);
1826 }
1827
1828 if (pHeader->virtualMethodsSize != 0) {
1829 int count = (int) pHeader->virtualMethodsSize;
1830 u4 lastIndex = 0;
1831 DexMethod method;
1832
1833 newClass->virtualMethodCount = count;
1834 newClass->virtualMethods = (Method*) dvmLinearAlloc(classLoader,
1835 count * sizeof(Method));
1836 for (i = 0; i < count; i++) {
1837 dexReadClassDataMethod(&pEncodedData, &method, &lastIndex);
1838 loadMethodFromDex(newClass, &method, &newClass->virtualMethods[i]);
The Android Open Source Project99409882009-03-18 22:20:24 -07001839 if (classMapData != NULL) {
Andy McFaddend45a8872009-03-24 20:41:52 -07001840 const RegisterMap* pMap = dvmRegisterMapGetNext(&classMapData);
1841 if (dvmRegisterMapGetFormat(pMap) != kRegMapFormatNone) {
The Android Open Source Project99409882009-03-18 22:20:24 -07001842 newClass->virtualMethods[i].registerMap = pMap;
1843 /* TODO: add rigorous checks */
1844 assert((newClass->virtualMethods[i].registersSize+7) / 8 ==
1845 newClass->virtualMethods[i].registerMap->regWidth);
1846 }
1847 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001848 }
1849 dvmLinearReadOnly(classLoader, newClass->virtualMethods);
1850 }
1851
1852 newClass->sourceFile = dexGetSourceFile(pDexFile, pClassDef);
1853 newClass->status = CLASS_LOADED;
1854
1855 /* caller must call dvmReleaseTrackedAlloc */
1856 return newClass;
1857}
1858
1859/*
1860 * Try to load the indicated class from the specified DEX file.
1861 *
1862 * This is effectively loadClass()+defineClass() for a DexClassDef. The
1863 * loading was largely done when we crunched through the DEX.
1864 *
1865 * Returns NULL on failure. If we locate the class but encounter an error
1866 * while processing it, an appropriate exception is thrown.
1867 */
1868static ClassObject* loadClassFromDex(DvmDex* pDvmDex,
1869 const DexClassDef* pClassDef, Object* classLoader)
1870{
1871 ClassObject* result;
1872 DexClassDataHeader header;
1873 const u1* pEncodedData;
1874 const DexFile* pDexFile;
1875
1876 assert((pDvmDex != NULL) && (pClassDef != NULL));
1877 pDexFile = pDvmDex->pDexFile;
1878
1879 if (gDvm.verboseClass) {
1880 LOGV("CLASS: loading '%s'...\n",
1881 dexGetClassDescriptor(pDexFile, pClassDef));
1882 }
1883
1884 pEncodedData = dexGetClassData(pDexFile, pClassDef);
1885
1886 if (pEncodedData != NULL) {
1887 dexReadClassDataHeader(&pEncodedData, &header);
1888 } else {
1889 // Provide an all-zeroes header for the rest of the loading.
1890 memset(&header, 0, sizeof(header));
1891 }
1892
1893 result = loadClassFromDex0(pDvmDex, pClassDef, &header, pEncodedData,
1894 classLoader);
1895
1896 if (gDvm.verboseClass && (result != NULL)) {
1897 LOGI("[Loaded %s from DEX %p (cl=%p)]\n",
1898 result->descriptor, pDvmDex, classLoader);
1899 }
1900
1901 return result;
1902}
1903
1904/*
1905 * Free anything in a ClassObject that was allocated on the system heap.
1906 *
1907 * The ClassObject itself is allocated on the GC heap, so we leave it for
1908 * the garbage collector.
1909 *
1910 * NOTE: this may be called with a partially-constructed object.
1911 * NOTE: there is no particular ordering imposed, so don't go poking at
1912 * superclasses.
1913 */
1914void dvmFreeClassInnards(ClassObject* clazz)
1915{
1916 void *tp;
1917 int i;
1918
1919 if (clazz == NULL)
1920 return;
1921
1922 assert(clazz->obj.clazz == gDvm.classJavaLangClass ||
1923 clazz->obj.clazz == gDvm.unlinkedJavaLangClass);
1924
1925 /* Guarantee that dvmFreeClassInnards can be called on a given
1926 * class multiple times by clearing things out as we free them.
1927 * We don't make any attempt at real atomicity here; higher
1928 * levels need to make sure that no two threads can free the
1929 * same ClassObject at the same time.
1930 *
1931 * TODO: maybe just make it so the GC will never free the
1932 * innards of an already-freed class.
1933 *
1934 * TODO: this #define isn't MT-safe -- the compiler could rearrange it.
1935 */
1936#define NULL_AND_FREE(p) \
1937 do { \
1938 if ((p) != NULL) { \
1939 tp = (p); \
1940 (p) = NULL; \
1941 free(tp); \
1942 } \
1943 } while (0)
1944#define NULL_AND_LINEAR_FREE(p) \
1945 do { \
1946 if ((p) != NULL) { \
1947 tp = (p); \
1948 (p) = NULL; \
1949 dvmLinearFree(clazz->classLoader, tp); \
1950 } \
1951 } while (0)
1952
1953 /* arrays just point at Object's vtable; don't free vtable in this case.
1954 * dvmIsArrayClass() checks clazz->descriptor, so we have to do this check
1955 * before freeing the name.
1956 */
1957 clazz->vtableCount = -1;
1958 if (dvmIsArrayClass(clazz)) {
1959 clazz->vtable = NULL;
1960 } else {
1961 NULL_AND_LINEAR_FREE(clazz->vtable);
1962 }
1963
1964 clazz->descriptor = NULL;
1965 NULL_AND_FREE(clazz->descriptorAlloc);
1966
1967 if (clazz->directMethods != NULL) {
1968 Method *directMethods = clazz->directMethods;
1969 int directMethodCount = clazz->directMethodCount;
1970 clazz->directMethods = NULL;
1971 clazz->directMethodCount = -1;
Andy McFaddenb51ea112009-05-08 16:50:17 -07001972 dvmLinearReadWrite(clazz->classLoader, directMethods);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001973 for (i = 0; i < directMethodCount; i++) {
1974 freeMethodInnards(&directMethods[i]);
1975 }
Andy McFaddenb51ea112009-05-08 16:50:17 -07001976 dvmLinearReadOnly(clazz->classLoader, directMethods);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001977 dvmLinearFree(clazz->classLoader, directMethods);
1978 }
1979 if (clazz->virtualMethods != NULL) {
1980 Method *virtualMethods = clazz->virtualMethods;
1981 int virtualMethodCount = clazz->virtualMethodCount;
1982 clazz->virtualMethodCount = -1;
1983 clazz->virtualMethods = NULL;
Andy McFaddenb51ea112009-05-08 16:50:17 -07001984 dvmLinearReadWrite(clazz->classLoader, virtualMethods);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001985 for (i = 0; i < virtualMethodCount; i++) {
1986 freeMethodInnards(&virtualMethods[i]);
1987 }
Andy McFaddenb51ea112009-05-08 16:50:17 -07001988 dvmLinearReadOnly(clazz->classLoader, virtualMethods);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001989 dvmLinearFree(clazz->classLoader, virtualMethods);
1990 }
1991
Barry Hayes2c987472009-04-06 10:03:48 -07001992 InitiatingLoaderList *loaderList = dvmGetInitiatingLoaderList(clazz);
1993 loaderList->initiatingLoaderCount = -1;
1994 NULL_AND_FREE(loaderList->initiatingLoaders);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001995
1996 clazz->interfaceCount = -1;
1997 NULL_AND_LINEAR_FREE(clazz->interfaces);
1998
1999 clazz->iftableCount = -1;
2000 NULL_AND_LINEAR_FREE(clazz->iftable);
2001
2002 clazz->ifviPoolCount = -1;
2003 NULL_AND_LINEAR_FREE(clazz->ifviPool);
2004
2005 clazz->sfieldCount = -1;
2006 NULL_AND_FREE(clazz->sfields);
2007
2008 clazz->ifieldCount = -1;
2009 NULL_AND_LINEAR_FREE(clazz->ifields);
2010
2011#undef NULL_AND_FREE
2012#undef NULL_AND_LINEAR_FREE
2013}
2014
2015/*
2016 * Free anything in a Method that was allocated on the system heap.
The Android Open Source Project99409882009-03-18 22:20:24 -07002017 *
2018 * The containing class is largely torn down by this point.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002019 */
2020static void freeMethodInnards(Method* meth)
2021{
2022#if 0
2023 free(meth->exceptions);
2024 free(meth->lines);
2025 free(meth->locals);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002026#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07002027
2028 /*
2029 * Some register maps are allocated on the heap, either because of late
2030 * verification or because we're caching an uncompressed form.
2031 */
2032 const RegisterMap* pMap = meth->registerMap;
Andy McFaddend45a8872009-03-24 20:41:52 -07002033 if (pMap != NULL && dvmRegisterMapGetOnHeap(pMap)) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002034 dvmFreeRegisterMap((RegisterMap*) pMap);
2035 meth->registerMap = NULL;
2036 }
Andy McFaddenb51ea112009-05-08 16:50:17 -07002037
2038 /*
2039 * We may have copied the instructions.
2040 */
2041 if (IS_METHOD_FLAG_SET(meth, METHOD_ISWRITABLE)) {
2042 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2043 dvmLinearFree(meth->clazz->classLoader, methodDexCode);
2044 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002045}
2046
2047/*
2048 * Clone a Method, making new copies of anything that will be freed up
The Android Open Source Project99409882009-03-18 22:20:24 -07002049 * by freeMethodInnards(). This is used for "miranda" methods.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002050 */
2051static void cloneMethod(Method* dst, const Method* src)
2052{
The Android Open Source Project99409882009-03-18 22:20:24 -07002053 if (src->registerMap != NULL) {
2054 LOGE("GLITCH: only expected abstract methods here\n");
2055 LOGE(" cloning %s.%s\n", src->clazz->descriptor, src->name);
2056 dvmAbort();
2057 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002058 memcpy(dst, src, sizeof(Method));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002059}
2060
2061/*
2062 * Pull the interesting pieces out of a DexMethod.
2063 *
2064 * The DEX file isn't going anywhere, so we don't need to make copies of
2065 * the code area.
2066 */
2067static void loadMethodFromDex(ClassObject* clazz, const DexMethod* pDexMethod,
2068 Method* meth)
2069{
2070 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2071 const DexMethodId* pMethodId;
2072 const DexCode* pDexCode;
2073
2074 pMethodId = dexGetMethodId(pDexFile, pDexMethod->methodIdx);
2075
2076 meth->name = dexStringById(pDexFile, pMethodId->nameIdx);
2077 dexProtoSetFromMethodId(&meth->prototype, pDexFile, pMethodId);
2078 meth->shorty = dexProtoGetShorty(&meth->prototype);
2079 meth->accessFlags = pDexMethod->accessFlags;
2080 meth->clazz = clazz;
2081 meth->jniArgInfo = 0;
2082
2083 if (dvmCompareNameDescriptorAndMethod("finalize", "()V", meth) == 0) {
2084 SET_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2085 }
2086
2087 pDexCode = dexGetCode(pDexFile, pDexMethod);
2088 if (pDexCode != NULL) {
2089 /* integer constants, copy over for faster access */
2090 meth->registersSize = pDexCode->registersSize;
2091 meth->insSize = pDexCode->insSize;
2092 meth->outsSize = pDexCode->outsSize;
2093
2094 /* pointer to code area */
2095 meth->insns = pDexCode->insns;
2096 } else {
2097 /*
2098 * We don't have a DexCode block, but we still want to know how
2099 * much space is needed for the arguments (so we don't have to
2100 * compute it later). We also take this opportunity to compute
2101 * JNI argument info.
2102 *
2103 * We do this for abstract methods as well, because we want to
2104 * be able to substitute our exception-throwing "stub" in.
2105 */
2106 int argsSize = dvmComputeMethodArgsSize(meth);
2107 if (!dvmIsStaticMethod(meth))
2108 argsSize++;
2109 meth->registersSize = meth->insSize = argsSize;
2110 assert(meth->outsSize == 0);
2111 assert(meth->insns == NULL);
2112
2113 if (dvmIsNativeMethod(meth)) {
2114 meth->nativeFunc = dvmResolveNativeMethod;
2115 meth->jniArgInfo = computeJniArgInfo(&meth->prototype);
2116 }
2117 }
2118}
2119
2120/*
Andy McFaddenb51ea112009-05-08 16:50:17 -07002121 * We usually map bytecode directly out of the DEX file, which is mapped
2122 * shared read-only. If we want to be able to modify it, we have to make
2123 * a new copy.
2124 *
2125 * Once copied, the code will be in the LinearAlloc region, which may be
2126 * marked read-only.
2127 *
2128 * The bytecode instructions are embedded inside a DexCode structure, so we
2129 * need to copy all of that. (The dvmGetMethodCode function backs up the
2130 * instruction pointer to find the start of the DexCode.)
2131 */
2132void dvmMakeCodeReadWrite(Method* meth)
2133{
2134 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2135
2136 if (IS_METHOD_FLAG_SET(meth, METHOD_ISWRITABLE)) {
2137 dvmLinearReadWrite(meth->clazz->classLoader, methodDexCode);
2138 return;
2139 }
2140
2141 assert(!dvmIsNativeMethod(meth) && !dvmIsAbstractMethod(meth));
2142
2143 size_t dexCodeSize = dexGetDexCodeSize(methodDexCode);
2144 LOGD("Making a copy of %s.%s code (%d bytes)\n",
2145 meth->clazz->descriptor, meth->name, dexCodeSize);
2146
2147 DexCode* newCode =
2148 (DexCode*) dvmLinearAlloc(meth->clazz->classLoader, dexCodeSize);
2149 memcpy(newCode, methodDexCode, dexCodeSize);
2150
2151 meth->insns = newCode->insns;
2152 SET_METHOD_FLAG(meth, METHOD_ISWRITABLE);
2153}
2154
2155/*
2156 * Mark the bytecode read-only.
2157 *
2158 * If the contents of the DexCode haven't actually changed, we could revert
2159 * to the original shared page.
2160 */
2161void dvmMakeCodeReadOnly(Method* meth)
2162{
2163 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2164 LOGV("+++ marking %p read-only\n", methodDexCode);
2165 dvmLinearReadOnly(meth->clazz->classLoader, methodDexCode);
2166}
2167
2168
2169/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002170 * jniArgInfo (32-bit int) layout:
2171 * SRRRHHHH HHHHHHHH HHHHHHHH HHHHHHHH
2172 *
2173 * S - if set, do things the hard way (scan the signature)
2174 * R - return-type enumeration
2175 * H - target-specific hints
2176 *
2177 * This info is used at invocation time by dvmPlatformInvoke. In most
2178 * cases, the target-specific hints allow dvmPlatformInvoke to avoid
2179 * having to fully parse the signature.
2180 *
2181 * The return-type bits are always set, even if target-specific hint bits
2182 * are unavailable.
2183 */
2184static int computeJniArgInfo(const DexProto* proto)
2185{
2186 const char* sig = dexProtoGetShorty(proto);
2187 int returnType, padFlags, jniArgInfo;
2188 char sigByte;
2189 int stackOffset, padMask;
2190 u4 hints;
2191
2192 /* The first shorty character is the return type. */
2193 switch (*(sig++)) {
2194 case 'V':
2195 returnType = DALVIK_JNI_RETURN_VOID;
2196 break;
2197 case 'F':
2198 returnType = DALVIK_JNI_RETURN_FLOAT;
2199 break;
2200 case 'D':
2201 returnType = DALVIK_JNI_RETURN_DOUBLE;
2202 break;
2203 case 'J':
2204 returnType = DALVIK_JNI_RETURN_S8;
2205 break;
Bill Buzbeee2557512009-07-27 15:51:54 -07002206 case 'Z':
2207 case 'B':
2208 returnType = DALVIK_JNI_RETURN_S1;
2209 break;
2210 case 'C':
2211 returnType = DALVIK_JNI_RETURN_U2;
2212 break;
2213 case 'S':
2214 returnType = DALVIK_JNI_RETURN_S2;
2215 break;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002216 default:
2217 returnType = DALVIK_JNI_RETURN_S4;
2218 break;
2219 }
2220
2221 jniArgInfo = returnType << DALVIK_JNI_RETURN_SHIFT;
2222
2223 hints = dvmPlatformInvokeHints(proto);
2224
2225 if (hints & DALVIK_JNI_NO_ARG_INFO) {
2226 jniArgInfo |= DALVIK_JNI_NO_ARG_INFO;
2227 } else {
2228 assert((hints & DALVIK_JNI_RETURN_MASK) == 0);
2229 jniArgInfo |= hints;
2230 }
2231
2232 return jniArgInfo;
2233}
2234
2235/*
2236 * Load information about a static field.
2237 *
2238 * This also "prepares" static fields by initializing them
2239 * to their "standard default values".
2240 */
2241static void loadSFieldFromDex(ClassObject* clazz,
2242 const DexField* pDexSField, StaticField* sfield)
2243{
2244 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2245 const DexFieldId* pFieldId;
2246
2247 pFieldId = dexGetFieldId(pDexFile, pDexSField->fieldIdx);
2248
2249 sfield->field.clazz = clazz;
2250 sfield->field.name = dexStringById(pDexFile, pFieldId->nameIdx);
2251 sfield->field.signature = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx);
2252 sfield->field.accessFlags = pDexSField->accessFlags;
2253
2254 /* Static object field values are set to "standard default values"
2255 * (null or 0) until the class is initialized. We delay loading
2256 * constant values from the class until that time.
2257 */
2258 //sfield->value.j = 0;
2259 assert(sfield->value.j == 0LL); // cleared earlier with calloc
2260
2261#ifdef PROFILE_FIELD_ACCESS
2262 sfield->field.gets = sfield->field.puts = 0;
2263#endif
2264}
2265
2266/*
2267 * Load information about an instance field.
2268 */
2269static void loadIFieldFromDex(ClassObject* clazz,
2270 const DexField* pDexIField, InstField* ifield)
2271{
2272 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2273 const DexFieldId* pFieldId;
2274
2275 pFieldId = dexGetFieldId(pDexFile, pDexIField->fieldIdx);
2276
2277 ifield->field.clazz = clazz;
2278 ifield->field.name = dexStringById(pDexFile, pFieldId->nameIdx);
2279 ifield->field.signature = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx);
2280 ifield->field.accessFlags = pDexIField->accessFlags;
2281#ifndef NDEBUG
2282 assert(ifield->byteOffset == 0); // cleared earlier with calloc
2283 ifield->byteOffset = -1; // make it obvious if we fail to set later
2284#endif
2285
2286#ifdef PROFILE_FIELD_ACCESS
2287 ifield->field.gets = ifield->field.puts = 0;
2288#endif
2289}
2290
2291/*
2292 * Cache java.lang.ref.Reference fields and methods.
2293 */
Barry Hayes6daaac12009-07-08 10:01:56 -07002294static bool precacheReferenceOffsets(ClassObject* clazz)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002295{
2296 Method *meth;
2297 int i;
2298
2299 /* We trick the GC object scanner by not counting
2300 * java.lang.ref.Reference.referent as an object
2301 * field. It will get explicitly scanned as part
2302 * of the reference-walking process.
2303 *
2304 * Find the object field named "referent" and put it
2305 * just after the list of object reference fields.
2306 */
2307 dvmLinearReadWrite(clazz->classLoader, clazz->ifields);
2308 for (i = 0; i < clazz->ifieldRefCount; i++) {
2309 InstField *pField = &clazz->ifields[i];
2310 if (strcmp(pField->field.name, "referent") == 0) {
2311 int targetIndex;
2312
2313 /* Swap this field with the last object field.
2314 */
2315 targetIndex = clazz->ifieldRefCount - 1;
2316 if (i != targetIndex) {
2317 InstField *swapField = &clazz->ifields[targetIndex];
2318 InstField tmpField;
2319 int tmpByteOffset;
2320
2321 /* It's not currently strictly necessary
2322 * for the fields to be in byteOffset order,
2323 * but it's more predictable that way.
2324 */
2325 tmpByteOffset = swapField->byteOffset;
2326 swapField->byteOffset = pField->byteOffset;
2327 pField->byteOffset = tmpByteOffset;
2328
2329 tmpField = *swapField;
2330 *swapField = *pField;
2331 *pField = tmpField;
2332 }
2333
2334 /* One fewer object field (wink wink).
2335 */
2336 clazz->ifieldRefCount--;
2337 i--; /* don't trip "didn't find it" test if field was last */
2338 break;
2339 }
2340 }
2341 dvmLinearReadOnly(clazz->classLoader, clazz->ifields);
2342 if (i == clazz->ifieldRefCount) {
2343 LOGE("Unable to reorder 'referent' in %s\n", clazz->descriptor);
2344 return false;
2345 }
2346
2347 /* Cache pretty much everything about Reference so that
2348 * we don't need to call interpreted code when clearing/enqueueing
2349 * references. This is fragile, so we'll be paranoid.
2350 */
2351 gDvm.classJavaLangRefReference = clazz;
2352
2353 gDvm.offJavaLangRefReference_referent =
2354 dvmFindFieldOffset(gDvm.classJavaLangRefReference,
2355 "referent", "Ljava/lang/Object;");
2356 assert(gDvm.offJavaLangRefReference_referent >= 0);
2357
2358 gDvm.offJavaLangRefReference_queue =
2359 dvmFindFieldOffset(gDvm.classJavaLangRefReference,
2360 "queue", "Ljava/lang/ref/ReferenceQueue;");
2361 assert(gDvm.offJavaLangRefReference_queue >= 0);
2362
2363 gDvm.offJavaLangRefReference_queueNext =
2364 dvmFindFieldOffset(gDvm.classJavaLangRefReference,
2365 "queueNext", "Ljava/lang/ref/Reference;");
2366 assert(gDvm.offJavaLangRefReference_queueNext >= 0);
2367
2368 gDvm.offJavaLangRefReference_vmData =
2369 dvmFindFieldOffset(gDvm.classJavaLangRefReference,
2370 "vmData", "I");
2371 assert(gDvm.offJavaLangRefReference_vmData >= 0);
2372
2373#if FANCY_REFERENCE_SUBCLASS
2374 meth = dvmFindVirtualMethodByDescriptor(clazz, "clear", "()V");
2375 assert(meth != NULL);
2376 gDvm.voffJavaLangRefReference_clear = meth->methodIndex;
2377
2378 meth = dvmFindVirtualMethodByDescriptor(clazz, "enqueue", "()Z");
2379 assert(meth != NULL);
2380 gDvm.voffJavaLangRefReference_enqueue = meth->methodIndex;
2381#else
2382 /* enqueueInternal() is private and thus a direct method. */
2383 meth = dvmFindDirectMethodByDescriptor(clazz, "enqueueInternal", "()Z");
2384 assert(meth != NULL);
2385 gDvm.methJavaLangRefReference_enqueueInternal = meth;
2386#endif
2387
2388 return true;
2389}
2390
2391
2392/*
Barry Hayes6daaac12009-07-08 10:01:56 -07002393 * Set the bitmap of reference offsets, refOffsets, from the ifields
2394 * list.
2395 */
2396static void computeRefOffsets(ClassObject* clazz)
2397{
2398 if (clazz->super != NULL) {
2399 clazz->refOffsets = clazz->super->refOffsets;
2400 } else {
2401 clazz->refOffsets = 0;
2402 }
2403 /*
2404 * If our superclass overflowed, we don't stand a chance.
2405 */
2406 if (clazz->refOffsets != CLASS_WALK_SUPER) {
2407 InstField *f;
2408 int i;
2409
2410 /* All of the fields that contain object references
2411 * are guaranteed to be at the beginning of the ifields list.
2412 */
2413 f = clazz->ifields;
2414 const int ifieldRefCount = clazz->ifieldRefCount;
2415 for (i = 0; i < ifieldRefCount; i++) {
2416 /*
2417 * Note that, per the comment on struct InstField,
2418 * f->byteOffset is the offset from the beginning of
2419 * obj, not the offset into obj->instanceData.
2420 */
Andy McFadden2fbe6d12009-09-04 15:38:13 -07002421 assert(f->byteOffset >= (int) CLASS_SMALLEST_OFFSET);
Barry Hayes6daaac12009-07-08 10:01:56 -07002422 assert((f->byteOffset & (CLASS_OFFSET_ALIGNMENT - 1)) == 0);
2423 if (CLASS_CAN_ENCODE_OFFSET(f->byteOffset)) {
2424 u4 newBit = CLASS_BIT_FROM_OFFSET(f->byteOffset);
2425 assert(newBit != 0);
2426 clazz->refOffsets |= newBit;
2427 } else {
2428 clazz->refOffsets = CLASS_WALK_SUPER;
2429 break;
2430 }
2431 f++;
2432 }
2433 }
2434}
2435
2436
2437/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002438 * Link (prepare and resolve). Verification is deferred until later.
2439 *
2440 * This converts symbolic references into pointers. It's independent of
2441 * the source file format.
2442 *
2443 * If "classesResolved" is false, we assume that superclassIdx and
2444 * interfaces[] are holding class reference indices rather than pointers.
2445 * The class references will be resolved during link. (This is done when
2446 * loading from DEX to avoid having to create additional storage to pass
2447 * the indices around.)
2448 *
2449 * Returns "false" with an exception pending on failure.
2450 */
2451bool dvmLinkClass(ClassObject* clazz, bool classesResolved)
2452{
2453 u4 superclassIdx = 0;
2454 bool okay = false;
2455 bool resolve_okay;
2456 int numInterfacesResolved = 0;
2457 int i;
2458
2459 if (gDvm.verboseClass)
2460 LOGV("CLASS: linking '%s'...\n", clazz->descriptor);
2461
2462 /* "Resolve" the class.
2463 *
2464 * At this point, clazz's reference fields contain Dex
2465 * file indices instead of direct object references.
2466 * We need to translate those indices into real references,
2467 * while making sure that the GC doesn't sweep any of
2468 * the referenced objects.
2469 *
2470 * The GC will avoid scanning this object as long as
2471 * clazz->obj.clazz is gDvm.unlinkedJavaLangClass.
2472 * Once clazz is ready, we'll replace clazz->obj.clazz
2473 * with gDvm.classJavaLangClass to let the GC know
2474 * to look at it.
2475 */
2476 assert(clazz->obj.clazz == gDvm.unlinkedJavaLangClass);
2477
2478 /* It's important that we take care of java.lang.Class
2479 * first. If we were to do this after looking up the
2480 * superclass (below), Class wouldn't be ready when
2481 * java.lang.Object needed it.
2482 *
2483 * Note that we don't set clazz->obj.clazz yet.
2484 */
2485 if (gDvm.classJavaLangClass == NULL) {
2486 if (clazz->classLoader == NULL &&
2487 strcmp(clazz->descriptor, "Ljava/lang/Class;") == 0)
2488 {
2489 gDvm.classJavaLangClass = clazz;
2490 } else {
2491 gDvm.classJavaLangClass =
2492 dvmFindSystemClassNoInit("Ljava/lang/Class;");
2493 if (gDvm.classJavaLangClass == NULL) {
2494 /* should have thrown one */
2495 assert(dvmCheckException(dvmThreadSelf()));
2496 goto bail;
2497 }
2498 }
2499 }
2500 assert(gDvm.classJavaLangClass != NULL);
2501
2502 /*
2503 * Resolve all Dex indices so we can hand the ClassObject
2504 * over to the GC. If we fail at any point, we need to remove
2505 * any tracked references to avoid leaking memory.
2506 */
2507
2508 /*
2509 * All classes have a direct superclass, except for java/lang/Object.
2510 */
2511 if (!classesResolved) {
2512 superclassIdx = (u4) clazz->super; /* unpack temp store */
2513 clazz->super = NULL;
2514 }
2515 if (strcmp(clazz->descriptor, "Ljava/lang/Object;") == 0) {
2516 assert(!classesResolved);
2517 if (superclassIdx != kDexNoIndex) {
2518 /* TODO: is this invariant true for all java/lang/Objects,
2519 * regardless of the class loader? For now, assume it is.
2520 */
2521 dvmThrowException("Ljava/lang/ClassFormatError;",
2522 "java.lang.Object has a superclass");
2523 goto bail;
2524 }
2525
2526 /* Don't finalize objects whose classes use the
2527 * default (empty) Object.finalize().
2528 */
2529 CLEAR_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2530 } else {
2531 if (!classesResolved) {
2532 if (superclassIdx == kDexNoIndex) {
2533 dvmThrowException("Ljava/lang/LinkageError;",
2534 "no superclass defined");
2535 goto bail;
2536 }
2537 clazz->super = dvmResolveClass(clazz, superclassIdx, false);
2538 if (clazz->super == NULL) {
2539 assert(dvmCheckException(dvmThreadSelf()));
2540 if (gDvm.optimizing) {
2541 /* happens with "external" libs */
2542 LOGV("Unable to resolve superclass of %s (%d)\n",
2543 clazz->descriptor, superclassIdx);
2544 } else {
2545 LOGW("Unable to resolve superclass of %s (%d)\n",
2546 clazz->descriptor, superclassIdx);
2547 }
2548 goto bail;
2549 }
2550 }
2551 /* verify */
2552 if (dvmIsFinalClass(clazz->super)) {
2553 LOGW("Superclass of '%s' is final '%s'\n",
2554 clazz->descriptor, clazz->super->descriptor);
2555 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;",
2556 "superclass is final");
2557 goto bail;
2558 } else if (dvmIsInterfaceClass(clazz->super)) {
2559 LOGW("Superclass of '%s' is interface '%s'\n",
2560 clazz->descriptor, clazz->super->descriptor);
2561 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;",
2562 "superclass is an interface");
2563 goto bail;
2564 } else if (!dvmCheckClassAccess(clazz, clazz->super)) {
2565 LOGW("Superclass of '%s' (%s) is not accessible\n",
2566 clazz->descriptor, clazz->super->descriptor);
2567 dvmThrowException("Ljava/lang/IllegalAccessError;",
2568 "superclass not accessible");
2569 goto bail;
2570 }
2571
2572 /* Don't let the GC reclaim the superclass.
2573 * TODO: shouldn't be needed; remove when things stabilize
2574 */
2575 dvmAddTrackedAlloc((Object *)clazz->super, NULL);
2576
2577 /* Inherit finalizability from the superclass. If this
2578 * class also overrides finalize(), its CLASS_ISFINALIZABLE
2579 * bit will already be set.
2580 */
2581 if (IS_CLASS_FLAG_SET(clazz->super, CLASS_ISFINALIZABLE)) {
2582 SET_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2583 }
2584
2585 /* See if this class descends from java.lang.Reference
2586 * and set the class flags appropriately.
2587 */
2588 if (IS_CLASS_FLAG_SET(clazz->super, CLASS_ISREFERENCE)) {
2589 u4 superRefFlags;
2590
2591 /* We've already determined the reference type of this
2592 * inheritance chain. Inherit reference-ness from the superclass.
2593 */
2594 superRefFlags = GET_CLASS_FLAG_GROUP(clazz->super,
2595 CLASS_ISREFERENCE |
2596 CLASS_ISWEAKREFERENCE |
2597 CLASS_ISPHANTOMREFERENCE);
2598 SET_CLASS_FLAG(clazz, superRefFlags);
2599 } else if (clazz->classLoader == NULL &&
2600 clazz->super->classLoader == NULL &&
2601 strcmp(clazz->super->descriptor,
2602 "Ljava/lang/ref/Reference;") == 0)
2603 {
2604 u4 refFlags;
2605
2606 /* This class extends Reference, which means it should
2607 * be one of the magic Soft/Weak/PhantomReference classes.
2608 */
2609 refFlags = CLASS_ISREFERENCE;
2610 if (strcmp(clazz->descriptor,
2611 "Ljava/lang/ref/SoftReference;") == 0)
2612 {
2613 /* Only CLASS_ISREFERENCE is set for soft references.
2614 */
2615 } else if (strcmp(clazz->descriptor,
2616 "Ljava/lang/ref/WeakReference;") == 0)
2617 {
2618 refFlags |= CLASS_ISWEAKREFERENCE;
2619 } else if (strcmp(clazz->descriptor,
2620 "Ljava/lang/ref/PhantomReference;") == 0)
2621 {
2622 refFlags |= CLASS_ISPHANTOMREFERENCE;
2623 } else {
2624 /* No-one else is allowed to inherit directly
2625 * from Reference.
2626 */
2627//xxx is this the right exception? better than an assertion.
2628 dvmThrowException("Ljava/lang/LinkageError;",
2629 "illegal inheritance from Reference");
2630 goto bail;
2631 }
2632
2633 /* The class should not have any reference bits set yet.
2634 */
2635 assert(GET_CLASS_FLAG_GROUP(clazz,
2636 CLASS_ISREFERENCE |
2637 CLASS_ISWEAKREFERENCE |
2638 CLASS_ISPHANTOMREFERENCE) == 0);
2639
2640 SET_CLASS_FLAG(clazz, refFlags);
2641 }
2642 }
2643
2644 if (!classesResolved && clazz->interfaceCount > 0) {
2645 /*
2646 * Resolve the interfaces implemented directly by this class. We
2647 * stuffed the class index into the interface pointer slot.
2648 */
2649 dvmLinearReadWrite(clazz->classLoader, clazz->interfaces);
2650 for (i = 0; i < clazz->interfaceCount; i++) {
2651 u4 interfaceIdx;
2652
2653 interfaceIdx = (u4) clazz->interfaces[i]; /* unpack temp store */
2654 assert(interfaceIdx != kDexNoIndex);
2655
2656 clazz->interfaces[i] = dvmResolveClass(clazz, interfaceIdx, false);
2657 if (clazz->interfaces[i] == NULL) {
2658 const DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2659
2660 assert(dvmCheckException(dvmThreadSelf()));
2661 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2662
2663 const char* classDescriptor;
2664 classDescriptor = dexStringByTypeIdx(pDexFile, interfaceIdx);
2665 if (gDvm.optimizing) {
2666 /* happens with "external" libs */
2667 LOGV("Failed resolving %s interface %d '%s'\n",
2668 clazz->descriptor, interfaceIdx, classDescriptor);
2669 } else {
2670 LOGI("Failed resolving %s interface %d '%s'\n",
2671 clazz->descriptor, interfaceIdx, classDescriptor);
2672 }
2673 goto bail_during_resolve;
2674 }
2675
2676 /* are we allowed to implement this interface? */
2677 if (!dvmCheckClassAccess(clazz, clazz->interfaces[i])) {
2678 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2679 LOGW("Interface '%s' is not accessible to '%s'\n",
2680 clazz->interfaces[i]->descriptor, clazz->descriptor);
2681 dvmThrowException("Ljava/lang/IllegalAccessError;",
2682 "interface not accessible");
2683 goto bail_during_resolve;
2684 }
2685
2686 /* Don't let the GC reclaim the interface class.
2687 * TODO: shouldn't be needed; remove when things stabilize
2688 */
2689 dvmAddTrackedAlloc((Object *)clazz->interfaces[i], NULL);
2690 numInterfacesResolved++;
2691
2692 LOGVV("+++ found interface '%s'\n",
2693 clazz->interfaces[i]->descriptor);
2694 }
2695 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2696 }
2697
2698 /*
2699 * The ClassObject is now in a GC-able state. We let the GC
2700 * realize this by punching in the real class type, which is
2701 * always java.lang.Class.
2702 *
2703 * After this line, clazz will be fair game for the GC.
2704 * Every field that the GC will look at must now be valid:
2705 * - clazz->super
2706 * - class->classLoader
2707 * - clazz->sfields
2708 * - clazz->interfaces
2709 */
2710 clazz->obj.clazz = gDvm.classJavaLangClass;
2711
2712 if (false) {
2713bail_during_resolve:
2714 resolve_okay = false;
2715 } else {
2716 resolve_okay = true;
2717 }
2718
2719 /*
2720 * Now that the GC can scan the ClassObject, we can let
2721 * go of the explicit references we were holding onto.
2722 *
2723 * Either that or we failed, in which case we need to
2724 * release the references so we don't leak memory.
2725 */
2726 if (clazz->super != NULL) {
2727 dvmReleaseTrackedAlloc((Object *)clazz->super, NULL);
2728 }
2729 for (i = 0; i < numInterfacesResolved; i++) {
2730 dvmReleaseTrackedAlloc((Object *)clazz->interfaces[i], NULL);
2731 }
2732
2733 if (!resolve_okay) {
2734 //LOGW("resolve_okay is false\n");
2735 goto bail;
2736 }
2737
2738 /*
2739 * Populate vtable.
2740 */
2741 if (dvmIsInterfaceClass(clazz)) {
2742 /* no vtable; just set the method indices */
2743 int count = clazz->virtualMethodCount;
2744
2745 if (count != (u2) count) {
2746 LOGE("Too many methods (%d) in interface '%s'\n", count,
2747 clazz->descriptor);
2748 goto bail;
2749 }
2750
2751 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
2752
2753 for (i = 0; i < count; i++)
2754 clazz->virtualMethods[i].methodIndex = (u2) i;
2755
2756 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
2757 } else {
2758 if (!createVtable(clazz)) {
2759 LOGW("failed creating vtable\n");
2760 goto bail;
2761 }
2762 }
2763
2764 /*
2765 * Populate interface method tables. Can alter the vtable.
2766 */
2767 if (!createIftable(clazz))
2768 goto bail;
2769
2770 /*
2771 * Insert special-purpose "stub" method implementations.
2772 */
2773 if (!insertMethodStubs(clazz))
2774 goto bail;
2775
2776 /*
2777 * Compute instance field offsets and, hence, the size of the object.
2778 */
2779 if (!computeFieldOffsets(clazz))
2780 goto bail;
2781
2782 /*
2783 * Cache fields and methods from java/lang/ref/Reference and
2784 * java/lang/Class. This has to happen after computeFieldOffsets().
2785 */
2786 if (clazz->classLoader == NULL) {
2787 if (strcmp(clazz->descriptor, "Ljava/lang/ref/Reference;") == 0) {
2788 if (!precacheReferenceOffsets(clazz)) {
2789 LOGE("failed pre-caching Reference offsets\n");
2790 dvmThrowException("Ljava/lang/InternalError;", NULL);
2791 goto bail;
2792 }
2793 } else if (clazz == gDvm.classJavaLangClass) {
2794 gDvm.offJavaLangClass_pd = dvmFindFieldOffset(clazz, "pd",
2795 "Ljava/security/ProtectionDomain;");
2796 if (gDvm.offJavaLangClass_pd <= 0) {
2797 LOGE("ERROR: unable to find 'pd' field in Class\n");
2798 dvmAbort(); /* we're not going to get much farther */
2799 //goto bail;
2800 }
2801 }
2802 }
2803
2804 /*
Barry Hayes6daaac12009-07-08 10:01:56 -07002805 * Compact the offsets the GC has to examine into a bitmap, if
2806 * possible. (This has to happen after Reference.referent is
2807 * massaged in precacheReferenceOffsets.)
2808 */
2809 computeRefOffsets(clazz);
2810
2811 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002812 * Done!
2813 */
2814 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISPREVERIFIED))
2815 clazz->status = CLASS_VERIFIED;
2816 else
2817 clazz->status = CLASS_RESOLVED;
2818 okay = true;
2819 if (gDvm.verboseClass)
2820 LOGV("CLASS: linked '%s'\n", clazz->descriptor);
2821
2822 /*
2823 * We send CLASS_PREPARE events to the debugger from here. The
2824 * definition of "preparation" is creating the static fields for a
2825 * class and initializing them to the standard default values, but not
2826 * executing any code (that comes later, during "initialization").
2827 *
2828 * We did the static prep in loadSFieldFromDex() while loading the class.
2829 *
2830 * The class has been prepared and resolved but possibly not yet verified
2831 * at this point.
2832 */
2833 if (gDvm.debuggerActive) {
2834 dvmDbgPostClassPrepare(clazz);
2835 }
2836
2837bail:
2838 if (!okay) {
2839 clazz->status = CLASS_ERROR;
2840 if (!dvmCheckException(dvmThreadSelf())) {
2841 dvmThrowException("Ljava/lang/VirtualMachineError;", NULL);
2842 }
2843 }
2844 return okay;
2845}
2846
2847/*
2848 * Create the virtual method table.
2849 *
2850 * The top part of the table is a copy of the table from our superclass,
2851 * with our local methods overriding theirs. The bottom part of the table
2852 * has any new methods we defined.
2853 */
2854static bool createVtable(ClassObject* clazz)
2855{
2856 bool result = false;
2857 int maxCount;
2858 int i;
2859
2860 if (clazz->super != NULL) {
2861 //LOGI("SUPER METHODS %d %s->%s\n", clazz->super->vtableCount,
2862 // clazz->descriptor, clazz->super->descriptor);
2863 }
2864
2865 /* the virtual methods we define, plus the superclass vtable size */
2866 maxCount = clazz->virtualMethodCount;
2867 if (clazz->super != NULL) {
2868 maxCount += clazz->super->vtableCount;
2869 } else {
2870 /* TODO: is this invariant true for all java/lang/Objects,
2871 * regardless of the class loader? For now, assume it is.
2872 */
2873 assert(strcmp(clazz->descriptor, "Ljava/lang/Object;") == 0);
2874 }
2875 //LOGD("+++ max vmethods for '%s' is %d\n", clazz->descriptor, maxCount);
2876
2877 /*
2878 * Over-allocate the table, then realloc it down if necessary. So
2879 * long as we don't allocate anything in between we won't cause
2880 * fragmentation, and reducing the size should be unlikely to cause
2881 * a buffer copy.
2882 */
2883 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
2884 clazz->vtable = (Method**) dvmLinearAlloc(clazz->classLoader,
2885 sizeof(Method*) * maxCount);
2886 if (clazz->vtable == NULL)
2887 goto bail;
2888
2889 if (clazz->super != NULL) {
2890 int actualCount;
2891
2892 memcpy(clazz->vtable, clazz->super->vtable,
2893 sizeof(*(clazz->vtable)) * clazz->super->vtableCount);
2894 actualCount = clazz->super->vtableCount;
2895
2896 /*
2897 * See if any of our virtual methods override the superclass.
2898 */
2899 for (i = 0; i < clazz->virtualMethodCount; i++) {
2900 Method* localMeth = &clazz->virtualMethods[i];
2901 int si;
2902
2903 for (si = 0; si < clazz->super->vtableCount; si++) {
2904 Method* superMeth = clazz->vtable[si];
2905
2906 if (dvmCompareMethodNamesAndProtos(localMeth, superMeth) == 0)
2907 {
2908 /* verify */
2909 if (dvmIsFinalMethod(superMeth)) {
2910 LOGW("Method %s.%s overrides final %s.%s\n",
2911 localMeth->clazz->descriptor, localMeth->name,
2912 superMeth->clazz->descriptor, superMeth->name);
2913 goto bail;
2914 }
2915 clazz->vtable[si] = localMeth;
2916 localMeth->methodIndex = (u2) si;
2917 //LOGV("+++ override %s.%s (slot %d)\n",
2918 // clazz->descriptor, localMeth->name, si);
2919 break;
2920 }
2921 }
2922
2923 if (si == clazz->super->vtableCount) {
2924 /* not an override, add to end */
2925 clazz->vtable[actualCount] = localMeth;
2926 localMeth->methodIndex = (u2) actualCount;
2927 actualCount++;
2928
2929 //LOGV("+++ add method %s.%s\n",
2930 // clazz->descriptor, localMeth->name);
2931 }
2932 }
2933
2934 if (actualCount != (u2) actualCount) {
2935 LOGE("Too many methods (%d) in class '%s'\n", actualCount,
2936 clazz->descriptor);
2937 goto bail;
2938 }
2939
2940 assert(actualCount <= maxCount);
2941
2942 if (actualCount < maxCount) {
2943 assert(clazz->vtable != NULL);
2944 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
2945 clazz->vtable = dvmLinearRealloc(clazz->classLoader, clazz->vtable,
2946 sizeof(*(clazz->vtable)) * actualCount);
2947 if (clazz->vtable == NULL) {
2948 LOGE("vtable realloc failed\n");
2949 goto bail;
2950 } else {
2951 LOGVV("+++ reduced vtable from %d to %d\n",
2952 maxCount, actualCount);
2953 }
2954 }
2955
2956 clazz->vtableCount = actualCount;
2957 } else {
2958 /* java/lang/Object case */
2959 int count = clazz->virtualMethodCount;
2960 if (count != (u2) count) {
2961 LOGE("Too many methods (%d) in base class '%s'\n", count,
2962 clazz->descriptor);
2963 goto bail;
2964 }
2965
2966 for (i = 0; i < count; i++) {
2967 clazz->vtable[i] = &clazz->virtualMethods[i];
2968 clazz->virtualMethods[i].methodIndex = (u2) i;
2969 }
2970 clazz->vtableCount = clazz->virtualMethodCount;
2971 }
2972
2973 result = true;
2974
2975bail:
2976 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
2977 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
2978 return result;
2979}
2980
2981/*
2982 * Create and populate "iftable".
2983 *
2984 * The set of interfaces we support is the combination of the interfaces
2985 * we implement directly and those implemented by our superclass. Each
2986 * interface can have one or more "superinterfaces", which we must also
2987 * support. For speed we flatten the tree out.
2988 *
2989 * We might be able to speed this up when there are lots of interfaces
2990 * by merge-sorting the class pointers and binary-searching when removing
2991 * duplicates. We could also drop the duplicate removal -- it's only
2992 * there to reduce the memory footprint.
2993 *
2994 * Because of "Miranda methods", this may reallocate clazz->virtualMethods.
2995 *
2996 * Returns "true" on success.
2997 */
2998static bool createIftable(ClassObject* clazz)
2999{
3000 bool result = false;
3001 bool zapIftable = false;
3002 bool zapVtable = false;
3003 bool zapIfvipool = false;
3004 int ifCount, superIfCount, idx;
3005 int i;
3006
3007 if (clazz->super != NULL)
3008 superIfCount = clazz->super->iftableCount;
3009 else
3010 superIfCount = 0;
3011
3012 ifCount = superIfCount;
3013 ifCount += clazz->interfaceCount;
3014 for (i = 0; i < clazz->interfaceCount; i++)
3015 ifCount += clazz->interfaces[i]->iftableCount;
3016
3017 LOGVV("INTF: class '%s' direct w/supra=%d super=%d total=%d\n",
3018 clazz->descriptor, ifCount - superIfCount, superIfCount, ifCount);
3019
3020 if (ifCount == 0) {
3021 assert(clazz->iftableCount == 0);
3022 assert(clazz->iftable == NULL);
3023 result = true;
3024 goto bail;
3025 }
3026
3027 /*
3028 * Create a table with enough space for all interfaces, and copy the
3029 * superclass' table in.
3030 */
3031 clazz->iftable = (InterfaceEntry*) dvmLinearAlloc(clazz->classLoader,
3032 sizeof(InterfaceEntry) * ifCount);
3033 zapIftable = true;
3034 memset(clazz->iftable, 0x00, sizeof(InterfaceEntry) * ifCount);
3035 if (superIfCount != 0) {
3036 memcpy(clazz->iftable, clazz->super->iftable,
3037 sizeof(InterfaceEntry) * superIfCount);
3038 }
3039
3040 /*
3041 * Create a flattened interface hierarchy of our immediate interfaces.
3042 */
3043 idx = superIfCount;
3044
3045 for (i = 0; i < clazz->interfaceCount; i++) {
3046 ClassObject* interf;
3047 int j;
3048
3049 interf = clazz->interfaces[i];
3050 assert(interf != NULL);
3051
3052 /* make sure this is still an interface class */
3053 if (!dvmIsInterfaceClass(interf)) {
3054 LOGW("Class '%s' implements non-interface '%s'\n",
3055 clazz->descriptor, interf->descriptor);
3056 dvmThrowExceptionWithClassMessage(
3057 "Ljava/lang/IncompatibleClassChangeError;",
3058 clazz->descriptor);
3059 goto bail;
3060 }
3061
3062 /* add entry for this interface */
3063 clazz->iftable[idx++].clazz = interf;
3064
3065 /* add entries for the interface's superinterfaces */
3066 for (j = 0; j < interf->iftableCount; j++) {
3067 clazz->iftable[idx++].clazz = interf->iftable[j].clazz;
3068 }
3069 }
3070
3071 assert(idx == ifCount);
3072
3073 if (false) {
3074 /*
3075 * Remove anything redundant from our recent additions. Note we have
3076 * to traverse the recent adds when looking for duplicates, because
3077 * it's possible the recent additions are self-redundant. This
3078 * reduces the memory footprint of classes with lots of inherited
3079 * interfaces.
3080 *
3081 * (I don't know if this will cause problems later on when we're trying
3082 * to find a static field. It looks like the proper search order is
3083 * (1) current class, (2) interfaces implemented by current class,
3084 * (3) repeat with superclass. A field implemented by an interface
3085 * and by a superclass might come out wrong if the superclass also
3086 * implements the interface. The javac compiler will reject the
3087 * situation as ambiguous, so the concern is somewhat artificial.)
3088 *
3089 * UPDATE: this makes ReferenceType.Interfaces difficult to implement,
3090 * because it wants to return just the interfaces declared to be
3091 * implemented directly by the class. I'm excluding this code for now.
3092 */
3093 for (i = superIfCount; i < ifCount; i++) {
3094 int j;
3095
3096 for (j = 0; j < ifCount; j++) {
3097 if (i == j)
3098 continue;
3099 if (clazz->iftable[i].clazz == clazz->iftable[j].clazz) {
3100 LOGVV("INTF: redundant interface %s in %s\n",
3101 clazz->iftable[i].clazz->descriptor,
3102 clazz->descriptor);
3103
3104 if (i != ifCount-1)
3105 memmove(&clazz->iftable[i], &clazz->iftable[i+1],
3106 (ifCount - i -1) * sizeof(InterfaceEntry));
3107 ifCount--;
3108 i--; // adjust for i++ above
3109 break;
3110 }
3111 }
3112 }
3113 LOGVV("INTF: class '%s' nodupes=%d\n", clazz->descriptor, ifCount);
3114 } // if (false)
3115
3116 clazz->iftableCount = ifCount;
3117
3118 /*
3119 * If we're an interface, we don't need the vtable pointers, so
3120 * we're done. If this class doesn't implement an interface that our
3121 * superclass doesn't have, then we again have nothing to do.
3122 */
3123 if (dvmIsInterfaceClass(clazz) || superIfCount == ifCount) {
3124 //dvmDumpClass(clazz, kDumpClassFullDetail);
3125 result = true;
3126 goto bail;
3127 }
3128
3129 /*
3130 * When we're handling invokeinterface, we probably have an object
3131 * whose type is an interface class rather than a concrete class. We
3132 * need to convert the method reference into a vtable index. So, for
3133 * every entry in "iftable", we create a list of vtable indices.
3134 *
3135 * Because our vtable encompasses the superclass vtable, we can use
3136 * the vtable indices from our superclass for all of the interfaces
3137 * that weren't directly implemented by us.
3138 *
3139 * Each entry in "iftable" has a pointer to the start of its set of
3140 * vtable offsets. The iftable entries in the superclass point to
3141 * storage allocated in the superclass, and the iftable entries added
3142 * for this class point to storage allocated in this class. "iftable"
3143 * is flat for fast access in a class and all of its subclasses, but
3144 * "ifviPool" is only created for the topmost implementor.
3145 */
3146 int poolSize = 0;
3147 for (i = superIfCount; i < ifCount; i++) {
3148 /*
3149 * Note it's valid for an interface to have no methods (e.g.
3150 * java/io/Serializable).
3151 */
3152 LOGVV("INTF: pool: %d from %s\n",
3153 clazz->iftable[i].clazz->virtualMethodCount,
3154 clazz->iftable[i].clazz->descriptor);
3155 poolSize += clazz->iftable[i].clazz->virtualMethodCount;
3156 }
3157
3158 if (poolSize == 0) {
3159 LOGVV("INTF: didn't find any new interfaces with methods\n");
3160 result = true;
3161 goto bail;
3162 }
3163
3164 clazz->ifviPoolCount = poolSize;
3165 clazz->ifviPool = (int*) dvmLinearAlloc(clazz->classLoader,
3166 poolSize * sizeof(int*));
3167 zapIfvipool = true;
3168
3169 /*
3170 * Fill in the vtable offsets for the interfaces that weren't part of
3171 * our superclass.
3172 */
3173 int poolOffset = 0;
3174 Method** mirandaList = NULL;
3175 int mirandaCount = 0, mirandaAlloc = 0;
3176
3177 for (i = superIfCount; i < ifCount; i++) {
3178 ClassObject* interface;
3179 int methIdx;
3180
3181 clazz->iftable[i].methodIndexArray = clazz->ifviPool + poolOffset;
3182 interface = clazz->iftable[i].clazz;
3183 poolOffset += interface->virtualMethodCount; // end here
3184
3185 /*
3186 * For each method listed in the interface's method list, find the
3187 * matching method in our class's method list. We want to favor the
3188 * subclass over the superclass, which just requires walking
3189 * back from the end of the vtable. (This only matters if the
3190 * superclass defines a private method and this class redefines
3191 * it -- otherwise it would use the same vtable slot. In Dalvik
3192 * those don't end up in the virtual method table, so it shouldn't
3193 * matter which direction we go. We walk it backward anyway.)
3194 *
3195 *
3196 * Suppose we have the following arrangement:
3197 * public interface MyInterface
3198 * public boolean inInterface();
3199 * public abstract class MirandaAbstract implements MirandaInterface
3200 * //public abstract boolean inInterface(); // not declared!
3201 * public boolean inAbstract() { stuff } // in vtable
3202 * public class MirandClass extends MirandaAbstract
3203 * public boolean inInterface() { stuff }
3204 * public boolean inAbstract() { stuff } // in vtable
3205 *
3206 * The javac compiler happily compiles MirandaAbstract even though
3207 * it doesn't declare all methods from its interface. When we try
3208 * to set up a vtable for MirandaAbstract, we find that we don't
3209 * have an slot for inInterface. To prevent this, we synthesize
3210 * abstract method declarations in MirandaAbstract.
3211 *
3212 * We have to expand vtable and update some things that point at it,
3213 * so we accumulate the method list and do it all at once below.
3214 */
3215 for (methIdx = 0; methIdx < interface->virtualMethodCount; methIdx++) {
3216 Method* imeth = &interface->virtualMethods[methIdx];
3217 int j;
3218
3219 IF_LOGVV() {
3220 char* desc = dexProtoCopyMethodDescriptor(&imeth->prototype);
3221 LOGVV("INTF: matching '%s' '%s'\n", imeth->name, desc);
3222 free(desc);
3223 }
3224
3225 for (j = clazz->vtableCount-1; j >= 0; j--) {
3226 if (dvmCompareMethodNamesAndProtos(imeth, clazz->vtable[j])
3227 == 0)
3228 {
3229 LOGVV("INTF: matched at %d\n", j);
3230 if (!dvmIsPublicMethod(clazz->vtable[j])) {
3231 LOGW("Implementation of %s.%s is not public\n",
3232 clazz->descriptor, clazz->vtable[j]->name);
3233 dvmThrowException("Ljava/lang/IllegalAccessError;",
3234 "interface implementation not public");
3235 goto bail;
3236 }
3237 clazz->iftable[i].methodIndexArray[methIdx] = j;
3238 break;
3239 }
3240 }
3241 if (j < 0) {
3242 IF_LOGV() {
3243 char* desc =
3244 dexProtoCopyMethodDescriptor(&imeth->prototype);
3245 LOGV("No match for '%s' '%s' in '%s' (creating miranda)\n",
3246 imeth->name, desc, clazz->descriptor);
3247 free(desc);
3248 }
3249 //dvmThrowException("Ljava/lang/RuntimeException;", "Miranda!");
3250 //return false;
3251
3252 if (mirandaCount == mirandaAlloc) {
3253 mirandaAlloc += 8;
3254 if (mirandaList == NULL) {
3255 mirandaList = dvmLinearAlloc(clazz->classLoader,
3256 mirandaAlloc * sizeof(Method*));
3257 } else {
3258 dvmLinearReadOnly(clazz->classLoader, mirandaList);
3259 mirandaList = dvmLinearRealloc(clazz->classLoader,
3260 mirandaList, mirandaAlloc * sizeof(Method*));
3261 }
3262 assert(mirandaList != NULL); // mem failed + we leaked
3263 }
3264
3265 /*
3266 * These may be redundant (e.g. method with same name and
3267 * signature declared in two interfaces implemented by the
3268 * same abstract class). We can squeeze the duplicates
3269 * out here.
3270 */
3271 int mir;
3272 for (mir = 0; mir < mirandaCount; mir++) {
3273 if (dvmCompareMethodNamesAndProtos(
3274 mirandaList[mir], imeth) == 0)
3275 {
3276 IF_LOGVV() {
3277 char* desc = dexProtoCopyMethodDescriptor(
3278 &imeth->prototype);
3279 LOGVV("MIRANDA dupe: %s and %s %s%s\n",
3280 mirandaList[mir]->clazz->descriptor,
3281 imeth->clazz->descriptor,
3282 imeth->name, desc);
3283 free(desc);
3284 }
3285 break;
3286 }
3287 }
3288
3289 /* point the iftable at a phantom slot index */
3290 clazz->iftable[i].methodIndexArray[methIdx] =
3291 clazz->vtableCount + mir;
3292 LOGVV("MIRANDA: %s points at slot %d\n",
3293 imeth->name, clazz->vtableCount + mir);
3294
3295 /* if non-duplicate among Mirandas, add to Miranda list */
3296 if (mir == mirandaCount) {
3297 //LOGV("MIRANDA: holding '%s' in slot %d\n",
3298 // imeth->name, mir);
3299 mirandaList[mirandaCount++] = imeth;
3300 }
3301 }
3302 }
3303 }
3304
3305 if (mirandaCount != 0) {
Andy McFadden68825972009-05-08 11:25:35 -07003306 static const int kManyMirandas = 150; /* arbitrary */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003307 Method* newVirtualMethods;
3308 Method* meth;
3309 int oldMethodCount, oldVtableCount;
3310
3311 for (i = 0; i < mirandaCount; i++) {
3312 LOGVV("MIRANDA %d: %s.%s\n", i,
3313 mirandaList[i]->clazz->descriptor, mirandaList[i]->name);
3314 }
Andy McFadden68825972009-05-08 11:25:35 -07003315 if (mirandaCount > kManyMirandas) {
3316 /*
3317 * Some obfuscators like to create an interface with a huge
3318 * pile of methods, declare classes as implementing it, and then
3319 * only define a couple of methods. This leads to a rather
3320 * massive collection of Miranda methods and a lot of wasted
3321 * space, sometimes enough to blow out the LinearAlloc cap.
3322 */
3323 LOGD("Note: class %s has %d unimplemented (abstract) methods\n",
3324 clazz->descriptor, mirandaCount);
3325 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003326
3327 /*
3328 * We found methods in one or more interfaces for which we do not
3329 * have vtable entries. We have to expand our virtualMethods
3330 * table (which might be empty) to hold some new entries.
3331 */
3332 if (clazz->virtualMethods == NULL) {
3333 newVirtualMethods = (Method*) dvmLinearAlloc(clazz->classLoader,
3334 sizeof(Method) * (clazz->virtualMethodCount + mirandaCount));
3335 } else {
3336 //dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3337 newVirtualMethods = (Method*) dvmLinearRealloc(clazz->classLoader,
3338 clazz->virtualMethods,
3339 sizeof(Method) * (clazz->virtualMethodCount + mirandaCount));
3340 }
3341 if (newVirtualMethods != clazz->virtualMethods) {
3342 /*
3343 * Table was moved in memory. We have to run through the
3344 * vtable and fix the pointers. The vtable entries might be
3345 * pointing at superclasses, so we flip it around: run through
3346 * all locally-defined virtual methods, and fix their entries
3347 * in the vtable. (This would get really messy if sub-classes
3348 * had already been loaded.)
3349 *
3350 * Reminder: clazz->virtualMethods and clazz->virtualMethodCount
3351 * hold the virtual methods declared by this class. The
3352 * method's methodIndex is the vtable index, and is the same
3353 * for all sub-classes (and all super classes in which it is
3354 * defined). We're messing with these because the Miranda
3355 * stuff makes it look like the class actually has an abstract
3356 * method declaration in it.
3357 */
3358 LOGVV("MIRANDA fixing vtable pointers\n");
3359 dvmLinearReadWrite(clazz->classLoader, clazz->vtable);
3360 Method* meth = newVirtualMethods;
3361 for (i = 0; i < clazz->virtualMethodCount; i++, meth++)
3362 clazz->vtable[meth->methodIndex] = meth;
3363 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
3364 }
3365
3366 oldMethodCount = clazz->virtualMethodCount;
3367 clazz->virtualMethods = newVirtualMethods;
3368 clazz->virtualMethodCount += mirandaCount;
3369
3370 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3371
3372 /*
3373 * We also have to expand the vtable.
3374 */
3375 assert(clazz->vtable != NULL);
3376 clazz->vtable = (Method**) dvmLinearRealloc(clazz->classLoader,
3377 clazz->vtable,
3378 sizeof(Method*) * (clazz->vtableCount + mirandaCount));
3379 if (clazz->vtable == NULL) {
3380 assert(false);
3381 goto bail;
3382 }
3383 zapVtable = true;
3384
3385 oldVtableCount = clazz->vtableCount;
3386 clazz->vtableCount += mirandaCount;
3387
3388 /*
3389 * Now we need to create the fake methods. We clone the abstract
3390 * method definition from the interface and then replace a few
3391 * things.
Andy McFadden68825972009-05-08 11:25:35 -07003392 *
3393 * The Method will be an "abstract native", with nativeFunc set to
3394 * dvmAbstractMethodStub().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003395 */
3396 meth = clazz->virtualMethods + oldMethodCount;
3397 for (i = 0; i < mirandaCount; i++, meth++) {
3398 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
3399 cloneMethod(meth, mirandaList[i]);
3400 meth->clazz = clazz;
3401 meth->accessFlags |= ACC_MIRANDA;
3402 meth->methodIndex = (u2) (oldVtableCount + i);
3403 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3404
3405 /* point the new vtable entry at the new method */
3406 clazz->vtable[oldVtableCount + i] = meth;
3407 }
3408
3409 dvmLinearReadOnly(clazz->classLoader, mirandaList);
3410 dvmLinearFree(clazz->classLoader, mirandaList);
3411
3412 }
3413
3414 /*
3415 * TODO?
3416 * Sort the interfaces by number of declared methods. All we really
3417 * want is to get the interfaces with zero methods at the end of the
3418 * list, so that when we walk through the list during invoke-interface
3419 * we don't examine interfaces that can't possibly be useful.
3420 *
3421 * The set will usually be small, so a simple insertion sort works.
3422 *
3423 * We have to be careful not to change the order of two interfaces
3424 * that define the same method. (Not a problem if we only move the
3425 * zero-method interfaces to the end.)
3426 *
3427 * PROBLEM:
3428 * If we do this, we will no longer be able to identify super vs.
3429 * current class interfaces by comparing clazz->super->iftableCount. This
3430 * breaks anything that only wants to find interfaces declared directly
3431 * by the class (dvmFindStaticFieldHier, ReferenceType.Interfaces,
3432 * dvmDbgOutputAllInterfaces, etc). Need to provide a workaround.
3433 *
3434 * We can sort just the interfaces implemented directly by this class,
3435 * but that doesn't seem like it would provide much of an advantage. I'm
3436 * not sure this is worthwhile.
3437 *
3438 * (This has been made largely obsolete by the interface cache mechanism.)
3439 */
3440
3441 //dvmDumpClass(clazz);
3442
3443 result = true;
3444
3445bail:
3446 if (zapIftable)
3447 dvmLinearReadOnly(clazz->classLoader, clazz->iftable);
3448 if (zapVtable)
3449 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
3450 if (zapIfvipool)
3451 dvmLinearReadOnly(clazz->classLoader, clazz->ifviPool);
3452 return result;
3453}
3454
3455
3456/*
3457 * Provide "stub" implementations for methods without them.
3458 *
3459 * Currently we provide an implementation for all abstract methods that
3460 * throws an AbstractMethodError exception. This allows us to avoid an
3461 * explicit check for abstract methods in every virtual call.
3462 *
3463 * NOTE: for Miranda methods, the method declaration is a clone of what
3464 * was found in the interface class. That copy may already have had the
3465 * function pointer filled in, so don't be surprised if it's not NULL.
3466 *
3467 * NOTE: this sets the "native" flag, giving us an "abstract native" method,
3468 * which is nonsensical. Need to make sure that this doesn't escape the
3469 * VM. We can either mask it out in reflection calls, or copy "native"
3470 * into the high 16 bits of accessFlags and check that internally.
3471 */
3472static bool insertMethodStubs(ClassObject* clazz)
3473{
3474 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
3475
3476 Method* meth;
3477 int i;
3478
3479 meth = clazz->virtualMethods;
3480 for (i = 0; i < clazz->virtualMethodCount; i++, meth++) {
3481 if (dvmIsAbstractMethod(meth)) {
3482 assert(meth->insns == NULL);
3483 assert(meth->nativeFunc == NULL ||
3484 meth->nativeFunc == (DalvikBridgeFunc)dvmAbstractMethodStub);
3485
3486 meth->accessFlags |= ACC_NATIVE;
3487 meth->nativeFunc = (DalvikBridgeFunc) dvmAbstractMethodStub;
3488 }
3489 }
3490
3491 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3492 return true;
3493}
3494
3495
3496/*
3497 * Swap two instance fields.
3498 */
3499static inline void swapField(InstField* pOne, InstField* pTwo)
3500{
3501 InstField swap;
3502
3503 LOGVV(" --- swap '%s' and '%s'\n", pOne->field.name, pTwo->field.name);
3504 swap = *pOne;
3505 *pOne = *pTwo;
3506 *pTwo = swap;
3507}
3508
3509/*
3510 * Assign instance fields to u4 slots.
3511 *
3512 * The top portion of the instance field area is occupied by the superclass
3513 * fields, the bottom by the fields for this class.
3514 *
3515 * "long" and "double" fields occupy two adjacent slots. On some
3516 * architectures, 64-bit quantities must be 64-bit aligned, so we need to
3517 * arrange fields (or introduce padding) to ensure this. We assume the
3518 * fields of the topmost superclass (i.e. Object) are 64-bit aligned, so
3519 * we can just ensure that the offset is "even". To avoid wasting space,
3520 * we want to move non-reference 32-bit fields into gaps rather than
3521 * creating pad words.
3522 *
3523 * In the worst case we will waste 4 bytes, but because objects are
3524 * allocated on >= 64-bit boundaries, those bytes may well be wasted anyway
3525 * (assuming this is the most-derived class).
3526 *
3527 * Pad words are not represented in the field table, so the field table
3528 * itself does not change size.
3529 *
3530 * The number of field slots determines the size of the object, so we
3531 * set that here too.
3532 *
3533 * This function feels a little more complicated than I'd like, but it
3534 * has the property of moving the smallest possible set of fields, which
3535 * should reduce the time required to load a class.
3536 *
3537 * NOTE: reference fields *must* come first, or precacheReferenceOffsets()
3538 * will break.
3539 */
3540static bool computeFieldOffsets(ClassObject* clazz)
3541{
3542 int fieldOffset;
3543 int i, j;
3544
3545 dvmLinearReadWrite(clazz->classLoader, clazz->ifields);
3546
3547 if (clazz->super != NULL)
3548 fieldOffset = clazz->super->objectSize;
3549 else
3550 fieldOffset = offsetof(DataObject, instanceData);
3551
3552 LOGVV("--- computeFieldOffsets '%s'\n", clazz->descriptor);
3553
3554 //LOGI("OFFSETS fieldCount=%d\n", clazz->ifieldCount);
3555 //LOGI("dataobj, instance: %d\n", offsetof(DataObject, instanceData));
3556 //LOGI("classobj, access: %d\n", offsetof(ClassObject, accessFlags));
3557 //LOGI("super=%p, fieldOffset=%d\n", clazz->super, fieldOffset);
3558
3559 /*
3560 * Start by moving all reference fields to the front.
3561 */
3562 clazz->ifieldRefCount = 0;
3563 j = clazz->ifieldCount - 1;
3564 for (i = 0; i < clazz->ifieldCount; i++) {
3565 InstField* pField = &clazz->ifields[i];
3566 char c = pField->field.signature[0];
3567
3568 if (c != '[' && c != 'L') {
3569 /* This isn't a reference field; see if any reference fields
3570 * follow this one. If so, we'll move it to this position.
3571 * (quicksort-style partitioning)
3572 */
3573 while (j > i) {
3574 InstField* refField = &clazz->ifields[j--];
3575 char rc = refField->field.signature[0];
3576
3577 if (rc == '[' || rc == 'L') {
3578 /* Here's a reference field that follows at least one
3579 * non-reference field. Swap it with the current field.
3580 * (When this returns, "pField" points to the reference
3581 * field, and "refField" points to the non-ref field.)
3582 */
3583 swapField(pField, refField);
3584
3585 /* Fix the signature.
3586 */
3587 c = rc;
3588
3589 clazz->ifieldRefCount++;
3590 break;
3591 }
3592 }
3593 /* We may or may not have swapped a field.
3594 */
3595 } else {
3596 /* This is a reference field.
3597 */
3598 clazz->ifieldRefCount++;
3599 }
3600
3601 /*
3602 * If we've hit the end of the reference fields, break.
3603 */
3604 if (c != '[' && c != 'L')
3605 break;
3606
3607 pField->byteOffset = fieldOffset;
3608 fieldOffset += sizeof(u4);
3609 LOGVV(" --- offset1 '%s'=%d\n", pField->field.name,pField->byteOffset);
3610 }
3611
3612 /*
3613 * Now we want to pack all of the double-wide fields together. If we're
3614 * not aligned, though, we want to shuffle one 32-bit field into place.
3615 * If we can't find one, we'll have to pad it.
3616 */
3617 if (i != clazz->ifieldCount && (fieldOffset & 0x04) != 0) {
3618 LOGVV(" +++ not aligned\n");
3619
3620 InstField* pField = &clazz->ifields[i];
3621 char c = pField->field.signature[0];
3622
3623 if (c != 'J' && c != 'D') {
3624 /*
3625 * The field that comes next is 32-bit, so just advance past it.
3626 */
3627 assert(c != '[' && c != 'L');
3628 pField->byteOffset = fieldOffset;
3629 fieldOffset += sizeof(u4);
3630 i++;
3631 LOGVV(" --- offset2 '%s'=%d\n",
3632 pField->field.name, pField->byteOffset);
3633 } else {
3634 /*
3635 * Next field is 64-bit, so search for a 32-bit field we can
3636 * swap into it.
3637 */
3638 bool found = false;
3639 j = clazz->ifieldCount - 1;
3640 while (j > i) {
3641 InstField* singleField = &clazz->ifields[j--];
3642 char rc = singleField->field.signature[0];
3643
3644 if (rc != 'J' && rc != 'D') {
3645 swapField(pField, singleField);
3646 //c = rc;
3647 LOGVV(" +++ swapped '%s' for alignment\n",
3648 pField->field.name);
3649 pField->byteOffset = fieldOffset;
3650 fieldOffset += sizeof(u4);
3651 LOGVV(" --- offset3 '%s'=%d\n",
3652 pField->field.name, pField->byteOffset);
3653 found = true;
3654 i++;
3655 break;
3656 }
3657 }
3658 if (!found) {
3659 LOGV(" +++ inserting pad field in '%s'\n", clazz->descriptor);
3660 fieldOffset += sizeof(u4);
3661 }
3662 }
3663 }
3664
3665 /*
3666 * Alignment is good, shuffle any double-wide fields forward, and
3667 * finish assigning field offsets to all fields.
3668 */
3669 assert(i == clazz->ifieldCount || (fieldOffset & 0x04) == 0);
3670 j = clazz->ifieldCount - 1;
3671 for ( ; i < clazz->ifieldCount; i++) {
3672 InstField* pField = &clazz->ifields[i];
3673 char c = pField->field.signature[0];
3674
3675 if (c != 'D' && c != 'J') {
3676 /* This isn't a double-wide field; see if any double fields
3677 * follow this one. If so, we'll move it to this position.
3678 * (quicksort-style partitioning)
3679 */
3680 while (j > i) {
3681 InstField* doubleField = &clazz->ifields[j--];
3682 char rc = doubleField->field.signature[0];
3683
3684 if (rc == 'D' || rc == 'J') {
3685 /* Here's a double-wide field that follows at least one
3686 * non-double field. Swap it with the current field.
3687 * (When this returns, "pField" points to the reference
3688 * field, and "doubleField" points to the non-double field.)
3689 */
3690 swapField(pField, doubleField);
3691 c = rc;
3692
3693 break;
3694 }
3695 }
3696 /* We may or may not have swapped a field.
3697 */
3698 } else {
3699 /* This is a double-wide field, leave it be.
3700 */
3701 }
3702
3703 pField->byteOffset = fieldOffset;
3704 LOGVV(" --- offset4 '%s'=%d\n", pField->field.name,pField->byteOffset);
3705 fieldOffset += sizeof(u4);
3706 if (c == 'J' || c == 'D')
3707 fieldOffset += sizeof(u4);
3708 }
3709
3710#ifndef NDEBUG
3711 /* Make sure that all reference fields appear before
3712 * non-reference fields, and all double-wide fields are aligned.
3713 */
3714 j = 0; // seen non-ref
3715 for (i = 0; i < clazz->ifieldCount; i++) {
3716 InstField *pField = &clazz->ifields[i];
3717 char c = pField->field.signature[0];
3718
3719 if (c == 'D' || c == 'J') {
3720 assert((pField->byteOffset & 0x07) == 0);
3721 }
3722
3723 if (c != '[' && c != 'L') {
3724 if (!j) {
3725 assert(i == clazz->ifieldRefCount);
3726 j = 1;
3727 }
3728 } else if (j) {
3729 assert(false);
3730 }
3731 }
3732 if (!j) {
3733 assert(clazz->ifieldRefCount == clazz->ifieldCount);
3734 }
3735#endif
3736
3737 /*
3738 * We map a C struct directly on top of java/lang/Class objects. Make
3739 * sure we left enough room for the instance fields.
3740 */
3741 assert(clazz != gDvm.classJavaLangClass || (size_t)fieldOffset <
3742 offsetof(ClassObject, instanceData) + sizeof(clazz->instanceData));
3743
3744 clazz->objectSize = fieldOffset;
3745
3746 dvmLinearReadOnly(clazz->classLoader, clazz->ifields);
3747 return true;
3748}
3749
3750/*
3751 * Throw the VM-spec-mandated error when an exception is thrown during
3752 * class initialization.
3753 *
3754 * The safest way to do this is to call the ExceptionInInitializerError
3755 * constructor that takes a Throwable.
3756 *
3757 * [Do we want to wrap it if the original is an Error rather than
3758 * an Exception?]
3759 */
3760static void throwClinitError(void)
3761{
3762 Thread* self = dvmThreadSelf();
3763 Object* exception;
3764 Object* eiie;
3765
3766 exception = dvmGetException(self);
3767 dvmAddTrackedAlloc(exception, self);
3768 dvmClearException(self);
3769
3770 if (gDvm.classJavaLangExceptionInInitializerError == NULL) {
3771 /*
3772 * Always resolves to same thing -- no race condition.
3773 */
3774 gDvm.classJavaLangExceptionInInitializerError =
3775 dvmFindSystemClass(
3776 "Ljava/lang/ExceptionInInitializerError;");
3777 if (gDvm.classJavaLangExceptionInInitializerError == NULL) {
3778 LOGE("Unable to prep java/lang/ExceptionInInitializerError\n");
3779 goto fail;
3780 }
3781
3782 gDvm.methJavaLangExceptionInInitializerError_init =
3783 dvmFindDirectMethodByDescriptor(gDvm.classJavaLangExceptionInInitializerError,
3784 "<init>", "(Ljava/lang/Throwable;)V");
3785 if (gDvm.methJavaLangExceptionInInitializerError_init == NULL) {
3786 LOGE("Unable to prep java/lang/ExceptionInInitializerError\n");
3787 goto fail;
3788 }
3789 }
3790
3791 eiie = dvmAllocObject(gDvm.classJavaLangExceptionInInitializerError,
3792 ALLOC_DEFAULT);
3793 if (eiie == NULL)
3794 goto fail;
3795
3796 /*
3797 * Construct the new object, and replace the exception with it.
3798 */
3799 JValue unused;
3800 dvmCallMethod(self, gDvm.methJavaLangExceptionInInitializerError_init,
3801 eiie, &unused, exception);
3802 dvmSetException(self, eiie);
3803 dvmReleaseTrackedAlloc(eiie, NULL);
3804 dvmReleaseTrackedAlloc(exception, self);
3805 return;
3806
3807fail: /* restore original exception */
3808 dvmSetException(self, exception);
3809 dvmReleaseTrackedAlloc(exception, self);
3810 return;
3811}
3812
3813/*
3814 * The class failed to initialize on a previous attempt, so we want to throw
3815 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
3816 * failed in verification, in which case v2 5.4.1 says we need to re-throw
3817 * the previous error.
3818 */
3819static void throwEarlierClassFailure(ClassObject* clazz)
3820{
3821 LOGI("Rejecting re-init on previously-failed class %s v=%p\n",
3822 clazz->descriptor, clazz->verifyErrorClass);
3823
3824 if (clazz->verifyErrorClass == NULL) {
3825 dvmThrowExceptionWithClassMessage("Ljava/lang/NoClassDefFoundError;",
3826 clazz->descriptor);
3827 } else {
3828 dvmThrowExceptionByClassWithClassMessage(clazz->verifyErrorClass,
3829 clazz->descriptor);
3830 }
3831}
3832
3833/*
3834 * Initialize any static fields whose values are stored in
3835 * the DEX file. This must be done during class initialization.
3836 */
3837static void initSFields(ClassObject* clazz)
3838{
3839 Thread* self = dvmThreadSelf(); /* for dvmReleaseTrackedAlloc() */
3840 DexFile* pDexFile;
3841 const DexClassDef* pClassDef;
3842 const DexEncodedArray* pValueList;
3843 EncodedArrayIterator iterator;
3844 int i;
3845
3846 if (clazz->sfieldCount == 0) {
3847 return;
3848 }
3849 if (clazz->pDvmDex == NULL) {
3850 /* generated class; any static fields should already be set up */
3851 LOGV("Not initializing static fields in %s\n", clazz->descriptor);
3852 return;
3853 }
3854 pDexFile = clazz->pDvmDex->pDexFile;
3855
3856 pClassDef = dexFindClass(pDexFile, clazz->descriptor);
3857 assert(pClassDef != NULL);
3858
3859 pValueList = dexGetStaticValuesList(pDexFile, pClassDef);
3860 if (pValueList == NULL) {
3861 return;
3862 }
3863
3864 dvmEncodedArrayIteratorInitialize(&iterator, pValueList, clazz);
3865
3866 /*
3867 * Iterate over the initial values array, setting the corresponding
3868 * static field for each array element.
3869 */
3870
3871 for (i = 0; dvmEncodedArrayIteratorHasNext(&iterator); i++) {
3872 AnnotationValue value;
3873 bool parsed = dvmEncodedArrayIteratorGetNext(&iterator, &value);
3874 StaticField* sfield = &clazz->sfields[i];
3875 const char* descriptor = sfield->field.signature;
3876 bool needRelease = false;
3877
3878 if (! parsed) {
3879 /*
3880 * TODO: Eventually verification should attempt to ensure
3881 * that this can't happen at least due to a data integrity
3882 * problem.
3883 */
3884 LOGE("Static initializer parse failed for %s at index %d",
3885 clazz->descriptor, i);
3886 dvmAbort();
3887 }
3888
3889 /* Verify that the value we got was of a valid type. */
3890
3891 switch (descriptor[0]) {
3892 case 'Z': parsed = (value.type == kDexAnnotationBoolean); break;
3893 case 'B': parsed = (value.type == kDexAnnotationByte); break;
3894 case 'C': parsed = (value.type == kDexAnnotationChar); break;
3895 case 'S': parsed = (value.type == kDexAnnotationShort); break;
3896 case 'I': parsed = (value.type == kDexAnnotationInt); break;
3897 case 'J': parsed = (value.type == kDexAnnotationLong); break;
3898 case 'F': parsed = (value.type == kDexAnnotationFloat); break;
3899 case 'D': parsed = (value.type == kDexAnnotationDouble); break;
3900 case '[': parsed = (value.type == kDexAnnotationNull); break;
3901 case 'L': {
3902 switch (value.type) {
3903 case kDexAnnotationNull: {
3904 /* No need for further tests. */
3905 break;
3906 }
3907 case kDexAnnotationString: {
3908 parsed =
3909 (strcmp(descriptor, "Ljava/lang/String;") == 0);
3910 needRelease = true;
3911 break;
3912 }
3913 case kDexAnnotationType: {
3914 parsed =
3915 (strcmp(descriptor, "Ljava/lang/Class;") == 0);
3916 needRelease = true;
3917 break;
3918 }
3919 default: {
3920 parsed = false;
3921 break;
3922 }
3923 }
3924 break;
3925 }
3926 default: {
3927 parsed = false;
3928 break;
3929 }
3930 }
3931
3932 if (parsed) {
3933 /*
3934 * All's well, so store the value. Note: This always
3935 * stores the full width of a JValue, even though most of
3936 * the time only the first word is needed.
3937 */
3938 sfield->value = value.value;
3939 if (needRelease) {
3940 dvmReleaseTrackedAlloc(value.value.l, self);
3941 }
3942 } else {
3943 /*
3944 * Something up above had a problem. TODO: See comment
3945 * above the switch about verfication.
3946 */
3947 LOGE("Bogus static initialization: value type %d in field type "
3948 "%s for %s at index %d",
3949 value.type, descriptor, clazz->descriptor, i);
3950 dvmAbort();
3951 }
3952 }
3953}
3954
3955
3956/*
3957 * Determine whether "descriptor" yields the same class object in the
3958 * context of clazz1 and clazz2.
3959 *
3960 * The caller must hold gDvm.loadedClasses.
3961 *
3962 * Returns "true" if they match.
3963 */
3964static bool compareDescriptorClasses(const char* descriptor,
3965 const ClassObject* clazz1, const ClassObject* clazz2)
3966{
3967 ClassObject* result1;
3968 ClassObject* result2;
3969
3970 /*
3971 * Do the first lookup by name.
3972 */
3973 result1 = dvmFindClassNoInit(descriptor, clazz1->classLoader);
3974
3975 /*
3976 * We can skip a second lookup by name if the second class loader is
3977 * in the initiating loader list of the class object we retrieved.
3978 * (This means that somebody already did a lookup of this class through
3979 * the second loader, and it resolved to the same class.) If it's not
3980 * there, we may simply not have had an opportunity to add it yet, so
3981 * we do the full lookup.
3982 *
3983 * The initiating loader test should catch the majority of cases
3984 * (in particular, the zillions of references to String/Object).
3985 *
3986 * Unfortunately we're still stuck grabbing a mutex to do the lookup.
3987 *
3988 * For this to work, the superclass/interface should be the first
3989 * argument, so that way if it's from the bootstrap loader this test
3990 * will work. (The bootstrap loader, by definition, never shows up
3991 * as the initiating loader of a class defined by some other loader.)
3992 */
3993 dvmHashTableLock(gDvm.loadedClasses);
3994 bool isInit = dvmLoaderInInitiatingList(result1, clazz2->classLoader);
3995 dvmHashTableUnlock(gDvm.loadedClasses);
3996
3997 if (isInit) {
3998 //printf("%s(obj=%p) / %s(cl=%p): initiating\n",
3999 // result1->descriptor, result1,
4000 // clazz2->descriptor, clazz2->classLoader);
4001 return true;
4002 } else {
4003 //printf("%s(obj=%p) / %s(cl=%p): RAW\n",
4004 // result1->descriptor, result1,
4005 // clazz2->descriptor, clazz2->classLoader);
4006 result2 = dvmFindClassNoInit(descriptor, clazz2->classLoader);
4007 }
4008
4009 if (result1 == NULL || result2 == NULL) {
4010 dvmClearException(dvmThreadSelf());
4011 if (result1 == result2) {
4012 /*
4013 * Neither class loader could find this class. Apparently it
4014 * doesn't exist.
4015 *
4016 * We can either throw some sort of exception now, or just
4017 * assume that it'll fail later when something actually tries
4018 * to use the class. For strict handling we should throw now,
4019 * because a "tricky" class loader could start returning
4020 * something later, and a pair of "tricky" loaders could set
4021 * us up for confusion.
4022 *
4023 * I'm not sure if we're allowed to complain about nonexistent
4024 * classes in method signatures during class init, so for now
4025 * this will just return "true" and let nature take its course.
4026 */
4027 return true;
4028 } else {
4029 /* only one was found, so clearly they're not the same */
4030 return false;
4031 }
4032 }
4033
4034 return result1 == result2;
4035}
4036
4037/*
4038 * For every component in the method descriptor, resolve the class in the
4039 * context of the two classes and compare the results.
4040 *
4041 * For best results, the "superclass" class should be first.
4042 *
4043 * Returns "true" if the classes match, "false" otherwise.
4044 */
4045static bool checkMethodDescriptorClasses(const Method* meth,
4046 const ClassObject* clazz1, const ClassObject* clazz2)
4047{
4048 DexParameterIterator iterator;
4049 const char* descriptor;
4050
4051 /* walk through the list of parameters */
4052 dexParameterIteratorInit(&iterator, &meth->prototype);
4053 while (true) {
4054 descriptor = dexParameterIteratorNextDescriptor(&iterator);
4055
4056 if (descriptor == NULL)
4057 break;
4058
4059 if (descriptor[0] == 'L' || descriptor[0] == '[') {
4060 /* non-primitive type */
4061 if (!compareDescriptorClasses(descriptor, clazz1, clazz2))
4062 return false;
4063 }
4064 }
4065
4066 /* check the return type */
4067 descriptor = dexProtoGetReturnType(&meth->prototype);
4068 if (descriptor[0] == 'L' || descriptor[0] == '[') {
4069 if (!compareDescriptorClasses(descriptor, clazz1, clazz2))
4070 return false;
4071 }
4072 return true;
4073}
4074
4075/*
4076 * Validate the descriptors in the superclass and interfaces.
4077 *
4078 * What we need to do is ensure that the classes named in the method
4079 * descriptors in our ancestors and ourselves resolve to the same class
Andy McFaddencab8be02009-05-26 13:39:57 -07004080 * objects. We can get conflicts when the classes come from different
4081 * class loaders, and the resolver comes up with different results for
4082 * the same class name in different contexts.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004083 *
Andy McFaddencab8be02009-05-26 13:39:57 -07004084 * An easy way to cause the problem is to declare a base class that uses
4085 * class Foo in a method signature (e.g. as the return type). Then,
4086 * define a subclass and a different version of Foo, and load them from a
4087 * different class loader. If the subclass overrides the method, it will
4088 * have a different concept of what Foo is than its parent does, so even
4089 * though the method signature strings are identical, they actually mean
4090 * different things.
4091 *
4092 * A call to the method through a base-class reference would be treated
4093 * differently than a call to the method through a subclass reference, which
4094 * isn't the way polymorphism works, so we have to reject the subclass.
4095 * If the subclass doesn't override the base method, then there's no
4096 * problem, because calls through base-class references and subclass
4097 * references end up in the same place.
4098 *
4099 * We don't need to check to see if an interface's methods match with its
4100 * superinterface's methods, because you can't instantiate an interface
4101 * and do something inappropriate with it. If interface I1 extends I2
4102 * and is implemented by C, and I1 and I2 are in separate class loaders
4103 * and have conflicting views of other classes, we will catch the conflict
4104 * when we process C. Anything that implements I1 is doomed to failure,
4105 * but we don't need to catch that while processing I1.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004106 *
4107 * On failure, throws an exception and returns "false".
4108 */
4109static bool validateSuperDescriptors(const ClassObject* clazz)
4110{
4111 int i;
4112
4113 if (dvmIsInterfaceClass(clazz))
4114 return true;
4115
4116 /*
4117 * Start with the superclass-declared methods.
4118 */
4119 if (clazz->super != NULL &&
4120 clazz->classLoader != clazz->super->classLoader)
4121 {
4122 /*
Andy McFaddencab8be02009-05-26 13:39:57 -07004123 * Walk through every overridden method and compare resolved
4124 * descriptor components. We pull the Method structs out of
4125 * the vtable. It doesn't matter whether we get the struct from
4126 * the parent or child, since we just need the UTF-8 descriptor,
4127 * which must match.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004128 *
4129 * We need to do this even for the stuff inherited from Object,
4130 * because it's possible that the new class loader has redefined
4131 * a basic class like String.
Andy McFaddene7b30942009-05-27 12:42:38 -07004132 *
4133 * We don't need to check stuff defined in a superclass because
4134 * it was checked when the superclass was loaded.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004135 */
4136 const Method* meth;
4137
4138 //printf("Checking %s %p vs %s %p\n",
4139 // clazz->descriptor, clazz->classLoader,
4140 // clazz->super->descriptor, clazz->super->classLoader);
4141 for (i = clazz->super->vtableCount - 1; i >= 0; i--) {
4142 meth = clazz->vtable[i];
Andy McFaddencab8be02009-05-26 13:39:57 -07004143 if (meth != clazz->super->vtable[i] &&
4144 !checkMethodDescriptorClasses(meth, clazz->super, clazz))
4145 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004146 LOGW("Method mismatch: %s in %s (cl=%p) and super %s (cl=%p)\n",
4147 meth->name, clazz->descriptor, clazz->classLoader,
4148 clazz->super->descriptor, clazz->super->classLoader);
4149 dvmThrowException("Ljava/lang/LinkageError;",
4150 "Classes resolve differently in superclass");
4151 return false;
4152 }
4153 }
4154 }
4155
4156 /*
Andy McFaddene7b30942009-05-27 12:42:38 -07004157 * Check the methods defined by this class against the interfaces it
4158 * implements. If we inherited the implementation from a superclass,
4159 * we have to check it against the superclass (which might be in a
4160 * different class loader). If the superclass also implements the
4161 * interface, we could skip the check since by definition it was
4162 * performed when the class was loaded.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004163 */
4164 for (i = 0; i < clazz->iftableCount; i++) {
4165 const InterfaceEntry* iftable = &clazz->iftable[i];
4166
4167 if (clazz->classLoader != iftable->clazz->classLoader) {
4168 const ClassObject* iface = iftable->clazz;
4169 int j;
4170
4171 for (j = 0; j < iface->virtualMethodCount; j++) {
4172 const Method* meth;
4173 int vtableIndex;
4174
4175 vtableIndex = iftable->methodIndexArray[j];
4176 meth = clazz->vtable[vtableIndex];
4177
Andy McFaddene7b30942009-05-27 12:42:38 -07004178 if (!checkMethodDescriptorClasses(meth, iface, meth->clazz)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004179 LOGW("Method mismatch: %s in %s (cl=%p) and "
4180 "iface %s (cl=%p)\n",
4181 meth->name, clazz->descriptor, clazz->classLoader,
4182 iface->descriptor, iface->classLoader);
4183 dvmThrowException("Ljava/lang/LinkageError;",
4184 "Classes resolve differently in interface");
4185 return false;
4186 }
4187 }
4188 }
4189 }
4190
4191 return true;
4192}
4193
4194/*
4195 * Returns true if the class is being initialized by us (which means that
4196 * calling dvmInitClass will return immediately after fiddling with locks).
4197 *
4198 * There isn't a race here, because either clazz->initThreadId won't match
4199 * us, or it will and it was set in the same thread.
4200 */
4201bool dvmIsClassInitializing(const ClassObject* clazz)
4202{
4203 return (clazz->status == CLASS_INITIALIZING &&
4204 clazz->initThreadId == dvmThreadSelf()->threadId);
4205}
4206
4207/*
4208 * If a class has not been initialized, do so by executing the code in
4209 * <clinit>. The sequence is described in the VM spec v2 2.17.5.
4210 *
4211 * It is possible for multiple threads to arrive here simultaneously, so
4212 * we need to lock the class while we check stuff. We know that no
4213 * interpreted code has access to the class yet, so we can use the class's
4214 * monitor lock.
4215 *
4216 * We will often be called recursively, e.g. when the <clinit> code resolves
4217 * one of its fields, the field resolution will try to initialize the class.
4218 *
4219 * This can get very interesting if a class has a static field initialized
4220 * to a new instance of itself. <clinit> will end up calling <init> on
4221 * the members it is initializing, which is fine unless it uses the contents
4222 * of static fields to initialize instance fields. This will leave the
4223 * static-referenced objects in a partially initialized state. This is
4224 * reasonably rare and can sometimes be cured with proper field ordering.
4225 *
4226 * On failure, returns "false" with an exception raised.
4227 *
4228 * -----
4229 *
4230 * It is possible to cause a deadlock by having a situation like this:
4231 * class A { static { sleep(10000); new B(); } }
4232 * class B { static { sleep(10000); new A(); } }
4233 * new Thread() { public void run() { new A(); } }.start();
4234 * new Thread() { public void run() { new B(); } }.start();
4235 * This appears to be expected under the spec.
4236 *
4237 * The interesting question is what to do if somebody calls Thread.interrupt()
4238 * on one of the deadlocked threads. According to the VM spec, they're both
4239 * sitting in "wait". Should the interrupt code quietly raise the
4240 * "interrupted" flag, or should the "wait" return immediately with an
4241 * exception raised?
4242 *
4243 * This gets a little murky. The VM spec says we call "wait", and the
4244 * spec for Thread.interrupt says Object.wait is interruptible. So it
4245 * seems that, if we get unlucky and interrupt class initialization, we
4246 * are expected to throw (which gets converted to ExceptionInInitializerError
4247 * since InterruptedException is checked).
4248 *
4249 * There are a couple of problems here. First, all threads are expected to
4250 * present a consistent view of class initialization, so we can't have it
4251 * fail in one thread and succeed in another. Second, once a class fails
4252 * to initialize, it must *always* fail. This means that a stray interrupt()
4253 * call could render a class unusable for the lifetime of the VM.
4254 *
4255 * In most cases -- the deadlock example above being a counter-example --
4256 * the interrupting thread can't tell whether the target thread handled
4257 * the initialization itself or had to wait while another thread did the
4258 * work. Refusing to interrupt class initialization is, in most cases,
4259 * not something that a program can reliably detect.
4260 *
4261 * On the assumption that interrupting class initialization is highly
4262 * undesirable in most circumstances, and that failing to do so does not
4263 * deviate from the spec in a meaningful way, we don't allow class init
4264 * to be interrupted by Thread.interrupt().
4265 */
4266bool dvmInitClass(ClassObject* clazz)
4267{
4268#if LOG_CLASS_LOADING
4269 bool initializedByUs = false;
4270#endif
4271
4272 Thread* self = dvmThreadSelf();
4273 const Method* method;
4274
4275 dvmLockObject(self, (Object*) clazz);
4276 assert(dvmIsClassLinked(clazz) || clazz->status == CLASS_ERROR);
4277
4278 /*
4279 * If the class hasn't been verified yet, do so now.
4280 */
4281 if (clazz->status < CLASS_VERIFIED) {
4282 /*
4283 * If we're in an "erroneous" state, throw an exception and bail.
4284 */
4285 if (clazz->status == CLASS_ERROR) {
4286 throwEarlierClassFailure(clazz);
4287 goto bail_unlock;
4288 }
4289
4290 assert(clazz->status == CLASS_RESOLVED);
4291 assert(!IS_CLASS_FLAG_SET(clazz, CLASS_ISPREVERIFIED));
4292
4293 if (gDvm.classVerifyMode == VERIFY_MODE_NONE ||
4294 (gDvm.classVerifyMode == VERIFY_MODE_REMOTE &&
4295 clazz->classLoader == NULL))
4296 {
4297 LOGV("+++ not verifying class %s (cl=%p)\n",
4298 clazz->descriptor, clazz->classLoader);
4299 goto noverify;
4300 }
4301
4302 if (!gDvm.optimizing)
4303 LOGV("+++ late verify on %s\n", clazz->descriptor);
4304
4305 /*
4306 * We're not supposed to optimize an unverified class, but during
4307 * development this mode was useful. We can't verify an optimized
4308 * class because the optimization process discards information.
4309 */
4310 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISOPTIMIZED)) {
4311 LOGW("Class '%s' was optimized without verification; "
4312 "not verifying now\n",
4313 clazz->descriptor);
4314 LOGW(" ('rm /data/dalvik-cache/*' and restart to fix this)");
4315 goto verify_failed;
4316 }
4317
4318 clazz->status = CLASS_VERIFYING;
4319 if (!dvmVerifyClass(clazz, VERIFY_DEFAULT)) {
4320verify_failed:
4321 dvmThrowExceptionWithClassMessage("Ljava/lang/VerifyError;",
4322 clazz->descriptor);
4323 clazz->verifyErrorClass = dvmGetException(self)->clazz;
4324 clazz->status = CLASS_ERROR;
4325 goto bail_unlock;
4326 }
4327
4328 clazz->status = CLASS_VERIFIED;
4329 }
4330noverify:
4331
4332 if (clazz->status == CLASS_INITIALIZED)
4333 goto bail_unlock;
4334
4335 while (clazz->status == CLASS_INITIALIZING) {
4336 /* we caught somebody else in the act; was it us? */
4337 if (clazz->initThreadId == self->threadId) {
4338 //LOGV("HEY: found a recursive <clinit>\n");
4339 goto bail_unlock;
4340 }
4341
4342 if (dvmCheckException(self)) {
4343 LOGW("GLITCH: exception pending at start of class init\n");
4344 dvmAbort();
4345 }
4346
4347 /*
4348 * Wait for the other thread to finish initialization. We pass
4349 * "false" for the "interruptShouldThrow" arg so it doesn't throw
4350 * an exception on interrupt.
4351 */
4352 dvmObjectWait(self, (Object*) clazz, 0, 0, false);
4353
4354 /*
4355 * When we wake up, repeat the test for init-in-progress. If there's
4356 * an exception pending (only possible if "interruptShouldThrow"
4357 * was set), bail out.
4358 */
4359 if (dvmCheckException(self)) {
4360 LOGI("Class init of '%s' failing with wait() exception\n",
4361 clazz->descriptor);
4362 /*
4363 * TODO: this is bogus, because it means the two threads have a
4364 * different idea of the class status. We need to flag the
4365 * class as bad and ensure that the initializer thread respects
4366 * our notice. If we get lucky and wake up after the class has
4367 * finished initialization but before being woken, we have to
4368 * swallow the exception, perhaps raising thread->interrupted
4369 * to preserve semantics.
4370 *
4371 * Since we're not currently allowing interrupts, this should
4372 * never happen and we don't need to fix this.
4373 */
4374 assert(false);
4375 throwClinitError();
4376 clazz->status = CLASS_ERROR;
4377 goto bail_unlock;
4378 }
4379 if (clazz->status == CLASS_INITIALIZING) {
4380 LOGI("Waiting again for class init\n");
4381 continue;
4382 }
4383 assert(clazz->status == CLASS_INITIALIZED ||
4384 clazz->status == CLASS_ERROR);
4385 if (clazz->status == CLASS_ERROR) {
4386 /*
4387 * The caller wants an exception, but it was thrown in a
4388 * different thread. Synthesize one here.
4389 */
4390 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;",
4391 "(<clinit> failed, see exception in other thread)");
4392 }
4393 goto bail_unlock;
4394 }
4395
4396 /* see if we failed previously */
4397 if (clazz->status == CLASS_ERROR) {
4398 // might be wise to unlock before throwing; depends on which class
4399 // it is that we have locked
4400 dvmUnlockObject(self, (Object*) clazz);
4401 throwEarlierClassFailure(clazz);
4402 return false;
4403 }
4404
4405 /*
4406 * We're ready to go, and have exclusive access to the class.
4407 *
4408 * Before we start initialization, we need to do one extra bit of
4409 * validation: make sure that the methods declared here match up
4410 * with our superclass and interfaces. We know that the UTF-8
4411 * descriptors match, but classes from different class loaders can
4412 * have the same name.
4413 *
4414 * We do this now, rather than at load/link time, for the same reason
4415 * that we defer verification.
4416 *
4417 * It's unfortunate that we need to do this at all, but we risk
4418 * mixing reference types with identical names (see Dalvik test 068).
4419 */
4420 if (!validateSuperDescriptors(clazz)) {
4421 assert(dvmCheckException(self));
4422 clazz->status = CLASS_ERROR;
4423 goto bail_unlock;
4424 }
4425
4426 /*
4427 * Let's initialize this thing.
4428 *
4429 * We unlock the object so that other threads can politely sleep on
4430 * our mutex with Object.wait(), instead of hanging or spinning trying
4431 * to grab our mutex.
4432 */
4433 assert(clazz->status < CLASS_INITIALIZING);
4434
4435#if LOG_CLASS_LOADING
4436 // We started initializing.
4437 logClassLoad('+', clazz);
4438 initializedByUs = true;
4439#endif
4440
4441 clazz->status = CLASS_INITIALIZING;
4442 clazz->initThreadId = self->threadId;
4443 dvmUnlockObject(self, (Object*) clazz);
4444
4445 /* init our superclass */
4446 if (clazz->super != NULL && clazz->super->status != CLASS_INITIALIZED) {
4447 assert(!dvmIsInterfaceClass(clazz));
4448 if (!dvmInitClass(clazz->super)) {
4449 assert(dvmCheckException(self));
4450 clazz->status = CLASS_ERROR;
4451 /* wake up anybody who started waiting while we were unlocked */
4452 dvmLockObject(self, (Object*) clazz);
4453 goto bail_notify;
4454 }
4455 }
4456
4457 /* Initialize any static fields whose values are
4458 * stored in the Dex file. This should include all of the
4459 * simple "final static" fields, which are required to
4460 * be initialized first. (vmspec 2 sec 2.17.5 item 8)
4461 * More-complicated final static fields should be set
4462 * at the beginning of <clinit>; all we can do is trust
4463 * that the compiler did the right thing.
4464 */
4465 initSFields(clazz);
4466
4467 /* Execute any static initialization code.
4468 */
4469 method = dvmFindDirectMethodByDescriptor(clazz, "<clinit>", "()V");
4470 if (method == NULL) {
4471 LOGVV("No <clinit> found for %s\n", clazz->descriptor);
4472 } else {
4473 LOGVV("Invoking %s.<clinit>\n", clazz->descriptor);
4474 JValue unused;
4475 dvmCallMethod(self, method, NULL, &unused);
4476 }
4477
4478 if (dvmCheckException(self)) {
4479 /*
4480 * We've had an exception thrown during static initialization. We
4481 * need to throw an ExceptionInInitializerError, but we want to
4482 * tuck the original exception into the "cause" field.
4483 */
4484 LOGW("Exception %s thrown during %s.<clinit>\n",
4485 (dvmGetException(self)->clazz)->descriptor, clazz->descriptor);
4486 throwClinitError();
4487 //LOGW("+++ replaced\n");
4488
4489 dvmLockObject(self, (Object*) clazz);
4490 clazz->status = CLASS_ERROR;
4491 } else {
4492 /* success! */
4493 dvmLockObject(self, (Object*) clazz);
4494 clazz->status = CLASS_INITIALIZED;
4495 LOGVV("Initialized class: %s\n", clazz->descriptor);
4496 }
4497
4498bail_notify:
4499 /*
4500 * Notify anybody waiting on the object.
4501 */
4502 dvmObjectNotifyAll(self, (Object*) clazz);
4503
4504bail_unlock:
4505
4506#if LOG_CLASS_LOADING
4507 if (initializedByUs) {
4508 // We finished initializing.
4509 logClassLoad('-', clazz);
4510 }
4511#endif
4512
4513 dvmUnlockObject(self, (Object*) clazz);
4514
4515 return (clazz->status != CLASS_ERROR);
4516}
4517
4518/*
4519 * Replace method->nativeFunc and method->insns with new values. This is
4520 * performed on resolution of a native method.
4521 */
4522void dvmSetNativeFunc(const Method* method, DalvikBridgeFunc func,
4523 const u2* insns)
4524{
4525 ClassObject* clazz = method->clazz;
4526
4527 /* just open up both; easier that way */
4528 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
4529 dvmLinearReadWrite(clazz->classLoader, clazz->directMethods);
4530
4531 ((Method*)method)->nativeFunc = func;
4532 ((Method*)method)->insns = insns;
4533
4534 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
4535 dvmLinearReadOnly(clazz->classLoader, clazz->directMethods);
4536}
4537
4538/*
4539 * Add a RegisterMap to a Method. This is done when we verify the class
The Android Open Source Project99409882009-03-18 22:20:24 -07004540 * and compute the register maps at class initialization time (i.e. when
4541 * we don't have a pre-generated map). This means "pMap" is on the heap
4542 * and should be freed when the Method is discarded.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004543 */
4544void dvmSetRegisterMap(Method* method, const RegisterMap* pMap)
4545{
4546 ClassObject* clazz = method->clazz;
4547
4548 if (method->registerMap != NULL) {
Andy McFaddend45a8872009-03-24 20:41:52 -07004549 /* unexpected during class loading, okay on first use (uncompress) */
Andy McFadden9faa9e62009-04-08 00:35:55 -07004550 LOGV("NOTE: registerMap already set for %s.%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004551 method->clazz->descriptor, method->name);
4552 /* keep going */
4553 }
The Android Open Source Project99409882009-03-18 22:20:24 -07004554 assert(!dvmIsNativeMethod(method) && !dvmIsAbstractMethod(method));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004555
4556 /* might be virtual or direct */
4557 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
4558 dvmLinearReadWrite(clazz->classLoader, clazz->directMethods);
4559
4560 method->registerMap = pMap;
4561
4562 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
4563 dvmLinearReadOnly(clazz->classLoader, clazz->directMethods);
4564}
4565
4566/*
4567 * dvmHashForeach callback. A nonzero return value causes foreach to
4568 * bail out.
4569 */
4570static int findClassCallback(void* vclazz, void* arg)
4571{
4572 ClassObject* clazz = vclazz;
4573 const char* descriptor = (const char*) arg;
4574
4575 if (strcmp(clazz->descriptor, descriptor) == 0)
4576 return (int) clazz;
4577 return 0;
4578}
4579
4580/*
4581 * Find a loaded class by descriptor. Returns the first one found.
4582 * Because there can be more than one if class loaders are involved,
4583 * this is not an especially good API. (Currently only used by the
4584 * debugger and "checking" JNI.)
4585 *
4586 * "descriptor" should have the form "Ljava/lang/Class;" or
4587 * "[Ljava/lang/Class;", i.e. a descriptor and not an internal-form
4588 * class name.
4589 */
4590ClassObject* dvmFindLoadedClass(const char* descriptor)
4591{
4592 int result;
4593
4594 dvmHashTableLock(gDvm.loadedClasses);
4595 result = dvmHashForeach(gDvm.loadedClasses, findClassCallback,
4596 (void*) descriptor);
4597 dvmHashTableUnlock(gDvm.loadedClasses);
4598
4599 return (ClassObject*) result;
4600}
4601
4602/*
4603 * Retrieve the system (a/k/a application) class loader.
4604 */
4605Object* dvmGetSystemClassLoader(void)
4606{
4607 ClassObject* clazz;
4608 Method* getSysMeth;
4609 Object* loader;
4610
4611 clazz = dvmFindSystemClass("Ljava/lang/ClassLoader;");
4612 if (clazz == NULL)
4613 return NULL;
4614
4615 getSysMeth = dvmFindDirectMethodByDescriptor(clazz, "getSystemClassLoader",
4616 "()Ljava/lang/ClassLoader;");
4617 if (getSysMeth == NULL)
4618 return NULL;
4619
4620 JValue result;
4621 dvmCallMethod(dvmThreadSelf(), getSysMeth, NULL, &result);
4622 loader = (Object*)result.l;
4623 return loader;
4624}
4625
4626
4627/*
4628 * This is a dvmHashForeach callback.
4629 */
4630static int dumpClass(void* vclazz, void* varg)
4631{
4632 const ClassObject* clazz = (const ClassObject*) vclazz;
4633 const ClassObject* super;
4634 int flags = (int) varg;
4635 char* desc;
4636 int i;
4637
4638 if (clazz == NULL) {
4639 LOGI("dumpClass: ignoring request to dump null class\n");
4640 return 0;
4641 }
4642
4643 if ((flags & kDumpClassFullDetail) == 0) {
4644 bool showInit = (flags & kDumpClassInitialized) != 0;
4645 bool showLoader = (flags & kDumpClassClassLoader) != 0;
4646 const char* initStr;
4647
4648 initStr = dvmIsClassInitialized(clazz) ? "true" : "false";
4649
4650 if (showInit && showLoader)
4651 LOGI("%s %p %s\n", clazz->descriptor, clazz->classLoader, initStr);
4652 else if (showInit)
4653 LOGI("%s %s\n", clazz->descriptor, initStr);
4654 else if (showLoader)
4655 LOGI("%s %p\n", clazz->descriptor, clazz->classLoader);
4656 else
4657 LOGI("%s\n", clazz->descriptor);
4658
4659 return 0;
4660 }
4661
4662 /* clazz->super briefly holds the superclass index during class prep */
4663 if ((u4)clazz->super > 0x10000 && (u4) clazz->super != (u4)-1)
4664 super = clazz->super;
4665 else
4666 super = NULL;
4667
4668 LOGI("----- %s '%s' cl=%p ser=0x%08x -----\n",
4669 dvmIsInterfaceClass(clazz) ? "interface" : "class",
4670 clazz->descriptor, clazz->classLoader, clazz->serialNumber);
4671 LOGI(" objectSize=%d (%d from super)\n", (int) clazz->objectSize,
4672 super != NULL ? (int) super->objectSize : -1);
4673 LOGI(" access=0x%04x.%04x\n", clazz->accessFlags >> 16,
4674 clazz->accessFlags & JAVA_FLAGS_MASK);
4675 if (super != NULL)
4676 LOGI(" super='%s' (cl=%p)\n", super->descriptor, super->classLoader);
4677 if (dvmIsArrayClass(clazz)) {
4678 LOGI(" dimensions=%d elementClass=%s\n",
4679 clazz->arrayDim, clazz->elementClass->descriptor);
4680 }
4681 if (clazz->iftableCount > 0) {
4682 LOGI(" interfaces (%d):\n", clazz->iftableCount);
4683 for (i = 0; i < clazz->iftableCount; i++) {
4684 InterfaceEntry* ent = &clazz->iftable[i];
4685 int j;
4686
4687 LOGI(" %2d: %s (cl=%p)\n",
4688 i, ent->clazz->descriptor, ent->clazz->classLoader);
4689
4690 /* enable when needed */
4691 if (false && ent->methodIndexArray != NULL) {
4692 for (j = 0; j < ent->clazz->virtualMethodCount; j++)
4693 LOGI(" %2d: %d %s %s\n",
4694 j, ent->methodIndexArray[j],
4695 ent->clazz->virtualMethods[j].name,
4696 clazz->vtable[ent->methodIndexArray[j]]->name);
4697 }
4698 }
4699 }
4700 if (!dvmIsInterfaceClass(clazz)) {
4701 LOGI(" vtable (%d entries, %d in super):\n", clazz->vtableCount,
4702 super != NULL ? super->vtableCount : 0);
4703 for (i = 0; i < clazz->vtableCount; i++) {
4704 desc = dexProtoCopyMethodDescriptor(&clazz->vtable[i]->prototype);
4705 LOGI(" %s%2d: %p %20s %s\n",
4706 (i != clazz->vtable[i]->methodIndex) ? "*** " : "",
4707 (u4) clazz->vtable[i]->methodIndex, clazz->vtable[i],
4708 clazz->vtable[i]->name, desc);
4709 free(desc);
4710 }
4711 LOGI(" direct methods (%d entries):\n", clazz->directMethodCount);
4712 for (i = 0; i < clazz->directMethodCount; i++) {
4713 desc = dexProtoCopyMethodDescriptor(
4714 &clazz->directMethods[i].prototype);
4715 LOGI(" %2d: %20s %s\n", i, clazz->directMethods[i].name,
4716 desc);
4717 free(desc);
4718 }
4719 } else {
4720 LOGI(" interface methods (%d):\n", clazz->virtualMethodCount);
4721 for (i = 0; i < clazz->virtualMethodCount; i++) {
4722 desc = dexProtoCopyMethodDescriptor(
4723 &clazz->virtualMethods[i].prototype);
4724 LOGI(" %2d: %2d %20s %s\n", i,
4725 (u4) clazz->virtualMethods[i].methodIndex,
4726 clazz->virtualMethods[i].name,
4727 desc);
4728 free(desc);
4729 }
4730 }
4731 if (clazz->sfieldCount > 0) {
4732 LOGI(" static fields (%d entries):\n", clazz->sfieldCount);
4733 for (i = 0; i < clazz->sfieldCount; i++) {
4734 LOGI(" %2d: %20s %s\n", i, clazz->sfields[i].field.name,
4735 clazz->sfields[i].field.signature);
4736 }
4737 }
4738 if (clazz->ifieldCount > 0) {
4739 LOGI(" instance fields (%d entries):\n", clazz->ifieldCount);
4740 for (i = 0; i < clazz->ifieldCount; i++) {
4741 LOGI(" %2d: %20s %s\n", i, clazz->ifields[i].field.name,
4742 clazz->ifields[i].field.signature);
4743 }
4744 }
4745 return 0;
4746}
4747
4748/*
4749 * Dump the contents of a single class.
4750 *
4751 * Pass kDumpClassFullDetail into "flags" to get lots of detail.
4752 */
4753void dvmDumpClass(const ClassObject* clazz, int flags)
4754{
4755 dumpClass((void*) clazz, (void*) flags);
4756}
4757
4758/*
4759 * Dump the contents of all classes.
4760 */
4761void dvmDumpAllClasses(int flags)
4762{
4763 dvmHashTableLock(gDvm.loadedClasses);
4764 dvmHashForeach(gDvm.loadedClasses, dumpClass, (void*) flags);
4765 dvmHashTableUnlock(gDvm.loadedClasses);
4766}
4767
4768/*
4769 * Get the number of loaded classes
4770 */
4771int dvmGetNumLoadedClasses()
4772{
4773 int count;
4774 dvmHashTableLock(gDvm.loadedClasses);
4775 count = dvmHashTableNumEntries(gDvm.loadedClasses);
4776 dvmHashTableUnlock(gDvm.loadedClasses);
4777 return count;
4778}
4779
4780/*
4781 * Write some statistics to the log file.
4782 */
4783void dvmDumpLoaderStats(const char* msg)
4784{
4785 LOGV("VM stats (%s): cls=%d/%d meth=%d ifld=%d sfld=%d linear=%d\n",
4786 msg, gDvm.numLoadedClasses, dvmHashTableNumEntries(gDvm.loadedClasses),
4787 gDvm.numDeclaredMethods, gDvm.numDeclaredInstFields,
4788 gDvm.numDeclaredStaticFields, gDvm.pBootLoaderAlloc->curOffset);
4789#ifdef COUNT_PRECISE_METHODS
4790 LOGI("GC precise methods: %d\n",
4791 dvmPointerSetGetCount(gDvm.preciseMethods));
4792#endif
4793}
4794
4795#ifdef PROFILE_FIELD_ACCESS
4796/*
4797 * Dump the field access counts for all fields in this method.
4798 */
4799static int dumpAccessCounts(void* vclazz, void* varg)
4800{
4801 const ClassObject* clazz = (const ClassObject*) vclazz;
4802 int i;
4803
4804 for (i = 0; i < clazz->ifieldCount; i++) {
4805 Field* field = &clazz->ifields[i].field;
4806
4807 if (field->gets != 0)
4808 printf("GI %d %s.%s\n", field->gets,
4809 field->clazz->descriptor, field->name);
4810 if (field->puts != 0)
4811 printf("PI %d %s.%s\n", field->puts,
4812 field->clazz->descriptor, field->name);
4813 }
4814 for (i = 0; i < clazz->sfieldCount; i++) {
4815 Field* field = &clazz->sfields[i].field;
4816
4817 if (field->gets != 0)
4818 printf("GS %d %s.%s\n", field->gets,
4819 field->clazz->descriptor, field->name);
4820 if (field->puts != 0)
4821 printf("PS %d %s.%s\n", field->puts,
4822 field->clazz->descriptor, field->name);
4823 }
4824
4825 return 0;
4826}
4827
4828/*
4829 * Dump the field access counts for all loaded classes.
4830 */
4831void dvmDumpFieldAccessCounts(void)
4832{
4833 dvmHashTableLock(gDvm.loadedClasses);
4834 dvmHashForeach(gDvm.loadedClasses, dumpAccessCounts, NULL);
4835 dvmHashTableUnlock(gDvm.loadedClasses);
4836}
4837#endif
4838
4839
4840/*
4841 * Mark all classes associated with the built-in loader.
4842 */
4843static int markClassObject(void *clazz, void *arg)
4844{
4845 UNUSED_PARAMETER(arg);
4846
4847 dvmMarkObjectNonNull((Object *)clazz);
4848 return 0;
4849}
4850
4851/*
4852 * The garbage collector calls this to mark the class objects for all
4853 * loaded classes.
4854 */
4855void dvmGcScanRootClassLoader()
4856{
4857 /* dvmClassStartup() may not have been called before the first GC.
4858 */
4859 if (gDvm.loadedClasses != NULL) {
4860 dvmHashTableLock(gDvm.loadedClasses);
4861 dvmHashForeach(gDvm.loadedClasses, markClassObject, NULL);
4862 dvmHashTableUnlock(gDvm.loadedClasses);
4863 }
4864}
4865
4866
4867/*
4868 * ===========================================================================
4869 * Method Prototypes and Descriptors
4870 * ===========================================================================
4871 */
4872
4873/*
4874 * Compare the two method names and prototypes, a la strcmp(). The
4875 * name is considered the "major" order and the prototype the "minor"
4876 * order. The prototypes are compared as if by dvmCompareMethodProtos().
4877 */
4878int dvmCompareMethodNamesAndProtos(const Method* method1,
4879 const Method* method2)
4880{
4881 int result = strcmp(method1->name, method2->name);
4882
4883 if (result != 0) {
4884 return result;
4885 }
4886
4887 return dvmCompareMethodProtos(method1, method2);
4888}
4889
4890/*
4891 * Compare the two method names and prototypes, a la strcmp(), ignoring
4892 * the return value. The name is considered the "major" order and the
4893 * prototype the "minor" order. The prototypes are compared as if by
4894 * dvmCompareMethodArgProtos().
4895 */
4896int dvmCompareMethodNamesAndParameterProtos(const Method* method1,
4897 const Method* method2)
4898{
4899 int result = strcmp(method1->name, method2->name);
4900
4901 if (result != 0) {
4902 return result;
4903 }
4904
4905 return dvmCompareMethodParameterProtos(method1, method2);
4906}
4907
4908/*
4909 * Compare a (name, prototype) pair with the (name, prototype) of
4910 * a method, a la strcmp(). The name is considered the "major" order and
4911 * the prototype the "minor" order. The descriptor and prototype are
4912 * compared as if by dvmCompareDescriptorAndMethodProto().
4913 */
4914int dvmCompareNameProtoAndMethod(const char* name,
4915 const DexProto* proto, const Method* method)
4916{
4917 int result = strcmp(name, method->name);
4918
4919 if (result != 0) {
4920 return result;
4921 }
4922
4923 return dexProtoCompare(proto, &method->prototype);
4924}
4925
4926/*
4927 * Compare a (name, method descriptor) pair with the (name, prototype) of
4928 * a method, a la strcmp(). The name is considered the "major" order and
4929 * the prototype the "minor" order. The descriptor and prototype are
4930 * compared as if by dvmCompareDescriptorAndMethodProto().
4931 */
4932int dvmCompareNameDescriptorAndMethod(const char* name,
4933 const char* descriptor, const Method* method)
4934{
4935 int result = strcmp(name, method->name);
4936
4937 if (result != 0) {
4938 return result;
4939 }
4940
4941 return dvmCompareDescriptorAndMethodProto(descriptor, method);
4942}