2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Class loading, including bootstrap class loader, linking, and
22 #define LOG_CLASS_LOADING 0
25 #include "libdex/DexClass.h"
26 #include "analysis/Optimize.h"
35 #include <cutils/process_name.h>
36 #include <sys/types.h>
40 Notes on Linking and Verification
42 The basic way to retrieve a class is to load it, make sure its superclass
43 and interfaces are available, prepare its fields, and return it. This gets
44 a little more complicated when multiple threads can be trying to retrieve
45 the class simultaneously, requiring that we use the class object's monitor
46 to keep things orderly.
48 The linking (preparing, resolving) of a class can cause us to recursively
49 load superclasses and interfaces. Barring circular references (e.g. two
50 classes that are superclasses of each other), this will complete without
51 the loader attempting to access the partially-linked class.
53 With verification, the situation is different. If we try to verify
54 every class as we load it, we quickly run into trouble. Even the lowly
55 java.lang.Object requires CloneNotSupportedException; follow the list
56 of referenced classes and you can head down quite a trail. The trail
57 eventually leads back to Object, which is officially not fully-formed yet.
59 The VM spec (specifically, v2 5.4.1) notes that classes pulled in during
60 verification do not need to be prepared or verified. This means that we
61 are allowed to have loaded but unverified classes. It further notes that
62 the class must be verified before it is initialized, which allows us to
63 defer verification for all classes until class init. You can't execute
64 code or access fields in an uninitialized class, so this is safe.
66 It also allows a more peaceful coexistence between verified and
67 unverifiable code. If class A refers to B, and B has a method that
68 refers to a bogus class C, should we allow class A to be verified?
69 If A only exercises parts of B that don't use class C, then there is
70 nothing wrong with running code in A. We can fully verify both A and B,
71 and allow execution to continue until B causes initialization of C. The
72 VerifyError is thrown close to the point of use.
74 This gets a little weird with java.lang.Class, which is the only class
75 that can be instantiated before it is initialized. We have to force
76 initialization right after the class is created, because by definition we
77 have instances of it on the heap, and somebody might get a class object and
78 start making virtual calls on it. We can end up going recursive during
79 verification of java.lang.Class, but we avoid that by checking to see if
80 verification is already in progress before we try to initialize it.
84 Notes on class loaders and interaction with optimization / verification
86 In what follows, "pre-verification" and "optimization" are the steps
87 performed by the dexopt command, which attempts to verify and optimize
88 classes as part of unpacking jar files and storing the DEX data in the
89 dalvik-cache directory. These steps are performed by loading the DEX
90 files directly, without any assistance from ClassLoader instances.
92 When we pre-verify and optimize a class in a DEX file, we make some
93 assumptions about where the class loader will go to look for classes.
94 If we can't guarantee those assumptions, e.g. because a class ("AppClass")
95 references something not defined in the bootstrap jars or the AppClass jar,
96 we can't pre-verify or optimize the class.
98 The VM doesn't define the behavior of user-defined class loaders.
99 For example, suppose application class AppClass, loaded by UserLoader,
100 has a method that creates a java.lang.String. The first time
101 AppClass.stringyMethod tries to do something with java.lang.String, it
102 asks UserLoader to find it. UserLoader is expected to defer to its parent
103 loader, but isn't required to. UserLoader might provide a replacement
106 We can run into trouble if we pre-verify AppClass with the assumption that
107 java.lang.String will come from core.jar, and don't verify this assumption
108 at runtime. There are two places that an alternate implementation of
109 java.lang.String can come from: the AppClass jar, or from some other jar
110 that UserLoader knows about. (Someday UserLoader will be able to generate
111 some bytecode and call DefineClass, but not yet.)
113 To handle the first situation, the pre-verifier will explicitly check for
114 conflicts between the class being optimized/verified and the bootstrap
115 classes. If an app jar contains a class that has the same package and
116 class name as a class in a bootstrap jar, the verification resolver refuses
117 to find either, which will block pre-verification and optimization on
118 classes that reference ambiguity. The VM will postpone verification of
119 the app class until first load.
121 For the second situation, we need to ensure that all references from a
122 pre-verified class are satisified by the class' jar or earlier bootstrap
123 jars. In concrete terms: when resolving a reference to NewClass,
124 which was caused by a reference in class AppClass, we check to see if
125 AppClass was pre-verified. If so, we require that NewClass comes out
126 of either the AppClass jar or one of the jars in the bootstrap path.
127 (We may not control the class loaders, but we do manage the DEX files.
128 We can verify that it's either (loader==null && dexFile==a_boot_dex)
129 or (loader==UserLoader && dexFile==AppClass.dexFile). Classes from
130 DefineClass can't be pre-verified, so this doesn't apply.)
132 This should ensure that you can't "fake out" the pre-verifier by creating
133 a user-defined class loader that replaces system classes. It should
134 also ensure that you can write such a loader and have it work in the
135 expected fashion; all you lose is some performance due to "just-in-time
136 verification" and the lack of DEX optimizations.
138 There is a "back door" of sorts in the class resolution check, due to
139 the fact that the "class ref" entries are shared between the bytecode
140 and meta-data references (e.g. annotations and exception handler lists).
141 The class references in annotations have no bearing on class verification,
142 so when a class does an annotation query that causes a class reference
143 index to be resolved, we don't want to fail just because the calling
144 class was pre-verified and the resolved class is in some random DEX file.
145 The successful resolution adds the class to the "resolved classes" table,
146 so when optimized bytecode references it we don't repeat the resolve-time
147 check. We can avoid this by not updating the "resolved classes" table
148 when the class reference doesn't come out of something that has been
149 checked by the verifier, but that has a nonzero performance impact.
150 Since the ultimate goal of this test is to catch an unusual situation
151 (user-defined class loaders redefining core classes), the added caution
152 may not be worth the performance hit.
156 * Class serial numbers start at this value. We use a nonzero initial
157 * value so they stand out in binary dumps (e.g. hprof output).
159 #define INITIAL_CLASS_SERIAL_NUMBER 0x50000000
162 * Constant used to size an auxillary class object data structure.
163 * For optimum memory use this should be equal to or slightly larger than
164 * the number of classes loaded when the zygote finishes initializing.
166 #define ZYGOTE_CLASS_CUTOFF 2304
168 #define CLASS_SFIELD_SLOTS 1
170 static ClassPathEntry* processClassPath(const char* pathStr, bool isBootstrap);
171 static void freeCpeArray(ClassPathEntry* cpe);
173 static ClassObject* findClassFromLoaderNoInit(
174 const char* descriptor, Object* loader);
175 static ClassObject* findClassNoInit(const char* descriptor, Object* loader,\
177 static ClassObject* loadClassFromDex(DvmDex* pDvmDex,
178 const DexClassDef* pClassDef, Object* loader);
179 static void loadMethodFromDex(ClassObject* clazz, const DexMethod* pDexMethod,\
181 static int computeJniArgInfo(const DexProto* proto);
182 static void loadSFieldFromDex(ClassObject* clazz,
183 const DexField* pDexSField, StaticField* sfield);
184 static void loadIFieldFromDex(ClassObject* clazz,
185 const DexField* pDexIField, InstField* field);
186 static bool precacheReferenceOffsets(ClassObject* clazz);
187 static void computeRefOffsets(ClassObject* clazz);
188 static void freeMethodInnards(Method* meth);
189 static bool createVtable(ClassObject* clazz);
190 static bool createIftable(ClassObject* clazz);
191 static bool insertMethodStubs(ClassObject* clazz);
192 static bool computeFieldOffsets(ClassObject* clazz);
193 static void throwEarlierClassFailure(ClassObject* clazz);
195 #if LOG_CLASS_LOADING
197 * Logs information about a class loading with given timestamp.
199 * TODO: In the case where we fail in dvmLinkClass() and log the class as closing (type='<'),
200 * it would probably be better to use a new type code to indicate the failure. This change would
201 * require a matching change in the parser and analysis code in frameworks/base/tools/preload.
203 static void logClassLoadWithTime(char type, ClassObject* clazz, u8 time) {
204 pid_t ppid = getppid();
205 pid_t pid = getpid();
206 unsigned int tid = (unsigned int) pthread_self();
208 ALOG(LOG_INFO, "PRELOAD", "%c%d:%d:%d:%s:%d:%s:%lld", type, ppid, pid, tid,
209 get_process_name(), (int) clazz->classLoader, clazz->descriptor,
214 * Logs information about a class loading.
216 static void logClassLoad(char type, ClassObject* clazz) {
217 logClassLoadWithTime(type, clazz, dvmGetThreadCpuTimeNsec());
222 * Some LinearAlloc unit tests.
224 static void linearAllocTests()
231 fiddle = (char*)dvmLinearAlloc(NULL, 3200-28);
232 dvmLinearReadOnly(NULL, (char*)fiddle);
235 fiddle = (char*)dvmLinearAlloc(NULL, 3200-24);
236 dvmLinearReadOnly(NULL, (char*)fiddle);
239 fiddle = (char*)dvmLinearAlloc(NULL, 3200-20);
240 dvmLinearReadOnly(NULL, (char*)fiddle);
243 fiddle = (char*)dvmLinearAlloc(NULL, 3200-16);
244 dvmLinearReadOnly(NULL, (char*)fiddle);
247 fiddle = (char*)dvmLinearAlloc(NULL, 3200-12);
248 dvmLinearReadOnly(NULL, (char*)fiddle);
251 fiddle = (char*)dvmLinearAlloc(NULL, 896);
252 dvmLinearReadOnly(NULL, (char*)fiddle);
253 fiddle = (char*)dvmLinearAlloc(NULL, 20); // watch addr of this alloc
254 dvmLinearReadOnly(NULL, (char*)fiddle);
256 fiddle = (char*)dvmLinearAlloc(NULL, 1);
258 dvmLinearReadOnly(NULL, fiddle);
259 fiddle = (char*)dvmLinearAlloc(NULL, 4096);
262 dvmLinearReadOnly(NULL, fiddle);
263 dvmLinearFree(NULL, fiddle);
264 fiddle = (char*)dvmLinearAlloc(NULL, 0);
265 dvmLinearReadOnly(NULL, fiddle);
266 fiddle = (char*)dvmLinearRealloc(NULL, fiddle, 12);
268 dvmLinearReadOnly(NULL, (char*)fiddle);
269 fiddle = (char*)dvmLinearRealloc(NULL, fiddle, 5);
270 dvmLinearReadOnly(NULL, fiddle);
271 fiddle = (char*)dvmLinearAlloc(NULL, 17001);
274 dvmLinearReadOnly(NULL, (char*)fiddle);
276 char* str = (char*)dvmLinearStrdup(NULL, "This is a test!");
277 ALOGI("GOT: '%s'", str);
279 /* try to check the bounds; allocator may round allocation size up */
280 fiddle = (char*)dvmLinearAlloc(NULL, 12);
281 ALOGI("Should be 1: %d", dvmLinearAllocContains(fiddle, 12));
282 ALOGI("Should be 0: %d", dvmLinearAllocContains(fiddle, 13));
283 ALOGI("Should be 0: %d", dvmLinearAllocContains(fiddle - 128*1024, 1));
285 dvmLinearAllocDump(NULL);
286 dvmLinearFree(NULL, (char*)str);
289 static size_t classObjectSize(size_t sfieldCount)
291 size_t offset = OFFSETOF_MEMBER(ClassObject, sfields);
292 return offset + sizeof(StaticField) * sfieldCount;
295 size_t dvmClassObjectSize(const ClassObject *clazz)
297 assert(clazz != NULL);
298 return classObjectSize(clazz->sfieldCount);
301 /* (documented in header) */
302 ClassObject* dvmFindPrimitiveClass(char type)
304 PrimitiveType primitiveType = dexGetPrimitiveTypeFromDescriptorChar(type);
306 switch (primitiveType) {
307 case PRIM_VOID: return gDvm.typeVoid;
308 case PRIM_BOOLEAN: return gDvm.typeBoolean;
309 case PRIM_BYTE: return gDvm.typeByte;
310 case PRIM_SHORT: return gDvm.typeShort;
311 case PRIM_CHAR: return gDvm.typeChar;
312 case PRIM_INT: return gDvm.typeInt;
313 case PRIM_LONG: return gDvm.typeLong;
314 case PRIM_FLOAT: return gDvm.typeFloat;
315 case PRIM_DOUBLE: return gDvm.typeDouble;
317 ALOGW("Unknown primitive type '%c'", type);
324 * Synthesize a primitive class.
326 * Just creates the class and returns it (does not add it to the class list).
328 static bool createPrimitiveType(PrimitiveType primitiveType, ClassObject** pClass)
331 * Fill out a few fields in the ClassObject.
333 * Note that primitive classes do not sub-class the class Object.
334 * This matters for "instanceof" checks. Also, we assume that the
335 * primitive class does not override finalize().
338 const char* descriptor = dexGetPrimitiveTypeDescriptor(primitiveType);
339 assert(descriptor != NULL);
341 ClassObject* newClass = (ClassObject*) dvmMalloc(sizeof(*newClass), ALLOC_NON_MOVING);
342 if (newClass == NULL) {
346 DVM_OBJECT_INIT(newClass, gDvm.classJavaLangClass);
347 dvmSetClassSerialNumber(newClass);
348 SET_CLASS_FLAG(newClass, ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT);
349 newClass->primitiveType = primitiveType;
350 newClass->descriptorAlloc = NULL;
351 newClass->descriptor = descriptor;
352 newClass->super = NULL;
353 newClass->status = CLASS_INITIALIZED;
355 /* don't need to set newClass->objectSize */
357 LOGVV("Constructed class for primitive type '%s'", newClass->descriptor);
360 dvmReleaseTrackedAlloc((Object*) newClass, NULL);
366 * Create the initial class instances. These consist of the class
367 * Class and all of the classes representing primitive types.
369 static bool createInitialClasses() {
371 * Initialize the class Class. This has to be done specially, particularly
372 * because it is an instance of itself.
374 ClassObject* clazz = (ClassObject*)
375 dvmMalloc(classObjectSize(CLASS_SFIELD_SLOTS), ALLOC_NON_MOVING);
379 DVM_OBJECT_INIT(clazz, clazz);
380 SET_CLASS_FLAG(clazz, ACC_PUBLIC | ACC_FINAL | CLASS_ISCLASS);
381 clazz->descriptor = "Ljava/lang/Class;";
382 gDvm.classJavaLangClass = clazz;
383 LOGVV("Constructed the class Class.");
386 * Initialize the classes representing primitive types. These are
387 * instances of the class Class, but other than that they're fairly
388 * different from regular classes.
391 ok &= createPrimitiveType(PRIM_VOID, &gDvm.typeVoid);
392 ok &= createPrimitiveType(PRIM_BOOLEAN, &gDvm.typeBoolean);
393 ok &= createPrimitiveType(PRIM_BYTE, &gDvm.typeByte);
394 ok &= createPrimitiveType(PRIM_SHORT, &gDvm.typeShort);
395 ok &= createPrimitiveType(PRIM_CHAR, &gDvm.typeChar);
396 ok &= createPrimitiveType(PRIM_INT, &gDvm.typeInt);
397 ok &= createPrimitiveType(PRIM_LONG, &gDvm.typeLong);
398 ok &= createPrimitiveType(PRIM_FLOAT, &gDvm.typeFloat);
399 ok &= createPrimitiveType(PRIM_DOUBLE, &gDvm.typeDouble);
405 * Initialize the bootstrap class loader.
407 * Call this after the bootclasspath string has been finalized.
409 bool dvmClassStartup()
411 /* make this a requirement -- don't currently support dirs in path */
412 if (strcmp(gDvm.bootClassPathStr, ".") == 0) {
413 ALOGE("ERROR: must specify non-'.' bootclasspath");
418 dvmHashTableCreate(256, (HashFreeFunc) dvmFreeClassInnards);
420 gDvm.pBootLoaderAlloc = dvmLinearAllocCreate(NULL);
421 if (gDvm.pBootLoaderAlloc == NULL)
430 * Class serial number. We start with a high value to make it distinct
431 * in binary dumps (e.g. hprof).
433 gDvm.classSerialNumber = INITIAL_CLASS_SERIAL_NUMBER;
436 * Set up the table we'll use for tracking initiating loaders for
438 * If it's NULL, we just fall back to the InitiatingLoaderList in the
439 * ClassObject, so it's not fatal to fail this allocation.
441 gDvm.initiatingLoaderList = (InitiatingLoaderList*)
442 calloc(ZYGOTE_CLASS_CUTOFF, sizeof(InitiatingLoaderList));
445 * Create the initial classes. These are the first objects constructed
446 * within the nascent VM.
448 if (!createInitialClasses()) {
453 * Process the bootstrap class path. This means opening the specified
454 * DEX or Jar files and possibly running them through the optimizer.
456 assert(gDvm.bootClassPath == NULL);
457 processClassPath(gDvm.bootClassPathStr, true);
459 if (gDvm.bootClassPath == NULL)
468 void dvmClassShutdown()
470 /* discard all system-loaded classes */
471 dvmHashTableFree(gDvm.loadedClasses);
472 gDvm.loadedClasses = NULL;
474 /* discard primitive classes created for arrays */
475 dvmFreeClassInnards(gDvm.typeVoid);
476 dvmFreeClassInnards(gDvm.typeBoolean);
477 dvmFreeClassInnards(gDvm.typeByte);
478 dvmFreeClassInnards(gDvm.typeShort);
479 dvmFreeClassInnards(gDvm.typeChar);
480 dvmFreeClassInnards(gDvm.typeInt);
481 dvmFreeClassInnards(gDvm.typeLong);
482 dvmFreeClassInnards(gDvm.typeFloat);
483 dvmFreeClassInnards(gDvm.typeDouble);
485 /* this closes DEX files, JAR files, etc. */
486 freeCpeArray(gDvm.bootClassPath);
487 gDvm.bootClassPath = NULL;
489 dvmLinearAllocDestroy(NULL);
491 free(gDvm.initiatingLoaderList);
496 * ===========================================================================
497 * Bootstrap class loader
498 * ===========================================================================
502 * Dump the contents of a ClassPathEntry array.
504 static void dumpClassPath(const ClassPathEntry* cpe)
508 while (cpe->kind != kCpeLastEntry) {
512 case kCpeJar: kindStr = "jar"; break;
513 case kCpeDex: kindStr = "dex"; break;
514 default: kindStr = "???"; break;
517 ALOGI(" %2d: type=%s %s %p", idx, kindStr, cpe->fileName, cpe->ptr);
518 if (CALC_CACHE_STATS && cpe->kind == kCpeJar) {
519 JarFile* pJarFile = (JarFile*) cpe->ptr;
520 DvmDex* pDvmDex = dvmGetJarFileDex(pJarFile);
521 dvmDumpAtomicCacheStats(pDvmDex->pInterfaceCache);
530 * Dump the contents of the bootstrap class path.
532 void dvmDumpBootClassPath()
534 dumpClassPath(gDvm.bootClassPath);
538 * Returns "true" if the class path contains the specified path.
540 bool dvmClassPathContains(const ClassPathEntry* cpe, const char* path)
542 while (cpe->kind != kCpeLastEntry) {
543 if (strcmp(cpe->fileName, path) == 0)
552 * Free an array of ClassPathEntry structs.
554 * We release the contents of each entry, then free the array itself.
556 static void freeCpeArray(ClassPathEntry* cpe)
558 ClassPathEntry* cpeStart = cpe;
563 while (cpe->kind != kCpeLastEntry) {
567 dvmJarFileFree((JarFile*) cpe->ptr);
570 /* free RawDexFile */
571 dvmRawDexFileFree((RawDexFile*) cpe->ptr);
586 * Get the filename suffix of the given file (everything after the
587 * last "." if any, or "<none>" if there's no apparent suffix). The
588 * passed-in buffer will always be '\0' terminated.
590 static void getFileNameSuffix(const char* fileName, char* suffixBuf, size_t suffixBufLen)
592 const char* lastDot = strrchr(fileName, '.');
594 strlcpy(suffixBuf, (lastDot == NULL) ? "<none>" : (lastDot + 1), suffixBufLen);
598 * Prepare a ClassPathEntry struct, which at this point only has a valid
599 * filename. We need to figure out what kind of file it is, and for
600 * everything other than directories we need to open it up and see
603 static bool prepareCpe(ClassPathEntry* cpe, bool isBootstrap)
607 if (stat(cpe->fileName, &sb) < 0) {
608 ALOGD("Unable to stat classpath element '%s'", cpe->fileName);
611 if (S_ISDIR(sb.st_mode)) {
612 ALOGE("Directory classpath elements are not supported: %s", cpe->fileName);
617 getFileNameSuffix(cpe->fileName, suffix, sizeof(suffix));
619 if ((strcmp(suffix, "jar") == 0) || (strcmp(suffix, "zip") == 0) ||
620 (strcmp(suffix, "apk") == 0)) {
621 JarFile* pJarFile = NULL;
622 if (dvmJarFileOpen(cpe->fileName, NULL, &pJarFile, isBootstrap) == 0) {
627 } else if (strcmp(suffix, "dex") == 0) {
628 RawDexFile* pRawDexFile = NULL;
629 if (dvmRawDexFileOpen(cpe->fileName, NULL, &pRawDexFile, isBootstrap) == 0) {
631 cpe->ptr = pRawDexFile;
635 ALOGE("Unknown type suffix '%s'", suffix);
638 ALOGD("Unable to process classpath element '%s'", cpe->fileName);
643 * Convert a colon-separated list of directories, Zip files, and DEX files
644 * into an array of ClassPathEntry structs.
646 * During normal startup we fail if there are no entries, because we won't
647 * get very far without the basic language support classes, but if we're
648 * optimizing a DEX file we allow it.
650 * If entries are added or removed from the bootstrap class path, the
651 * dependencies in the DEX files will break, and everything except the
652 * very first entry will need to be regenerated.
654 static ClassPathEntry* processClassPath(const char* pathStr, bool isBootstrap)
656 ClassPathEntry* cpe = NULL;
662 assert(pathStr != NULL);
664 mangle = strdup(pathStr);
667 * Run through and essentially strtok() the string. Get a count of
668 * the #of elements while we're at it.
670 * If the path was constructed strangely (e.g. ":foo::bar:") this will
671 * over-allocate, which isn't ideal but is mostly harmless.
674 for (cp = mangle; *cp != '\0'; cp++) {
675 if (*cp == ':') { /* separates two entries */
683 * Allocate storage. We over-alloc by one so we can set an "end" marker.
685 cpe = (ClassPathEntry*) calloc(count+1, sizeof(ClassPathEntry));
688 * Set the global pointer so the DEX file dependency stuff can find it.
690 gDvm.bootClassPath = cpe;
693 * Go through a second time, pulling stuff out.
699 /* leading, trailing, or doubled ':'; ignore it */
702 dvmPathToAbsolutePortion(cp) == NULL) {
703 ALOGE("Non-absolute bootclasspath entry '%s'", cp);
710 tmp.kind = kCpeUnknown;
711 tmp.fileName = strdup(cp);
715 * Drop an end marker here so DEX loader can walk unfinished
718 cpe[idx].kind = kCpeLastEntry;
719 cpe[idx].fileName = NULL;
722 if (!prepareCpe(&tmp, isBootstrap)) {
723 /* drop from list and continue on */
726 /* copy over, pointers and all */
734 assert(idx <= count);
735 if (idx == 0 && !gDvm.optimizing) {
737 * There's no way the vm will be doing anything if this is the
738 * case, so just bail out (reasonably) gracefully.
740 ALOGE("No valid entries found in bootclasspath '%s'", pathStr);
741 gDvm.lastMessage = pathStr;
745 LOGVV(" (filled %d of %d slots)", idx, count);
747 /* put end marker in over-alloc slot */
748 cpe[idx].kind = kCpeLastEntry;
749 cpe[idx].fileName = NULL;
752 //dumpClassPath(cpe);
756 gDvm.bootClassPath = cpe;
761 * Search the DEX files we loaded from the bootstrap class path for a DEX
762 * file that has the class with the matching descriptor.
764 * Returns the matching DEX file and DexClassDef entry if found, otherwise
767 static DvmDex* searchBootPathForClass(const char* descriptor,
768 const DexClassDef** ppClassDef)
770 const ClassPathEntry* cpe = gDvm.bootClassPath;
771 const DexClassDef* pFoundDef = NULL;
772 DvmDex* pFoundFile = NULL;
774 LOGVV("+++ class '%s' not yet loaded, scanning bootclasspath...",
777 while (cpe->kind != kCpeLastEntry) {
778 //ALOGV("+++ checking '%s' (%d)", cpe->fileName, cpe->kind);
783 JarFile* pJarFile = (JarFile*) cpe->ptr;
784 const DexClassDef* pClassDef;
787 pDvmDex = dvmGetJarFileDex(pJarFile);
788 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
789 if (pClassDef != NULL) {
791 pFoundDef = pClassDef;
792 pFoundFile = pDvmDex;
799 RawDexFile* pRawDexFile = (RawDexFile*) cpe->ptr;
800 const DexClassDef* pClassDef;
803 pDvmDex = dvmGetRawDexFileDex(pRawDexFile);
804 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
805 if (pClassDef != NULL) {
807 pFoundDef = pClassDef;
808 pFoundFile = pDvmDex;
814 ALOGE("Unknown kind %d", cpe->kind);
823 * Special handling during verification + optimization.
825 * The DEX optimizer needs to load classes from the DEX file it's working
826 * on. Rather than trying to insert it into the bootstrap class path
827 * or synthesizing a class loader to manage it, we just make it available
828 * here. It logically comes after all existing entries in the bootstrap
831 if (gDvm.bootClassPathOptExtra != NULL) {
832 const DexClassDef* pClassDef;
835 dexFindClass(gDvm.bootClassPathOptExtra->pDexFile, descriptor);
836 if (pClassDef != NULL) {
838 pFoundDef = pClassDef;
839 pFoundFile = gDvm.bootClassPathOptExtra;
844 *ppClassDef = pFoundDef;
849 * Set the "extra" DEX, which becomes a de facto member of the bootstrap
852 void dvmSetBootPathExtraDex(DvmDex* pDvmDex)
854 gDvm.bootClassPathOptExtra = pDvmDex;
859 * Return the #of entries in the bootstrap class path.
861 * (Used for ClassLoader.getResources().)
863 int dvmGetBootPathSize()
865 const ClassPathEntry* cpe = gDvm.bootClassPath;
867 while (cpe->kind != kCpeLastEntry)
870 return cpe - gDvm.bootClassPath;
874 * Find a resource with the specified name in entry N of the boot class path.
876 * We return a newly-allocated String of one of these forms:
878 * jar:file://path!/name
879 * Where "path" is the bootstrap class path entry and "name" is the string
880 * passed into this method. "path" needs to be an absolute path (starting
881 * with '/'); if it's not we'd need to "absolutify" it as part of forming
884 StringObject* dvmGetBootPathResource(const char* name, int idx)
886 const int kUrlOverhead = 13; // worst case for Jar URL
887 const ClassPathEntry* cpe = gDvm.bootClassPath;
888 StringObject* urlObj = NULL;
890 ALOGV("+++ searching for resource '%s' in %d(%s)",
891 name, idx, cpe[idx].fileName);
893 /* we could use direct array index, but I don't entirely trust "idx" */
894 while (idx-- && cpe->kind != kCpeLastEntry)
896 if (cpe->kind == kCpeLastEntry) {
901 char urlBuf[strlen(name) + strlen(cpe->fileName) + kUrlOverhead +1];
906 JarFile* pJarFile = (JarFile*) cpe->ptr;
907 if (dexZipFindEntry(&pJarFile->archive, name) == NULL)
909 sprintf(urlBuf, "jar:file://%s!/%s", cpe->fileName, name);
913 ALOGV("No resources in DEX files");
920 ALOGV("+++ using URL='%s'", urlBuf);
921 urlObj = dvmCreateStringFromCstr(urlBuf);
929 * ===========================================================================
930 * Class list management
931 * ===========================================================================
934 /* search for these criteria in the Class hash table */
935 struct ClassMatchCriteria {
936 const char* descriptor;
940 #define kInitLoaderInc 4 /* must be power of 2 */
942 static InitiatingLoaderList *dvmGetInitiatingLoaderList(ClassObject* clazz)
944 assert(clazz->serialNumber >= INITIAL_CLASS_SERIAL_NUMBER);
945 int classIndex = clazz->serialNumber-INITIAL_CLASS_SERIAL_NUMBER;
946 if (gDvm.initiatingLoaderList != NULL &&
947 classIndex < ZYGOTE_CLASS_CUTOFF) {
948 return &(gDvm.initiatingLoaderList[classIndex]);
950 return &(clazz->initiatingLoaderList);
955 * Determine if "loader" appears in clazz' initiating loader list.
957 * The class hash table lock must be held when calling here, since
958 * it's also used when updating a class' initiating loader list.
960 * TODO: switch to some sort of lock-free data structure so we don't have
961 * to grab the lock to do a lookup. Among other things, this would improve
962 * the speed of compareDescriptorClasses().
964 bool dvmLoaderInInitiatingList(const ClassObject* clazz, const Object* loader)
967 * The bootstrap class loader can't be just an initiating loader for
968 * anything (it's always the defining loader if the class is visible
969 * to it). We don't put defining loaders in the initiating list.
975 * Scan the list for a match. The list is expected to be short.
977 /* Cast to remove the const from clazz, but use const loaderList */
978 ClassObject* nonConstClazz = (ClassObject*) clazz;
979 const InitiatingLoaderList *loaderList =
980 dvmGetInitiatingLoaderList(nonConstClazz);
982 for (i = loaderList->initiatingLoaderCount-1; i >= 0; --i) {
983 if (loaderList->initiatingLoaders[i] == loader) {
984 //ALOGI("+++ found initiating match %p in %s",
985 // loader, clazz->descriptor);
993 * Add "loader" to clazz's initiating loader set, unless it's the defining
996 * In the common case this will be a short list, so we don't need to do
997 * anything too fancy here.
999 * This locks gDvm.loadedClasses for synchronization, so don't hold it
1000 * when calling here.
1002 void dvmAddInitiatingLoader(ClassObject* clazz, Object* loader)
1004 if (loader != clazz->classLoader) {
1005 assert(loader != NULL);
1007 LOGVV("Adding %p to '%s' init list", loader, clazz->descriptor);
1008 dvmHashTableLock(gDvm.loadedClasses);
1011 * Make sure nobody snuck in. The penalty for adding twice is
1012 * pretty minor, and probably outweighs the O(n^2) hit for
1013 * checking before every add, so we may not want to do this.
1015 //if (dvmLoaderInInitiatingList(clazz, loader)) {
1016 // ALOGW("WOW: simultaneous add of initiating class loader");
1017 // goto bail_unlock;
1021 * The list never shrinks, so we just keep a count of the
1022 * number of elements in it, and reallocate the buffer when
1023 * we run off the end.
1025 * The pointer is initially NULL, so we *do* want to call realloc
1028 InitiatingLoaderList *loaderList = dvmGetInitiatingLoaderList(clazz);
1029 if ((loaderList->initiatingLoaderCount & (kInitLoaderInc-1)) == 0) {
1032 newList = (Object**) realloc(loaderList->initiatingLoaders,
1033 (loaderList->initiatingLoaderCount + kInitLoaderInc)
1035 if (newList == NULL) {
1036 /* this is mainly a cache, so it's not the EotW */
1040 loaderList->initiatingLoaders = newList;
1042 //ALOGI("Expanded init list to %d (%s)",
1043 // loaderList->initiatingLoaderCount+kInitLoaderInc,
1044 // clazz->descriptor);
1046 loaderList->initiatingLoaders[loaderList->initiatingLoaderCount++] =
1050 dvmHashTableUnlock(gDvm.loadedClasses);
1055 * (This is a dvmHashTableLookup callback.)
1057 * Entries in the class hash table are stored as { descriptor, d-loader }
1058 * tuples. If the hashed class descriptor matches the requested descriptor,
1059 * and the hashed defining class loader matches the requested class
1060 * loader, we're good. If only the descriptor matches, we check to see if the
1061 * loader is in the hashed class' initiating loader list. If so, we
1062 * can return "true" immediately and skip some of the loadClass melodrama.
1064 * The caller must lock the hash table before calling here.
1066 * Returns 0 if a matching entry is found, nonzero otherwise.
1068 static int hashcmpClassByCrit(const void* vclazz, const void* vcrit)
1070 const ClassObject* clazz = (const ClassObject*) vclazz;
1071 const ClassMatchCriteria* pCrit = (const ClassMatchCriteria*) vcrit;
1074 match = (strcmp(clazz->descriptor, pCrit->descriptor) == 0 &&
1075 (clazz->classLoader == pCrit->loader ||
1076 (pCrit->loader != NULL &&
1077 dvmLoaderInInitiatingList(clazz, pCrit->loader)) ));
1079 // ALOGI("+++ %s %p matches existing %s %p",
1080 // pCrit->descriptor, pCrit->loader,
1081 // clazz->descriptor, clazz->classLoader);
1086 * Like hashcmpClassByCrit, but passing in a fully-formed ClassObject
1087 * instead of a ClassMatchCriteria.
1089 static int hashcmpClassByClass(const void* vclazz, const void* vaddclazz)
1091 const ClassObject* clazz = (const ClassObject*) vclazz;
1092 const ClassObject* addClazz = (const ClassObject*) vaddclazz;
1095 match = (strcmp(clazz->descriptor, addClazz->descriptor) == 0 &&
1096 (clazz->classLoader == addClazz->classLoader ||
1097 (addClazz->classLoader != NULL &&
1098 dvmLoaderInInitiatingList(clazz, addClazz->classLoader)) ));
1103 * Search through the hash table to find an entry with a matching descriptor
1104 * and an initiating class loader that matches "loader".
1106 * The table entries are hashed on descriptor only, because they're unique
1107 * on *defining* class loader, not *initiating* class loader. This isn't
1108 * great, because it guarantees we will have to probe when multiple
1109 * class loaders are used.
1111 * Note this does NOT try to load a class; it just finds a class that
1112 * has already been loaded.
1114 * If "unprepOkay" is set, this will return classes that have been added
1115 * to the hash table but are not yet fully loaded and linked. Otherwise,
1116 * such classes are ignored. (The only place that should set "unprepOkay"
1117 * is findClassNoInit(), which will wait for the prep to finish.)
1119 * Returns NULL if not found.
1121 ClassObject* dvmLookupClass(const char* descriptor, Object* loader,
1124 ClassMatchCriteria crit;
1128 crit.descriptor = descriptor;
1129 crit.loader = loader;
1130 hash = dvmComputeUtf8Hash(descriptor);
1132 LOGVV("threadid=%d: dvmLookupClass searching for '%s' %p",
1133 dvmThreadSelf()->threadId, descriptor, loader);
1135 dvmHashTableLock(gDvm.loadedClasses);
1136 found = dvmHashTableLookup(gDvm.loadedClasses, hash, &crit,
1137 hashcmpClassByCrit, false);
1138 dvmHashTableUnlock(gDvm.loadedClasses);
1141 * The class has been added to the hash table but isn't ready for use.
1142 * We're going to act like we didn't see it, so that the caller will
1143 * go through the full "find class" path, which includes locking the
1144 * object and waiting until it's ready. We could do that lock/wait
1145 * here, but this is an extremely rare case, and it's simpler to have
1146 * the wait-for-class code centralized.
1148 if (found && !unprepOkay && !dvmIsClassLinked((ClassObject*)found)) {
1149 ALOGV("Ignoring not-yet-ready %s, using slow path",
1150 ((ClassObject*)found)->descriptor);
1154 return (ClassObject*) found;
1158 * Add a new class to the hash table.
1160 * The class is considered "new" if it doesn't match on both the class
1161 * descriptor and the defining class loader.
1163 * TODO: we should probably have separate hash tables for each
1164 * ClassLoader. This could speed up dvmLookupClass and
1165 * other common operations. It does imply a VM-visible data structure
1166 * for each ClassLoader object with loaded classes, which we don't
1169 bool dvmAddClassToHash(ClassObject* clazz)
1174 hash = dvmComputeUtf8Hash(clazz->descriptor);
1176 dvmHashTableLock(gDvm.loadedClasses);
1177 found = dvmHashTableLookup(gDvm.loadedClasses, hash, clazz,
1178 hashcmpClassByClass, true);
1179 dvmHashTableUnlock(gDvm.loadedClasses);
1181 ALOGV("+++ dvmAddClassToHash '%s' %p (isnew=%d) --> %p",
1182 clazz->descriptor, clazz->classLoader,
1183 (found == (void*) clazz), clazz);
1185 //dvmCheckClassTablePerf();
1187 /* can happen if two threads load the same class simultaneously */
1188 return (found == (void*) clazz);
1193 * Compute hash value for a class.
1195 u4 hashcalcClass(const void* item)
1197 return dvmComputeUtf8Hash(((const ClassObject*) item)->descriptor);
1201 * Check the performance of the "loadedClasses" hash table.
1203 void dvmCheckClassTablePerf()
1205 dvmHashTableLock(gDvm.loadedClasses);
1206 dvmHashTableProbeCount(gDvm.loadedClasses, hashcalcClass,
1207 hashcmpClassByClass);
1208 dvmHashTableUnlock(gDvm.loadedClasses);
1213 * Remove a class object from the hash table.
1215 static void removeClassFromHash(ClassObject* clazz)
1217 ALOGV("+++ removeClassFromHash '%s'", clazz->descriptor);
1219 u4 hash = dvmComputeUtf8Hash(clazz->descriptor);
1221 dvmHashTableLock(gDvm.loadedClasses);
1222 if (!dvmHashTableRemove(gDvm.loadedClasses, hash, clazz))
1223 ALOGW("Hash table remove failed on class '%s'", clazz->descriptor);
1224 dvmHashTableUnlock(gDvm.loadedClasses);
1229 * ===========================================================================
1231 * ===========================================================================
1235 * Set clazz->serialNumber to the next available value.
1237 * This usually happens *very* early in class creation, so don't expect
1238 * anything else in the class to be ready.
1240 void dvmSetClassSerialNumber(ClassObject* clazz)
1242 assert(clazz->serialNumber == 0);
1243 clazz->serialNumber = android_atomic_inc(&gDvm.classSerialNumber);
1248 * Find the named class (by descriptor), using the specified
1249 * initiating ClassLoader.
1251 * The class will be loaded and initialized if it has not already been.
1252 * If necessary, the superclass will be loaded.
1254 * If the class can't be found, returns NULL with an appropriate exception
1257 ClassObject* dvmFindClass(const char* descriptor, Object* loader)
1261 clazz = dvmFindClassNoInit(descriptor, loader);
1262 if (clazz != NULL && clazz->status < CLASS_INITIALIZED) {
1263 /* initialize class */
1264 if (!dvmInitClass(clazz)) {
1265 /* init failed; leave it in the list, marked as bad */
1266 assert(dvmCheckException(dvmThreadSelf()));
1267 assert(clazz->status == CLASS_ERROR);
1276 * Find the named class (by descriptor), using the specified
1277 * initiating ClassLoader.
1279 * The class will be loaded if it has not already been, as will its
1280 * superclass. It will not be initialized.
1282 * If the class can't be found, returns NULL with an appropriate exception
1285 ClassObject* dvmFindClassNoInit(const char* descriptor,
1288 assert(descriptor != NULL);
1289 //assert(loader != NULL);
1291 LOGVV("FindClassNoInit '%s' %p", descriptor, loader);
1293 if (*descriptor == '[') {
1295 * Array class. Find in table, generate if not found.
1297 return dvmFindArrayClass(descriptor, loader);
1300 * Regular class. Find in table, load if not found.
1302 if (loader != NULL) {
1303 return findClassFromLoaderNoInit(descriptor, loader);
1305 return dvmFindSystemClassNoInit(descriptor);
1311 * Load the named class (by descriptor) from the specified class
1312 * loader. This calls out to let the ClassLoader object do its thing.
1314 * Returns with NULL and an exception raised on error.
1316 static ClassObject* findClassFromLoaderNoInit(const char* descriptor,
1319 //ALOGI("##### findClassFromLoaderNoInit (%s,%p)",
1320 // descriptor, loader);
1322 Thread* self = dvmThreadSelf();
1324 assert(loader != NULL);
1327 * Do we already have it?
1329 * The class loader code does the "is it already loaded" check as
1330 * well. However, this call is much faster than calling through
1331 * interpreted code. Doing this does mean that in the common case
1332 * (365 out of 420 calls booting the sim) we're doing the
1333 * lookup-by-descriptor twice. It appears this is still a win, so
1334 * I'm keeping it in.
1336 ClassObject* clazz = dvmLookupClass(descriptor, loader, false);
1337 if (clazz != NULL) {
1338 LOGVV("Already loaded: %s %p", descriptor, loader);
1341 LOGVV("Not already loaded: %s %p", descriptor, loader);
1344 char* dotName = NULL;
1345 StringObject* nameObj = NULL;
1347 /* convert "Landroid/debug/Stuff;" to "android.debug.Stuff" */
1348 dotName = dvmDescriptorToDot(descriptor);
1349 if (dotName == NULL) {
1350 dvmThrowOutOfMemoryError(NULL);
1353 nameObj = dvmCreateStringFromCstr(dotName);
1354 if (nameObj == NULL) {
1355 assert(dvmCheckException(self));
1359 dvmMethodTraceClassPrepBegin();
1362 * Invoke loadClass(). This will probably result in a couple of
1363 * exceptions being thrown, because the ClassLoader.loadClass()
1364 * implementation eventually calls VMClassLoader.loadClass to see if
1365 * the bootstrap class loader can find it before doing its own load.
1367 LOGVV("--- Invoking loadClass(%s, %p)", dotName, loader);
1369 const Method* loadClass =
1370 loader->clazz->vtable[gDvm.voffJavaLangClassLoader_loadClass];
1372 dvmCallMethod(self, loadClass, loader, &result, nameObj);
1373 clazz = (ClassObject*) result.l;
1375 dvmMethodTraceClassPrepEnd();
1376 Object* excep = dvmGetException(self);
1377 if (excep != NULL) {
1378 #if DVM_SHOW_EXCEPTION >= 2
1379 ALOGD("NOTE: loadClass '%s' %p threw exception %s",
1380 dotName, loader, excep->clazz->descriptor);
1382 dvmAddTrackedAlloc(excep, self);
1383 dvmClearException(self);
1384 dvmThrowChainedNoClassDefFoundError(descriptor, excep);
1385 dvmReleaseTrackedAlloc(excep, self);
1388 } else if (clazz == NULL) {
1389 ALOGW("ClassLoader returned NULL w/o exception pending");
1390 dvmThrowNullPointerException("ClassLoader returned null");
1395 /* not adding clazz to tracked-alloc list, because it's a ClassObject */
1397 dvmAddInitiatingLoader(clazz, loader);
1399 LOGVV("--- Successfully loaded %s %p (thisldr=%p clazz=%p)",
1400 descriptor, clazz->classLoader, loader, clazz);
1403 dvmReleaseTrackedAlloc((Object*)nameObj, NULL);
1409 * Load the named class (by descriptor) from the specified DEX file.
1410 * Used by class loaders to instantiate a class object from a
1413 ClassObject* dvmDefineClass(DvmDex* pDvmDex, const char* descriptor,
1414 Object* classLoader)
1416 assert(pDvmDex != NULL);
1418 return findClassNoInit(descriptor, classLoader, pDvmDex);
1423 * Find the named class (by descriptor), scanning through the
1424 * bootclasspath if it hasn't already been loaded.
1426 * "descriptor" looks like "Landroid/debug/Stuff;".
1428 * Uses NULL as the defining class loader.
1430 ClassObject* dvmFindSystemClass(const char* descriptor)
1434 clazz = dvmFindSystemClassNoInit(descriptor);
1435 if (clazz != NULL && clazz->status < CLASS_INITIALIZED) {
1436 /* initialize class */
1437 if (!dvmInitClass(clazz)) {
1438 /* init failed; leave it in the list, marked as bad */
1439 assert(dvmCheckException(dvmThreadSelf()));
1440 assert(clazz->status == CLASS_ERROR);
1449 * Find the named class (by descriptor), searching for it in the
1452 * On failure, this returns NULL with an exception raised.
1454 ClassObject* dvmFindSystemClassNoInit(const char* descriptor)
1456 return findClassNoInit(descriptor, NULL, NULL);
1460 * Find the named class (by descriptor). If it's not already loaded,
1461 * we load it and link it, but don't execute <clinit>. (The VM has
1462 * specific limitations on which events can cause initialization.)
1464 * If "pDexFile" is NULL, we will search the bootclasspath for an entry.
1466 * On failure, this returns NULL with an exception raised.
1468 * TODO: we need to return an indication of whether we loaded the class or
1469 * used an existing definition. If somebody deliberately tries to load a
1470 * class twice in the same class loader, they should get a LinkageError,
1471 * but inadvertent simultaneous class references should "just work".
1473 static ClassObject* findClassNoInit(const char* descriptor, Object* loader,
1476 Thread* self = dvmThreadSelf();
1478 bool profilerNotified = false;
1480 if (loader != NULL) {
1481 LOGVV("#### findClassNoInit(%s,%p,%p)", descriptor, loader,
1486 * We don't expect an exception to be raised at this point. The
1487 * exception handling code is good about managing this. This *can*
1488 * happen if a JNI lookup fails and the JNI code doesn't do any
1489 * error checking before doing another class lookup, so we may just
1490 * want to clear this and restore it on exit. If we don't, some kinds
1491 * of failures can't be detected without rearranging other stuff.
1493 * Most often when we hit this situation it means that something is
1494 * broken in the VM or in JNI code, so I'm keeping it in place (and
1495 * making it an informative abort rather than an assert).
1497 if (dvmCheckException(self)) {
1498 ALOGE("Class lookup %s attempted with exception pending", descriptor);
1499 ALOGW("Pending exception is:");
1500 dvmLogExceptionStackTrace();
1501 dvmDumpAllThreads(false);
1505 clazz = dvmLookupClass(descriptor, loader, true);
1506 if (clazz == NULL) {
1507 const DexClassDef* pClassDef;
1509 dvmMethodTraceClassPrepBegin();
1510 profilerNotified = true;
1512 #if LOG_CLASS_LOADING
1513 u8 startTime = dvmGetThreadCpuTimeNsec();
1516 if (pDvmDex == NULL) {
1517 assert(loader == NULL); /* shouldn't be here otherwise */
1518 pDvmDex = searchBootPathForClass(descriptor, &pClassDef);
1520 pClassDef = dexFindClass(pDvmDex->pDexFile, descriptor);
1523 if (pDvmDex == NULL || pClassDef == NULL) {
1524 if (gDvm.noClassDefFoundErrorObj != NULL) {
1525 /* usual case -- use prefabricated object */
1526 dvmSetException(self, gDvm.noClassDefFoundErrorObj);
1528 /* dexopt case -- can't guarantee prefab (core.jar) */
1529 dvmThrowNoClassDefFoundError(descriptor);
1534 /* found a match, try to load it */
1535 clazz = loadClassFromDex(pDvmDex, pClassDef, loader);
1536 if (dvmCheckException(self)) {
1537 /* class was found but had issues */
1538 if (clazz != NULL) {
1539 dvmFreeClassInnards(clazz);
1540 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1546 * Lock the class while we link it so other threads must wait for us
1547 * to finish. Set the "initThreadId" so we can identify recursive
1548 * invocation. (Note all accesses to initThreadId here are
1549 * guarded by the class object's lock.)
1551 dvmLockObject(self, (Object*) clazz);
1552 clazz->initThreadId = self->threadId;
1555 * Add to hash table so lookups succeed.
1557 * [Are circular references possible when linking a class?]
1559 assert(clazz->classLoader == loader);
1560 if (!dvmAddClassToHash(clazz)) {
1562 * Another thread must have loaded the class after we
1563 * started but before we finished. Discard what we've
1564 * done and leave some hints for the GC.
1566 * (Yes, this happens.)
1568 //ALOGW("WOW: somebody loaded %s simultaneously", descriptor);
1569 clazz->initThreadId = 0;
1570 dvmUnlockObject(self, (Object*) clazz);
1572 /* Let the GC free the class.
1574 dvmFreeClassInnards(clazz);
1575 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1577 /* Grab the winning class.
1579 clazz = dvmLookupClass(descriptor, loader, true);
1580 assert(clazz != NULL);
1583 dvmReleaseTrackedAlloc((Object*) clazz, NULL);
1585 #if LOG_CLASS_LOADING
1586 logClassLoadWithTime('>', clazz, startTime);
1589 * Prepare and resolve.
1591 if (!dvmLinkClass(clazz)) {
1592 assert(dvmCheckException(self));
1594 /* Make note of the error and clean up the class.
1596 removeClassFromHash(clazz);
1597 clazz->status = CLASS_ERROR;
1598 dvmFreeClassInnards(clazz);
1600 /* Let any waiters know.
1602 clazz->initThreadId = 0;
1603 dvmObjectNotifyAll(self, (Object*) clazz);
1604 dvmUnlockObject(self, (Object*) clazz);
1606 #if LOG_CLASS_LOADING
1607 ALOG(LOG_INFO, "DVMLINK FAILED FOR CLASS ", "%s in %s",
1608 clazz->descriptor, get_process_name());
1611 * TODO: It would probably be better to use a new type code here (instead of '<') to
1612 * indicate the failure. This change would require a matching change in the parser
1613 * and analysis code in frameworks/base/tools/preload.
1615 logClassLoad('<', clazz);
1618 if (gDvm.optimizing) {
1619 /* happens with "external" libs */
1620 ALOGV("Link of class '%s' failed", descriptor);
1622 ALOGW("Link of class '%s' failed", descriptor);
1626 dvmObjectNotifyAll(self, (Object*) clazz);
1627 dvmUnlockObject(self, (Object*) clazz);
1630 * Add class stats to global counters.
1632 * TODO: these should probably be atomic ops.
1634 gDvm.numLoadedClasses++;
1635 gDvm.numDeclaredMethods +=
1636 clazz->virtualMethodCount + clazz->directMethodCount;
1637 gDvm.numDeclaredInstFields += clazz->ifieldCount;
1638 gDvm.numDeclaredStaticFields += clazz->sfieldCount;
1641 * Cache pointers to basic classes. We want to use these in
1642 * various places, and it's easiest to initialize them on first
1643 * use rather than trying to force them to initialize (startup
1644 * ordering makes it weird).
1646 if (gDvm.classJavaLangObject == NULL &&
1647 strcmp(descriptor, "Ljava/lang/Object;") == 0)
1649 /* It should be impossible to get here with anything
1650 * but the bootclasspath loader.
1652 assert(loader == NULL);
1653 gDvm.classJavaLangObject = clazz;
1656 #if LOG_CLASS_LOADING
1657 logClassLoad('<', clazz);
1662 if (!dvmIsClassLinked(clazz) && clazz->status != CLASS_ERROR) {
1664 * We can race with other threads for class linking. We should
1665 * never get here recursively; doing so indicates that two
1666 * classes have circular dependencies.
1668 * One exception: we force discovery of java.lang.Class in
1669 * dvmLinkClass(), and Class has Object as its superclass. So
1670 * if the first thing we ever load is Object, we will init
1671 * Object->Class->Object. The easiest way to avoid this is to
1672 * ensure that Object is never the first thing we look up, so
1673 * we get Foo->Class->Object instead.
1675 dvmLockObject(self, (Object*) clazz);
1676 if (!dvmIsClassLinked(clazz) &&
1677 clazz->initThreadId == self->threadId)
1679 ALOGW("Recursive link on class %s", clazz->descriptor);
1680 dvmUnlockObject(self, (Object*) clazz);
1681 dvmThrowClassCircularityError(clazz->descriptor);
1685 //ALOGI("WAITING for '%s' (owner=%d)",
1686 // clazz->descriptor, clazz->initThreadId);
1687 while (!dvmIsClassLinked(clazz) && clazz->status != CLASS_ERROR) {
1688 dvmObjectWait(self, (Object*) clazz, 0, 0, false);
1690 dvmUnlockObject(self, (Object*) clazz);
1692 if (clazz->status == CLASS_ERROR) {
1694 * Somebody else tried to load this and failed. We need to raise
1695 * an exception and report failure.
1697 throwEarlierClassFailure(clazz);
1703 /* check some invariants */
1704 assert(dvmIsClassLinked(clazz));
1705 assert(gDvm.classJavaLangClass != NULL);
1706 assert(clazz->clazz == gDvm.classJavaLangClass);
1707 assert(dvmIsClassObject(clazz));
1708 assert(clazz == gDvm.classJavaLangObject || clazz->super != NULL);
1709 if (!dvmIsInterfaceClass(clazz)) {
1710 //ALOGI("class=%s vtableCount=%d, virtualMeth=%d",
1711 // clazz->descriptor, clazz->vtableCount,
1712 // clazz->virtualMethodCount);
1713 assert(clazz->vtableCount >= clazz->virtualMethodCount);
1717 if (profilerNotified)
1718 dvmMethodTraceClassPrepEnd();
1719 assert(clazz != NULL || dvmCheckException(self));
1724 * Helper for loadClassFromDex, which takes a DexClassDataHeader and
1725 * encoded data pointer in addition to the other arguments.
1727 static ClassObject* loadClassFromDex0(DvmDex* pDvmDex,
1728 const DexClassDef* pClassDef, const DexClassDataHeader* pHeader,
1729 const u1* pEncodedData, Object* classLoader)
1731 ClassObject* newClass = NULL;
1732 const DexFile* pDexFile;
1733 const char* descriptor;
1736 pDexFile = pDvmDex->pDexFile;
1737 descriptor = dexGetClassDescriptor(pDexFile, pClassDef);
1740 * Make sure the aren't any "bonus" flags set, since we use them for
1743 if ((pClassDef->accessFlags & ~EXPECTED_FILE_FLAGS) != 0) {
1744 ALOGW("Invalid file flags in class %s: %04x",
1745 descriptor, pClassDef->accessFlags);
1750 * Allocate storage for the class object on the GC heap, so that other
1751 * objects can have references to it. We bypass the usual mechanism
1752 * (allocObject), because we don't have all the bits and pieces yet.
1754 * Note that we assume that java.lang.Class does not override
1757 /* TODO: Can there be fewer special checks in the usual path? */
1758 assert(descriptor != NULL);
1759 if (classLoader == NULL &&
1760 strcmp(descriptor, "Ljava/lang/Class;") == 0) {
1761 assert(gDvm.classJavaLangClass != NULL);
1762 newClass = gDvm.classJavaLangClass;
1764 size_t size = classObjectSize(pHeader->staticFieldsSize);
1765 newClass = (ClassObject*) dvmMalloc(size, ALLOC_NON_MOVING);
1767 if (newClass == NULL)
1770 DVM_OBJECT_INIT(newClass, gDvm.classJavaLangClass);
1771 dvmSetClassSerialNumber(newClass);
1772 newClass->descriptor = descriptor;
1773 assert(newClass->descriptorAlloc == NULL);
1774 SET_CLASS_FLAG(newClass, pClassDef->accessFlags);
1775 dvmSetFieldObject((Object *)newClass,
1776 OFFSETOF_MEMBER(ClassObject, classLoader),
1777 (Object *)classLoader);
1778 newClass->pDvmDex = pDvmDex;
1779 newClass->primitiveType = PRIM_NOT;
1780 newClass->status = CLASS_IDX;
1783 * Stuff the superclass index into the object pointer field. The linker
1784 * pulls it out and replaces it with a resolved ClassObject pointer.
1785 * I'm doing it this way (rather than having a dedicated superclassIdx
1786 * field) to save a few bytes of overhead per class.
1788 * newClass->super is not traversed or freed by dvmFreeClassInnards, so
1791 assert(sizeof(u4) == sizeof(ClassObject*)); /* 32-bit check */
1792 newClass->super = (ClassObject*) pClassDef->superclassIdx;
1795 * Stuff class reference indices into the pointer fields.
1797 * The elements of newClass->interfaces are not traversed or freed by
1798 * dvmFreeClassInnards, so this is GC-safe.
1800 const DexTypeList* pInterfacesList;
1801 pInterfacesList = dexGetInterfacesList(pDexFile, pClassDef);
1802 if (pInterfacesList != NULL) {
1803 newClass->interfaceCount = pInterfacesList->size;
1804 newClass->interfaces = (ClassObject**) dvmLinearAlloc(classLoader,
1805 newClass->interfaceCount * sizeof(ClassObject*));
1807 for (i = 0; i < newClass->interfaceCount; i++) {
1808 const DexTypeItem* pType = dexGetTypeItem(pInterfacesList, i);
1809 newClass->interfaces[i] = (ClassObject*)(u4) pType->typeIdx;
1811 dvmLinearReadOnly(classLoader, newClass->interfaces);
1814 /* load field definitions */
1817 * Over-allocate the class object and append static field info
1818 * onto the end. It's fixed-size and known at alloc time. This
1819 * seems to increase zygote sharing. Heap compaction will have to
1820 * be careful if it ever tries to move ClassObject instances,
1821 * because we pass Field pointers around internally. But at least
1822 * now these Field pointers are in the object heap.
1825 if (pHeader->staticFieldsSize != 0) {
1826 /* static fields stay on system heap; field data isn't "write once" */
1827 int count = (int) pHeader->staticFieldsSize;
1831 newClass->sfieldCount = count;
1832 for (i = 0; i < count; i++) {
1833 dexReadClassDataField(&pEncodedData, &field, &lastIndex);
1834 loadSFieldFromDex(newClass, &field, &newClass->sfields[i]);
1838 if (pHeader->instanceFieldsSize != 0) {
1839 int count = (int) pHeader->instanceFieldsSize;
1843 newClass->ifieldCount = count;
1844 newClass->ifields = (InstField*) dvmLinearAlloc(classLoader,
1845 count * sizeof(InstField));
1846 for (i = 0; i < count; i++) {
1847 dexReadClassDataField(&pEncodedData, &field, &lastIndex);
1848 loadIFieldFromDex(newClass, &field, &newClass->ifields[i]);
1850 dvmLinearReadOnly(classLoader, newClass->ifields);
1854 * Load method definitions. We do this in two batches, direct then
1857 * If register maps have already been generated for this class, and
1858 * precise GC is enabled, we pull out pointers to them. We know that
1859 * they were streamed to the DEX file in the same order in which the
1862 * If the class wasn't pre-verified, the maps will be generated when
1863 * the class is verified during class initialization.
1865 u4 classDefIdx = dexGetIndexForClassDef(pDexFile, pClassDef);
1866 const void* classMapData;
1869 if (gDvm.preciseGc) {
1871 dvmRegisterMapGetClassData(pDexFile, classDefIdx, &numMethods);
1874 if (classMapData != NULL &&
1875 pHeader->directMethodsSize + pHeader->virtualMethodsSize != numMethods)
1877 ALOGE("ERROR: in %s, direct=%d virtual=%d, maps have %d",
1878 newClass->descriptor, pHeader->directMethodsSize,
1879 pHeader->virtualMethodsSize, numMethods);
1881 classMapData = NULL; /* abandon */
1884 classMapData = NULL;
1887 if (pHeader->directMethodsSize != 0) {
1888 int count = (int) pHeader->directMethodsSize;
1892 newClass->directMethodCount = count;
1893 newClass->directMethods = (Method*) dvmLinearAlloc(classLoader,
1894 count * sizeof(Method));
1895 for (i = 0; i < count; i++) {
1896 dexReadClassDataMethod(&pEncodedData, &method, &lastIndex);
1897 loadMethodFromDex(newClass, &method, &newClass->directMethods[i]);
1898 if (classMapData != NULL) {
1899 const RegisterMap* pMap = dvmRegisterMapGetNext(&classMapData);
1900 if (dvmRegisterMapGetFormat(pMap) != kRegMapFormatNone) {
1901 newClass->directMethods[i].registerMap = pMap;
1902 /* TODO: add rigorous checks */
1903 assert((newClass->directMethods[i].registersSize+7) / 8 ==
1904 newClass->directMethods[i].registerMap->regWidth);
1908 dvmLinearReadOnly(classLoader, newClass->directMethods);
1911 if (pHeader->virtualMethodsSize != 0) {
1912 int count = (int) pHeader->virtualMethodsSize;
1916 newClass->virtualMethodCount = count;
1917 newClass->virtualMethods = (Method*) dvmLinearAlloc(classLoader,
1918 count * sizeof(Method));
1919 for (i = 0; i < count; i++) {
1920 dexReadClassDataMethod(&pEncodedData, &method, &lastIndex);
1921 loadMethodFromDex(newClass, &method, &newClass->virtualMethods[i]);
1922 if (classMapData != NULL) {
1923 const RegisterMap* pMap = dvmRegisterMapGetNext(&classMapData);
1924 if (dvmRegisterMapGetFormat(pMap) != kRegMapFormatNone) {
1925 newClass->virtualMethods[i].registerMap = pMap;
1926 /* TODO: add rigorous checks */
1927 assert((newClass->virtualMethods[i].registersSize+7) / 8 ==
1928 newClass->virtualMethods[i].registerMap->regWidth);
1932 dvmLinearReadOnly(classLoader, newClass->virtualMethods);
1935 newClass->sourceFile = dexGetSourceFile(pDexFile, pClassDef);
1937 /* caller must call dvmReleaseTrackedAlloc */
1942 * Try to load the indicated class from the specified DEX file.
1944 * This is effectively loadClass()+defineClass() for a DexClassDef. The
1945 * loading was largely done when we crunched through the DEX.
1947 * Returns NULL on failure. If we locate the class but encounter an error
1948 * while processing it, an appropriate exception is thrown.
1950 static ClassObject* loadClassFromDex(DvmDex* pDvmDex,
1951 const DexClassDef* pClassDef, Object* classLoader)
1953 ClassObject* result;
1954 DexClassDataHeader header;
1955 const u1* pEncodedData;
1956 const DexFile* pDexFile;
1958 assert((pDvmDex != NULL) && (pClassDef != NULL));
1959 pDexFile = pDvmDex->pDexFile;
1961 if (gDvm.verboseClass) {
1962 ALOGV("CLASS: loading '%s'...",
1963 dexGetClassDescriptor(pDexFile, pClassDef));
1966 pEncodedData = dexGetClassData(pDexFile, pClassDef);
1968 if (pEncodedData != NULL) {
1969 dexReadClassDataHeader(&pEncodedData, &header);
1971 // Provide an all-zeroes header for the rest of the loading.
1972 memset(&header, 0, sizeof(header));
1975 result = loadClassFromDex0(pDvmDex, pClassDef, &header, pEncodedData,
1978 if (gDvm.verboseClass && (result != NULL)) {
1979 ALOGI("[Loaded %s from DEX %p (cl=%p)]",
1980 result->descriptor, pDvmDex, classLoader);
1987 * Free anything in a ClassObject that was allocated on the system heap.
1989 * The ClassObject itself is allocated on the GC heap, so we leave it for
1990 * the garbage collector.
1992 * NOTE: this may be called with a partially-constructed object.
1993 * NOTE: there is no particular ordering imposed, so don't go poking at
1996 void dvmFreeClassInnards(ClassObject* clazz)
2004 assert(clazz->clazz == gDvm.classJavaLangClass);
2005 assert(dvmIsClassObject(clazz));
2007 /* Guarantee that dvmFreeClassInnards can be called on a given
2008 * class multiple times by clearing things out as we free them.
2009 * We don't make any attempt at real atomicity here; higher
2010 * levels need to make sure that no two threads can free the
2011 * same ClassObject at the same time.
2013 * TODO: maybe just make it so the GC will never free the
2014 * innards of an already-freed class.
2016 * TODO: this #define isn't MT-safe -- the compiler could rearrange it.
2018 #define NULL_AND_FREE(p) \
2020 if ((p) != NULL) { \
2026 #define NULL_AND_LINEAR_FREE(p) \
2028 if ((p) != NULL) { \
2031 dvmLinearFree(clazz->classLoader, tp); \
2035 /* arrays just point at Object's vtable; don't free vtable in this case.
2037 clazz->vtableCount = -1;
2038 if (clazz->vtable == gDvm.classJavaLangObject->vtable) {
2039 clazz->vtable = NULL;
2041 NULL_AND_LINEAR_FREE(clazz->vtable);
2044 clazz->descriptor = NULL;
2045 NULL_AND_FREE(clazz->descriptorAlloc);
2047 if (clazz->directMethods != NULL) {
2048 Method *directMethods = clazz->directMethods;
2049 int directMethodCount = clazz->directMethodCount;
2050 clazz->directMethods = NULL;
2051 clazz->directMethodCount = -1;
2052 dvmLinearReadWrite(clazz->classLoader, directMethods);
2053 for (i = 0; i < directMethodCount; i++) {
2054 freeMethodInnards(&directMethods[i]);
2056 dvmLinearReadOnly(clazz->classLoader, directMethods);
2057 dvmLinearFree(clazz->classLoader, directMethods);
2059 if (clazz->virtualMethods != NULL) {
2060 Method *virtualMethods = clazz->virtualMethods;
2061 int virtualMethodCount = clazz->virtualMethodCount;
2062 clazz->virtualMethodCount = -1;
2063 clazz->virtualMethods = NULL;
2064 dvmLinearReadWrite(clazz->classLoader, virtualMethods);
2065 for (i = 0; i < virtualMethodCount; i++) {
2066 freeMethodInnards(&virtualMethods[i]);
2068 dvmLinearReadOnly(clazz->classLoader, virtualMethods);
2069 dvmLinearFree(clazz->classLoader, virtualMethods);
2072 InitiatingLoaderList *loaderList = dvmGetInitiatingLoaderList(clazz);
2073 loaderList->initiatingLoaderCount = -1;
2074 NULL_AND_FREE(loaderList->initiatingLoaders);
2076 clazz->interfaceCount = -1;
2077 NULL_AND_LINEAR_FREE(clazz->interfaces);
2079 clazz->iftableCount = -1;
2080 NULL_AND_LINEAR_FREE(clazz->iftable);
2082 clazz->ifviPoolCount = -1;
2083 NULL_AND_LINEAR_FREE(clazz->ifviPool);
2085 clazz->sfieldCount = -1;
2086 /* The sfields are attached to the ClassObject, and will be freed
2089 clazz->ifieldCount = -1;
2090 NULL_AND_LINEAR_FREE(clazz->ifields);
2092 #undef NULL_AND_FREE
2093 #undef NULL_AND_LINEAR_FREE
2097 * Free anything in a Method that was allocated on the system heap.
2099 * The containing class is largely torn down by this point.
2101 static void freeMethodInnards(Method* meth)
2104 free(meth->exceptions);
2110 * Some register maps are allocated on the heap, either because of late
2111 * verification or because we're caching an uncompressed form.
2113 const RegisterMap* pMap = meth->registerMap;
2114 if (pMap != NULL && dvmRegisterMapGetOnHeap(pMap)) {
2115 dvmFreeRegisterMap((RegisterMap*) pMap);
2116 meth->registerMap = NULL;
2120 * We may have copied the instructions.
2122 if (IS_METHOD_FLAG_SET(meth, METHOD_ISWRITABLE)) {
2123 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2124 dvmLinearFree(meth->clazz->classLoader, methodDexCode);
2129 * Clone a Method, making new copies of anything that will be freed up
2130 * by freeMethodInnards(). This is used for "miranda" methods.
2132 static void cloneMethod(Method* dst, const Method* src)
2134 if (src->registerMap != NULL) {
2135 ALOGE("GLITCH: only expected abstract methods here");
2136 ALOGE(" cloning %s.%s", src->clazz->descriptor, src->name);
2139 memcpy(dst, src, sizeof(Method));
2143 * Pull the interesting pieces out of a DexMethod.
2145 * The DEX file isn't going anywhere, so we don't need to make copies of
2148 static void loadMethodFromDex(ClassObject* clazz, const DexMethod* pDexMethod,
2151 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2152 const DexMethodId* pMethodId;
2153 const DexCode* pDexCode;
2155 pMethodId = dexGetMethodId(pDexFile, pDexMethod->methodIdx);
2157 meth->name = dexStringById(pDexFile, pMethodId->nameIdx);
2158 dexProtoSetFromMethodId(&meth->prototype, pDexFile, pMethodId);
2159 meth->shorty = dexProtoGetShorty(&meth->prototype);
2160 meth->accessFlags = pDexMethod->accessFlags;
2161 meth->clazz = clazz;
2162 meth->jniArgInfo = 0;
2164 if (dvmCompareNameDescriptorAndMethod("finalize", "()V", meth) == 0) {
2166 * The Enum class declares a "final" finalize() method to
2167 * prevent subclasses from introducing a finalizer. We don't
2168 * want to set the finalizable flag for Enum or its subclasses,
2169 * so we check for it here.
2171 * We also want to avoid setting it on Object, but it's easier
2172 * to just strip that out later.
2174 if (clazz->classLoader != NULL ||
2175 strcmp(clazz->descriptor, "Ljava/lang/Enum;") != 0)
2177 SET_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2181 pDexCode = dexGetCode(pDexFile, pDexMethod);
2182 if (pDexCode != NULL) {
2183 /* integer constants, copy over for faster access */
2184 meth->registersSize = pDexCode->registersSize;
2185 meth->insSize = pDexCode->insSize;
2186 meth->outsSize = pDexCode->outsSize;
2188 /* pointer to code area */
2189 meth->insns = pDexCode->insns;
2192 * We don't have a DexCode block, but we still want to know how
2193 * much space is needed for the arguments (so we don't have to
2194 * compute it later). We also take this opportunity to compute
2195 * JNI argument info.
2197 * We do this for abstract methods as well, because we want to
2198 * be able to substitute our exception-throwing "stub" in.
2200 int argsSize = dvmComputeMethodArgsSize(meth);
2201 if (!dvmIsStaticMethod(meth))
2203 meth->registersSize = meth->insSize = argsSize;
2204 assert(meth->outsSize == 0);
2205 assert(meth->insns == NULL);
2207 if (dvmIsNativeMethod(meth)) {
2208 meth->nativeFunc = dvmResolveNativeMethod;
2209 meth->jniArgInfo = computeJniArgInfo(&meth->prototype);
2214 #if 0 /* replaced with private/read-write mapping */
2216 * We usually map bytecode directly out of the DEX file, which is mapped
2217 * shared read-only. If we want to be able to modify it, we have to make
2220 * Once copied, the code will be in the LinearAlloc region, which may be
2223 * The bytecode instructions are embedded inside a DexCode structure, so we
2224 * need to copy all of that. (The dvmGetMethodCode function backs up the
2225 * instruction pointer to find the start of the DexCode.)
2227 void dvmMakeCodeReadWrite(Method* meth)
2229 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2231 if (IS_METHOD_FLAG_SET(meth, METHOD_ISWRITABLE)) {
2232 dvmLinearReadWrite(meth->clazz->classLoader, methodDexCode);
2236 assert(!dvmIsNativeMethod(meth) && !dvmIsAbstractMethod(meth));
2238 size_t dexCodeSize = dexGetDexCodeSize(methodDexCode);
2239 ALOGD("Making a copy of %s.%s code (%d bytes)",
2240 meth->clazz->descriptor, meth->name, dexCodeSize);
2243 (DexCode*) dvmLinearAlloc(meth->clazz->classLoader, dexCodeSize);
2244 memcpy(newCode, methodDexCode, dexCodeSize);
2246 meth->insns = newCode->insns;
2247 SET_METHOD_FLAG(meth, METHOD_ISWRITABLE);
2251 * Mark the bytecode read-only.
2253 * If the contents of the DexCode haven't actually changed, we could revert
2254 * to the original shared page.
2256 void dvmMakeCodeReadOnly(Method* meth)
2258 DexCode* methodDexCode = (DexCode*) dvmGetMethodCode(meth);
2259 ALOGV("+++ marking %p read-only", methodDexCode);
2260 dvmLinearReadOnly(meth->clazz->classLoader, methodDexCode);
2266 * jniArgInfo (32-bit int) layout:
2267 * SRRRHHHH HHHHHHHH HHHHHHHH HHHHHHHH
2269 * S - if set, do things the hard way (scan the signature)
2270 * R - return-type enumeration
2271 * H - target-specific hints
2273 * This info is used at invocation time by dvmPlatformInvoke. In most
2274 * cases, the target-specific hints allow dvmPlatformInvoke to avoid
2275 * having to fully parse the signature.
2277 * The return-type bits are always set, even if target-specific hint bits
2280 static int computeJniArgInfo(const DexProto* proto)
2282 const char* sig = dexProtoGetShorty(proto);
2283 int returnType, jniArgInfo;
2286 /* The first shorty character is the return type. */
2289 returnType = DALVIK_JNI_RETURN_VOID;
2292 returnType = DALVIK_JNI_RETURN_FLOAT;
2295 returnType = DALVIK_JNI_RETURN_DOUBLE;
2298 returnType = DALVIK_JNI_RETURN_S8;
2302 returnType = DALVIK_JNI_RETURN_S1;
2305 returnType = DALVIK_JNI_RETURN_U2;
2308 returnType = DALVIK_JNI_RETURN_S2;
2311 returnType = DALVIK_JNI_RETURN_S4;
2315 jniArgInfo = returnType << DALVIK_JNI_RETURN_SHIFT;
2317 hints = dvmPlatformInvokeHints(proto);
2319 if (hints & DALVIK_JNI_NO_ARG_INFO) {
2320 jniArgInfo |= DALVIK_JNI_NO_ARG_INFO;
2322 assert((hints & DALVIK_JNI_RETURN_MASK) == 0);
2323 jniArgInfo |= hints;
2330 * Load information about a static field.
2332 * This also "prepares" static fields by initializing them
2333 * to their "standard default values".
2335 static void loadSFieldFromDex(ClassObject* clazz,
2336 const DexField* pDexSField, StaticField* sfield)
2338 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2339 const DexFieldId* pFieldId;
2341 pFieldId = dexGetFieldId(pDexFile, pDexSField->fieldIdx);
2343 sfield->clazz = clazz;
2344 sfield->name = dexStringById(pDexFile, pFieldId->nameIdx);
2345 sfield->signature = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx);
2346 sfield->accessFlags = pDexSField->accessFlags;
2348 /* Static object field values are set to "standard default values"
2349 * (null or 0) until the class is initialized. We delay loading
2350 * constant values from the class until that time.
2352 //sfield->value.j = 0;
2353 assert(sfield->value.j == 0LL); // cleared earlier with calloc
2357 * Load information about an instance field.
2359 static void loadIFieldFromDex(ClassObject* clazz,
2360 const DexField* pDexIField, InstField* ifield)
2362 DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2363 const DexFieldId* pFieldId;
2365 pFieldId = dexGetFieldId(pDexFile, pDexIField->fieldIdx);
2367 ifield->clazz = clazz;
2368 ifield->name = dexStringById(pDexFile, pFieldId->nameIdx);
2369 ifield->signature = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx);
2370 ifield->accessFlags = pDexIField->accessFlags;
2372 assert(ifield->byteOffset == 0); // cleared earlier with calloc
2373 ifield->byteOffset = -1; // make it obvious if we fail to set later
2378 * Cache java.lang.ref.Reference fields and methods.
2380 static bool precacheReferenceOffsets(ClassObject* clazz)
2384 /* We trick the GC object scanner by not counting
2385 * java.lang.ref.Reference.referent as an object
2386 * field. It will get explicitly scanned as part
2387 * of the reference-walking process.
2389 * Find the object field named "referent" and put it
2390 * just after the list of object reference fields.
2392 dvmLinearReadWrite(clazz->classLoader, clazz->ifields);
2393 for (i = 0; i < clazz->ifieldRefCount; i++) {
2394 InstField *pField = &clazz->ifields[i];
2395 if (strcmp(pField->name, "referent") == 0) {
2398 /* Swap this field with the last object field.
2400 targetIndex = clazz->ifieldRefCount - 1;
2401 if (i != targetIndex) {
2402 InstField *swapField = &clazz->ifields[targetIndex];
2406 /* It's not currently strictly necessary
2407 * for the fields to be in byteOffset order,
2408 * but it's more predictable that way.
2410 tmpByteOffset = swapField->byteOffset;
2411 swapField->byteOffset = pField->byteOffset;
2412 pField->byteOffset = tmpByteOffset;
2414 tmpField = *swapField;
2415 *swapField = *pField;
2419 /* One fewer object field (wink wink).
2421 clazz->ifieldRefCount--;
2422 i--; /* don't trip "didn't find it" test if field was last */
2426 dvmLinearReadOnly(clazz->classLoader, clazz->ifields);
2427 if (i == clazz->ifieldRefCount) {
2428 ALOGE("Unable to reorder 'referent' in %s", clazz->descriptor);
2433 * Now that the above has been done, it is safe to cache
2434 * info about the class.
2436 if (!dvmFindReferenceMembers(clazz)) {
2437 ALOGE("Trouble with Reference setup");
2446 * Set the bitmap of reference offsets, refOffsets, from the ifields
2449 static void computeRefOffsets(ClassObject* clazz)
2451 if (clazz->super != NULL) {
2452 clazz->refOffsets = clazz->super->refOffsets;
2454 clazz->refOffsets = 0;
2457 * If our superclass overflowed, we don't stand a chance.
2459 if (clazz->refOffsets != CLASS_WALK_SUPER) {
2463 /* All of the fields that contain object references
2464 * are guaranteed to be at the beginning of the ifields list.
2467 const int ifieldRefCount = clazz->ifieldRefCount;
2468 for (i = 0; i < ifieldRefCount; i++) {
2470 * Note that, per the comment on struct InstField,
2471 * f->byteOffset is the offset from the beginning of
2472 * obj, not the offset into obj->instanceData.
2474 assert(f->byteOffset >= (int) CLASS_SMALLEST_OFFSET);
2475 assert((f->byteOffset & (CLASS_OFFSET_ALIGNMENT - 1)) == 0);
2476 if (CLASS_CAN_ENCODE_OFFSET(f->byteOffset)) {
2477 u4 newBit = CLASS_BIT_FROM_OFFSET(f->byteOffset);
2478 assert(newBit != 0);
2479 clazz->refOffsets |= newBit;
2481 clazz->refOffsets = CLASS_WALK_SUPER;
2491 * Link (prepare and resolve). Verification is deferred until later.
2493 * This converts symbolic references into pointers. It's independent of
2494 * the source file format.
2496 * If clazz->status is CLASS_IDX, then clazz->super and interfaces[] are
2497 * holding class reference indices rather than pointers. The class
2498 * references will be resolved during link. (This is done when
2499 * loading from DEX to avoid having to create additional storage to
2500 * pass the indices around.)
2502 * Returns "false" with an exception pending on failure.
2504 bool dvmLinkClass(ClassObject* clazz)
2506 u4 superclassIdx = 0;
2507 u4 *interfaceIdxArray = NULL;
2511 assert(clazz != NULL);
2512 assert(clazz->descriptor != NULL);
2513 assert(clazz->status == CLASS_IDX || clazz->status == CLASS_LOADED);
2514 if (gDvm.verboseClass)
2515 ALOGV("CLASS: linking '%s'...", clazz->descriptor);
2517 assert(gDvm.classJavaLangClass != NULL);
2518 assert(clazz->clazz == gDvm.classJavaLangClass);
2519 assert(dvmIsClassObject(clazz));
2520 if (clazz->classLoader == NULL &&
2521 (strcmp(clazz->descriptor, "Ljava/lang/Class;") == 0))
2523 if (gDvm.classJavaLangClass->ifieldCount > CLASS_FIELD_SLOTS) {
2524 ALOGE("java.lang.Class has %d instance fields (expected at most %d)",
2525 gDvm.classJavaLangClass->ifieldCount, CLASS_FIELD_SLOTS);
2528 if (gDvm.classJavaLangClass->sfieldCount != CLASS_SFIELD_SLOTS) {
2529 ALOGE("java.lang.Class has %d static fields (expected %d)",
2530 gDvm.classJavaLangClass->sfieldCount, CLASS_SFIELD_SLOTS);
2535 /* "Resolve" the class.
2537 * At this point, clazz's reference fields may contain Dex file
2538 * indices instead of direct object references. Proxy objects are
2539 * an exception, and may be the only exception. We need to
2540 * translate those indices into real references, and let the GC
2541 * look inside this ClassObject.
2543 if (clazz->status == CLASS_IDX) {
2544 if (clazz->interfaceCount > 0) {
2545 /* Copy u4 DEX idx values out of the ClassObject* array
2546 * where we stashed them.
2548 assert(sizeof(*interfaceIdxArray) == sizeof(*clazz->interfaces));
2549 size_t len = clazz->interfaceCount * sizeof(*interfaceIdxArray);
2550 interfaceIdxArray = (u4*)malloc(len);
2551 if (interfaceIdxArray == NULL) {
2552 ALOGW("Unable to allocate memory to link %s", clazz->descriptor);
2555 memcpy(interfaceIdxArray, clazz->interfaces, len);
2557 dvmLinearReadWrite(clazz->classLoader, clazz->interfaces);
2558 memset(clazz->interfaces, 0, len);
2559 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2562 assert(sizeof(superclassIdx) == sizeof(clazz->super));
2563 superclassIdx = (u4) clazz->super;
2564 clazz->super = NULL;
2565 /* After this line, clazz will be fair game for the GC. The
2566 * superclass and interfaces are all NULL.
2568 clazz->status = CLASS_LOADED;
2570 if (superclassIdx != kDexNoIndex) {
2571 ClassObject* super = dvmResolveClass(clazz, superclassIdx, false);
2572 if (super == NULL) {
2573 assert(dvmCheckException(dvmThreadSelf()));
2574 if (gDvm.optimizing) {
2575 /* happens with "external" libs */
2576 ALOGV("Unable to resolve superclass of %s (%d)",
2577 clazz->descriptor, superclassIdx);
2579 ALOGW("Unable to resolve superclass of %s (%d)",
2580 clazz->descriptor, superclassIdx);
2584 dvmSetFieldObject((Object *)clazz,
2585 OFFSETOF_MEMBER(ClassObject, super),
2589 if (clazz->interfaceCount > 0) {
2590 /* Resolve the interfaces implemented directly by this class. */
2591 assert(interfaceIdxArray != NULL);
2592 dvmLinearReadWrite(clazz->classLoader, clazz->interfaces);
2593 for (i = 0; i < clazz->interfaceCount; i++) {
2594 assert(interfaceIdxArray[i] != kDexNoIndex);
2595 clazz->interfaces[i] =
2596 dvmResolveClass(clazz, interfaceIdxArray[i], false);
2597 if (clazz->interfaces[i] == NULL) {
2598 const DexFile* pDexFile = clazz->pDvmDex->pDexFile;
2600 assert(dvmCheckException(dvmThreadSelf()));
2601 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2603 const char* classDescriptor;
2605 dexStringByTypeIdx(pDexFile, interfaceIdxArray[i]);
2606 if (gDvm.optimizing) {
2607 /* happens with "external" libs */
2608 ALOGV("Failed resolving %s interface %d '%s'",
2609 clazz->descriptor, interfaceIdxArray[i],
2612 ALOGI("Failed resolving %s interface %d '%s'",
2613 clazz->descriptor, interfaceIdxArray[i],
2619 /* are we allowed to implement this interface? */
2620 if (!dvmCheckClassAccess(clazz, clazz->interfaces[i])) {
2621 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2622 ALOGW("Interface '%s' is not accessible to '%s'",
2623 clazz->interfaces[i]->descriptor, clazz->descriptor);
2624 dvmThrowIllegalAccessError("interface not accessible");
2627 LOGVV("+++ found interface '%s'",
2628 clazz->interfaces[i]->descriptor);
2630 dvmLinearReadOnly(clazz->classLoader, clazz->interfaces);
2634 * There are now Class references visible to the GC in super and
2639 * All classes have a direct superclass, except for
2640 * java/lang/Object and primitive classes. Primitive classes are
2641 * are created CLASS_INITIALIZED, so won't get here.
2643 assert(clazz->primitiveType == PRIM_NOT);
2644 if (strcmp(clazz->descriptor, "Ljava/lang/Object;") == 0) {
2645 if (clazz->super != NULL) {
2646 /* TODO: is this invariant true for all java/lang/Objects,
2647 * regardless of the class loader? For now, assume it is.
2649 dvmThrowClassFormatError("java.lang.Object has a superclass");
2653 /* Don't finalize objects whose classes use the
2654 * default (empty) Object.finalize().
2656 CLEAR_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2658 if (clazz->super == NULL) {
2659 dvmThrowLinkageError("no superclass defined");
2663 if (dvmIsFinalClass(clazz->super)) {
2664 ALOGW("Superclass of '%s' is final '%s'",
2665 clazz->descriptor, clazz->super->descriptor);
2666 dvmThrowIncompatibleClassChangeError("superclass is final");
2668 } else if (dvmIsInterfaceClass(clazz->super)) {
2669 ALOGW("Superclass of '%s' is interface '%s'",
2670 clazz->descriptor, clazz->super->descriptor);
2671 dvmThrowIncompatibleClassChangeError("superclass is an interface");
2673 } else if (!dvmCheckClassAccess(clazz, clazz->super)) {
2674 ALOGW("Superclass of '%s' (%s) is not accessible",
2675 clazz->descriptor, clazz->super->descriptor);
2676 dvmThrowIllegalAccessError("superclass not accessible");
2680 /* Inherit finalizability from the superclass. If this
2681 * class also overrides finalize(), its CLASS_ISFINALIZABLE
2682 * bit will already be set.
2684 if (IS_CLASS_FLAG_SET(clazz->super, CLASS_ISFINALIZABLE)) {
2685 SET_CLASS_FLAG(clazz, CLASS_ISFINALIZABLE);
2688 /* See if this class descends from java.lang.Reference
2689 * and set the class flags appropriately.
2691 if (IS_CLASS_FLAG_SET(clazz->super, CLASS_ISREFERENCE)) {
2694 /* We've already determined the reference type of this
2695 * inheritance chain. Inherit reference-ness from the superclass.
2697 superRefFlags = GET_CLASS_FLAG_GROUP(clazz->super,
2699 CLASS_ISWEAKREFERENCE |
2700 CLASS_ISFINALIZERREFERENCE |
2701 CLASS_ISPHANTOMREFERENCE);
2702 SET_CLASS_FLAG(clazz, superRefFlags);
2703 } else if (clazz->classLoader == NULL &&
2704 clazz->super->classLoader == NULL &&
2705 strcmp(clazz->super->descriptor,
2706 "Ljava/lang/ref/Reference;") == 0)
2710 /* This class extends Reference, which means it should
2711 * be one of the magic Soft/Weak/PhantomReference classes.
2713 refFlags = CLASS_ISREFERENCE;
2714 if (strcmp(clazz->descriptor,
2715 "Ljava/lang/ref/SoftReference;") == 0)
2717 /* Only CLASS_ISREFERENCE is set for soft references.
2719 } else if (strcmp(clazz->descriptor,
2720 "Ljava/lang/ref/WeakReference;") == 0)
2722 refFlags |= CLASS_ISWEAKREFERENCE;
2723 } else if (strcmp(clazz->descriptor,
2724 "Ljava/lang/ref/FinalizerReference;") == 0)
2726 refFlags |= CLASS_ISFINALIZERREFERENCE;
2727 } else if (strcmp(clazz->descriptor,
2728 "Ljava/lang/ref/PhantomReference;") == 0)
2730 refFlags |= CLASS_ISPHANTOMREFERENCE;
2732 /* No-one else is allowed to inherit directly
2735 //xxx is this the right exception? better than an assertion.
2736 dvmThrowLinkageError("illegal inheritance from Reference");
2740 /* The class should not have any reference bits set yet.
2742 assert(GET_CLASS_FLAG_GROUP(clazz,
2744 CLASS_ISWEAKREFERENCE |
2745 CLASS_ISFINALIZERREFERENCE |
2746 CLASS_ISPHANTOMREFERENCE) == 0);
2748 SET_CLASS_FLAG(clazz, refFlags);
2755 if (dvmIsInterfaceClass(clazz)) {
2756 /* no vtable; just set the method indices */
2757 int count = clazz->virtualMethodCount;
2759 if (count != (u2) count) {
2760 ALOGE("Too many methods (%d) in interface '%s'", count,
2765 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
2767 for (i = 0; i < count; i++)
2768 clazz->virtualMethods[i].methodIndex = (u2) i;
2770 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
2772 if (!createVtable(clazz)) {
2773 ALOGW("failed creating vtable");
2779 * Populate interface method tables. Can alter the vtable.
2781 if (!createIftable(clazz))
2785 * Insert special-purpose "stub" method implementations.
2787 if (!insertMethodStubs(clazz))
2791 * Compute instance field offsets and, hence, the size of the object.
2793 if (!computeFieldOffsets(clazz))
2797 * Cache field and method info for the class Reference (as loaded
2798 * by the boot classloader). This has to happen after the call to
2799 * computeFieldOffsets().
2801 if ((clazz->classLoader == NULL)
2802 && (strcmp(clazz->descriptor, "Ljava/lang/ref/Reference;") == 0)) {
2803 if (!precacheReferenceOffsets(clazz)) {
2804 ALOGE("failed pre-caching Reference offsets");
2805 dvmThrowInternalError(NULL);
2811 * Compact the offsets the GC has to examine into a bitmap, if
2812 * possible. (This has to happen after Reference.referent is
2813 * massaged in precacheReferenceOffsets.)
2815 computeRefOffsets(clazz);
2820 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISPREVERIFIED))
2821 clazz->status = CLASS_VERIFIED;
2823 clazz->status = CLASS_RESOLVED;
2825 if (gDvm.verboseClass)
2826 ALOGV("CLASS: linked '%s'", clazz->descriptor);
2829 * We send CLASS_PREPARE events to the debugger from here. The
2830 * definition of "preparation" is creating the static fields for a
2831 * class and initializing them to the standard default values, but not
2832 * executing any code (that comes later, during "initialization").
2834 * We did the static prep in loadSFieldFromDex() while loading the class.
2836 * The class has been prepared and resolved but possibly not yet verified
2839 if (gDvm.debuggerActive) {
2840 dvmDbgPostClassPrepare(clazz);
2845 clazz->status = CLASS_ERROR;
2846 if (!dvmCheckException(dvmThreadSelf())) {
2847 dvmThrowVirtualMachineError(NULL);
2850 if (interfaceIdxArray != NULL) {
2851 free(interfaceIdxArray);
2858 * Create the virtual method table.
2860 * The top part of the table is a copy of the table from our superclass,
2861 * with our local methods overriding theirs. The bottom part of the table
2862 * has any new methods we defined.
2864 static bool createVtable(ClassObject* clazz)
2866 bool result = false;
2870 if (clazz->super != NULL) {
2871 //ALOGI("SUPER METHODS %d %s->%s", clazz->super->vtableCount,
2872 // clazz->descriptor, clazz->super->descriptor);
2875 /* the virtual methods we define, plus the superclass vtable size */
2876 maxCount = clazz->virtualMethodCount;
2877 if (clazz->super != NULL) {
2878 maxCount += clazz->super->vtableCount;
2880 /* TODO: is this invariant true for all java/lang/Objects,
2881 * regardless of the class loader? For now, assume it is.
2883 assert(strcmp(clazz->descriptor, "Ljava/lang/Object;") == 0);
2885 //ALOGD("+++ max vmethods for '%s' is %d", clazz->descriptor, maxCount);
2888 * Over-allocate the table, then realloc it down if necessary. So
2889 * long as we don't allocate anything in between we won't cause
2890 * fragmentation, and reducing the size should be unlikely to cause
2893 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
2894 clazz->vtable = (Method**) dvmLinearAlloc(clazz->classLoader,
2895 sizeof(Method*) * maxCount);
2896 if (clazz->vtable == NULL)
2899 if (clazz->super != NULL) {
2902 memcpy(clazz->vtable, clazz->super->vtable,
2903 sizeof(*(clazz->vtable)) * clazz->super->vtableCount);
2904 actualCount = clazz->super->vtableCount;
2907 * See if any of our virtual methods override the superclass.
2909 for (i = 0; i < clazz->virtualMethodCount; i++) {
2910 Method* localMeth = &clazz->virtualMethods[i];
2913 for (si = 0; si < clazz->super->vtableCount; si++) {
2914 Method* superMeth = clazz->vtable[si];
2916 if (dvmCompareMethodNamesAndProtos(localMeth, superMeth) == 0) {
2917 // Some apps were relying on us not checking access: http://b/7301030
2918 bool isPreJbMr1 = (gDvm.targetSdkVersion > 0 && gDvm.targetSdkVersion < 17);
2919 bool isAccessible = dvmCheckMethodAccess(clazz, superMeth);
2920 if (isPreJbMr1 || isAccessible) {
2921 if (dvmIsFinalMethod(superMeth)) {
2922 ALOGW("Method %s.%s overrides final %s.%s",
2923 localMeth->clazz->descriptor, localMeth->name,
2924 superMeth->clazz->descriptor, superMeth->name);
2928 // Warn if we may have just worked around broken code...
2929 if (!isAccessible) {
2930 ALOGW("in older Android releases, method %s.%s would have incorrectly "
2931 "overridden package-private method with same name in %s",
2932 localMeth->clazz->descriptor, localMeth->name,
2933 superMeth->clazz->descriptor);
2936 clazz->vtable[si] = localMeth;
2937 localMeth->methodIndex = (u2) si;
2938 //ALOGV("+++ override %s.%s (slot %d)",
2939 // clazz->descriptor, localMeth->name, si);
2945 if (si == clazz->super->vtableCount) {
2946 /* not an override, add to end */
2947 clazz->vtable[actualCount] = localMeth;
2948 localMeth->methodIndex = (u2) actualCount;
2951 //ALOGV("+++ add method %s.%s",
2952 // clazz->descriptor, localMeth->name);
2956 if (actualCount != (u2) actualCount) {
2957 ALOGE("Too many methods (%d) in class '%s'", actualCount,
2962 assert(actualCount <= maxCount);
2964 if (actualCount < maxCount) {
2965 assert(clazz->vtable != NULL);
2966 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
2967 clazz->vtable = (Method **)dvmLinearRealloc(clazz->classLoader,
2968 clazz->vtable, sizeof(*(clazz->vtable)) * actualCount);
2969 if (clazz->vtable == NULL) {
2970 ALOGE("vtable realloc failed");
2973 LOGVV("+++ reduced vtable from %d to %d",
2974 maxCount, actualCount);
2978 clazz->vtableCount = actualCount;
2980 /* java/lang/Object case */
2981 int count = clazz->virtualMethodCount;
2982 if (count != (u2) count) {
2983 ALOGE("Too many methods (%d) in base class '%s'", count,
2988 for (i = 0; i < count; i++) {
2989 clazz->vtable[i] = &clazz->virtualMethods[i];
2990 clazz->virtualMethods[i].methodIndex = (u2) i;
2992 clazz->vtableCount = clazz->virtualMethodCount;
2998 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
2999 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3004 * Create and populate "iftable".
3006 * The set of interfaces we support is the combination of the interfaces
3007 * we implement directly and those implemented by our superclass. Each
3008 * interface can have one or more "superinterfaces", which we must also
3009 * support. For speed we flatten the tree out.
3011 * We might be able to speed this up when there are lots of interfaces
3012 * by merge-sorting the class pointers and binary-searching when removing
3013 * duplicates. We could also drop the duplicate removal -- it's only
3014 * there to reduce the memory footprint.
3016 * Because of "Miranda methods", this may reallocate clazz->virtualMethods.
3018 * Returns "true" on success.
3020 static bool createIftable(ClassObject* clazz)
3022 bool result = false;
3023 bool zapIftable = false;
3024 bool zapVtable = false;
3025 bool zapIfvipool = false;
3026 int poolOffset = 0, poolSize = 0;
3027 Method** mirandaList = NULL;
3028 int mirandaCount = 0, mirandaAlloc = 0;
3031 if (clazz->super != NULL)
3032 superIfCount = clazz->super->iftableCount;
3036 int ifCount = superIfCount;
3037 ifCount += clazz->interfaceCount;
3038 for (int i = 0; i < clazz->interfaceCount; i++)
3039 ifCount += clazz->interfaces[i]->iftableCount;
3041 LOGVV("INTF: class '%s' direct w/supra=%d super=%d total=%d",
3042 clazz->descriptor, ifCount - superIfCount, superIfCount, ifCount);
3045 assert(clazz->iftableCount == 0);
3046 assert(clazz->iftable == NULL);
3051 * Create a table with enough space for all interfaces, and copy the
3052 * superclass' table in.
3054 clazz->iftable = (InterfaceEntry*) dvmLinearAlloc(clazz->classLoader,
3055 sizeof(InterfaceEntry) * ifCount);
3057 memset(clazz->iftable, 0x00, sizeof(InterfaceEntry) * ifCount);
3058 if (superIfCount != 0) {
3059 memcpy(clazz->iftable, clazz->super->iftable,
3060 sizeof(InterfaceEntry) * superIfCount);
3064 * Create a flattened interface hierarchy of our immediate interfaces.
3066 int idx = superIfCount;
3068 for (int i = 0; i < clazz->interfaceCount; i++) {
3069 ClassObject* interf = clazz->interfaces[i];
3070 assert(interf != NULL);
3072 /* make sure this is still an interface class */
3073 if (!dvmIsInterfaceClass(interf)) {
3074 ALOGW("Class '%s' implements non-interface '%s'",
3075 clazz->descriptor, interf->descriptor);
3076 dvmThrowIncompatibleClassChangeErrorWithClassMessage(
3081 /* add entry for this interface */
3082 clazz->iftable[idx++].clazz = interf;
3084 /* add entries for the interface's superinterfaces */
3085 for (int j = 0; j < interf->iftableCount; j++) {
3089 cand = interf->iftable[j].clazz;
3092 * Check if this interface was already added and add only if new.
3093 * This is to avoid a potential blowup in the number of
3094 * interfaces for sufficiently complicated interface hierarchies.
3095 * This has quadratic runtime in the number of interfaces.
3096 * However, in common cases with little interface inheritance, this
3097 * doesn't make much of a difference.
3099 for (k = 0; k < idx; k++)
3100 if (clazz->iftable[k].clazz == cand)
3104 clazz->iftable[idx++].clazz = cand;
3108 assert(idx <= ifCount);
3111 * Adjust the ifCount. We could reallocate the interface memory here,
3112 * but it's probably not worth the effort, the important thing here
3113 * is to avoid the interface blowup and keep the ifCount low.
3116 if (idx != ifCount) {
3117 int newIfCount = idx;
3118 InterfaceEntry* oldmem = clazz->iftable;
3120 clazz->iftable = (InterfaceEntry*) dvmLinearAlloc(clazz->classLoader,
3121 sizeof(InterfaceEntry) * newIfCount);
3122 memcpy(clazz->iftable, oldmem, sizeof(InterfaceEntry) * newIfCount);
3123 dvmLinearFree(clazz->classLoader, oldmem);
3128 clazz->iftableCount = ifCount;
3131 * If we're an interface, we don't need the vtable pointers, so
3132 * we're done. If this class doesn't implement an interface that our
3133 * superclass doesn't have, then we again have nothing to do.
3135 if (dvmIsInterfaceClass(clazz) || superIfCount == ifCount) {
3136 //dvmDumpClass(clazz, kDumpClassFullDetail);
3142 * When we're handling invokeinterface, we probably have an object
3143 * whose type is an interface class rather than a concrete class. We
3144 * need to convert the method reference into a vtable index. So, for
3145 * every entry in "iftable", we create a list of vtable indices.
3147 * Because our vtable encompasses the superclass vtable, we can use
3148 * the vtable indices from our superclass for all of the interfaces
3149 * that weren't directly implemented by us.
3151 * Each entry in "iftable" has a pointer to the start of its set of
3152 * vtable offsets. The iftable entries in the superclass point to
3153 * storage allocated in the superclass, and the iftable entries added
3154 * for this class point to storage allocated in this class. "iftable"
3155 * is flat for fast access in a class and all of its subclasses, but
3156 * "ifviPool" is only created for the topmost implementor.
3158 for (int i = superIfCount; i < ifCount; i++) {
3160 * Note it's valid for an interface to have no methods (e.g.
3161 * java/io/Serializable).
3163 LOGVV("INTF: pool: %d from %s",
3164 clazz->iftable[i].clazz->virtualMethodCount,
3165 clazz->iftable[i].clazz->descriptor);
3166 poolSize += clazz->iftable[i].clazz->virtualMethodCount;
3169 if (poolSize == 0) {
3170 LOGVV("INTF: didn't find any new interfaces with methods");
3175 clazz->ifviPoolCount = poolSize;
3176 clazz->ifviPool = (int*) dvmLinearAlloc(clazz->classLoader,
3177 poolSize * sizeof(int*));
3181 * Fill in the vtable offsets for the interfaces that weren't part of
3184 for (int i = superIfCount; i < ifCount; i++) {
3185 ClassObject* interface;
3188 clazz->iftable[i].methodIndexArray = clazz->ifviPool + poolOffset;
3189 interface = clazz->iftable[i].clazz;
3190 poolOffset += interface->virtualMethodCount; // end here
3193 * For each method listed in the interface's method list, find the
3194 * matching method in our class's method list. We want to favor the
3195 * subclass over the superclass, which just requires walking
3196 * back from the end of the vtable. (This only matters if the
3197 * superclass defines a private method and this class redefines
3198 * it -- otherwise it would use the same vtable slot. In Dalvik
3199 * those don't end up in the virtual method table, so it shouldn't
3200 * matter which direction we go. We walk it backward anyway.)
3203 * Suppose we have the following arrangement:
3204 * public interface MyInterface
3205 * public boolean inInterface();
3206 * public abstract class MirandaAbstract implements MirandaInterface
3207 * //public abstract boolean inInterface(); // not declared!
3208 * public boolean inAbstract() { stuff } // in vtable
3209 * public class MirandClass extends MirandaAbstract
3210 * public boolean inInterface() { stuff }
3211 * public boolean inAbstract() { stuff } // in vtable
3213 * The javac compiler happily compiles MirandaAbstract even though
3214 * it doesn't declare all methods from its interface. When we try
3215 * to set up a vtable for MirandaAbstract, we find that we don't
3216 * have an slot for inInterface. To prevent this, we synthesize
3217 * abstract method declarations in MirandaAbstract.
3219 * We have to expand vtable and update some things that point at it,
3220 * so we accumulate the method list and do it all at once below.
3222 for (methIdx = 0; methIdx < interface->virtualMethodCount; methIdx++) {
3223 Method* imeth = &interface->virtualMethods[methIdx];
3227 char* desc = dexProtoCopyMethodDescriptor(&imeth->prototype);
3228 LOGVV("INTF: matching '%s' '%s'", imeth->name, desc);
3232 for (j = clazz->vtableCount-1; j >= 0; j--) {
3233 if (dvmCompareMethodNamesAndProtos(imeth, clazz->vtable[j])
3236 LOGVV("INTF: matched at %d", j);
3237 if (!dvmIsPublicMethod(clazz->vtable[j])) {
3238 ALOGW("Implementation of %s.%s is not public",
3239 clazz->descriptor, clazz->vtable[j]->name);
3240 dvmThrowIllegalAccessError(
3241 "interface implementation not public");
3244 clazz->iftable[i].methodIndexArray[methIdx] = j;
3251 dexProtoCopyMethodDescriptor(&imeth->prototype);
3252 ALOGV("No match for '%s' '%s' in '%s' (creating miranda)",
3253 imeth->name, desc, clazz->descriptor);
3256 //dvmThrowRuntimeException("Miranda!");
3259 if (mirandaCount == mirandaAlloc) {
3261 if (mirandaList == NULL) {
3262 mirandaList = (Method**)dvmLinearAlloc(
3264 mirandaAlloc * sizeof(Method*));
3266 dvmLinearReadOnly(clazz->classLoader, mirandaList);
3267 mirandaList = (Method**)dvmLinearRealloc(
3269 mirandaList, mirandaAlloc * sizeof(Method*));
3271 assert(mirandaList != NULL); // mem failed + we leaked
3275 * These may be redundant (e.g. method with same name and
3276 * signature declared in two interfaces implemented by the
3277 * same abstract class). We can squeeze the duplicates
3281 for (mir = 0; mir < mirandaCount; mir++) {
3282 if (dvmCompareMethodNamesAndProtos(
3283 mirandaList[mir], imeth) == 0)
3286 char* desc = dexProtoCopyMethodDescriptor(
3288 LOGVV("MIRANDA dupe: %s and %s %s%s",
3289 mirandaList[mir]->clazz->descriptor,
3290 imeth->clazz->descriptor,
3298 /* point the iftable at a phantom slot index */
3299 clazz->iftable[i].methodIndexArray[methIdx] =
3300 clazz->vtableCount + mir;
3301 LOGVV("MIRANDA: %s points at slot %d",
3302 imeth->name, clazz->vtableCount + mir);
3304 /* if non-duplicate among Mirandas, add to Miranda list */
3305 if (mir == mirandaCount) {
3306 //ALOGV("MIRANDA: holding '%s' in slot %d",
3307 // imeth->name, mir);
3308 mirandaList[mirandaCount++] = imeth;
3314 if (mirandaCount != 0) {
3315 static const int kManyMirandas = 150; /* arbitrary */
3316 Method* newVirtualMethods;
3318 int oldMethodCount, oldVtableCount;
3320 for (int i = 0; i < mirandaCount; i++) {
3321 LOGVV("MIRANDA %d: %s.%s", i,
3322 mirandaList[i]->clazz->descriptor, mirandaList[i]->name);
3324 if (mirandaCount > kManyMirandas) {
3326 * Some obfuscators like to create an interface with a huge
3327 * pile of methods, declare classes as implementing it, and then
3328 * only define a couple of methods. This leads to a rather
3329 * massive collection of Miranda methods and a lot of wasted
3330 * space, sometimes enough to blow out the LinearAlloc cap.
3332 ALOGD("Note: class %s has %d unimplemented (abstract) methods",
3333 clazz->descriptor, mirandaCount);
3337 * We found methods in one or more interfaces for which we do not
3338 * have vtable entries. We have to expand our virtualMethods
3339 * table (which might be empty) to hold some new entries.
3341 if (clazz->virtualMethods == NULL) {
3342 newVirtualMethods = (Method*) dvmLinearAlloc(clazz->classLoader,
3343 sizeof(Method) * (clazz->virtualMethodCount + mirandaCount));
3345 //dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3346 newVirtualMethods = (Method*) dvmLinearRealloc(clazz->classLoader,
3347 clazz->virtualMethods,
3348 sizeof(Method) * (clazz->virtualMethodCount + mirandaCount));
3350 if (newVirtualMethods != clazz->virtualMethods) {
3352 * Table was moved in memory. We have to run through the
3353 * vtable and fix the pointers. The vtable entries might be
3354 * pointing at superclasses, so we flip it around: run through
3355 * all locally-defined virtual methods, and fix their entries
3356 * in the vtable. (This would get really messy if sub-classes
3357 * had already been loaded.)
3359 * Reminder: clazz->virtualMethods and clazz->virtualMethodCount
3360 * hold the virtual methods declared by this class. The
3361 * method's methodIndex is the vtable index, and is the same
3362 * for all sub-classes (and all super classes in which it is
3363 * defined). We're messing with these because the Miranda
3364 * stuff makes it look like the class actually has an abstract
3365 * method declaration in it.
3367 LOGVV("MIRANDA fixing vtable pointers");
3368 dvmLinearReadWrite(clazz->classLoader, clazz->vtable);
3369 Method* meth = newVirtualMethods;
3370 for (int i = 0; i < clazz->virtualMethodCount; i++, meth++)
3371 clazz->vtable[meth->methodIndex] = meth;
3372 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
3375 oldMethodCount = clazz->virtualMethodCount;
3376 clazz->virtualMethods = newVirtualMethods;
3377 clazz->virtualMethodCount += mirandaCount;
3379 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3382 * We also have to expand the vtable.
3384 assert(clazz->vtable != NULL);
3385 clazz->vtable = (Method**) dvmLinearRealloc(clazz->classLoader,
3387 sizeof(Method*) * (clazz->vtableCount + mirandaCount));
3388 if (clazz->vtable == NULL) {
3394 oldVtableCount = clazz->vtableCount;
3395 clazz->vtableCount += mirandaCount;
3398 * Now we need to create the fake methods. We clone the abstract
3399 * method definition from the interface and then replace a few
3402 * The Method will be an "abstract native", with nativeFunc set to
3403 * dvmAbstractMethodStub().
3405 meth = clazz->virtualMethods + oldMethodCount;
3406 for (int i = 0; i < mirandaCount; i++, meth++) {
3407 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
3408 cloneMethod(meth, mirandaList[i]);
3409 meth->clazz = clazz;
3410 meth->accessFlags |= ACC_MIRANDA;
3411 meth->methodIndex = (u2) (oldVtableCount + i);
3412 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3414 /* point the new vtable entry at the new method */
3415 clazz->vtable[oldVtableCount + i] = meth;
3418 dvmLinearReadOnly(clazz->classLoader, mirandaList);
3419 dvmLinearFree(clazz->classLoader, mirandaList);
3425 * Sort the interfaces by number of declared methods. All we really
3426 * want is to get the interfaces with zero methods at the end of the
3427 * list, so that when we walk through the list during invoke-interface
3428 * we don't examine interfaces that can't possibly be useful.
3430 * The set will usually be small, so a simple insertion sort works.
3432 * We have to be careful not to change the order of two interfaces
3433 * that define the same method. (Not a problem if we only move the
3434 * zero-method interfaces to the end.)
3437 * If we do this, we will no longer be able to identify super vs.
3438 * current class interfaces by comparing clazz->super->iftableCount. This
3439 * breaks anything that only wants to find interfaces declared directly
3440 * by the class (dvmFindStaticFieldHier, ReferenceType.Interfaces,
3441 * dvmDbgOutputAllInterfaces, etc). Need to provide a workaround.
3443 * We can sort just the interfaces implemented directly by this class,
3444 * but that doesn't seem like it would provide much of an advantage. I'm
3445 * not sure this is worthwhile.
3447 * (This has been made largely obsolete by the interface cache mechanism.)
3450 //dvmDumpClass(clazz);
3456 dvmLinearReadOnly(clazz->classLoader, clazz->iftable);
3458 dvmLinearReadOnly(clazz->classLoader, clazz->vtable);
3460 dvmLinearReadOnly(clazz->classLoader, clazz->ifviPool);
3466 * Provide "stub" implementations for methods without them.
3468 * Currently we provide an implementation for all abstract methods that
3469 * throws an AbstractMethodError exception. This allows us to avoid an
3470 * explicit check for abstract methods in every virtual call.
3472 * NOTE: for Miranda methods, the method declaration is a clone of what
3473 * was found in the interface class. That copy may already have had the
3474 * function pointer filled in, so don't be surprised if it's not NULL.
3476 * NOTE: this sets the "native" flag, giving us an "abstract native" method,
3477 * which is nonsensical. Need to make sure that this doesn't escape the
3478 * VM. We can either mask it out in reflection calls, or copy "native"
3479 * into the high 16 bits of accessFlags and check that internally.
3481 static bool insertMethodStubs(ClassObject* clazz)
3483 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
3488 meth = clazz->virtualMethods;
3489 for (i = 0; i < clazz->virtualMethodCount; i++, meth++) {
3490 if (dvmIsAbstractMethod(meth)) {
3491 assert(meth->insns == NULL);
3492 assert(meth->nativeFunc == NULL ||
3493 meth->nativeFunc == (DalvikBridgeFunc)dvmAbstractMethodStub);
3495 meth->accessFlags |= ACC_NATIVE;
3496 meth->nativeFunc = (DalvikBridgeFunc) dvmAbstractMethodStub;
3500 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
3506 * Swap two instance fields.
3508 static inline void swapField(InstField* pOne, InstField* pTwo)
3512 LOGVV(" --- swap '%s' and '%s'", pOne->name, pTwo->name);
3519 * Assign instance fields to u4 slots.
3521 * The top portion of the instance field area is occupied by the superclass
3522 * fields, the bottom by the fields for this class.
3524 * "long" and "double" fields occupy two adjacent slots. On some
3525 * architectures, 64-bit quantities must be 64-bit aligned, so we need to
3526 * arrange fields (or introduce padding) to ensure this. We assume the
3527 * fields of the topmost superclass (i.e. Object) are 64-bit aligned, so
3528 * we can just ensure that the offset is "even". To avoid wasting space,
3529 * we want to move non-reference 32-bit fields into gaps rather than
3530 * creating pad words.
3532 * In the worst case we will waste 4 bytes, but because objects are
3533 * allocated on >= 64-bit boundaries, those bytes may well be wasted anyway
3534 * (assuming this is the most-derived class).
3536 * Pad words are not represented in the field table, so the field table
3537 * itself does not change size.
3539 * The number of field slots determines the size of the object, so we
3540 * set that here too.
3542 * This function feels a little more complicated than I'd like, but it
3543 * has the property of moving the smallest possible set of fields, which
3544 * should reduce the time required to load a class.
3546 * NOTE: reference fields *must* come first, or precacheReferenceOffsets()
3549 static bool computeFieldOffsets(ClassObject* clazz)
3554 dvmLinearReadWrite(clazz->classLoader, clazz->ifields);
3556 if (clazz->super != NULL)
3557 fieldOffset = clazz->super->objectSize;
3559 fieldOffset = OFFSETOF_MEMBER(DataObject, instanceData);
3561 LOGVV("--- computeFieldOffsets '%s'", clazz->descriptor);
3563 //ALOGI("OFFSETS fieldCount=%d", clazz->ifieldCount);
3564 //ALOGI("dataobj, instance: %d", offsetof(DataObject, instanceData));
3565 //ALOGI("classobj, access: %d", offsetof(ClassObject, accessFlags));
3566 //ALOGI("super=%p, fieldOffset=%d", clazz->super, fieldOffset);
3569 * Start by moving all reference fields to the front.
3571 clazz->ifieldRefCount = 0;
3572 j = clazz->ifieldCount - 1;
3573 for (i = 0; i < clazz->ifieldCount; i++) {
3574 InstField* pField = &clazz->ifields[i];
3575 char c = pField->signature[0];
3577 if (c != '[' && c != 'L') {
3578 /* This isn't a reference field; see if any reference fields
3579 * follow this one. If so, we'll move it to this position.
3580 * (quicksort-style partitioning)
3583 InstField* refField = &clazz->ifields[j--];
3584 char rc = refField->signature[0];
3586 if (rc == '[' || rc == 'L') {
3587 /* Here's a reference field that follows at least one
3588 * non-reference field. Swap it with the current field.
3589 * (When this returns, "pField" points to the reference
3590 * field, and "refField" points to the non-ref field.)
3592 swapField(pField, refField);
3594 /* Fix the signature.
3598 clazz->ifieldRefCount++;
3602 /* We may or may not have swapped a field.
3605 /* This is a reference field.
3607 clazz->ifieldRefCount++;
3611 * If we've hit the end of the reference fields, break.
3613 if (c != '[' && c != 'L')
3616 pField->byteOffset = fieldOffset;
3617 fieldOffset += sizeof(u4);
3618 LOGVV(" --- offset1 '%s'=%d", pField->name,pField->byteOffset);
3622 * Now we want to pack all of the double-wide fields together. If we're
3623 * not aligned, though, we want to shuffle one 32-bit field into place.
3624 * If we can't find one, we'll have to pad it.
3626 if (i != clazz->ifieldCount && (fieldOffset & 0x04) != 0) {
3627 LOGVV(" +++ not aligned");
3629 InstField* pField = &clazz->ifields[i];
3630 char c = pField->signature[0];
3632 if (c != 'J' && c != 'D') {
3634 * The field that comes next is 32-bit, so just advance past it.
3636 assert(c != '[' && c != 'L');
3637 pField->byteOffset = fieldOffset;
3638 fieldOffset += sizeof(u4);
3640 LOGVV(" --- offset2 '%s'=%d",
3641 pField->name, pField->byteOffset);
3644 * Next field is 64-bit, so search for a 32-bit field we can
3648 j = clazz->ifieldCount - 1;
3650 InstField* singleField = &clazz->ifields[j--];
3651 char rc = singleField->signature[0];
3653 if (rc != 'J' && rc != 'D') {
3654 swapField(pField, singleField);
3656 LOGVV(" +++ swapped '%s' for alignment",
3658 pField->byteOffset = fieldOffset;
3659 fieldOffset += sizeof(u4);
3660 LOGVV(" --- offset3 '%s'=%d",
3661 pField->name, pField->byteOffset);
3668 ALOGV(" +++ inserting pad field in '%s'", clazz->descriptor);
3669 fieldOffset += sizeof(u4);
3675 * Alignment is good, shuffle any double-wide fields forward, and
3676 * finish assigning field offsets to all fields.
3678 assert(i == clazz->ifieldCount || (fieldOffset & 0x04) == 0);
3679 j = clazz->ifieldCount - 1;
3680 for ( ; i < clazz->ifieldCount; i++) {
3681 InstField* pField = &clazz->ifields[i];
3682 char c = pField->signature[0];
3684 if (c != 'D' && c != 'J') {
3685 /* This isn't a double-wide field; see if any double fields
3686 * follow this one. If so, we'll move it to this position.
3687 * (quicksort-style partitioning)
3690 InstField* doubleField = &clazz->ifields[j--];
3691 char rc = doubleField->signature[0];
3693 if (rc == 'D' || rc == 'J') {
3694 /* Here's a double-wide field that follows at least one
3695 * non-double field. Swap it with the current field.
3696 * (When this returns, "pField" points to the reference
3697 * field, and "doubleField" points to the non-double field.)
3699 swapField(pField, doubleField);
3705 /* We may or may not have swapped a field.
3708 /* This is a double-wide field, leave it be.
3712 pField->byteOffset = fieldOffset;
3713 LOGVV(" --- offset4 '%s'=%d", pField->name,pField->byteOffset);
3714 fieldOffset += sizeof(u4);
3715 if (c == 'J' || c == 'D')
3716 fieldOffset += sizeof(u4);
3720 /* Make sure that all reference fields appear before
3721 * non-reference fields, and all double-wide fields are aligned.
3723 j = 0; // seen non-ref
3724 for (i = 0; i < clazz->ifieldCount; i++) {
3725 InstField *pField = &clazz->ifields[i];
3726 char c = pField->signature[0];
3728 if (c == 'D' || c == 'J') {
3729 assert((pField->byteOffset & 0x07) == 0);
3732 if (c != '[' && c != 'L') {
3734 assert(i == clazz->ifieldRefCount);
3742 assert(clazz->ifieldRefCount == clazz->ifieldCount);
3747 * We map a C struct directly on top of java/lang/Class objects. Make
3748 * sure we left enough room for the instance fields.
3750 assert(!dvmIsTheClassClass(clazz) || (size_t)fieldOffset <
3751 OFFSETOF_MEMBER(ClassObject, instanceData) + sizeof(clazz->instanceData));
3753 clazz->objectSize = fieldOffset;
3755 dvmLinearReadOnly(clazz->classLoader, clazz->ifields);
3760 * The class failed to initialize on a previous attempt, so we want to throw
3761 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
3762 * failed in verification, in which case v2 5.4.1 says we need to re-throw
3763 * the previous error.
3765 static void throwEarlierClassFailure(ClassObject* clazz)
3767 ALOGI("Rejecting re-init on previously-failed class %s v=%p",
3768 clazz->descriptor, clazz->verifyErrorClass);
3770 if (clazz->verifyErrorClass == NULL) {
3771 dvmThrowNoClassDefFoundError(clazz->descriptor);
3773 dvmThrowExceptionWithClassMessage(clazz->verifyErrorClass,
3779 * Initialize any static fields whose values are stored in
3780 * the DEX file. This must be done during class initialization.
3782 static void initSFields(ClassObject* clazz)
3784 Thread* self = dvmThreadSelf(); /* for dvmReleaseTrackedAlloc() */
3786 const DexClassDef* pClassDef;
3787 const DexEncodedArray* pValueList;
3788 EncodedArrayIterator iterator;
3791 if (clazz->sfieldCount == 0) {
3794 if (clazz->pDvmDex == NULL) {
3795 /* generated class; any static fields should already be set up */
3796 ALOGV("Not initializing static fields in %s", clazz->descriptor);
3799 pDexFile = clazz->pDvmDex->pDexFile;
3801 pClassDef = dexFindClass(pDexFile, clazz->descriptor);
3802 assert(pClassDef != NULL);
3804 pValueList = dexGetStaticValuesList(pDexFile, pClassDef);
3805 if (pValueList == NULL) {
3809 dvmEncodedArrayIteratorInitialize(&iterator, pValueList, clazz);
3812 * Iterate over the initial values array, setting the corresponding
3813 * static field for each array element.
3816 for (i = 0; dvmEncodedArrayIteratorHasNext(&iterator); i++) {
3817 AnnotationValue value;
3818 bool parsed = dvmEncodedArrayIteratorGetNext(&iterator, &value);
3819 StaticField* sfield = &clazz->sfields[i];
3820 const char* descriptor = sfield->signature;
3825 * TODO: Eventually verification should attempt to ensure
3826 * that this can't happen at least due to a data integrity
3829 ALOGE("Static initializer parse failed for %s at index %d",
3830 clazz->descriptor, i);
3834 /* Verify that the value we got was of a valid type. */
3836 switch (descriptor[0]) {
3837 case 'Z': parsed = (value.type == kDexAnnotationBoolean); break;
3838 case 'B': parsed = (value.type == kDexAnnotationByte); break;
3839 case 'C': parsed = (value.type == kDexAnnotationChar); break;
3840 case 'S': parsed = (value.type == kDexAnnotationShort); break;
3841 case 'I': parsed = (value.type == kDexAnnotationInt); break;
3842 case 'J': parsed = (value.type == kDexAnnotationLong); break;
3843 case 'F': parsed = (value.type == kDexAnnotationFloat); break;
3844 case 'D': parsed = (value.type == kDexAnnotationDouble); break;
3845 case '[': parsed = (value.type == kDexAnnotationNull); break;
3847 switch (value.type) {
3848 case kDexAnnotationNull: {
3849 /* No need for further tests. */
3852 case kDexAnnotationString: {
3854 (strcmp(descriptor, "Ljava/lang/String;") == 0);
3858 case kDexAnnotationType: {
3860 (strcmp(descriptor, "Ljava/lang/Class;") == 0);
3879 * All's well, so store the value.
3882 dvmSetStaticFieldObject(sfield, (Object*)value.value.l);
3883 dvmReleaseTrackedAlloc((Object*)value.value.l, self);
3886 * Note: This always stores the full width of a
3887 * JValue, even though most of the time only the first
3890 sfield->value = value.value;
3894 * Something up above had a problem. TODO: See comment
3895 * above the switch about verfication.
3897 ALOGE("Bogus static initialization: value type %d in field type "
3898 "%s for %s at index %d",
3899 value.type, descriptor, clazz->descriptor, i);
3907 * Determine whether "descriptor" yields the same class object in the
3908 * context of clazz1 and clazz2.
3910 * The caller must hold gDvm.loadedClasses.
3912 * Returns "true" if they match.
3914 static bool compareDescriptorClasses(const char* descriptor,
3915 const ClassObject* clazz1, const ClassObject* clazz2)
3917 ClassObject* result1;
3918 ClassObject* result2;
3921 * Do the first lookup by name.
3923 result1 = dvmFindClassNoInit(descriptor, clazz1->classLoader);
3926 * We can skip a second lookup by name if the second class loader is
3927 * in the initiating loader list of the class object we retrieved.
3928 * (This means that somebody already did a lookup of this class through
3929 * the second loader, and it resolved to the same class.) If it's not
3930 * there, we may simply not have had an opportunity to add it yet, so
3931 * we do the full lookup.
3933 * The initiating loader test should catch the majority of cases
3934 * (in particular, the zillions of references to String/Object).
3936 * Unfortunately we're still stuck grabbing a mutex to do the lookup.
3938 * For this to work, the superclass/interface should be the first
3939 * argument, so that way if it's from the bootstrap loader this test
3940 * will work. (The bootstrap loader, by definition, never shows up
3941 * as the initiating loader of a class defined by some other loader.)
3943 dvmHashTableLock(gDvm.loadedClasses);
3944 bool isInit = dvmLoaderInInitiatingList(result1, clazz2->classLoader);
3945 dvmHashTableUnlock(gDvm.loadedClasses);
3948 //printf("%s(obj=%p) / %s(cl=%p): initiating\n",
3949 // result1->descriptor, result1,
3950 // clazz2->descriptor, clazz2->classLoader);
3953 //printf("%s(obj=%p) / %s(cl=%p): RAW\n",
3954 // result1->descriptor, result1,
3955 // clazz2->descriptor, clazz2->classLoader);
3956 result2 = dvmFindClassNoInit(descriptor, clazz2->classLoader);
3959 if (result1 == NULL || result2 == NULL) {
3960 dvmClearException(dvmThreadSelf());
3961 if (result1 == result2) {
3963 * Neither class loader could find this class. Apparently it
3966 * We can either throw some sort of exception now, or just
3967 * assume that it'll fail later when something actually tries
3968 * to use the class. For strict handling we should throw now,
3969 * because a "tricky" class loader could start returning
3970 * something later, and a pair of "tricky" loaders could set
3971 * us up for confusion.
3973 * I'm not sure if we're allowed to complain about nonexistent
3974 * classes in method signatures during class init, so for now
3975 * this will just return "true" and let nature take its course.
3979 /* only one was found, so clearly they're not the same */
3984 return result1 == result2;
3988 * For every component in the method descriptor, resolve the class in the
3989 * context of the two classes and compare the results.
3991 * For best results, the "superclass" class should be first.
3993 * Returns "true" if the classes match, "false" otherwise.
3995 static bool checkMethodDescriptorClasses(const Method* meth,
3996 const ClassObject* clazz1, const ClassObject* clazz2)
3998 DexParameterIterator iterator;
3999 const char* descriptor;
4001 /* walk through the list of parameters */
4002 dexParameterIteratorInit(&iterator, &meth->prototype);
4004 descriptor = dexParameterIteratorNextDescriptor(&iterator);
4006 if (descriptor == NULL)
4009 if (descriptor[0] == 'L' || descriptor[0] == '[') {
4010 /* non-primitive type */
4011 if (!compareDescriptorClasses(descriptor, clazz1, clazz2))
4016 /* check the return type */
4017 descriptor = dexProtoGetReturnType(&meth->prototype);
4018 if (descriptor[0] == 'L' || descriptor[0] == '[') {
4019 if (!compareDescriptorClasses(descriptor, clazz1, clazz2))
4026 * Validate the descriptors in the superclass and interfaces.
4028 * What we need to do is ensure that the classes named in the method
4029 * descriptors in our ancestors and ourselves resolve to the same class
4030 * objects. We can get conflicts when the classes come from different
4031 * class loaders, and the resolver comes up with different results for
4032 * the same class name in different contexts.
4034 * An easy way to cause the problem is to declare a base class that uses
4035 * class Foo in a method signature (e.g. as the return type). Then,
4036 * define a subclass and a different version of Foo, and load them from a
4037 * different class loader. If the subclass overrides the method, it will
4038 * have a different concept of what Foo is than its parent does, so even
4039 * though the method signature strings are identical, they actually mean
4042 * A call to the method through a base-class reference would be treated
4043 * differently than a call to the method through a subclass reference, which
4044 * isn't the way polymorphism works, so we have to reject the subclass.
4045 * If the subclass doesn't override the base method, then there's no
4046 * problem, because calls through base-class references and subclass
4047 * references end up in the same place.
4049 * We don't need to check to see if an interface's methods match with its
4050 * superinterface's methods, because you can't instantiate an interface
4051 * and do something inappropriate with it. If interface I1 extends I2
4052 * and is implemented by C, and I1 and I2 are in separate class loaders
4053 * and have conflicting views of other classes, we will catch the conflict
4054 * when we process C. Anything that implements I1 is doomed to failure,
4055 * but we don't need to catch that while processing I1.
4057 * On failure, throws an exception and returns "false".
4059 static bool validateSuperDescriptors(const ClassObject* clazz)
4063 if (dvmIsInterfaceClass(clazz))
4067 * Start with the superclass-declared methods.
4069 if (clazz->super != NULL &&
4070 clazz->classLoader != clazz->super->classLoader)
4073 * Walk through every overridden method and compare resolved
4074 * descriptor components. We pull the Method structs out of
4075 * the vtable. It doesn't matter whether we get the struct from
4076 * the parent or child, since we just need the UTF-8 descriptor,
4079 * We need to do this even for the stuff inherited from Object,
4080 * because it's possible that the new class loader has redefined
4081 * a basic class like String.
4083 * We don't need to check stuff defined in a superclass because
4084 * it was checked when the superclass was loaded.
4088 //printf("Checking %s %p vs %s %p\n",
4089 // clazz->descriptor, clazz->classLoader,
4090 // clazz->super->descriptor, clazz->super->classLoader);
4091 for (i = clazz->super->vtableCount - 1; i >= 0; i--) {
4092 meth = clazz->vtable[i];
4093 if (meth != clazz->super->vtable[i] &&
4094 !checkMethodDescriptorClasses(meth, clazz->super, clazz))
4096 ALOGW("Method mismatch: %s in %s (cl=%p) and super %s (cl=%p)",
4097 meth->name, clazz->descriptor, clazz->classLoader,
4098 clazz->super->descriptor, clazz->super->classLoader);
4099 dvmThrowLinkageError(
4100 "Classes resolve differently in superclass");
4107 * Check the methods defined by this class against the interfaces it
4108 * implements. If we inherited the implementation from a superclass,
4109 * we have to check it against the superclass (which might be in a
4110 * different class loader). If the superclass also implements the
4111 * interface, we could skip the check since by definition it was
4112 * performed when the class was loaded.
4114 for (i = 0; i < clazz->iftableCount; i++) {
4115 const InterfaceEntry* iftable = &clazz->iftable[i];
4117 if (clazz->classLoader != iftable->clazz->classLoader) {
4118 const ClassObject* iface = iftable->clazz;
4121 for (j = 0; j < iface->virtualMethodCount; j++) {
4125 vtableIndex = iftable->methodIndexArray[j];
4126 meth = clazz->vtable[vtableIndex];
4128 if (!checkMethodDescriptorClasses(meth, iface, meth->clazz)) {
4129 ALOGW("Method mismatch: %s in %s (cl=%p) and "
4131 meth->name, clazz->descriptor, clazz->classLoader,
4132 iface->descriptor, iface->classLoader);
4133 dvmThrowLinkageError(
4134 "Classes resolve differently in interface");
4145 * Returns true if the class is being initialized by us (which means that
4146 * calling dvmInitClass will return immediately after fiddling with locks).
4147 * Returns false if it's not being initialized, or if it's being
4148 * initialized by another thread.
4150 * The value for initThreadId is always set to "self->threadId", by the
4151 * thread doing the initializing. If it was done by the current thread,
4152 * we are guaranteed to see "initializing" and our thread ID, even on SMP.
4153 * If it was done by another thread, the only bad situation is one in
4154 * which we see "initializing" and a stale copy of our own thread ID
4155 * while another thread is actually handling init.
4157 * The initThreadId field is used during class linking, so it *is*
4158 * possible to have a stale value floating around. We need to ensure
4159 * that memory accesses happen in the correct order.
4161 bool dvmIsClassInitializing(const ClassObject* clazz)
4163 const int32_t* addr = (const int32_t*)(const void*)&clazz->status;
4164 int32_t value = android_atomic_acquire_load(addr);
4165 ClassStatus status = static_cast<ClassStatus>(value);
4166 return (status == CLASS_INITIALIZING &&
4167 clazz->initThreadId == dvmThreadSelf()->threadId);
4171 * If a class has not been initialized, do so by executing the code in
4172 * <clinit>. The sequence is described in the VM spec v2 2.17.5.
4174 * It is possible for multiple threads to arrive here simultaneously, so
4175 * we need to lock the class while we check stuff. We know that no
4176 * interpreted code has access to the class yet, so we can use the class's
4179 * We will often be called recursively, e.g. when the <clinit> code resolves
4180 * one of its fields, the field resolution will try to initialize the class.
4181 * In that case we will return "true" even though the class isn't actually
4182 * ready to go. The ambiguity can be resolved with dvmIsClassInitializing().
4183 * (TODO: consider having this return an enum to avoid the extra call --
4184 * return -1 on failure, 0 on success, 1 on still-initializing. Looks like
4185 * dvmIsClassInitializing() is always paired with *Initialized())
4187 * This can get very interesting if a class has a static field initialized
4188 * to a new instance of itself. <clinit> will end up calling <init> on
4189 * the members it is initializing, which is fine unless it uses the contents
4190 * of static fields to initialize instance fields. This will leave the
4191 * static-referenced objects in a partially initialized state. This is
4192 * reasonably rare and can sometimes be cured with proper field ordering.
4194 * On failure, returns "false" with an exception raised.
4198 * It is possible to cause a deadlock by having a situation like this:
4199 * class A { static { sleep(10000); new B(); } }
4200 * class B { static { sleep(10000); new A(); } }
4201 * new Thread() { public void run() { new A(); } }.start();
4202 * new Thread() { public void run() { new B(); } }.start();
4203 * This appears to be expected under the spec.
4205 * The interesting question is what to do if somebody calls Thread.interrupt()
4206 * on one of the deadlocked threads. According to the VM spec, they're both
4207 * sitting in "wait". Should the interrupt code quietly raise the
4208 * "interrupted" flag, or should the "wait" return immediately with an
4211 * This gets a little murky. The VM spec says we call "wait", and the
4212 * spec for Thread.interrupt says Object.wait is interruptible. So it
4213 * seems that, if we get unlucky and interrupt class initialization, we
4214 * are expected to throw (which gets converted to ExceptionInInitializerError
4215 * since InterruptedException is checked).
4217 * There are a couple of problems here. First, all threads are expected to
4218 * present a consistent view of class initialization, so we can't have it
4219 * fail in one thread and succeed in another. Second, once a class fails
4220 * to initialize, it must *always* fail. This means that a stray interrupt()
4221 * call could render a class unusable for the lifetime of the VM.
4223 * In most cases -- the deadlock example above being a counter-example --
4224 * the interrupting thread can't tell whether the target thread handled
4225 * the initialization itself or had to wait while another thread did the
4226 * work. Refusing to interrupt class initialization is, in most cases,
4227 * not something that a program can reliably detect.
4229 * On the assumption that interrupting class initialization is highly
4230 * undesirable in most circumstances, and that failing to do so does not
4231 * deviate from the spec in a meaningful way, we don't allow class init
4232 * to be interrupted by Thread.interrupt().
4234 bool dvmInitClass(ClassObject* clazz)
4238 #if LOG_CLASS_LOADING
4239 bool initializedByUs = false;
4242 Thread* self = dvmThreadSelf();
4243 const Method* method;
4245 dvmLockObject(self, (Object*) clazz);
4246 assert(dvmIsClassLinked(clazz) || clazz->status == CLASS_ERROR);
4249 * If the class hasn't been verified yet, do so now.
4251 if (clazz->status < CLASS_VERIFIED) {
4253 * If we're in an "erroneous" state, throw an exception and bail.
4255 if (clazz->status == CLASS_ERROR) {
4256 throwEarlierClassFailure(clazz);
4260 assert(clazz->status == CLASS_RESOLVED);
4261 assert(!IS_CLASS_FLAG_SET(clazz, CLASS_ISPREVERIFIED));
4263 if (gDvm.classVerifyMode == VERIFY_MODE_NONE ||
4264 (gDvm.classVerifyMode == VERIFY_MODE_REMOTE &&
4265 clazz->classLoader == NULL))
4267 /* advance to "verified" state */
4268 ALOGV("+++ not verifying class %s (cl=%p)",
4269 clazz->descriptor, clazz->classLoader);
4270 clazz->status = CLASS_VERIFIED;
4274 if (!gDvm.optimizing)
4275 ALOGV("+++ late verify on %s", clazz->descriptor);
4278 * We're not supposed to optimize an unverified class, but during
4279 * development this mode was useful. We can't verify an optimized
4280 * class because the optimization process discards information.
4282 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISOPTIMIZED)) {
4283 ALOGW("Class '%s' was optimized without verification; "
4284 "not verifying now",
4286 ALOGW(" ('rm /data/dalvik-cache/*' and restart to fix this)");
4290 clazz->status = CLASS_VERIFYING;
4291 if (!dvmVerifyClass(clazz)) {
4293 dvmThrowVerifyError(clazz->descriptor);
4294 dvmSetFieldObject((Object*) clazz,
4295 OFFSETOF_MEMBER(ClassObject, verifyErrorClass),
4296 (Object*) dvmGetException(self)->clazz);
4297 clazz->status = CLASS_ERROR;
4301 clazz->status = CLASS_VERIFIED;
4306 * We need to ensure that certain instructions, notably accesses to
4307 * volatile fields, are replaced before any code is executed. This
4308 * must happen even if DEX optimizations are disabled.
4310 * The only exception to this rule is that we don't want to do this
4311 * during dexopt. We don't generally initialize classes at all
4312 * during dexopt, but because we're loading classes we need Class and
4313 * Object (and possibly some Throwable stuff if a class isn't found).
4314 * If optimizations are disabled, we don't want to output optimized
4315 * instructions at this time. This means we will be executing <clinit>
4316 * code with un-fixed volatiles, but we're only doing it for a few
4317 * system classes, and dexopt runs single-threaded.
4319 if (!IS_CLASS_FLAG_SET(clazz, CLASS_ISOPTIMIZED) && !gDvm.optimizing) {
4320 ALOGV("+++ late optimize on %s (pv=%d)",
4321 clazz->descriptor, IS_CLASS_FLAG_SET(clazz, CLASS_ISPREVERIFIED));
4322 bool essentialOnly = (gDvm.dexOptMode != OPTIMIZE_MODE_FULL);
4323 dvmOptimizeClass(clazz, essentialOnly);
4324 SET_CLASS_FLAG(clazz, CLASS_ISOPTIMIZED);
4327 /* update instruction stream now that verification + optimization is done */
4328 dvmFlushBreakpoints(clazz);
4330 if (clazz->status == CLASS_INITIALIZED)
4333 while (clazz->status == CLASS_INITIALIZING) {
4334 /* we caught somebody else in the act; was it us? */
4335 if (clazz->initThreadId == self->threadId) {
4336 //ALOGV("HEY: found a recursive <clinit>");
4340 if (dvmCheckException(self)) {
4341 ALOGW("GLITCH: exception pending at start of class init");
4346 * Wait for the other thread to finish initialization. We pass
4347 * "false" for the "interruptShouldThrow" arg so it doesn't throw
4348 * an exception on interrupt.
4350 dvmObjectWait(self, (Object*) clazz, 0, 0, false);
4353 * When we wake up, repeat the test for init-in-progress. If there's
4354 * an exception pending (only possible if "interruptShouldThrow"
4355 * was set), bail out.
4357 if (dvmCheckException(self)) {
4358 ALOGI("Class init of '%s' failing with wait() exception",
4361 * TODO: this is bogus, because it means the two threads have a
4362 * different idea of the class status. We need to flag the
4363 * class as bad and ensure that the initializer thread respects
4364 * our notice. If we get lucky and wake up after the class has
4365 * finished initialization but before being woken, we have to
4366 * swallow the exception, perhaps raising thread->interrupted
4367 * to preserve semantics.
4369 * Since we're not currently allowing interrupts, this should
4370 * never happen and we don't need to fix this.
4373 dvmThrowExceptionInInitializerError();
4374 clazz->status = CLASS_ERROR;
4377 if (clazz->status == CLASS_INITIALIZING) {
4378 ALOGI("Waiting again for class init");
4381 assert(clazz->status == CLASS_INITIALIZED ||
4382 clazz->status == CLASS_ERROR);
4383 if (clazz->status == CLASS_ERROR) {
4385 * The caller wants an exception, but it was thrown in a
4386 * different thread. Synthesize one here.
4388 dvmThrowUnsatisfiedLinkError(
4389 "(<clinit> failed, see exception in other thread)");
4394 /* see if we failed previously */
4395 if (clazz->status == CLASS_ERROR) {
4396 // might be wise to unlock before throwing; depends on which class
4397 // it is that we have locked
4398 dvmUnlockObject(self, (Object*) clazz);
4399 throwEarlierClassFailure(clazz);
4403 if (gDvm.allocProf.enabled) {
4404 startWhen = dvmGetRelativeTimeNsec();
4408 * We're ready to go, and have exclusive access to the class.
4410 * Before we start initialization, we need to do one extra bit of
4411 * validation: make sure that the methods declared here match up
4412 * with our superclass and interfaces. We know that the UTF-8
4413 * descriptors match, but classes from different class loaders can
4414 * have the same name.
4416 * We do this now, rather than at load/link time, for the same reason
4417 * that we defer verification.
4419 * It's unfortunate that we need to do this at all, but we risk
4420 * mixing reference types with identical names (see Dalvik test 068).
4422 if (!validateSuperDescriptors(clazz)) {
4423 assert(dvmCheckException(self));
4424 clazz->status = CLASS_ERROR;
4429 * Let's initialize this thing.
4431 * We unlock the object so that other threads can politely sleep on
4432 * our mutex with Object.wait(), instead of hanging or spinning trying
4433 * to grab our mutex.
4435 assert(clazz->status < CLASS_INITIALIZING);
4437 #if LOG_CLASS_LOADING
4438 // We started initializing.
4439 logClassLoad('+', clazz);
4440 initializedByUs = true;
4443 /* order matters here, esp. interaction with dvmIsClassInitializing */
4444 clazz->initThreadId = self->threadId;
4445 android_atomic_release_store(CLASS_INITIALIZING,
4446 (int32_t*)(void*)&clazz->status);
4447 dvmUnlockObject(self, (Object*) clazz);
4449 /* init our superclass */
4450 if (clazz->super != NULL && clazz->super->status != CLASS_INITIALIZED) {
4451 assert(!dvmIsInterfaceClass(clazz));
4452 if (!dvmInitClass(clazz->super)) {
4453 assert(dvmCheckException(self));
4454 clazz->status = CLASS_ERROR;
4455 /* wake up anybody who started waiting while we were unlocked */
4456 dvmLockObject(self, (Object*) clazz);
4461 /* Initialize any static fields whose values are
4462 * stored in the Dex file. This should include all of the
4463 * simple "final static" fields, which are required to
4464 * be initialized first. (vmspec 2 sec 2.17.5 item 8)
4465 * More-complicated final static fields should be set
4466 * at the beginning of <clinit>; all we can do is trust
4467 * that the compiler did the right thing.
4471 /* Execute any static initialization code.
4473 method = dvmFindDirectMethodByDescriptor(clazz, "<clinit>", "()V");
4474 if (method == NULL) {
4475 LOGVV("No <clinit> found for %s", clazz->descriptor);
4477 LOGVV("Invoking %s.<clinit>", clazz->descriptor);
4479 dvmCallMethod(self, method, NULL, &unused);
4482 if (dvmCheckException(self)) {
4484 * We've had an exception thrown during static initialization. We
4485 * need to throw an ExceptionInInitializerError, but we want to
4486 * tuck the original exception into the "cause" field.
4488 ALOGW("Exception %s thrown while initializing %s",
4489 (dvmGetException(self)->clazz)->descriptor, clazz->descriptor);
4490 dvmThrowExceptionInInitializerError();
4491 //ALOGW("+++ replaced");
4493 dvmLockObject(self, (Object*) clazz);
4494 clazz->status = CLASS_ERROR;
4497 dvmLockObject(self, (Object*) clazz);
4498 clazz->status = CLASS_INITIALIZED;
4499 LOGVV("Initialized class: %s", clazz->descriptor);
4502 * Update alloc counters. TODO: guard with mutex.
4504 if (gDvm.allocProf.enabled && startWhen != 0) {
4505 u8 initDuration = dvmGetRelativeTimeNsec() - startWhen;
4506 gDvm.allocProf.classInitTime += initDuration;
4507 self->allocProf.classInitTime += initDuration;
4508 gDvm.allocProf.classInitCount++;
4509 self->allocProf.classInitCount++;
4515 * Notify anybody waiting on the object.
4517 dvmObjectNotifyAll(self, (Object*) clazz);
4521 #if LOG_CLASS_LOADING
4522 if (initializedByUs) {
4523 // We finished initializing.
4524 logClassLoad('-', clazz);
4528 dvmUnlockObject(self, (Object*) clazz);
4530 return (clazz->status != CLASS_ERROR);
4534 * Replace method->nativeFunc and method->insns with new values. This is
4535 * commonly performed after successful resolution of a native method.
4537 * There are three basic states:
4538 * (1) (initial) nativeFunc = dvmResolveNativeMethod, insns = NULL
4539 * (2) (internal native) nativeFunc = <impl>, insns = NULL
4540 * (3) (JNI) nativeFunc = JNI call bridge, insns = <impl>
4542 * nativeFunc must never be NULL for a native method.
4544 * The most common transitions are (1)->(2) and (1)->(3). The former is
4545 * atomic, since only one field is updated; the latter is not, but since
4546 * dvmResolveNativeMethod ignores the "insns" field we just need to make
4547 * sure the update happens in the correct order.
4549 * A transition from (2)->(1) would work fine, but (3)->(1) will not,
4550 * because both fields change. If we did this while a thread was executing
4551 * in the call bridge, we could null out the "insns" field right before
4552 * the bridge tried to call through it. So, once "insns" is set, we do
4553 * not allow it to be cleared. A NULL value for the "insns" argument is
4554 * treated as "do not change existing value".
4556 void dvmSetNativeFunc(Method* method, DalvikBridgeFunc func,
4559 ClassObject* clazz = method->clazz;
4561 assert(func != NULL);
4563 /* just open up both; easier that way */
4564 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
4565 dvmLinearReadWrite(clazz->classLoader, clazz->directMethods);
4567 if (insns != NULL) {
4568 /* update both, ensuring that "insns" is observed first */
4569 method->insns = insns;
4570 android_atomic_release_store((int32_t) func,
4571 (volatile int32_t*)(void*) &method->nativeFunc);
4573 /* only update nativeFunc */
4574 method->nativeFunc = func;
4577 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
4578 dvmLinearReadOnly(clazz->classLoader, clazz->directMethods);
4582 * Add a RegisterMap to a Method. This is done when we verify the class
4583 * and compute the register maps at class initialization time (i.e. when
4584 * we don't have a pre-generated map). This means "pMap" is on the heap
4585 * and should be freed when the Method is discarded.
4587 void dvmSetRegisterMap(Method* method, const RegisterMap* pMap)
4589 ClassObject* clazz = method->clazz;
4591 if (method->registerMap != NULL) {
4592 /* unexpected during class loading, okay on first use (uncompress) */
4593 ALOGV("NOTE: registerMap already set for %s.%s",
4594 method->clazz->descriptor, method->name);
4597 assert(!dvmIsNativeMethod(method) && !dvmIsAbstractMethod(method));
4599 /* might be virtual or direct */
4600 dvmLinearReadWrite(clazz->classLoader, clazz->virtualMethods);
4601 dvmLinearReadWrite(clazz->classLoader, clazz->directMethods);
4603 method->registerMap = pMap;
4605 dvmLinearReadOnly(clazz->classLoader, clazz->virtualMethods);
4606 dvmLinearReadOnly(clazz->classLoader, clazz->directMethods);
4610 * dvmHashForeach callback. A nonzero return value causes foreach to
4613 static int findClassCallback(void* vclazz, void* arg)
4615 ClassObject* clazz = (ClassObject*)vclazz;
4616 const char* descriptor = (const char*) arg;
4618 if (strcmp(clazz->descriptor, descriptor) == 0)
4624 * Find a loaded class by descriptor. Returns the first one found.
4625 * Because there can be more than one if class loaders are involved,
4626 * this is not an especially good API. (Currently only used by the
4627 * debugger and "checking" JNI.)
4629 * "descriptor" should have the form "Ljava/lang/Class;" or
4630 * "[Ljava/lang/Class;", i.e. a descriptor and not an internal-form
4633 ClassObject* dvmFindLoadedClass(const char* descriptor)
4637 dvmHashTableLock(gDvm.loadedClasses);
4638 result = dvmHashForeach(gDvm.loadedClasses, findClassCallback,
4639 (void*) descriptor);
4640 dvmHashTableUnlock(gDvm.loadedClasses);
4642 return (ClassObject*) result;
4646 * Retrieve the system (a/k/a application) class loader.
4648 * The caller must call dvmReleaseTrackedAlloc on the result.
4650 Object* dvmGetSystemClassLoader()
4652 Thread* self = dvmThreadSelf();
4653 ClassObject* clClass = gDvm.classJavaLangClassLoader;
4655 if (!dvmIsClassInitialized(clClass) && !dvmInitClass(clClass))
4659 dvmCallMethod(self, gDvm.methJavaLangClassLoader_getSystemClassLoader,
4661 Object* loader = (Object*)result.l;
4662 dvmAddTrackedAlloc(loader, self);
4668 * This is a dvmHashForeach callback.
4670 static int dumpClass(void* vclazz, void* varg)
4672 const ClassObject* clazz = (const ClassObject*) vclazz;
4673 const ClassObject* super;
4674 int flags = (int) varg;
4678 if (clazz == NULL) {
4679 ALOGI("dumpClass: ignoring request to dump null class");
4683 if ((flags & kDumpClassFullDetail) == 0) {
4684 bool showInit = (flags & kDumpClassInitialized) != 0;
4685 bool showLoader = (flags & kDumpClassClassLoader) != 0;
4686 const char* initStr;
4688 initStr = dvmIsClassInitialized(clazz) ? "true" : "false";
4690 if (showInit && showLoader)
4691 ALOGI("%s %p %s", clazz->descriptor, clazz->classLoader, initStr);
4693 ALOGI("%s %s", clazz->descriptor, initStr);
4694 else if (showLoader)
4695 ALOGI("%s %p", clazz->descriptor, clazz->classLoader);
4697 ALOGI("%s", clazz->descriptor);
4702 /* clazz->super briefly holds the superclass index during class prep */
4703 if ((u4)clazz->super > 0x10000 && (u4) clazz->super != (u4)-1)
4704 super = clazz->super;
4708 ALOGI("----- %s '%s' cl=%p ser=0x%08x -----",
4709 dvmIsInterfaceClass(clazz) ? "interface" : "class",
4710 clazz->descriptor, clazz->classLoader, clazz->serialNumber);
4711 ALOGI(" objectSize=%d (%d from super)", (int) clazz->objectSize,
4712 super != NULL ? (int) super->objectSize : -1);
4713 ALOGI(" access=0x%04x.%04x", clazz->accessFlags >> 16,
4714 clazz->accessFlags & JAVA_FLAGS_MASK);
4716 ALOGI(" super='%s' (cl=%p)", super->descriptor, super->classLoader);
4717 if (dvmIsArrayClass(clazz)) {
4718 ALOGI(" dimensions=%d elementClass=%s",
4719 clazz->arrayDim, clazz->elementClass->descriptor);
4721 if (clazz->iftableCount > 0) {
4722 ALOGI(" interfaces (%d):", clazz->iftableCount);
4723 for (i = 0; i < clazz->iftableCount; i++) {
4724 InterfaceEntry* ent = &clazz->iftable[i];
4727 ALOGI(" %2d: %s (cl=%p)",
4728 i, ent->clazz->descriptor, ent->clazz->classLoader);
4730 /* enable when needed */
4731 if (false && ent->methodIndexArray != NULL) {
4732 for (j = 0; j < ent->clazz->virtualMethodCount; j++)
4733 ALOGI(" %2d: %d %s %s",
4734 j, ent->methodIndexArray[j],
4735 ent->clazz->virtualMethods[j].name,
4736 clazz->vtable[ent->methodIndexArray[j]]->name);
4740 if (!dvmIsInterfaceClass(clazz)) {
4741 ALOGI(" vtable (%d entries, %d in super):", clazz->vtableCount,
4742 super != NULL ? super->vtableCount : 0);
4743 for (i = 0; i < clazz->vtableCount; i++) {
4744 desc = dexProtoCopyMethodDescriptor(&clazz->vtable[i]->prototype);
4745 ALOGI(" %s%2d: %p %20s %s",
4746 (i != clazz->vtable[i]->methodIndex) ? "*** " : "",
4747 (u4) clazz->vtable[i]->methodIndex, clazz->vtable[i],
4748 clazz->vtable[i]->name, desc);
4751 ALOGI(" direct methods (%d entries):", clazz->directMethodCount);
4752 for (i = 0; i < clazz->directMethodCount; i++) {
4753 desc = dexProtoCopyMethodDescriptor(
4754 &clazz->directMethods[i].prototype);
4755 ALOGI(" %2d: %20s %s", i, clazz->directMethods[i].name,
4760 ALOGI(" interface methods (%d):", clazz->virtualMethodCount);
4761 for (i = 0; i < clazz->virtualMethodCount; i++) {
4762 desc = dexProtoCopyMethodDescriptor(
4763 &clazz->virtualMethods[i].prototype);
4764 ALOGI(" %2d: %2d %20s %s", i,
4765 (u4) clazz->virtualMethods[i].methodIndex,
4766 clazz->virtualMethods[i].name,
4771 if (clazz->sfieldCount > 0) {
4772 ALOGI(" static fields (%d entries):", clazz->sfieldCount);
4773 for (i = 0; i < clazz->sfieldCount; i++) {
4774 ALOGI(" %2d: %20s %s", i, clazz->sfields[i].name,
4775 clazz->sfields[i].signature);
4778 if (clazz->ifieldCount > 0) {
4779 ALOGI(" instance fields (%d entries):", clazz->ifieldCount);
4780 for (i = 0; i < clazz->ifieldCount; i++) {
4781 ALOGI(" %2d: %20s %s", i, clazz->ifields[i].name,
4782 clazz->ifields[i].signature);
4789 * Dump the contents of a single class.
4791 * Pass kDumpClassFullDetail into "flags" to get lots of detail.
4793 void dvmDumpClass(const ClassObject* clazz, int flags)
4795 dumpClass((void*) clazz, (void*) flags);
4799 * Dump the contents of all classes.
4801 void dvmDumpAllClasses(int flags)
4803 dvmHashTableLock(gDvm.loadedClasses);
4804 dvmHashForeach(gDvm.loadedClasses, dumpClass, (void*) flags);
4805 dvmHashTableUnlock(gDvm.loadedClasses);
4809 * Get the number of loaded classes
4811 int dvmGetNumLoadedClasses()
4814 dvmHashTableLock(gDvm.loadedClasses);
4815 count = dvmHashTableNumEntries(gDvm.loadedClasses);
4816 dvmHashTableUnlock(gDvm.loadedClasses);
4821 * Write some statistics to the log file.
4823 void dvmDumpLoaderStats(const char* msg)
4825 ALOGV("VM stats (%s): cls=%d/%d meth=%d ifld=%d sfld=%d linear=%d",
4826 msg, gDvm.numLoadedClasses, dvmHashTableNumEntries(gDvm.loadedClasses),
4827 gDvm.numDeclaredMethods, gDvm.numDeclaredInstFields,
4828 gDvm.numDeclaredStaticFields, gDvm.pBootLoaderAlloc->curOffset);
4829 #ifdef COUNT_PRECISE_METHODS
4830 ALOGI("GC precise methods: %d",
4831 dvmPointerSetGetCount(gDvm.preciseMethods));
4836 * ===========================================================================
4837 * Method Prototypes and Descriptors
4838 * ===========================================================================
4842 * Compare the two method names and prototypes, a la strcmp(). The
4843 * name is considered the "major" order and the prototype the "minor"
4844 * order. The prototypes are compared as if by dvmCompareMethodProtos().
4846 int dvmCompareMethodNamesAndProtos(const Method* method1,
4847 const Method* method2)
4849 int result = strcmp(method1->name, method2->name);
4855 return dvmCompareMethodProtos(method1, method2);
4859 * Compare the two method names and prototypes, a la strcmp(), ignoring
4860 * the return value. The name is considered the "major" order and the
4861 * prototype the "minor" order. The prototypes are compared as if by
4862 * dvmCompareMethodArgProtos().
4864 int dvmCompareMethodNamesAndParameterProtos(const Method* method1,
4865 const Method* method2)
4867 int result = strcmp(method1->name, method2->name);
4873 return dvmCompareMethodParameterProtos(method1, method2);
4877 * Compare a (name, prototype) pair with the (name, prototype) of
4878 * a method, a la strcmp(). The name is considered the "major" order and
4879 * the prototype the "minor" order. The descriptor and prototype are
4880 * compared as if by dvmCompareDescriptorAndMethodProto().
4882 int dvmCompareNameProtoAndMethod(const char* name,
4883 const DexProto* proto, const Method* method)
4885 int result = strcmp(name, method->name);
4891 return dexProtoCompare(proto, &method->prototype);
4895 * Compare a (name, method descriptor) pair with the (name, prototype) of
4896 * a method, a la strcmp(). The name is considered the "major" order and
4897 * the prototype the "minor" order. The descriptor and prototype are
4898 * compared as if by dvmCompareDescriptorAndMethodProto().
4900 int dvmCompareNameDescriptorAndMethod(const char* name,
4901 const char* descriptor, const Method* method)
4903 int result = strcmp(name, method->name);
4909 return dvmCompareDescriptorAndMethodProto(descriptor, method);