2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Prepare a DEX file for use by the VM. Depending upon the VM options
19 * we will attempt to verify and/or optimize the code, possibly appending
22 * TODO: the format of the optimized header is currently "whatever we
23 * happen to write", since the VM that writes it is by definition the same
24 * as the VM that reads it. Still, it should be better documented and
25 * more rigorously structured.
28 #include "libdex/OptInvocation.h"
29 #include "analysis/RegisterMap.h"
30 #include "analysis/Optimize.h"
45 static bool rewriteDex(u1* addr, int len, u4* pHeaderFlags,
46 DexClassLookup** ppClassLookup);
47 static bool loadAllClasses(DvmDex* pDvmDex);
48 static void verifyAndOptimizeClasses(DexFile* pDexFile, bool doVerify,
50 static void verifyAndOptimizeClass(DexFile* pDexFile, ClassObject* clazz,
51 const DexClassDef* pClassDef, bool doVerify, bool doOpt);
52 static void updateChecksum(u1* addr, int len, DexHeader* pHeader);
53 static int writeDependencies(int fd, u4 modWhen, u4 crc);
54 static bool writeOptData(int fd, const DexClassLookup* pClassLookup,\
55 const RegisterMapBuilder* pRegMapBuilder);
56 static bool computeFileChecksum(int fd, off_t start, size_t length, u4* pSum);
60 * Return the fd of an open file in the DEX file cache area. If the cache
61 * file doesn't exist or is out of date, this will remove the old entry,
62 * create a new one (writing only the file header), and return with the
63 * "new file" flag set.
65 * It's possible to execute from an unoptimized DEX file directly,
66 * assuming the byte ordering and structure alignment is correct, but
67 * disadvantageous because some significant optimizations are not possible.
68 * It's not generally possible to do the same from an uncompressed Jar
69 * file entry, because we have to guarantee 32-bit alignment in the
72 * For a Jar/APK file (a zip archive with "classes.dex" inside), "modWhen"
73 * and "crc32" come from the Zip directory entry. For a stand-alone DEX
74 * file, it's the modification date of the file and the Adler32 from the
75 * DEX header (which immediately follows the magic). If these don't
76 * match what's stored in the opt header, we reject the file immediately.
78 * On success, the file descriptor will be positioned just past the "opt"
79 * file header, and will be locked with flock. "*pCachedName" will point
80 * to newly-allocated storage.
82 int dvmOpenCachedDexFile(const char* fileName, const char* cacheFileName,
83 u4 modWhen, u4 crc, bool isBootstrap, bool* pNewFile, bool createIfMissing)
86 struct stat fdStat, fileStat;
87 bool readOnly = false;
93 * Try to open the cache file. If we've been asked to,
94 * create it if it doesn't exist.
96 fd = createIfMissing ? open(cacheFileName, O_CREAT|O_RDWR, 0644) : -1;
98 fd = open(cacheFileName, O_RDONLY, 0);
100 if (createIfMissing) {
101 LOGE("Can't open dex cache '%s': %s\n",
102 cacheFileName, strerror(errno));
110 * Grab an exclusive lock on the cache file. If somebody else is
111 * working on it, we'll block here until they complete. Because
112 * we're waiting on an external resource, we go into VMWAIT mode.
115 LOGV("DexOpt: locking cache file %s (fd=%d, boot=%d)\n",
116 cacheFileName, fd, isBootstrap);
117 oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
118 cc = flock(fd, LOCK_EX | LOCK_NB);
120 LOGD("DexOpt: sleeping on flock(%s)\n", cacheFileName);
121 cc = flock(fd, LOCK_EX);
123 dvmChangeStatus(NULL, oldStatus);
125 LOGE("Can't lock dex cache '%s': %d\n", cacheFileName, cc);
129 LOGV("DexOpt: locked cache file\n");
132 * Check to see if the fd we opened and locked matches the file in
133 * the filesystem. If they don't, then somebody else unlinked ours
134 * and created a new file, and we need to use that one instead. (If
135 * we caught them between the unlink and the create, we'll get an
136 * ENOENT from the file stat.)
138 cc = fstat(fd, &fdStat);
140 LOGE("Can't stat open file '%s'\n", cacheFileName);
141 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
144 cc = stat(cacheFileName, &fileStat);
146 fdStat.st_dev != fileStat.st_dev || fdStat.st_ino != fileStat.st_ino)
148 LOGD("DexOpt: our open cache file is stale; sleeping and retrying\n");
149 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
152 usleep(250 * 1000); /* if something is hosed, don't peg machine */
157 * We have the correct file open and locked. If the file size is zero,
158 * then it was just created by us, and we want to fill in some fields
159 * in the "opt" header and set "*pNewFile". Otherwise, we want to
160 * verify that the fields in the header match our expectations, and
161 * reset the file if they don't.
163 if (fdStat.st_size == 0) {
165 LOGW("DexOpt: file has zero length and isn't writable\n");
168 cc = dexOptCreateEmptyHeader(fd);
172 LOGV("DexOpt: successfully initialized new cache file\n");
174 bool expectVerify, expectOpt;
176 if (gDvm.classVerifyMode == VERIFY_MODE_NONE)
177 expectVerify = false;
178 else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE)
179 expectVerify = !isBootstrap;
180 else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/
183 if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
185 else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
186 expectOpt = expectVerify;
187 else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
190 LOGV("checking deps, expecting vfy=%d opt=%d\n",
191 expectVerify, expectOpt);
193 if (!dvmCheckOptHeaderAndDependencies(fd, true, modWhen, crc,
194 expectVerify, expectOpt))
198 * We could unlink and rewrite the file if we own it or
199 * the "sticky" bit isn't set on the directory. However,
200 * we're not able to truncate it, which spoils things. So,
203 if (createIfMissing) {
204 LOGW("Cached DEX '%s' (%s) is stale and not writable\n",
205 fileName, cacheFileName);
211 * If we truncate the existing file before unlinking it, any
212 * process that has it mapped will fail when it tries to touch
215 * This is very important. The zygote process will have the
216 * boot DEX files (core, framework, etc.) mapped early. If
217 * (say) core.dex gets updated, and somebody launches an app
218 * that uses App.dex, then App.dex gets reoptimized because it's
219 * dependent upon the boot classes. However, dexopt will be
220 * using the *new* core.dex to do the optimizations, while the
221 * app will actually be running against the *old* core.dex
222 * because it starts from zygote.
224 * Even without zygote, it's still possible for a class loader
225 * to pull in an APK that was optimized against an older set
226 * of DEX files. We must ensure that everything fails when a
227 * boot DEX gets updated, and for general "why aren't my
228 * changes doing anything" purposes its best if we just make
229 * everything crash when a DEX they're using gets updated.
231 LOGD("ODEX file is stale or bad; removing and retrying (%s)\n",
233 if (ftruncate(fd, 0) != 0) {
234 LOGW("Warning: unable to truncate cache file '%s': %s\n",
235 cacheFileName, strerror(errno));
238 if (unlink(cacheFileName) != 0) {
239 LOGW("Warning: unable to remove cache file '%s': %d %s\n",
240 cacheFileName, errno, strerror(errno));
241 /* keep going; permission failure should probably be fatal */
243 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
248 LOGV("DexOpt: good deps in cache file\n");
262 * Unlock the file descriptor.
264 * Returns "true" on success.
266 bool dvmUnlockCachedDexFile(int fd)
268 LOGVV("DexOpt: unlocking cache file fd=%d\n", fd);
269 return (flock(fd, LOCK_UN) == 0);
274 * Given a descriptor for a file with DEX data in it, produce an
277 * The file pointed to by "fd" is expected to be a locked shared resource
278 * (or private); we make no efforts to enforce multi-process correctness
281 * "fileName" is only used for debug output. "modWhen" and "crc" are stored
282 * in the dependency set.
284 * The "isBootstrap" flag determines how the optimizer and verifier handle
285 * package-scope access checks. When optimizing, we only load the bootstrap
286 * class DEX files and the target DEX, so the flag determines whether the
287 * target DEX classes are given a (synthetic) non-NULL classLoader pointer.
288 * This only really matters if the target DEX contains classes that claim to
289 * be in the same package as bootstrap classes.
291 * The optimizer will need to load every class in the target DEX file.
292 * This is generally undesirable, so we start a subprocess to do the
293 * work and wait for it to complete.
295 * Returns "true" on success. All data will have been written to "fd".
297 bool dvmOptimizeDexFile(int fd, off_t dexOffset, long dexLength,
298 const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
300 const char* lastPart = strrchr(fileName, '/');
301 if (lastPart != NULL)
306 LOGD("DexOpt: --- BEGIN '%s' (bootstrap=%d) ---\n", lastPart, isBootstrap);
311 * This could happen if something in our bootclasspath, which we thought
312 * was all optimized, got rejected.
314 if (gDvm.optimizing) {
315 LOGW("Rejecting recursive optimization attempt on '%s'\n", fileName);
321 static const int kUseValgrind = 0;
322 static const char* kDexOptBin = "/bin/dexopt";
323 static const char* kValgrinder = "/usr/bin/valgrind";
324 static const int kFixedArgCount = 10;
325 static const int kValgrindArgCount = 5;
326 static const int kMaxIntLen = 12; // '-'+10dig+'\0' -OR- 0x+8dig
327 int bcpSize = dvmGetBootPathSize();
328 int argc = kFixedArgCount + bcpSize
329 + (kValgrindArgCount * kUseValgrind);
330 char* argv[argc+1]; // last entry is NULL
331 char values[argc][kMaxIntLen];
336 /* change process groups, so we don't clash with ProcessManager */
339 /* full path to optimizer */
340 androidRoot = getenv("ANDROID_ROOT");
341 if (androidRoot == NULL) {
342 LOGW("ANDROID_ROOT not set, defaulting to /system\n");
343 androidRoot = "/system";
345 execFile = malloc(strlen(androidRoot) + strlen(kDexOptBin) + 1);
346 strcpy(execFile, androidRoot);
347 strcat(execFile, kDexOptBin);
355 /* probably shouldn't ship the hard-coded path */
356 argv[curArg++] = (char*)kValgrinder;
357 argv[curArg++] = "--tool=memcheck";
358 argv[curArg++] = "--leak-check=yes"; // check for leaks too
359 argv[curArg++] = "--leak-resolution=med"; // increase from 2 to 4
360 argv[curArg++] = "--num-callers=16"; // default is 12
361 assert(curArg == kValgrindArgCount);
363 argv[curArg++] = execFile;
365 argv[curArg++] = "--dex";
367 sprintf(values[2], "%d", DALVIK_VM_BUILD);
368 argv[curArg++] = values[2];
370 sprintf(values[3], "%d", fd);
371 argv[curArg++] = values[3];
373 sprintf(values[4], "%d", (int) dexOffset);
374 argv[curArg++] = values[4];
376 sprintf(values[5], "%d", (int) dexLength);
377 argv[curArg++] = values[5];
379 argv[curArg++] = (char*)fileName;
381 sprintf(values[7], "%d", (int) modWhen);
382 argv[curArg++] = values[7];
384 sprintf(values[8], "%d", (int) crc);
385 argv[curArg++] = values[8];
388 if (gDvm.dexOptMode != OPTIMIZE_MODE_NONE) {
389 flags |= DEXOPT_OPT_ENABLED;
390 if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)
391 flags |= DEXOPT_OPT_ALL;
393 if (gDvm.classVerifyMode != VERIFY_MODE_NONE) {
394 flags |= DEXOPT_VERIFY_ENABLED;
395 if (gDvm.classVerifyMode == VERIFY_MODE_ALL)
396 flags |= DEXOPT_VERIFY_ALL;
399 flags |= DEXOPT_IS_BOOTSTRAP;
400 if (gDvm.generateRegisterMaps)
401 flags |= DEXOPT_GEN_REGISTER_MAPS;
402 sprintf(values[9], "%d", flags);
403 argv[curArg++] = values[9];
405 assert(((!kUseValgrind && curArg == kFixedArgCount) ||
406 ((kUseValgrind && curArg == kFixedArgCount+kValgrindArgCount))));
409 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
410 argv[curArg++] = cpe->fileName;
412 assert(curArg == argc);
417 execv(kValgrinder, argv);
419 execv(execFile, argv);
421 LOGE("execv '%s'%s failed: %s\n", execFile,
422 kUseValgrind ? " [valgrind]" : "", strerror(errno));
425 LOGV("DexOpt: waiting for verify+opt, pid=%d\n", (int) pid);
431 * Wait for the optimization process to finish. We go into VMWAIT
432 * mode here so GC suspension won't have to wait for us.
434 oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
436 gotPid = waitpid(pid, &status, 0);
437 if (gotPid == -1 && errno == EINTR) {
438 LOGD("waitpid interrupted, retrying\n");
443 dvmChangeStatus(NULL, oldStatus);
445 LOGE("waitpid failed: wanted %d, got %d: %s\n",
446 (int) pid, (int) gotPid, strerror(errno));
450 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
451 LOGD("DexOpt: --- END '%s' (success) ---\n", lastPart);
454 LOGW("DexOpt: --- END '%s' --- status=0x%04x, process failed\n",
462 * Do the actual optimization. This is executed in the dexopt process.
464 * For best use of disk/memory, we want to extract once and perform
465 * optimizations in place. If the file has to expand or contract
466 * to match local structure padding/alignment expectations, we want
467 * to do the rewrite as part of the extract, rather than extracting
468 * into a temp file and slurping it back out. (The structure alignment
469 * is currently correct for all platforms, and this isn't expected to
470 * change, so we should be okay with having it already extracted.)
472 * Returns "true" on success.
474 bool dvmContinueOptimization(int fd, off_t dexOffset, long dexLength,
475 const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
477 DexClassLookup* pClassLookup = NULL;
478 RegisterMapBuilder* pRegMapBuilder = NULL;
481 assert(gDvm.optimizing);
483 LOGV("Continuing optimization (%s, isb=%d)\n", fileName, isBootstrap);
485 assert(dexOffset >= 0);
487 /* quick test so we don't blow up on empty file */
488 if (dexLength < (int) sizeof(DexHeader)) {
489 LOGE("too small to be DEX\n");
492 if (dexOffset < (int) sizeof(DexOptHeader)) {
493 LOGE("not enough room for opt header\n");
500 * Drop this into a global so we don't have to pass it around. We could
501 * also add a field to DexFile, but since it only pertains to DEX
502 * creation that probably doesn't make sense.
504 gDvm.optimizingBootstrapClass = isBootstrap;
508 * Map the entire file (so we don't have to worry about page
509 * alignment). The expectation is that the output file contains
510 * our DEX data plus room for a small header.
514 mapAddr = mmap(NULL, dexOffset + dexLength, PROT_READ|PROT_WRITE,
516 if (mapAddr == MAP_FAILED) {
517 LOGE("unable to mmap DEX cache: %s\n", strerror(errno));
522 * Rewrite the file. Byte reordering, structure realigning,
523 * class verification, and bytecode optimization are all performed
526 * In theory the file could change size and bits could shift around.
527 * In practice this would be annoying to deal with, so the file
528 * layout is designed so that it can always be rewritten in place.
530 * This sets "headerFlags" and creates the class lookup table as
531 * part of doing the processing.
533 success = rewriteDex(((u1*) mapAddr) + dexOffset, dexLength,
534 &headerFlags, &pClassLookup);
537 DvmDex* pDvmDex = NULL;
538 u1* dexAddr = ((u1*) mapAddr) + dexOffset;
540 if (dvmDexFileOpenPartial(dexAddr, dexLength, &pDvmDex) != 0) {
541 LOGE("Unable to create DexFile\n");
545 * If configured to do so, generate register map output
546 * for all verified classes. The register maps were
547 * generated during verification, and will now be serialized.
549 if (gDvm.generateRegisterMaps) {
550 pRegMapBuilder = dvmGenerateRegisterMaps(pDvmDex);
551 if (pRegMapBuilder == NULL) {
552 LOGE("Failed generating register maps\n");
557 DexHeader* pHeader = (DexHeader*)pDvmDex->pHeader;
558 updateChecksum(dexAddr, dexLength, pHeader);
560 dvmDexFileFree(pDvmDex);
564 /* unmap the read-write version, forcing writes to disk */
565 if (msync(mapAddr, dexOffset + dexLength, MS_SYNC) != 0) {
566 LOGW("msync failed: %s\n", strerror(errno));
567 // weird, but keep going
571 * This causes clean shutdown to fail, because we have loaded classes
572 * that point into it. For the optimizer this isn't a problem,
573 * because it's more efficient for the process to simply exit.
574 * Exclude this code when doing clean shutdown for valgrind.
576 if (munmap(mapAddr, dexOffset + dexLength) != 0) {
577 LOGE("munmap failed: %s\n", strerror(errno));
586 /* get start offset, and adjust deps start for 64-bit alignment */
587 off_t depsOffset, optOffset, endOffset, adjOffset;
588 int depsLength, optLength;
591 depsOffset = lseek(fd, 0, SEEK_END);
592 if (depsOffset < 0) {
593 LOGE("lseek to EOF failed: %s\n", strerror(errno));
596 adjOffset = (depsOffset + 7) & ~(0x07);
597 if (adjOffset != depsOffset) {
598 LOGV("Adjusting deps start from %d to %d\n",
599 (int) depsOffset, (int) adjOffset);
600 depsOffset = adjOffset;
601 lseek(fd, depsOffset, SEEK_SET);
605 * Append the dependency list.
607 if (writeDependencies(fd, modWhen, crc) != 0) {
608 LOGW("Failed writing dependencies\n");
612 /* compute deps length, then adjust opt start for 64-bit alignment */
613 optOffset = lseek(fd, 0, SEEK_END);
614 depsLength = optOffset - depsOffset;
616 adjOffset = (optOffset + 7) & ~(0x07);
617 if (adjOffset != optOffset) {
618 LOGV("Adjusting opt start from %d to %d\n",
619 (int) optOffset, (int) adjOffset);
620 optOffset = adjOffset;
621 lseek(fd, optOffset, SEEK_SET);
625 * Append any optimized pre-computed data structures.
627 if (!writeOptData(fd, pClassLookup, pRegMapBuilder)) {
628 LOGW("Failed writing opt data\n");
632 endOffset = lseek(fd, 0, SEEK_END);
633 optLength = endOffset - optOffset;
635 /* compute checksum from start of deps to end of opt area */
636 if (!computeFileChecksum(fd, depsOffset,
637 (optOffset+optLength) - depsOffset, &optChecksum))
643 * Output the "opt" header with all values filled in and a correct
647 memset(&optHdr, 0xff, sizeof(optHdr));
648 memcpy(optHdr.magic, DEX_OPT_MAGIC, 4);
649 memcpy(optHdr.magic+4, DEX_OPT_MAGIC_VERS, 4);
650 optHdr.dexOffset = (u4) dexOffset;
651 optHdr.dexLength = (u4) dexLength;
652 optHdr.depsOffset = (u4) depsOffset;
653 optHdr.depsLength = (u4) depsLength;
654 optHdr.optOffset = (u4) optOffset;
655 optHdr.optLength = (u4) optLength;
657 optHdr.flags = headerFlags;
658 optHdr.checksum = optChecksum;
660 fsync(fd); /* ensure previous writes go before header is written */
662 lseek(fd, 0, SEEK_SET);
663 if (sysWriteFully(fd, &optHdr, sizeof(optHdr), "DexOpt opt header") != 0)
666 LOGV("Successfully wrote DEX header\n");
669 //dvmRegisterMapDumpStats();
672 dvmFreeRegisterMapBuilder(pRegMapBuilder);
679 * Perform in-place rewrites on a memory-mapped DEX file.
681 * This happens in a short-lived child process, so we can go nutty with
682 * loading classes and allocating memory.
684 static bool rewriteDex(u1* addr, int len, u4* pHeaderFlags,
685 DexClassLookup** ppClassLookup)
687 u8 prepWhen, loadWhen, verifyOptWhen;
688 DvmDex* pDvmDex = NULL;
689 bool doVerify, doOpt;
694 /* if the DEX is in the wrong byte order, swap it now */
695 if (dexSwapAndVerify(addr, len) != 0)
697 #if __BYTE_ORDER != __LITTLE_ENDIAN
698 *pHeaderFlags |= DEX_OPT_FLAG_BIG;
701 if (gDvm.classVerifyMode == VERIFY_MODE_NONE)
703 else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE)
704 doVerify = !gDvm.optimizingBootstrapClass;
705 else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/
708 if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
710 else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
712 else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
715 /* TODO: decide if this is actually useful */
717 *pHeaderFlags |= DEX_FLAG_VERIFIED;
719 *pHeaderFlags |= DEX_OPT_FLAG_FIELDS | DEX_OPT_FLAG_INVOCATIONS;
722 * Now that the DEX file can be read directly, create a DexFile struct
725 if (dvmDexFileOpenPartial(addr, len, &pDvmDex) != 0) {
726 LOGE("Unable to create DexFile\n");
731 * Create the class lookup table. This will eventually be appended
732 * to the end of the .odex.
734 *ppClassLookup = dexCreateClassLookup(pDvmDex->pDexFile);
735 if (*ppClassLookup == NULL)
739 * If we're not going to attempt to verify or optimize the classes,
740 * there's no value in loading them, so bail out early.
742 if (!doVerify && !doOpt) {
747 /* this is needed for the next part */
748 pDvmDex->pDexFile->pClassLookup = *ppClassLookup;
750 prepWhen = dvmGetRelativeTimeUsec();
753 * Load all classes found in this DEX file. If they fail to load for
754 * some reason, they won't get verified (which is as it should be).
756 if (!loadAllClasses(pDvmDex))
758 loadWhen = dvmGetRelativeTimeUsec();
761 * Verify and optimize all classes in the DEX file (command-line
762 * options permitting).
764 * This is best-effort, so there's really no way for dexopt to
765 * fail at this point.
767 verifyAndOptimizeClasses(pDvmDex->pDexFile, doVerify, doOpt);
768 verifyOptWhen = dvmGetRelativeTimeUsec();
770 const char* msgStr = "???";
771 if (doVerify && doOpt)
772 msgStr = "verify+opt";
777 LOGD("DexOpt: load %dms, %s %dms\n",
778 (int) (loadWhen - prepWhen) / 1000,
780 (int) (verifyOptWhen - loadWhen) / 1000);
785 /* free up storage */
786 dvmDexFileFree(pDvmDex);
792 * Try to load all classes in the specified DEX. If they have some sort
793 * of broken dependency, e.g. their superclass lives in a different DEX
794 * that wasn't previously loaded into the bootstrap class path, loading
795 * will fail. This is the desired behavior.
797 * We have no notion of class loader at this point, so we load all of
798 * the classes with the bootstrap class loader. It turns out this has
799 * exactly the behavior we want, and has no ill side effects because we're
800 * running in a separate process and anything we load here will be forgotten.
802 * We set the CLASS_MULTIPLE_DEFS flag here if we see multiple definitions.
803 * This works because we only call here as part of optimization / pre-verify,
804 * not during verification as part of loading a class into a running VM.
806 * This returns "false" if the world is too screwed up to do anything
809 static bool loadAllClasses(DvmDex* pDvmDex)
811 u4 count = pDvmDex->pDexFile->pHeader->classDefsSize;
815 LOGV("DexOpt: +++ trying to load %d classes\n", count);
817 dvmSetBootPathExtraDex(pDvmDex);
820 * We have some circularity issues with Class and Object that are most
821 * easily avoided by ensuring that Object is never the first thing we
822 * try to find. Take care of that here. (We only need to do this when
823 * loading classes from the DEX file that contains Object, and only
824 * when Object comes first in the list, but it costs very little to
825 * do it in all cases.)
827 if (dvmFindSystemClass("Ljava/lang/Class;") == NULL) {
828 LOGE("ERROR: java.lang.Class does not exist!\n");
832 for (idx = 0; idx < count; idx++) {
833 const DexClassDef* pClassDef;
834 const char* classDescriptor;
835 ClassObject* newClass;
837 pClassDef = dexGetClassDef(pDvmDex->pDexFile, idx);
839 dexStringByTypeIdx(pDvmDex->pDexFile, pClassDef->classIdx);
841 LOGV("+++ loading '%s'", classDescriptor);
842 //newClass = dvmDefineClass(pDexFile, classDescriptor,
844 newClass = dvmFindSystemClassNoInit(classDescriptor);
845 if (newClass == NULL) {
846 LOGV("DexOpt: failed loading '%s'\n", classDescriptor);
847 dvmClearOptException(dvmThreadSelf());
848 } else if (newClass->pDvmDex != pDvmDex) {
850 * We don't load the new one, and we tag the first one found
851 * with the "multiple def" flag so the resolver doesn't try
852 * to make it available.
854 LOGD("DexOpt: '%s' has an earlier definition; blocking out\n",
856 SET_CLASS_FLAG(newClass, CLASS_MULTIPLE_DEFS);
861 LOGV("DexOpt: +++ successfully loaded %d classes\n", loaded);
863 dvmSetBootPathExtraDex(NULL);
868 * Verify and/or optimize all classes that were successfully loaded from
871 static void verifyAndOptimizeClasses(DexFile* pDexFile, bool doVerify,
874 u4 count = pDexFile->pHeader->classDefsSize;
878 * Create a data structure for use by the bytecode optimizer. We
879 * stuff it into a global so we don't have to pass it around as
880 * a function argument.
882 * We could create this at VM startup, but there's no need to do so
883 * unless we're optimizing, which means we're in dexopt, and we're
884 * only going to call here once.
887 gDvm.inlineSubs = dvmCreateInlineSubsTable();
888 if (gDvm.inlineSubs == NULL)
892 for (idx = 0; idx < count; idx++) {
893 const DexClassDef* pClassDef;
894 const char* classDescriptor;
897 pClassDef = dexGetClassDef(pDexFile, idx);
898 classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
900 /* all classes are loaded into the bootstrap class loader */
901 clazz = dvmLookupClass(classDescriptor, NULL, false);
903 verifyAndOptimizeClass(pDexFile, clazz, pClassDef, doVerify, doOpt);
906 // TODO: log when in verbose mode
907 LOGV("DexOpt: not optimizing unavailable class '%s'\n",
912 if (gDvm.inlineSubs != NULL) {
913 dvmFreeInlineSubsTable(gDvm.inlineSubs);
914 gDvm.inlineSubs = NULL;
919 * Verify and/or optimize a specific class.
921 static void verifyAndOptimizeClass(DexFile* pDexFile, ClassObject* clazz,
922 const DexClassDef* pClassDef, bool doVerify, bool doOpt)
924 const char* classDescriptor;
925 bool verified = false;
927 if (clazz->pDvmDex->pDexFile != pDexFile) {
929 * The current DEX file defined a class that is also present in the
930 * bootstrap class path. The class loader favored the bootstrap
931 * version, which means that we have a pointer to a class that is
932 * (a) not the one we want to examine, and (b) mapped read-only,
933 * so we will seg fault if we try to rewrite instructions inside it.
935 LOGD("DexOpt: not verifying/optimizing '%s': multiple definitions\n",
940 classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
943 * First, try to verify it.
946 if (dvmVerifyClass(clazz)) {
948 * Set the "is preverified" flag in the DexClassDef. We
949 * do it here, rather than in the ClassObject structure,
950 * because the DexClassDef is part of the odex file.
952 assert((clazz->accessFlags & JAVA_FLAGS_MASK) ==
953 pClassDef->accessFlags);
954 ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISPREVERIFIED;
957 // TODO: log when in verbose mode
958 LOGV("DexOpt: '%s' failed verification\n", classDescriptor);
963 if (!verified && gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED) {
964 LOGV("DexOpt: not optimizing '%s': not verified\n",
967 dvmOptimizeClass(clazz, false);
969 /* set the flag whether or not we actually changed anything */
970 ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISOPTIMIZED;
977 * Get the cache file name from a ClassPathEntry.
979 static const char* getCacheFileName(const ClassPathEntry* cpe)
983 return dvmGetJarFileCacheFileName((JarFile*) cpe->ptr);
985 return dvmGetRawDexFileCacheFileName((RawDexFile*) cpe->ptr);
987 LOGE("DexOpt: unexpected cpe kind %d\n", cpe->kind);
994 * Get the SHA-1 signature.
996 static const u1* getSignature(const ClassPathEntry* cpe)
1000 switch (cpe->kind) {
1002 pDvmDex = dvmGetJarFileDex((JarFile*) cpe->ptr);
1005 pDvmDex = dvmGetRawDexFileDex((RawDexFile*) cpe->ptr);
1008 LOGE("unexpected cpe kind %d\n", cpe->kind);
1010 pDvmDex = NULL; // make gcc happy
1013 assert(pDvmDex != NULL);
1014 return pDvmDex->pDexFile->pHeader->signature;
1019 * Dependency layout:
1020 * 4b Source file modification time, in seconds since 1970 UTC
1021 * 4b CRC-32 from Zip entry, or Adler32 from source DEX header
1022 * 4b Dalvik VM build number
1023 * 4b Number of dependency entries that follow
1024 * Dependency entries:
1025 * 4b Name length (including terminating null)
1026 * var Full path of cache entry (null terminated)
1027 * 20b SHA-1 signature from source DEX file
1029 * If this changes, update DEX_OPT_MAGIC_VERS.
1031 static const size_t kMinDepSize = 4 * 4;
1032 static const size_t kMaxDepSize = 4 * 4 + 2048; // sanity check
1035 * Read the "opt" header, verify it, then read the dependencies section
1036 * and verify that data as well.
1038 * If "sourceAvail" is "true", this will verify that "modWhen" and "crc"
1039 * match up with what is stored in the header. If they don't, we reject
1040 * the file so that it can be recreated from the updated original. If
1041 * "sourceAvail" isn't set, e.g. for a .odex file, we ignore these arguments.
1043 * On successful return, the file will be seeked immediately past the
1046 bool dvmCheckOptHeaderAndDependencies(int fd, bool sourceAvail, u4 modWhen,
1047 u4 crc, bool expectVerify, bool expectOpt)
1049 DexOptHeader optHdr;
1057 * Start at the start. The "opt" header, when present, will always be
1058 * the first thing in the file.
1060 if (lseek(fd, 0, SEEK_SET) != 0) {
1061 LOGE("DexOpt: failed to seek to start of file: %s\n", strerror(errno));
1066 * Read and do trivial verification on the opt header. The header is
1067 * always in host byte order.
1069 actual = read(fd, &optHdr, sizeof(optHdr));
1071 LOGE("DexOpt: failed reading opt header: %s\n", strerror(errno));
1073 } else if (actual != sizeof(optHdr)) {
1074 LOGE("DexOpt: failed reading opt header (got %d of %zd)\n",
1075 (int) actual, sizeof(optHdr));
1079 magic = optHdr.magic;
1080 if (memcmp(magic, DEX_MAGIC, 4) == 0) {
1081 /* somebody probably pointed us at the wrong file */
1082 LOGD("DexOpt: expected optimized DEX, found unoptimized\n");
1084 } else if (memcmp(magic, DEX_OPT_MAGIC, 4) != 0) {
1085 /* not a DEX file, or previous attempt was interrupted */
1086 LOGD("DexOpt: incorrect opt magic number (0x%02x %02x %02x %02x)\n",
1087 magic[0], magic[1], magic[2], magic[3]);
1090 if (memcmp(magic+4, DEX_OPT_MAGIC_VERS, 4) != 0) {
1091 LOGW("DexOpt: stale opt version (0x%02x %02x %02x %02x)\n",
1092 magic[4], magic[5], magic[6], magic[7]);
1095 if (optHdr.depsLength < kMinDepSize || optHdr.depsLength > kMaxDepSize) {
1096 LOGW("DexOpt: weird deps length %d, bailing\n", optHdr.depsLength);
1101 * Do the header flags match up with what we want?
1103 * This is useful because it allows us to automatically regenerate
1104 * a file when settings change (e.g. verification is now mandatory),
1105 * but can cause difficulties if the bootstrap classes we depend upon
1106 * were handled differently than the current options specify. We get
1107 * upset because they're not verified or optimized, but we're not able
1108 * to regenerate them because the installer won't let us.
1110 * (This is also of limited value when !sourceAvail.)
1112 * So, for now, we essentially ignore "expectVerify" and "expectOpt"
1113 * by limiting the match mask.
1115 * The only thing we really can't handle is incorrect byte-ordering.
1117 const u4 matchMask = DEX_OPT_FLAG_BIG;
1118 u4 expectedFlags = 0;
1119 #if __BYTE_ORDER != __LITTLE_ENDIAN
1120 expectedFlags |= DEX_OPT_FLAG_BIG;
1123 expectedFlags |= DEX_FLAG_VERIFIED;
1125 expectedFlags |= DEX_OPT_FLAG_FIELDS | DEX_OPT_FLAG_INVOCATIONS;
1126 if ((expectedFlags & matchMask) != (optHdr.flags & matchMask)) {
1127 LOGI("DexOpt: header flag mismatch (0x%02x vs 0x%02x, mask=0x%02x)\n",
1128 expectedFlags, optHdr.flags, matchMask);
1132 posn = lseek(fd, optHdr.depsOffset, SEEK_SET);
1134 LOGW("DexOpt: seek to deps failed: %s\n", strerror(errno));
1139 * Read all of the dependency stuff into memory.
1141 depData = (u1*) malloc(optHdr.depsLength);
1142 if (depData == NULL) {
1143 LOGW("DexOpt: unable to allocate %d bytes for deps\n",
1147 actual = read(fd, depData, optHdr.depsLength);
1149 LOGW("DexOpt: failed reading deps: %s\n", strerror(errno));
1151 } else if (actual != (ssize_t) optHdr.depsLength) {
1152 LOGW("DexOpt: failed reading deps: got %d of %d\n",
1153 (int) actual, optHdr.depsLength);
1158 * Verify simple items.
1164 val = read4LE(&ptr);
1165 if (sourceAvail && val != modWhen) {
1166 LOGI("DexOpt: source file mod time mismatch (%08x vs %08x)\n",
1170 val = read4LE(&ptr);
1171 if (sourceAvail && val != crc) {
1172 LOGI("DexOpt: source file CRC mismatch (%08x vs %08x)\n", val, crc);
1175 val = read4LE(&ptr);
1176 if (val != DALVIK_VM_BUILD) {
1177 LOGD("DexOpt: VM build version mismatch (%d vs %d)\n",
1178 val, DALVIK_VM_BUILD);
1183 * Verify dependencies on other cached DEX files. It must match
1184 * exactly with what is currently defined in the bootclasspath.
1186 ClassPathEntry* cpe;
1189 numDeps = read4LE(&ptr);
1190 LOGV("+++ DexOpt: numDeps = %d\n", numDeps);
1191 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1192 const char* cacheFileName =
1193 dvmPathToAbsolutePortion(getCacheFileName(cpe));
1194 assert(cacheFileName != NULL); /* guaranteed by Class.c */
1196 const u1* signature = getSignature(cpe);
1197 size_t len = strlen(cacheFileName) +1;
1201 /* more entries in bootclasspath than in deps list */
1202 LOGI("DexOpt: not all deps represented\n");
1206 storedStrLen = read4LE(&ptr);
1207 if (len != storedStrLen ||
1208 strcmp(cacheFileName, (const char*) ptr) != 0)
1210 LOGI("DexOpt: mismatch dep name: '%s' vs. '%s'\n",
1211 cacheFileName, ptr);
1215 ptr += storedStrLen;
1217 if (memcmp(signature, ptr, kSHA1DigestLen) != 0) {
1218 LOGI("DexOpt: mismatch dep signature for '%s'\n", cacheFileName);
1221 ptr += kSHA1DigestLen;
1223 LOGV("DexOpt: dep match on '%s'\n", cacheFileName);
1229 /* more entries in deps list than in classpath */
1230 LOGI("DexOpt: Some deps went away\n");
1234 // consumed all data and no more?
1235 if (ptr != depData + optHdr.depsLength) {
1236 LOGW("DexOpt: Spurious dep data? %d vs %d\n",
1237 (int) (ptr - depData), optHdr.depsLength);
1249 * Write the dependency info to "fd" at the current file position.
1251 static int writeDependencies(int fd, u4 modWhen, u4 crc)
1256 ClassPathEntry* cpe;
1260 * Count up the number of completed entries in the bootclasspath.
1264 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1265 const char* cacheFileName =
1266 dvmPathToAbsolutePortion(getCacheFileName(cpe));
1267 assert(cacheFileName != NULL); /* guaranteed by Class.c */
1269 LOGV("+++ DexOpt: found dep '%s'\n", cacheFileName);
1272 bufLen += strlen(cacheFileName) +1;
1275 bufLen += 4*4 + numDeps * (4+kSHA1DigestLen);
1277 buf = malloc(bufLen);
1279 set4LE(buf+0, modWhen);
1281 set4LE(buf+8, DALVIK_VM_BUILD);
1282 set4LE(buf+12, numDeps);
1284 // TODO: do we want to add dvmGetInlineOpsTableLength() here? Won't
1285 // help us if somebody replaces an existing entry, but it'd catch
1286 // additions/removals.
1288 u1* ptr = buf + 4*4;
1289 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1290 const char* cacheFileName =
1291 dvmPathToAbsolutePortion(getCacheFileName(cpe));
1292 assert(cacheFileName != NULL); /* guaranteed by Class.c */
1294 const u1* signature = getSignature(cpe);
1295 int len = strlen(cacheFileName) +1;
1297 if (ptr + 4 + len + kSHA1DigestLen > buf + bufLen) {
1298 LOGE("DexOpt: overran buffer\n");
1304 memcpy(ptr, cacheFileName, len);
1306 memcpy(ptr, signature, kSHA1DigestLen);
1307 ptr += kSHA1DigestLen;
1310 assert(ptr == buf + bufLen);
1312 result = sysWriteFully(fd, buf, bufLen, "DexOpt dep info");
1320 * Write a block of data in "chunk" format.
1322 * The chunk header fields are always in "native" byte order. If "size"
1323 * is not a multiple of 8 bytes, the data area is padded out.
1325 static bool writeChunk(int fd, u4 type, const void* data, size_t size)
1327 union { /* save a syscall by grouping these together */
1335 assert(sizeof(header) == 8);
1337 LOGV("Writing chunk, type=%.4s size=%d\n", (char*) &type, size);
1339 header.ts.type = type;
1340 header.ts.size = (u4) size;
1341 if (sysWriteFully(fd, &header, sizeof(header),
1342 "DexOpt opt chunk header write") != 0)
1348 if (sysWriteFully(fd, data, size, "DexOpt opt chunk write") != 0)
1352 /* if necessary, pad to 64-bit alignment */
1353 if ((size & 7) != 0) {
1354 int padSize = 8 - (size & 7);
1355 LOGV("size was %d, inserting %d pad bytes\n", size, padSize);
1356 lseek(fd, padSize, SEEK_CUR);
1359 assert( ((int)lseek(fd, 0, SEEK_CUR) & 7) == 0);
1367 * We have different pieces, some of which may be optional. To make the
1368 * most effective use of space, we use a "chunk" format, with a 4-byte
1369 * type and a 4-byte length. We guarantee 64-bit alignment for the data,
1370 * so it can be used directly when the file is mapped for reading.
1372 static bool writeOptData(int fd, const DexClassLookup* pClassLookup,
1373 const RegisterMapBuilder* pRegMapBuilder)
1375 /* pre-computed class lookup hash table */
1376 if (!writeChunk(fd, (u4) kDexChunkClassLookup,
1377 pClassLookup, pClassLookup->size))
1382 /* register maps (optional) */
1383 if (pRegMapBuilder != NULL) {
1384 if (!writeChunk(fd, (u4) kDexChunkRegisterMaps,
1385 pRegMapBuilder->data, pRegMapBuilder->size))
1391 /* write the end marker */
1392 if (!writeChunk(fd, (u4) kDexChunkEnd, NULL, 0)) {
1400 * Compute a checksum on a piece of an open file.
1402 * File will be positioned at end of checksummed area.
1404 * Returns "true" on success.
1406 static bool computeFileChecksum(int fd, off_t start, size_t length, u4* pSum)
1408 unsigned char readBuf[8192];
1412 if (lseek(fd, start, SEEK_SET) != start) {
1413 LOGE("Unable to seek to start of checksum area (%ld): %s\n",
1414 (long) start, strerror(errno));
1418 adler = adler32(0L, Z_NULL, 0);
1420 while (length != 0) {
1421 size_t wanted = (length < sizeof(readBuf)) ? length : sizeof(readBuf);
1422 actual = read(fd, readBuf, wanted);
1424 LOGE("Read failed (%d) while computing checksum (len=%zu): %s\n",
1425 (int) actual, length, strerror(errno));
1429 adler = adler32(adler, readBuf, actual);
1439 * Update the Adler-32 checksum stored in the DEX file. This covers the
1440 * swapped and optimized DEX data, but does not include the opt header
1441 * or optimized data.
1443 static void updateChecksum(u1* addr, int len, DexHeader* pHeader)
1446 * Rewrite the checksum. We leave the SHA-1 signature alone.
1448 uLong adler = adler32(0L, Z_NULL, 0);
1449 const int nonSum = sizeof(pHeader->magic) + sizeof(pHeader->checksum);
1451 adler = adler32(adler, addr + nonSum, len - nonSum);
1452 pHeader->checksum = adler;