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