Home | History | Annotate | Download | only in oo
      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  * Resolve classes, methods, fields, and strings.
     19  *
     20  * According to the VM spec (v2 5.5), classes may be initialized by use
     21  * of the "new", "getstatic", "putstatic", or "invokestatic" instructions.
     22  * If we are resolving a static method or static field, we make the
     23  * initialization check here.
     24  *
     25  * (NOTE: the verifier has its own resolve functions, which can be invoked
     26  * if a class isn't pre-verified.  Those functions must not update the
     27  * "resolved stuff" tables for static fields and methods, because they do
     28  * not perform initialization.)
     29  */
     30 #include "Dalvik.h"
     31 
     32 #include <stdlib.h>
     33 
     34 
     35 /*
     36  * Find the class corresponding to "classIdx", which maps to a class name
     37  * string.  It might be in the same DEX file as "referrer", in a different
     38  * DEX file, generated by a class loader, or generated by the VM (e.g.
     39  * array classes).
     40  *
     41  * Because the DexTypeId is associated with the referring class' DEX file,
     42  * we may have to resolve the same class more than once if it's referred
     43  * to from classes in multiple DEX files.  This is a necessary property for
     44  * DEX files associated with different class loaders.
     45  *
     46  * We cache a copy of the lookup in the DexFile's "resolved class" table,
     47  * so future references to "classIdx" are faster.
     48  *
     49  * Note that "referrer" may be in the process of being linked.
     50  *
     51  * Traditional VMs might do access checks here, but in Dalvik the class
     52  * "constant pool" is shared between all classes in the DEX file.  We rely
     53  * on the verifier to do the checks for us.
     54  *
     55  * Does not initialize the class.
     56  *
     57  * "fromUnverifiedConstant" should only be set if this call is the direct
     58  * result of executing a "const-class" or "instance-of" instruction, which
     59  * use class constants not resolved by the bytecode verifier.
     60  *
     61  * Returns NULL with an exception raised on failure.
     62  */
     63 ClassObject* dvmResolveClass(const ClassObject* referrer, u4 classIdx,
     64     bool fromUnverifiedConstant)
     65 {
     66     DvmDex* pDvmDex = referrer->pDvmDex;
     67     ClassObject* resClass;
     68     const char* className;
     69 
     70     /*
     71      * Check the table first -- this gets called from the other "resolve"
     72      * methods.
     73      */
     74     resClass = dvmDexGetResolvedClass(pDvmDex, classIdx);
     75     if (resClass != NULL)
     76         return resClass;
     77 
     78     LOGVV("--- resolving class %u (referrer=%s cl=%p)",
     79         classIdx, referrer->descriptor, referrer->classLoader);
     80 
     81     /*
     82      * Class hasn't been loaded yet, or is in the process of being loaded
     83      * and initialized now.  Try to get a copy.  If we find one, put the
     84      * pointer in the DexTypeId.  There isn't a race condition here --
     85      * 32-bit writes are guaranteed atomic on all target platforms.  Worst
     86      * case we have two threads storing the same value.
     87      *
     88      * If this is an array class, we'll generate it here.
     89      */
     90     className = dexStringByTypeIdx(pDvmDex->pDexFile, classIdx);
     91     if (className[0] != '\0' && className[1] == '\0') {
     92         /* primitive type */
     93         resClass = dvmFindPrimitiveClass(className[0]);
     94     } else {
     95         resClass = dvmFindClassNoInit(className, referrer->classLoader);
     96     }
     97 
     98     if (resClass != NULL) {
     99         /*
    100          * If the referrer was pre-verified, the resolved class must come
    101          * from the same DEX or from a bootstrap class.  The pre-verifier
    102          * makes assumptions that could be invalidated by a wacky class
    103          * loader.  (See the notes at the top of oo/Class.c.)
    104          *
    105          * The verifier does *not* fail a class for using a const-class
    106          * or instance-of instruction referring to an unresolveable class,
    107          * because the result of the instruction is simply a Class object
    108          * or boolean -- there's no need to resolve the class object during
    109          * verification.  Instance field and virtual method accesses can
    110          * break dangerously if we get the wrong class, but const-class and
    111          * instance-of are only interesting at execution time.  So, if we
    112          * we got here as part of executing one of the "unverified class"
    113          * instructions, we skip the additional check.
    114          *
    115          * Ditto for class references from annotations and exception
    116          * handler lists.
    117          */
    118         if (!fromUnverifiedConstant &&
    119             IS_CLASS_FLAG_SET(referrer, CLASS_ISPREVERIFIED))
    120         {
    121             ClassObject* resClassCheck = resClass;
    122             if (dvmIsArrayClass(resClassCheck))
    123                 resClassCheck = resClassCheck->elementClass;
    124 
    125             if (referrer->pDvmDex != resClassCheck->pDvmDex &&
    126                 resClassCheck->classLoader != NULL)
    127             {
    128                 ALOGW("Class resolved by unexpected DEX:"
    129                      " %s(%p):%p ref [%s] %s(%p):%p",
    130                     referrer->descriptor, referrer->classLoader,
    131                     referrer->pDvmDex,
    132                     resClass->descriptor, resClassCheck->descriptor,
    133                     resClassCheck->classLoader, resClassCheck->pDvmDex);
    134                 ALOGW("(%s had used a different %s during pre-verification)",
    135                     referrer->descriptor, resClass->descriptor);
    136                 dvmThrowIllegalAccessError(
    137                     "Class ref in pre-verified class resolved to unexpected "
    138                     "implementation");
    139                 return NULL;
    140             }
    141         }
    142 
    143         LOGVV("##### +ResolveClass(%s): referrer=%s dex=%p ldr=%p ref=%d",
    144             resClass->descriptor, referrer->descriptor, referrer->pDvmDex,
    145             referrer->classLoader, classIdx);
    146 
    147         /*
    148          * Add what we found to the list so we can skip the class search
    149          * next time through.
    150          *
    151          * TODO: should we be doing this when fromUnverifiedConstant==true?
    152          * (see comments at top of oo/Class.c)
    153          */
    154         dvmDexSetResolvedClass(pDvmDex, classIdx, resClass);
    155     } else {
    156         /* not found, exception should be raised */
    157         LOGVV("Class not found: %s",
    158             dexStringByTypeIdx(pDvmDex->pDexFile, classIdx));
    159         assert(dvmCheckException(dvmThreadSelf()));
    160     }
    161 
    162     return resClass;
    163 }
    164 
    165 
    166 /*
    167  * Find the method corresponding to "methodRef".
    168  *
    169  * We use "referrer" to find the DexFile with the constant pool that
    170  * "methodRef" is an index into.  We also use its class loader.  The method
    171  * being resolved may very well be in a different DEX file.
    172  *
    173  * If this is a static method, we ensure that the method's class is
    174  * initialized.
    175  */
    176 Method* dvmResolveMethod(const ClassObject* referrer, u4 methodIdx,
    177     MethodType methodType)
    178 {
    179     DvmDex* pDvmDex = referrer->pDvmDex;
    180     ClassObject* resClass;
    181     const DexMethodId* pMethodId;
    182     Method* resMethod;
    183 
    184     assert(methodType != METHOD_INTERFACE);
    185 
    186     LOGVV("--- resolving method %u (referrer=%s)", methodIdx,
    187         referrer->descriptor);
    188     pMethodId = dexGetMethodId(pDvmDex->pDexFile, methodIdx);
    189 
    190     resClass = dvmResolveClass(referrer, pMethodId->classIdx, false);
    191     if (resClass == NULL) {
    192         /* can't find the class that the method is a part of */
    193         assert(dvmCheckException(dvmThreadSelf()));
    194         return NULL;
    195     }
    196     if (dvmIsInterfaceClass(resClass)) {
    197         /* method is part of an interface */
    198         dvmThrowIncompatibleClassChangeErrorWithClassMessage(
    199                 resClass->descriptor);
    200         return NULL;
    201     }
    202 
    203     const char* name = dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx);
    204     DexProto proto;
    205     dexProtoSetFromMethodId(&proto, pDvmDex->pDexFile, pMethodId);
    206 
    207     /*
    208      * We need to chase up the class hierarchy to find methods defined
    209      * in super-classes.  (We only want to check the current class
    210      * if we're looking for a constructor; since DIRECT calls are only
    211      * for constructors and private methods, we don't want to walk up.)
    212      */
    213     if (methodType == METHOD_DIRECT) {
    214         resMethod = dvmFindDirectMethod(resClass, name, &proto);
    215     } else if (methodType == METHOD_STATIC) {
    216         resMethod = dvmFindDirectMethodHier(resClass, name, &proto);
    217     } else {
    218         resMethod = dvmFindVirtualMethodHier(resClass, name, &proto);
    219     }
    220 
    221     if (resMethod == NULL) {
    222         std::string msg;
    223         msg += resClass->descriptor;
    224         msg += ".";
    225         msg += name;
    226         dvmThrowNoSuchMethodError(msg.c_str());
    227         return NULL;
    228     }
    229 
    230     LOGVV("--- found method %d (%s.%s)",
    231         methodIdx, resClass->descriptor, resMethod->name);
    232 
    233     /* see if this is a pure-abstract method */
    234     if (dvmIsAbstractMethod(resMethod) && !dvmIsAbstractClass(resClass)) {
    235         dvmThrowAbstractMethodError(name);
    236         return NULL;
    237     }
    238 
    239     /*
    240      * If we're the first to resolve this class, we need to initialize
    241      * it now.  Only necessary for METHOD_STATIC.
    242      */
    243     if (methodType == METHOD_STATIC) {
    244         if (!dvmIsClassInitialized(resMethod->clazz) &&
    245             !dvmInitClass(resMethod->clazz))
    246         {
    247             assert(dvmCheckException(dvmThreadSelf()));
    248             return NULL;
    249         } else {
    250             assert(!dvmCheckException(dvmThreadSelf()));
    251         }
    252     } else {
    253         /*
    254          * Edge case: if the <clinit> for a class creates an instance
    255          * of itself, we will call <init> on a class that is still being
    256          * initialized by us.
    257          */
    258         assert(dvmIsClassInitialized(resMethod->clazz) ||
    259                dvmIsClassInitializing(resMethod->clazz));
    260     }
    261 
    262     /*
    263      * If the class has been initialized, add a pointer to our data structure
    264      * so we don't have to jump through the hoops again.  If this is a
    265      * static method and the defining class is still initializing (i.e. this
    266      * thread is executing <clinit>), don't do the store, otherwise other
    267      * threads could call the method without waiting for class init to finish.
    268      */
    269     if (methodType == METHOD_STATIC && !dvmIsClassInitialized(resMethod->clazz))
    270     {
    271         LOGVV("--- not caching resolved method %s.%s (class init=%d/%d)",
    272             resMethod->clazz->descriptor, resMethod->name,
    273             dvmIsClassInitializing(resMethod->clazz),
    274             dvmIsClassInitialized(resMethod->clazz));
    275     } else {
    276         dvmDexSetResolvedMethod(pDvmDex, methodIdx, resMethod);
    277     }
    278 
    279     return resMethod;
    280 }
    281 
    282 /*
    283  * Resolve an interface method reference.
    284  *
    285  * Returns NULL with an exception raised on failure.
    286  */
    287 Method* dvmResolveInterfaceMethod(const ClassObject* referrer, u4 methodIdx)
    288 {
    289     DvmDex* pDvmDex = referrer->pDvmDex;
    290     ClassObject* resClass;
    291     const DexMethodId* pMethodId;
    292     Method* resMethod;
    293 
    294     LOGVV("--- resolving interface method %d (referrer=%s)",
    295         methodIdx, referrer->descriptor);
    296     pMethodId = dexGetMethodId(pDvmDex->pDexFile, methodIdx);
    297 
    298     resClass = dvmResolveClass(referrer, pMethodId->classIdx, false);
    299     if (resClass == NULL) {
    300         /* can't find the class that the method is a part of */
    301         assert(dvmCheckException(dvmThreadSelf()));
    302         return NULL;
    303     }
    304     if (!dvmIsInterfaceClass(resClass)) {
    305         /* whoops */
    306         dvmThrowIncompatibleClassChangeErrorWithClassMessage(
    307                 resClass->descriptor);
    308         return NULL;
    309     }
    310 
    311     /*
    312      * This is the first time the method has been resolved.  Set it in our
    313      * resolved-method structure.  It always resolves to the same thing,
    314      * so looking it up and storing it doesn't create a race condition.
    315      *
    316      * If we scan into the interface's superclass -- which is always
    317      * java/lang/Object -- we will catch things like:
    318      *   interface I ...
    319      *   I myobj = (something that implements I)
    320      *   myobj.hashCode()
    321      * However, the Method->methodIndex will be an offset into clazz->vtable,
    322      * rather than an offset into clazz->iftable.  The invoke-interface
    323      * code can test to see if the method returned is abstract or concrete,
    324      * and use methodIndex accordingly.  I'm not doing this yet because
    325      * (a) we waste time in an unusual case, and (b) we're probably going
    326      * to fix it in the DEX optimizer.
    327      *
    328      * We do need to scan the superinterfaces, in case we're invoking a
    329      * superinterface method on an interface reference.  The class in the
    330      * DexTypeId is for the static type of the object, not the class in
    331      * which the method is first defined.  We have the full, flattened
    332      * list in "iftable".
    333      */
    334     const char* methodName =
    335         dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx);
    336 
    337     DexProto proto;
    338     dexProtoSetFromMethodId(&proto, pDvmDex->pDexFile, pMethodId);
    339 
    340     LOGVV("+++ looking for '%s' in resClass='%s'", methodName, resClass->descriptor);
    341     resMethod = dvmFindInterfaceMethodHier(resClass, methodName, &proto);
    342     if (resMethod == NULL) {
    343         std::string msg;
    344         msg += resClass->descriptor;
    345         msg += ".";
    346         msg += methodName;
    347         dvmThrowNoSuchMethodError(msg.c_str());
    348         return NULL;
    349     }
    350 
    351     LOGVV("--- found interface method %d (%s.%s)",
    352         methodIdx, resClass->descriptor, resMethod->name);
    353 
    354     /* we're expecting this to be abstract */
    355     assert(dvmIsAbstractMethod(resMethod));
    356 
    357     /* interface methods are always public; no need to check access */
    358 
    359     /*
    360      * The interface class *may* be initialized.  According to VM spec
    361      * v2 2.17.4, the interfaces a class refers to "need not" be initialized
    362      * when the class is initialized.
    363      *
    364      * It isn't necessary for an interface class to be initialized before
    365      * we resolve methods on that interface.
    366      *
    367      * We choose not to do the initialization now.
    368      */
    369     //assert(dvmIsClassInitialized(resMethod->clazz));
    370 
    371     /*
    372      * Add a pointer to our data structure so we don't have to jump
    373      * through the hoops again.
    374      *
    375      * As noted above, no need to worry about whether the interface that
    376      * defines the method has been or is currently executing <clinit>.
    377      */
    378     dvmDexSetResolvedMethod(pDvmDex, methodIdx, resMethod);
    379 
    380     return resMethod;
    381 }
    382 
    383 /*
    384  * Resolve an instance field reference.
    385  *
    386  * Returns NULL and throws an exception on error (no such field, illegal
    387  * access).
    388  */
    389 InstField* dvmResolveInstField(const ClassObject* referrer, u4 ifieldIdx)
    390 {
    391     DvmDex* pDvmDex = referrer->pDvmDex;
    392     ClassObject* resClass;
    393     const DexFieldId* pFieldId;
    394     InstField* resField;
    395 
    396     LOGVV("--- resolving field %u (referrer=%s cl=%p)",
    397         ifieldIdx, referrer->descriptor, referrer->classLoader);
    398 
    399     pFieldId = dexGetFieldId(pDvmDex->pDexFile, ifieldIdx);
    400 
    401     /*
    402      * Find the field's class.
    403      */
    404     resClass = dvmResolveClass(referrer, pFieldId->classIdx, false);
    405     if (resClass == NULL) {
    406         assert(dvmCheckException(dvmThreadSelf()));
    407         return NULL;
    408     }
    409 
    410     resField = dvmFindInstanceFieldHier(resClass,
    411         dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx),
    412         dexStringByTypeIdx(pDvmDex->pDexFile, pFieldId->typeIdx));
    413     if (resField == NULL) {
    414         dvmThrowNoSuchFieldError(
    415             dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx));
    416         return NULL;
    417     }
    418 
    419     /*
    420      * Class must be initialized by now (unless verifier is buggy).  We
    421      * could still be in the process of initializing it if the field
    422      * access is from a static initializer.
    423      */
    424     assert(dvmIsClassInitialized(resField->clazz) ||
    425            dvmIsClassInitializing(resField->clazz));
    426 
    427     /*
    428      * The class is initialized (or initializing), the field has been
    429      * found.  Add a pointer to our data structure so we don't have to
    430      * jump through the hoops again.
    431      *
    432      * Anything that uses the resolved table entry must have an instance
    433      * of the class, so any class init activity has already happened (or
    434      * been deliberately bypassed when <clinit> created an instance).
    435      * So it's always okay to update the table.
    436      */
    437     dvmDexSetResolvedField(pDvmDex, ifieldIdx, (Field*)resField);
    438     LOGVV("    field %u is %s.%s",
    439         ifieldIdx, resField->clazz->descriptor, resField->name);
    440 
    441     return resField;
    442 }
    443 
    444 /*
    445  * Resolve a static field reference.  The DexFile format doesn't distinguish
    446  * between static and instance field references, so the "resolved" pointer
    447  * in the Dex struct will have the wrong type.  We trivially cast it here.
    448  *
    449  * Causes the field's class to be initialized.
    450  */
    451 StaticField* dvmResolveStaticField(const ClassObject* referrer, u4 sfieldIdx)
    452 {
    453     DvmDex* pDvmDex = referrer->pDvmDex;
    454     ClassObject* resClass;
    455     const DexFieldId* pFieldId;
    456     StaticField* resField;
    457 
    458     pFieldId = dexGetFieldId(pDvmDex->pDexFile, sfieldIdx);
    459 
    460     /*
    461      * Find the field's class.
    462      */
    463     resClass = dvmResolveClass(referrer, pFieldId->classIdx, false);
    464     if (resClass == NULL) {
    465         assert(dvmCheckException(dvmThreadSelf()));
    466         return NULL;
    467     }
    468 
    469     resField = dvmFindStaticFieldHier(resClass,
    470                 dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx),
    471                 dexStringByTypeIdx(pDvmDex->pDexFile, pFieldId->typeIdx));
    472     if (resField == NULL) {
    473         dvmThrowNoSuchFieldError(
    474             dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx));
    475         return NULL;
    476     }
    477 
    478     /*
    479      * If we're the first to resolve the field in which this class resides,
    480      * we need to do it now.  Note that, if the field was inherited from
    481      * a superclass, it is not necessarily the same as "resClass".
    482      */
    483     if (!dvmIsClassInitialized(resField->clazz) &&
    484         !dvmInitClass(resField->clazz))
    485     {
    486         assert(dvmCheckException(dvmThreadSelf()));
    487         return NULL;
    488     }
    489 
    490     /*
    491      * If the class has been initialized, add a pointer to our data structure
    492      * so we don't have to jump through the hoops again.  If it's still
    493      * initializing (i.e. this thread is executing <clinit>), don't do
    494      * the store, otherwise other threads could use the field without waiting
    495      * for class init to finish.
    496      */
    497     if (dvmIsClassInitialized(resField->clazz)) {
    498         dvmDexSetResolvedField(pDvmDex, sfieldIdx, (Field*) resField);
    499     } else {
    500         LOGVV("--- not caching resolved field %s.%s (class init=%d/%d)",
    501             resField->clazz->descriptor, resField->name,
    502             dvmIsClassInitializing(resField->clazz),
    503             dvmIsClassInitialized(resField->clazz));
    504     }
    505 
    506     return resField;
    507 }
    508 
    509 
    510 /*
    511  * Resolve a string reference.
    512  *
    513  * Finding the string is easy.  We need to return a reference to a
    514  * java/lang/String object, not a bunch of characters, which means the
    515  * first time we get here we need to create an interned string.
    516  */
    517 StringObject* dvmResolveString(const ClassObject* referrer, u4 stringIdx)
    518 {
    519     DvmDex* pDvmDex = referrer->pDvmDex;
    520     StringObject* strObj;
    521     StringObject* internStrObj;
    522     const char* utf8;
    523     u4 utf16Size;
    524 
    525     LOGVV("+++ resolving string, referrer is %s", referrer->descriptor);
    526 
    527     /*
    528      * Create a UTF-16 version so we can trivially compare it to what's
    529      * already interned.
    530      */
    531     utf8 = dexStringAndSizeById(pDvmDex->pDexFile, stringIdx, &utf16Size);
    532     strObj = dvmCreateStringFromCstrAndLength(utf8, utf16Size);
    533     if (strObj == NULL) {
    534         /* ran out of space in GC heap? */
    535         assert(dvmCheckException(dvmThreadSelf()));
    536         goto bail;
    537     }
    538 
    539     /*
    540      * Add it to the intern list.  The return value is the one in the
    541      * intern list, which (due to race conditions) may or may not be
    542      * the one we just created.  The intern list is synchronized, so
    543      * there will be only one "live" version.
    544      *
    545      * By requesting an immortal interned string, we guarantee that
    546      * the returned object will never be collected by the GC.
    547      *
    548      * A NULL return here indicates some sort of hashing failure.
    549      */
    550     internStrObj = dvmLookupImmortalInternedString(strObj);
    551     dvmReleaseTrackedAlloc((Object*) strObj, NULL);
    552     strObj = internStrObj;
    553     if (strObj == NULL) {
    554         assert(dvmCheckException(dvmThreadSelf()));
    555         goto bail;
    556     }
    557 
    558     /* save a reference so we can go straight to the object next time */
    559     dvmDexSetResolvedString(pDvmDex, stringIdx, strObj);
    560 
    561 bail:
    562     return strObj;
    563 }
    564 
    565 /*
    566  * For debugging: return a string representing the methodType.
    567  */
    568 const char* dvmMethodTypeStr(MethodType methodType)
    569 {
    570     switch (methodType) {
    571     case METHOD_DIRECT:         return "direct";
    572     case METHOD_STATIC:         return "static";
    573     case METHOD_VIRTUAL:        return "virtual";
    574     case METHOD_INTERFACE:      return "interface";
    575     case METHOD_UNKNOWN:        return "UNKNOWN";
    576     }
    577     assert(false);
    578     return "BOGUS";
    579 }
    580