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