• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * 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
20  * register maps.
21  *
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.
26  */
27 #include "Dalvik.h"
28 #include "libdex/OptInvocation.h"
29 #include "analysis/RegisterMap.h"
30 #include "analysis/Optimize.h"
31 
32 #include <string>
33 
34 #include <libgen.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <unistd.h>
46 #include <zlib.h>
47 
48 /* fwd */
49 static bool rewriteDex(u1* addr, int len, bool doVerify, bool doOpt,
50     DexClassLookup** ppClassLookup, DvmDex** ppDvmDex);
51 static bool loadAllClasses(DvmDex* pDvmDex);
52 static void verifyAndOptimizeClasses(DexFile* pDexFile, bool doVerify,
53     bool doOpt);
54 static void verifyAndOptimizeClass(DexFile* pDexFile, ClassObject* clazz,
55     const DexClassDef* pClassDef, bool doVerify, bool doOpt);
56 static void updateChecksum(u1* addr, int len, DexHeader* pHeader);
57 static int writeDependencies(int fd, u4 modWhen, u4 crc);
58 static bool writeOptData(int fd, const DexClassLookup* pClassLookup,\
59     const RegisterMapBuilder* pRegMapBuilder);
60 static bool computeFileChecksum(int fd, off_t start, size_t length, u4* pSum);
61 
62 /*
63  * Get just the directory portion of the given path. Equivalent to dirname(3).
64  */
saneDirName(const std::string & path)65 static std::string saneDirName(const std::string& path) {
66     size_t n = path.rfind('/');
67     if (n == std::string::npos) {
68         return ".";
69     }
70     return path.substr(0, n);
71 }
72 
73 /*
74  * Helper for dvmOpenCacheDexFile() in a known-error case: Check to
75  * see if the directory part of the given path (all but the last
76  * component) exists and is writable. Complain to the log if not.
77  */
directoryIsValid(const std::string & fileName)78 static bool directoryIsValid(const std::string& fileName)
79 {
80     std::string dirName(saneDirName(fileName));
81 
82     struct stat sb;
83     if (stat(dirName.c_str(), &sb) < 0) {
84         LOGE("Could not stat dex cache directory '%s': %s", dirName.c_str(), strerror(errno));
85         return false;
86     }
87 
88     if (!S_ISDIR(sb.st_mode)) {
89         LOGE("Dex cache directory isn't a directory: %s", dirName.c_str());
90         return false;
91     }
92 
93     if (access(dirName.c_str(), W_OK) < 0) {
94         LOGE("Dex cache directory isn't writable: %s", dirName.c_str());
95         return false;
96     }
97 
98     if (access(dirName.c_str(), R_OK) < 0) {
99         LOGE("Dex cache directory isn't readable: %s", dirName.c_str());
100         return false;
101     }
102 
103     return true;
104 }
105 
106 /*
107  * Return the fd of an open file in the DEX file cache area.  If the cache
108  * file doesn't exist or is out of date, this will remove the old entry,
109  * create a new one (writing only the file header), and return with the
110  * "new file" flag set.
111  *
112  * It's possible to execute from an unoptimized DEX file directly,
113  * assuming the byte ordering and structure alignment is correct, but
114  * disadvantageous because some significant optimizations are not possible.
115  * It's not generally possible to do the same from an uncompressed Jar
116  * file entry, because we have to guarantee 32-bit alignment in the
117  * memory-mapped file.
118  *
119  * For a Jar/APK file (a zip archive with "classes.dex" inside), "modWhen"
120  * and "crc32" come from the Zip directory entry.  For a stand-alone DEX
121  * file, it's the modification date of the file and the Adler32 from the
122  * DEX header (which immediately follows the magic).  If these don't
123  * match what's stored in the opt header, we reject the file immediately.
124  *
125  * On success, the file descriptor will be positioned just past the "opt"
126  * file header, and will be locked with flock.  "*pCachedName" will point
127  * to newly-allocated storage.
128  */
dvmOpenCachedDexFile(const char * fileName,const char * cacheFileName,u4 modWhen,u4 crc,bool isBootstrap,bool * pNewFile,bool createIfMissing)129 int dvmOpenCachedDexFile(const char* fileName, const char* cacheFileName,
130     u4 modWhen, u4 crc, bool isBootstrap, bool* pNewFile, bool createIfMissing)
131 {
132     int fd, cc;
133     struct stat fdStat, fileStat;
134     bool readOnly = false;
135 
136     *pNewFile = false;
137 
138 retry:
139     /*
140      * Try to open the cache file.  If we've been asked to,
141      * create it if it doesn't exist.
142      */
143     fd = createIfMissing ? open(cacheFileName, O_CREAT|O_RDWR, 0644) : -1;
144     if (fd < 0) {
145         fd = open(cacheFileName, O_RDONLY, 0);
146         if (fd < 0) {
147             if (createIfMissing) {
148                 // TODO: write an equivalent of strerror_r that returns a std::string.
149                 const std::string errnoString(strerror(errno));
150                 if (directoryIsValid(cacheFileName)) {
151                     LOGE("Can't open dex cache file '%s': %s", cacheFileName, errnoString.c_str());
152                 }
153             }
154             return fd;
155         }
156         readOnly = true;
157     } else {
158         fchmod(fd, 0644);
159     }
160 
161     /*
162      * Grab an exclusive lock on the cache file.  If somebody else is
163      * working on it, we'll block here until they complete.  Because
164      * we're waiting on an external resource, we go into VMWAIT mode.
165      */
166     LOGV("DexOpt: locking cache file %s (fd=%d, boot=%d)",
167         cacheFileName, fd, isBootstrap);
168     ThreadStatus oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
169     cc = flock(fd, LOCK_EX | LOCK_NB);
170     if (cc != 0) {
171         LOGD("DexOpt: sleeping on flock(%s)", cacheFileName);
172         cc = flock(fd, LOCK_EX);
173     }
174     dvmChangeStatus(NULL, oldStatus);
175     if (cc != 0) {
176         LOGE("Can't lock dex cache '%s': %d", cacheFileName, cc);
177         close(fd);
178         return -1;
179     }
180     LOGV("DexOpt:  locked cache file");
181 
182     /*
183      * Check to see if the fd we opened and locked matches the file in
184      * the filesystem.  If they don't, then somebody else unlinked ours
185      * and created a new file, and we need to use that one instead.  (If
186      * we caught them between the unlink and the create, we'll get an
187      * ENOENT from the file stat.)
188      */
189     cc = fstat(fd, &fdStat);
190     if (cc != 0) {
191         LOGE("Can't stat open file '%s'", cacheFileName);
192         LOGVV("DexOpt: unlocking cache file %s", cacheFileName);
193         goto close_fail;
194     }
195     cc = stat(cacheFileName, &fileStat);
196     if (cc != 0 ||
197         fdStat.st_dev != fileStat.st_dev || fdStat.st_ino != fileStat.st_ino)
198     {
199         LOGD("DexOpt: our open cache file is stale; sleeping and retrying");
200         LOGVV("DexOpt: unlocking cache file %s", cacheFileName);
201         flock(fd, LOCK_UN);
202         close(fd);
203         usleep(250 * 1000);     /* if something is hosed, don't peg machine */
204         goto retry;
205     }
206 
207     /*
208      * We have the correct file open and locked.  If the file size is zero,
209      * then it was just created by us, and we want to fill in some fields
210      * in the "opt" header and set "*pNewFile".  Otherwise, we want to
211      * verify that the fields in the header match our expectations, and
212      * reset the file if they don't.
213      */
214     if (fdStat.st_size == 0) {
215         if (readOnly) {
216             LOGW("DexOpt: file has zero length and isn't writable");
217             goto close_fail;
218         }
219         cc = dexOptCreateEmptyHeader(fd);
220         if (cc != 0)
221             goto close_fail;
222         *pNewFile = true;
223         LOGV("DexOpt: successfully initialized new cache file");
224     } else {
225         bool expectVerify, expectOpt;
226 
227         if (gDvm.classVerifyMode == VERIFY_MODE_NONE) {
228             expectVerify = false;
229         } else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE) {
230             expectVerify = !isBootstrap;
231         } else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/ {
232             expectVerify = true;
233         }
234 
235         if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE) {
236             expectOpt = false;
237         } else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED ||
238                    gDvm.dexOptMode == OPTIMIZE_MODE_FULL) {
239             expectOpt = expectVerify;
240         } else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/ {
241             expectOpt = true;
242         }
243 
244         LOGV("checking deps, expecting vfy=%d opt=%d",
245             expectVerify, expectOpt);
246 
247         if (!dvmCheckOptHeaderAndDependencies(fd, true, modWhen, crc,
248                 expectVerify, expectOpt))
249         {
250             if (readOnly) {
251                 /*
252                  * We could unlink and rewrite the file if we own it or
253                  * the "sticky" bit isn't set on the directory.  However,
254                  * we're not able to truncate it, which spoils things.  So,
255                  * give up now.
256                  */
257                 if (createIfMissing) {
258                     LOGW("Cached DEX '%s' (%s) is stale and not writable",
259                         fileName, cacheFileName);
260                 }
261                 goto close_fail;
262             }
263 
264             /*
265              * If we truncate the existing file before unlinking it, any
266              * process that has it mapped will fail when it tries to touch
267              * the pages.
268              *
269              * This is very important.  The zygote process will have the
270              * boot DEX files (core, framework, etc.) mapped early.  If
271              * (say) core.dex gets updated, and somebody launches an app
272              * that uses App.dex, then App.dex gets reoptimized because it's
273              * dependent upon the boot classes.  However, dexopt will be
274              * using the *new* core.dex to do the optimizations, while the
275              * app will actually be running against the *old* core.dex
276              * because it starts from zygote.
277              *
278              * Even without zygote, it's still possible for a class loader
279              * to pull in an APK that was optimized against an older set
280              * of DEX files.  We must ensure that everything fails when a
281              * boot DEX gets updated, and for general "why aren't my
282              * changes doing anything" purposes its best if we just make
283              * everything crash when a DEX they're using gets updated.
284              */
285             LOGD("ODEX file is stale or bad; removing and retrying (%s)",
286                 cacheFileName);
287             if (ftruncate(fd, 0) != 0) {
288                 LOGW("Warning: unable to truncate cache file '%s': %s",
289                     cacheFileName, strerror(errno));
290                 /* keep going */
291             }
292             if (unlink(cacheFileName) != 0) {
293                 LOGW("Warning: unable to remove cache file '%s': %d %s",
294                     cacheFileName, errno, strerror(errno));
295                 /* keep going; permission failure should probably be fatal */
296             }
297             LOGVV("DexOpt: unlocking cache file %s", cacheFileName);
298             flock(fd, LOCK_UN);
299             close(fd);
300             goto retry;
301         } else {
302             LOGV("DexOpt: good deps in cache file");
303         }
304     }
305 
306     assert(fd >= 0);
307     return fd;
308 
309 close_fail:
310     flock(fd, LOCK_UN);
311     close(fd);
312     return -1;
313 }
314 
315 /*
316  * Unlock the file descriptor.
317  *
318  * Returns "true" on success.
319  */
dvmUnlockCachedDexFile(int fd)320 bool dvmUnlockCachedDexFile(int fd)
321 {
322     LOGVV("DexOpt: unlocking cache file fd=%d", fd);
323     return (flock(fd, LOCK_UN) == 0);
324 }
325 
326 
327 /*
328  * Given a descriptor for a file with DEX data in it, produce an
329  * optimized version.
330  *
331  * The file pointed to by "fd" is expected to be a locked shared resource
332  * (or private); we make no efforts to enforce multi-process correctness
333  * here.
334  *
335  * "fileName" is only used for debug output.  "modWhen" and "crc" are stored
336  * in the dependency set.
337  *
338  * The "isBootstrap" flag determines how the optimizer and verifier handle
339  * package-scope access checks.  When optimizing, we only load the bootstrap
340  * class DEX files and the target DEX, so the flag determines whether the
341  * target DEX classes are given a (synthetic) non-NULL classLoader pointer.
342  * This only really matters if the target DEX contains classes that claim to
343  * be in the same package as bootstrap classes.
344  *
345  * The optimizer will need to load every class in the target DEX file.
346  * This is generally undesirable, so we start a subprocess to do the
347  * work and wait for it to complete.
348  *
349  * Returns "true" on success.  All data will have been written to "fd".
350  */
dvmOptimizeDexFile(int fd,off_t dexOffset,long dexLength,const char * fileName,u4 modWhen,u4 crc,bool isBootstrap)351 bool dvmOptimizeDexFile(int fd, off_t dexOffset, long dexLength,
352     const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
353 {
354     const char* lastPart = strrchr(fileName, '/');
355     if (lastPart != NULL)
356         lastPart++;
357     else
358         lastPart = fileName;
359 
360     LOGD("DexOpt: --- BEGIN '%s' (bootstrap=%d) ---", lastPart, isBootstrap);
361 
362     pid_t pid;
363 
364     /*
365      * This could happen if something in our bootclasspath, which we thought
366      * was all optimized, got rejected.
367      */
368     if (gDvm.optimizing) {
369         LOGW("Rejecting recursive optimization attempt on '%s'", fileName);
370         return false;
371     }
372 
373     pid = fork();
374     if (pid == 0) {
375         static const int kUseValgrind = 0;
376         static const char* kDexOptBin = "/bin/dexopt";
377         static const char* kValgrinder = "/usr/bin/valgrind";
378         static const int kFixedArgCount = 10;
379         static const int kValgrindArgCount = 5;
380         static const int kMaxIntLen = 12;   // '-'+10dig+'\0' -OR- 0x+8dig
381         int bcpSize = dvmGetBootPathSize();
382         int argc = kFixedArgCount + bcpSize
383             + (kValgrindArgCount * kUseValgrind);
384         const char* argv[argc+1];             // last entry is NULL
385         char values[argc][kMaxIntLen];
386         char* execFile;
387         const char* androidRoot;
388         int flags;
389 
390         /* change process groups, so we don't clash with ProcessManager */
391         setpgid(0, 0);
392 
393         /* full path to optimizer */
394         androidRoot = getenv("ANDROID_ROOT");
395         if (androidRoot == NULL) {
396             LOGW("ANDROID_ROOT not set, defaulting to /system");
397             androidRoot = "/system";
398         }
399         execFile = (char*)malloc(strlen(androidRoot) + strlen(kDexOptBin) + 1);
400         strcpy(execFile, androidRoot);
401         strcat(execFile, kDexOptBin);
402 
403         /*
404          * Create arg vector.
405          */
406         int curArg = 0;
407 
408         if (kUseValgrind) {
409             /* probably shouldn't ship the hard-coded path */
410             argv[curArg++] = (char*)kValgrinder;
411             argv[curArg++] = "--tool=memcheck";
412             argv[curArg++] = "--leak-check=yes";        // check for leaks too
413             argv[curArg++] = "--leak-resolution=med";   // increase from 2 to 4
414             argv[curArg++] = "--num-callers=16";        // default is 12
415             assert(curArg == kValgrindArgCount);
416         }
417         argv[curArg++] = execFile;
418 
419         argv[curArg++] = "--dex";
420 
421         sprintf(values[2], "%d", DALVIK_VM_BUILD);
422         argv[curArg++] = values[2];
423 
424         sprintf(values[3], "%d", fd);
425         argv[curArg++] = values[3];
426 
427         sprintf(values[4], "%d", (int) dexOffset);
428         argv[curArg++] = values[4];
429 
430         sprintf(values[5], "%d", (int) dexLength);
431         argv[curArg++] = values[5];
432 
433         argv[curArg++] = (char*)fileName;
434 
435         sprintf(values[7], "%d", (int) modWhen);
436         argv[curArg++] = values[7];
437 
438         sprintf(values[8], "%d", (int) crc);
439         argv[curArg++] = values[8];
440 
441         flags = 0;
442         if (gDvm.dexOptMode != OPTIMIZE_MODE_NONE) {
443             flags |= DEXOPT_OPT_ENABLED;
444             if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)
445                 flags |= DEXOPT_OPT_ALL;
446         }
447         if (gDvm.classVerifyMode != VERIFY_MODE_NONE) {
448             flags |= DEXOPT_VERIFY_ENABLED;
449             if (gDvm.classVerifyMode == VERIFY_MODE_ALL)
450                 flags |= DEXOPT_VERIFY_ALL;
451         }
452         if (isBootstrap)
453             flags |= DEXOPT_IS_BOOTSTRAP;
454         if (gDvm.generateRegisterMaps)
455             flags |= DEXOPT_GEN_REGISTER_MAPS;
456         sprintf(values[9], "%d", flags);
457         argv[curArg++] = values[9];
458 
459         assert(((!kUseValgrind && curArg == kFixedArgCount) ||
460                ((kUseValgrind && curArg == kFixedArgCount+kValgrindArgCount))));
461 
462         ClassPathEntry* cpe;
463         for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
464             argv[curArg++] = cpe->fileName;
465         }
466         assert(curArg == argc);
467 
468         argv[curArg] = NULL;
469 
470         if (kUseValgrind)
471             execv(kValgrinder, const_cast<char**>(argv));
472         else
473             execv(execFile, const_cast<char**>(argv));
474 
475         LOGE("execv '%s'%s failed: %s", execFile,
476             kUseValgrind ? " [valgrind]" : "", strerror(errno));
477         exit(1);
478     } else {
479         LOGV("DexOpt: waiting for verify+opt, pid=%d", (int) pid);
480         int status;
481         pid_t gotPid;
482 
483         /*
484          * Wait for the optimization process to finish.  We go into VMWAIT
485          * mode here so GC suspension won't have to wait for us.
486          */
487         ThreadStatus oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
488         while (true) {
489             gotPid = waitpid(pid, &status, 0);
490             if (gotPid == -1 && errno == EINTR) {
491                 LOGD("waitpid interrupted, retrying");
492             } else {
493                 break;
494             }
495         }
496         dvmChangeStatus(NULL, oldStatus);
497         if (gotPid != pid) {
498             LOGE("waitpid failed: wanted %d, got %d: %s",
499                 (int) pid, (int) gotPid, strerror(errno));
500             return false;
501         }
502 
503         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
504             LOGD("DexOpt: --- END '%s' (success) ---", lastPart);
505             return true;
506         } else {
507             LOGW("DexOpt: --- END '%s' --- status=0x%04x, process failed",
508                 lastPart, status);
509             return false;
510         }
511     }
512 }
513 
514 /*
515  * Do the actual optimization.  This is executed in the dexopt process.
516  *
517  * For best use of disk/memory, we want to extract once and perform
518  * optimizations in place.  If the file has to expand or contract
519  * to match local structure padding/alignment expectations, we want
520  * to do the rewrite as part of the extract, rather than extracting
521  * into a temp file and slurping it back out.  (The structure alignment
522  * is currently correct for all platforms, and this isn't expected to
523  * change, so we should be okay with having it already extracted.)
524  *
525  * Returns "true" on success.
526  */
dvmContinueOptimization(int fd,off_t dexOffset,long dexLength,const char * fileName,u4 modWhen,u4 crc,bool isBootstrap)527 bool dvmContinueOptimization(int fd, off_t dexOffset, long dexLength,
528     const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
529 {
530     DexClassLookup* pClassLookup = NULL;
531     RegisterMapBuilder* pRegMapBuilder = NULL;
532 
533     assert(gDvm.optimizing);
534 
535     LOGV("Continuing optimization (%s, isb=%d)", fileName, isBootstrap);
536 
537     assert(dexOffset >= 0);
538 
539     /* quick test so we don't blow up on empty file */
540     if (dexLength < (int) sizeof(DexHeader)) {
541         LOGE("too small to be DEX");
542         return false;
543     }
544     if (dexOffset < (int) sizeof(DexOptHeader)) {
545         LOGE("not enough room for opt header");
546         return false;
547     }
548 
549     bool result = false;
550 
551     /*
552      * Drop this into a global so we don't have to pass it around.  We could
553      * also add a field to DexFile, but since it only pertains to DEX
554      * creation that probably doesn't make sense.
555      */
556     gDvm.optimizingBootstrapClass = isBootstrap;
557 
558     {
559         /*
560          * Map the entire file (so we don't have to worry about page
561          * alignment).  The expectation is that the output file contains
562          * our DEX data plus room for a small header.
563          */
564         bool success;
565         void* mapAddr;
566         mapAddr = mmap(NULL, dexOffset + dexLength, PROT_READ|PROT_WRITE,
567                     MAP_SHARED, fd, 0);
568         if (mapAddr == MAP_FAILED) {
569             LOGE("unable to mmap DEX cache: %s", strerror(errno));
570             goto bail;
571         }
572 
573         bool doVerify, doOpt;
574         if (gDvm.classVerifyMode == VERIFY_MODE_NONE) {
575             doVerify = false;
576         } else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE) {
577             doVerify = !gDvm.optimizingBootstrapClass;
578         } else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/ {
579             doVerify = true;
580         }
581 
582         if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE) {
583             doOpt = false;
584         } else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED ||
585                    gDvm.dexOptMode == OPTIMIZE_MODE_FULL) {
586             doOpt = doVerify;
587         } else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/ {
588             doOpt = true;
589         }
590 
591         /*
592          * Rewrite the file.  Byte reordering, structure realigning,
593          * class verification, and bytecode optimization are all performed
594          * here.
595          *
596          * In theory the file could change size and bits could shift around.
597          * In practice this would be annoying to deal with, so the file
598          * layout is designed so that it can always be rewritten in place.
599          *
600          * This creates the class lookup table as part of doing the processing.
601          */
602         success = rewriteDex(((u1*) mapAddr) + dexOffset, dexLength,
603                     doVerify, doOpt, &pClassLookup, NULL);
604 
605         if (success) {
606             DvmDex* pDvmDex = NULL;
607             u1* dexAddr = ((u1*) mapAddr) + dexOffset;
608 
609             if (dvmDexFileOpenPartial(dexAddr, dexLength, &pDvmDex) != 0) {
610                 LOGE("Unable to create DexFile");
611                 success = false;
612             } else {
613                 /*
614                  * If configured to do so, generate register map output
615                  * for all verified classes.  The register maps were
616                  * generated during verification, and will now be serialized.
617                  */
618                 if (gDvm.generateRegisterMaps) {
619                     pRegMapBuilder = dvmGenerateRegisterMaps(pDvmDex);
620                     if (pRegMapBuilder == NULL) {
621                         LOGE("Failed generating register maps");
622                         success = false;
623                     }
624                 }
625 
626                 DexHeader* pHeader = (DexHeader*)pDvmDex->pHeader;
627                 updateChecksum(dexAddr, dexLength, pHeader);
628 
629                 dvmDexFileFree(pDvmDex);
630             }
631         }
632 
633         /* unmap the read-write version, forcing writes to disk */
634         if (msync(mapAddr, dexOffset + dexLength, MS_SYNC) != 0) {
635             LOGW("msync failed: %s", strerror(errno));
636             // weird, but keep going
637         }
638 #if 1
639         /*
640          * This causes clean shutdown to fail, because we have loaded classes
641          * that point into it.  For the optimizer this isn't a problem,
642          * because it's more efficient for the process to simply exit.
643          * Exclude this code when doing clean shutdown for valgrind.
644          */
645         if (munmap(mapAddr, dexOffset + dexLength) != 0) {
646             LOGE("munmap failed: %s", strerror(errno));
647             goto bail;
648         }
649 #endif
650 
651         if (!success)
652             goto bail;
653     }
654 
655     /* get start offset, and adjust deps start for 64-bit alignment */
656     off_t depsOffset, optOffset, endOffset, adjOffset;
657     int depsLength, optLength;
658     u4 optChecksum;
659 
660     depsOffset = lseek(fd, 0, SEEK_END);
661     if (depsOffset < 0) {
662         LOGE("lseek to EOF failed: %s", strerror(errno));
663         goto bail;
664     }
665     adjOffset = (depsOffset + 7) & ~(0x07);
666     if (adjOffset != depsOffset) {
667         LOGV("Adjusting deps start from %d to %d",
668             (int) depsOffset, (int) adjOffset);
669         depsOffset = adjOffset;
670         lseek(fd, depsOffset, SEEK_SET);
671     }
672 
673     /*
674      * Append the dependency list.
675      */
676     if (writeDependencies(fd, modWhen, crc) != 0) {
677         LOGW("Failed writing dependencies");
678         goto bail;
679     }
680 
681     /* compute deps length, then adjust opt start for 64-bit alignment */
682     optOffset = lseek(fd, 0, SEEK_END);
683     depsLength = optOffset - depsOffset;
684 
685     adjOffset = (optOffset + 7) & ~(0x07);
686     if (adjOffset != optOffset) {
687         LOGV("Adjusting opt start from %d to %d",
688             (int) optOffset, (int) adjOffset);
689         optOffset = adjOffset;
690         lseek(fd, optOffset, SEEK_SET);
691     }
692 
693     /*
694      * Append any optimized pre-computed data structures.
695      */
696     if (!writeOptData(fd, pClassLookup, pRegMapBuilder)) {
697         LOGW("Failed writing opt data");
698         goto bail;
699     }
700 
701     endOffset = lseek(fd, 0, SEEK_END);
702     optLength = endOffset - optOffset;
703 
704     /* compute checksum from start of deps to end of opt area */
705     if (!computeFileChecksum(fd, depsOffset,
706             (optOffset+optLength) - depsOffset, &optChecksum))
707     {
708         goto bail;
709     }
710 
711     /*
712      * Output the "opt" header with all values filled in and a correct
713      * magic number.
714      */
715     DexOptHeader optHdr;
716     memset(&optHdr, 0xff, sizeof(optHdr));
717     memcpy(optHdr.magic, DEX_OPT_MAGIC, 4);
718     memcpy(optHdr.magic+4, DEX_OPT_MAGIC_VERS, 4);
719     optHdr.dexOffset = (u4) dexOffset;
720     optHdr.dexLength = (u4) dexLength;
721     optHdr.depsOffset = (u4) depsOffset;
722     optHdr.depsLength = (u4) depsLength;
723     optHdr.optOffset = (u4) optOffset;
724     optHdr.optLength = (u4) optLength;
725 #if __BYTE_ORDER != __LITTLE_ENDIAN
726     optHdr.flags = DEX_OPT_FLAG_BIG;
727 #else
728     optHdr.flags = 0;
729 #endif
730     optHdr.checksum = optChecksum;
731 
732     fsync(fd);      /* ensure previous writes go before header is written */
733 
734     lseek(fd, 0, SEEK_SET);
735     if (sysWriteFully(fd, &optHdr, sizeof(optHdr), "DexOpt opt header") != 0)
736         goto bail;
737 
738     LOGV("Successfully wrote DEX header");
739     result = true;
740 
741     //dvmRegisterMapDumpStats();
742 
743 bail:
744     dvmFreeRegisterMapBuilder(pRegMapBuilder);
745     free(pClassLookup);
746     return result;
747 }
748 
749 /*
750  * Prepare an in-memory DEX file.
751  *
752  * The data was presented to the VM as a byte array rather than a file.
753  * We want to do the same basic set of operations, but we can just leave
754  * them in memory instead of writing them out to a cached optimized DEX file.
755  */
dvmPrepareDexInMemory(u1 * addr,size_t len,DvmDex ** ppDvmDex)756 bool dvmPrepareDexInMemory(u1* addr, size_t len, DvmDex** ppDvmDex)
757 {
758     DexClassLookup* pClassLookup = NULL;
759 
760     /*
761      * Byte-swap, realign, verify basic DEX file structure.
762      *
763      * We could load + verify + optimize here as well, but that's probably
764      * not desirable.
765      *
766      * (The bulk-verification code is currently only setting the DEX
767      * file's "verified" flag, not updating the ClassObject.  This would
768      * also need to be changed, or we will try to verify the class twice,
769      * and possibly reject it when optimized opcodes are encountered.)
770      */
771     if (!rewriteDex(addr, len, false, false, &pClassLookup, ppDvmDex)) {
772         return false;
773     }
774 
775     (*ppDvmDex)->pDexFile->pClassLookup = pClassLookup;
776 
777     return true;
778 }
779 
780 /*
781  * Perform in-place rewrites on a memory-mapped DEX file.
782  *
783  * If this is called from a short-lived child process (dexopt), we can
784  * go nutty with loading classes and allocating memory.  When it's
785  * called to prepare classes provided in a byte array, we may want to
786  * be more conservative.
787  *
788  * If "ppClassLookup" is non-NULL, a pointer to a newly-allocated
789  * DexClassLookup will be returned on success.
790  *
791  * If "ppDvmDex" is non-NULL, a newly-allocated DvmDex struct will be
792  * returned on success.
793  */
rewriteDex(u1 * addr,int len,bool doVerify,bool doOpt,DexClassLookup ** ppClassLookup,DvmDex ** ppDvmDex)794 static bool rewriteDex(u1* addr, int len, bool doVerify, bool doOpt,
795     DexClassLookup** ppClassLookup, DvmDex** ppDvmDex)
796 {
797     DexClassLookup* pClassLookup = NULL;
798     u8 prepWhen, loadWhen, verifyOptWhen;
799     DvmDex* pDvmDex = NULL;
800     bool result = false;
801     const char* msgStr = "???";
802 
803     /* if the DEX is in the wrong byte order, swap it now */
804     if (dexSwapAndVerify(addr, len) != 0)
805         goto bail;
806 
807     /*
808      * Now that the DEX file can be read directly, create a DexFile struct
809      * for it.
810      */
811     if (dvmDexFileOpenPartial(addr, len, &pDvmDex) != 0) {
812         LOGE("Unable to create DexFile");
813         goto bail;
814     }
815 
816     /*
817      * Create the class lookup table.  This will eventually be appended
818      * to the end of the .odex.
819      *
820      * We create a temporary link from the DexFile for the benefit of
821      * class loading, below.
822      */
823     pClassLookup = dexCreateClassLookup(pDvmDex->pDexFile);
824     if (pClassLookup == NULL)
825         goto bail;
826     pDvmDex->pDexFile->pClassLookup = pClassLookup;
827 
828     /*
829      * If we're not going to attempt to verify or optimize the classes,
830      * there's no value in loading them, so bail out early.
831      */
832     if (!doVerify && !doOpt) {
833         result = true;
834         goto bail;
835     }
836 
837     prepWhen = dvmGetRelativeTimeUsec();
838 
839     /*
840      * Load all classes found in this DEX file.  If they fail to load for
841      * some reason, they won't get verified (which is as it should be).
842      */
843     if (!loadAllClasses(pDvmDex))
844         goto bail;
845     loadWhen = dvmGetRelativeTimeUsec();
846 
847     /*
848      * Create a data structure for use by the bytecode optimizer.
849      * We need to look up methods in a few classes, so this may cause
850      * a bit of class loading.  We usually do this during VM init, but
851      * for dexopt on core.jar the order of operations gets a bit tricky,
852      * so we defer it to here.
853      */
854     if (!dvmCreateInlineSubsTable())
855         goto bail;
856 
857     /*
858      * Verify and optimize all classes in the DEX file (command-line
859      * options permitting).
860      *
861      * This is best-effort, so there's really no way for dexopt to
862      * fail at this point.
863      */
864     verifyAndOptimizeClasses(pDvmDex->pDexFile, doVerify, doOpt);
865     verifyOptWhen = dvmGetRelativeTimeUsec();
866 
867     if (doVerify && doOpt)
868         msgStr = "verify+opt";
869     else if (doVerify)
870         msgStr = "verify";
871     else if (doOpt)
872         msgStr = "opt";
873     LOGD("DexOpt: load %dms, %s %dms",
874         (int) (loadWhen - prepWhen) / 1000,
875         msgStr,
876         (int) (verifyOptWhen - loadWhen) / 1000);
877 
878     result = true;
879 
880 bail:
881     /*
882      * On success, return the pieces that the caller asked for.
883      */
884 
885     if (pDvmDex != NULL) {
886         /* break link between the two */
887         pDvmDex->pDexFile->pClassLookup = NULL;
888     }
889 
890     if (ppDvmDex == NULL || !result) {
891         dvmDexFileFree(pDvmDex);
892     } else {
893         *ppDvmDex = pDvmDex;
894     }
895 
896     if (ppClassLookup == NULL || !result) {
897         free(pClassLookup);
898     } else {
899         *ppClassLookup = pClassLookup;
900     }
901 
902     return result;
903 }
904 
905 /*
906  * Try to load all classes in the specified DEX.  If they have some sort
907  * of broken dependency, e.g. their superclass lives in a different DEX
908  * that wasn't previously loaded into the bootstrap class path, loading
909  * will fail.  This is the desired behavior.
910  *
911  * We have no notion of class loader at this point, so we load all of
912  * the classes with the bootstrap class loader.  It turns out this has
913  * exactly the behavior we want, and has no ill side effects because we're
914  * running in a separate process and anything we load here will be forgotten.
915  *
916  * We set the CLASS_MULTIPLE_DEFS flag here if we see multiple definitions.
917  * This works because we only call here as part of optimization / pre-verify,
918  * not during verification as part of loading a class into a running VM.
919  *
920  * This returns "false" if the world is too screwed up to do anything
921  * useful at all.
922  */
loadAllClasses(DvmDex * pDvmDex)923 static bool loadAllClasses(DvmDex* pDvmDex)
924 {
925     u4 count = pDvmDex->pDexFile->pHeader->classDefsSize;
926     u4 idx;
927     int loaded = 0;
928 
929     LOGV("DexOpt: +++ trying to load %d classes", count);
930 
931     dvmSetBootPathExtraDex(pDvmDex);
932 
933     /*
934      * At this point, it is safe -- and necessary! -- to look up the
935      * VM's required classes and members, even when what we are in the
936      * process of processing is the core library that defines these
937      * classes itself. (The reason it is necessary is that in the act
938      * of initializing the class Class, below, the system will end up
939      * referring to many of the class references that got set up by
940      * this call.)
941      */
942     if (!dvmFindRequiredClassesAndMembers()) {
943         return false;
944     }
945 
946     /*
947      * We have some circularity issues with Class and Object that are
948      * most easily avoided by ensuring that Object is never the first
949      * thing we try to find-and-initialize. The call to
950      * dvmFindSystemClass() here takes care of that situation. (We
951      * only need to do this when loading classes from the DEX file
952      * that contains Object, and only when Object comes first in the
953      * list, but it costs very little to do it in all cases.)
954      */
955     if (!dvmInitClass(gDvm.classJavaLangClass)) {
956         LOGE("ERROR: failed to initialize the class Class!");
957         return false;
958     }
959 
960     for (idx = 0; idx < count; idx++) {
961         const DexClassDef* pClassDef;
962         const char* classDescriptor;
963         ClassObject* newClass;
964 
965         pClassDef = dexGetClassDef(pDvmDex->pDexFile, idx);
966         classDescriptor =
967             dexStringByTypeIdx(pDvmDex->pDexFile, pClassDef->classIdx);
968 
969         LOGV("+++  loading '%s'", classDescriptor);
970         //newClass = dvmDefineClass(pDexFile, classDescriptor,
971         //        NULL);
972         newClass = dvmFindSystemClassNoInit(classDescriptor);
973         if (newClass == NULL) {
974             LOGV("DexOpt: failed loading '%s'", classDescriptor);
975             dvmClearOptException(dvmThreadSelf());
976         } else if (newClass->pDvmDex != pDvmDex) {
977             /*
978              * We don't load the new one, and we tag the first one found
979              * with the "multiple def" flag so the resolver doesn't try
980              * to make it available.
981              */
982             LOGD("DexOpt: '%s' has an earlier definition; blocking out",
983                 classDescriptor);
984             SET_CLASS_FLAG(newClass, CLASS_MULTIPLE_DEFS);
985         } else {
986             loaded++;
987         }
988     }
989     LOGV("DexOpt: +++ successfully loaded %d classes", loaded);
990 
991     dvmSetBootPathExtraDex(NULL);
992     return true;
993 }
994 
995 /*
996  * Verify and/or optimize all classes that were successfully loaded from
997  * this DEX file.
998  */
verifyAndOptimizeClasses(DexFile * pDexFile,bool doVerify,bool doOpt)999 static void verifyAndOptimizeClasses(DexFile* pDexFile, bool doVerify,
1000     bool doOpt)
1001 {
1002     u4 count = pDexFile->pHeader->classDefsSize;
1003     u4 idx;
1004 
1005     for (idx = 0; idx < count; idx++) {
1006         const DexClassDef* pClassDef;
1007         const char* classDescriptor;
1008         ClassObject* clazz;
1009 
1010         pClassDef = dexGetClassDef(pDexFile, idx);
1011         classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
1012 
1013         /* all classes are loaded into the bootstrap class loader */
1014         clazz = dvmLookupClass(classDescriptor, NULL, false);
1015         if (clazz != NULL) {
1016             verifyAndOptimizeClass(pDexFile, clazz, pClassDef, doVerify, doOpt);
1017 
1018         } else {
1019             // TODO: log when in verbose mode
1020             LOGV("DexOpt: not optimizing unavailable class '%s'",
1021                 classDescriptor);
1022         }
1023     }
1024 
1025 #ifdef VERIFIER_STATS
1026     LOGI("Verifier stats:");
1027     LOGI(" methods examined        : %u", gDvm.verifierStats.methodsExamined);
1028     LOGI(" monitor-enter methods   : %u", gDvm.verifierStats.monEnterMethods);
1029     LOGI(" instructions examined   : %u", gDvm.verifierStats.instrsExamined);
1030     LOGI(" instructions re-examined: %u", gDvm.verifierStats.instrsReexamined);
1031     LOGI(" copying of register sets: %u", gDvm.verifierStats.copyRegCount);
1032     LOGI(" merging of register sets: %u", gDvm.verifierStats.mergeRegCount);
1033     LOGI(" ...that caused changes  : %u", gDvm.verifierStats.mergeRegChanged);
1034     LOGI(" uninit searches         : %u", gDvm.verifierStats.uninitSearches);
1035     LOGI(" max memory required     : %u", gDvm.verifierStats.biggestAlloc);
1036 #endif
1037 }
1038 
1039 /*
1040  * Verify and/or optimize a specific class.
1041  */
verifyAndOptimizeClass(DexFile * pDexFile,ClassObject * clazz,const DexClassDef * pClassDef,bool doVerify,bool doOpt)1042 static void verifyAndOptimizeClass(DexFile* pDexFile, ClassObject* clazz,
1043     const DexClassDef* pClassDef, bool doVerify, bool doOpt)
1044 {
1045     const char* classDescriptor;
1046     bool verified = false;
1047 
1048     if (clazz->pDvmDex->pDexFile != pDexFile) {
1049         /*
1050          * The current DEX file defined a class that is also present in the
1051          * bootstrap class path.  The class loader favored the bootstrap
1052          * version, which means that we have a pointer to a class that is
1053          * (a) not the one we want to examine, and (b) mapped read-only,
1054          * so we will seg fault if we try to rewrite instructions inside it.
1055          */
1056         LOGD("DexOpt: not verifying/optimizing '%s': multiple definitions",
1057             clazz->descriptor);
1058         return;
1059     }
1060 
1061     classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
1062 
1063     /*
1064      * First, try to verify it.
1065      */
1066     if (doVerify) {
1067         if (dvmVerifyClass(clazz)) {
1068             /*
1069              * Set the "is preverified" flag in the DexClassDef.  We
1070              * do it here, rather than in the ClassObject structure,
1071              * because the DexClassDef is part of the odex file.
1072              */
1073             assert((clazz->accessFlags & JAVA_FLAGS_MASK) ==
1074                 pClassDef->accessFlags);
1075             ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISPREVERIFIED;
1076             verified = true;
1077         } else {
1078             // TODO: log when in verbose mode
1079             LOGV("DexOpt: '%s' failed verification", classDescriptor);
1080         }
1081     }
1082 
1083     if (doOpt) {
1084         bool needVerify = (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED ||
1085                            gDvm.dexOptMode == OPTIMIZE_MODE_FULL);
1086         if (!verified && needVerify) {
1087             LOGV("DexOpt: not optimizing '%s': not verified",
1088                 classDescriptor);
1089         } else {
1090             dvmOptimizeClass(clazz, false);
1091 
1092             /* set the flag whether or not we actually changed anything */
1093             ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISOPTIMIZED;
1094         }
1095     }
1096 }
1097 
1098 
1099 /*
1100  * Get the cache file name from a ClassPathEntry.
1101  */
getCacheFileName(const ClassPathEntry * cpe)1102 static const char* getCacheFileName(const ClassPathEntry* cpe)
1103 {
1104     switch (cpe->kind) {
1105     case kCpeJar:
1106         return dvmGetJarFileCacheFileName((JarFile*) cpe->ptr);
1107     case kCpeDex:
1108         return dvmGetRawDexFileCacheFileName((RawDexFile*) cpe->ptr);
1109     default:
1110         LOGE("DexOpt: unexpected cpe kind %d", cpe->kind);
1111         dvmAbort();
1112         return NULL;
1113     }
1114 }
1115 
1116 /*
1117  * Get the SHA-1 signature.
1118  */
getSignature(const ClassPathEntry * cpe)1119 static const u1* getSignature(const ClassPathEntry* cpe)
1120 {
1121     DvmDex* pDvmDex;
1122 
1123     switch (cpe->kind) {
1124     case kCpeJar:
1125         pDvmDex = dvmGetJarFileDex((JarFile*) cpe->ptr);
1126         break;
1127     case kCpeDex:
1128         pDvmDex = dvmGetRawDexFileDex((RawDexFile*) cpe->ptr);
1129         break;
1130     default:
1131         LOGE("unexpected cpe kind %d", cpe->kind);
1132         dvmAbort();
1133         pDvmDex = NULL;         // make gcc happy
1134     }
1135 
1136     assert(pDvmDex != NULL);
1137     return pDvmDex->pDexFile->pHeader->signature;
1138 }
1139 
1140 
1141 /*
1142  * Dependency layout:
1143  *  4b  Source file modification time, in seconds since 1970 UTC
1144  *  4b  CRC-32 from Zip entry, or Adler32 from source DEX header
1145  *  4b  Dalvik VM build number
1146  *  4b  Number of dependency entries that follow
1147  *  Dependency entries:
1148  *    4b  Name length (including terminating null)
1149  *    var Full path of cache entry (null terminated)
1150  *    20b SHA-1 signature from source DEX file
1151  *
1152  * If this changes, update DEX_OPT_MAGIC_VERS.
1153  */
1154 static const size_t kMinDepSize = 4 * 4;
1155 static const size_t kMaxDepSize = 4 * 4 + 2048;     // sanity check
1156 
1157 /*
1158  * Read the "opt" header, verify it, then read the dependencies section
1159  * and verify that data as well.
1160  *
1161  * If "sourceAvail" is "true", this will verify that "modWhen" and "crc"
1162  * match up with what is stored in the header.  If they don't, we reject
1163  * the file so that it can be recreated from the updated original.  If
1164  * "sourceAvail" isn't set, e.g. for a .odex file, we ignore these arguments.
1165  *
1166  * On successful return, the file will be seeked immediately past the
1167  * "opt" header.
1168  */
dvmCheckOptHeaderAndDependencies(int fd,bool sourceAvail,u4 modWhen,u4 crc,bool expectVerify,bool expectOpt)1169 bool dvmCheckOptHeaderAndDependencies(int fd, bool sourceAvail, u4 modWhen,
1170     u4 crc, bool expectVerify, bool expectOpt)
1171 {
1172     DexOptHeader optHdr;
1173     u1* depData = NULL;
1174     const u1* magic;
1175     off_t posn;
1176     int result = false;
1177     ssize_t actual;
1178 
1179     /*
1180      * Start at the start.  The "opt" header, when present, will always be
1181      * the first thing in the file.
1182      */
1183     if (lseek(fd, 0, SEEK_SET) != 0) {
1184         LOGE("DexOpt: failed to seek to start of file: %s", strerror(errno));
1185         goto bail;
1186     }
1187 
1188     /*
1189      * Read and do trivial verification on the opt header.  The header is
1190      * always in host byte order.
1191      */
1192     actual = read(fd, &optHdr, sizeof(optHdr));
1193     if (actual < 0) {
1194         LOGE("DexOpt: failed reading opt header: %s", strerror(errno));
1195         goto bail;
1196     } else if (actual != sizeof(optHdr)) {
1197         LOGE("DexOpt: failed reading opt header (got %d of %zd)",
1198             (int) actual, sizeof(optHdr));
1199         goto bail;
1200     }
1201 
1202     magic = optHdr.magic;
1203     if (memcmp(magic, DEX_MAGIC, 4) == 0) {
1204         /* somebody probably pointed us at the wrong file */
1205         LOGD("DexOpt: expected optimized DEX, found unoptimized");
1206         goto bail;
1207     } else if (memcmp(magic, DEX_OPT_MAGIC, 4) != 0) {
1208         /* not a DEX file, or previous attempt was interrupted */
1209         LOGD("DexOpt: incorrect opt magic number (0x%02x %02x %02x %02x)",
1210             magic[0], magic[1], magic[2], magic[3]);
1211         goto bail;
1212     }
1213     if (memcmp(magic+4, DEX_OPT_MAGIC_VERS, 4) != 0) {
1214         LOGW("DexOpt: stale opt version (0x%02x %02x %02x %02x)",
1215             magic[4], magic[5], magic[6], magic[7]);
1216         goto bail;
1217     }
1218     if (optHdr.depsLength < kMinDepSize || optHdr.depsLength > kMaxDepSize) {
1219         LOGW("DexOpt: weird deps length %d, bailing", optHdr.depsLength);
1220         goto bail;
1221     }
1222 
1223     /*
1224      * Do the header flags match up with what we want?
1225      *
1226      * The only thing we really can't handle is incorrect byte ordering.
1227      */
1228     {
1229         const u4 matchMask = DEX_OPT_FLAG_BIG;
1230         u4 expectedFlags = 0;
1231 #if __BYTE_ORDER != __LITTLE_ENDIAN
1232         expectedFlags |= DEX_OPT_FLAG_BIG;
1233 #endif
1234         if ((expectedFlags & matchMask) != (optHdr.flags & matchMask)) {
1235             LOGI("DexOpt: header flag mismatch (0x%02x vs 0x%02x, mask=0x%02x)",
1236                 expectedFlags, optHdr.flags, matchMask);
1237             goto bail;
1238         }
1239     }
1240 
1241     posn = lseek(fd, optHdr.depsOffset, SEEK_SET);
1242     if (posn < 0) {
1243         LOGW("DexOpt: seek to deps failed: %s", strerror(errno));
1244         goto bail;
1245     }
1246 
1247     /*
1248      * Read all of the dependency stuff into memory.
1249      */
1250     depData = (u1*) malloc(optHdr.depsLength);
1251     if (depData == NULL) {
1252         LOGW("DexOpt: unable to allocate %d bytes for deps",
1253             optHdr.depsLength);
1254         goto bail;
1255     }
1256     actual = read(fd, depData, optHdr.depsLength);
1257     if (actual < 0) {
1258         LOGW("DexOpt: failed reading deps: %s", strerror(errno));
1259         goto bail;
1260     } else if (actual != (ssize_t) optHdr.depsLength) {
1261         LOGW("DexOpt: failed reading deps: got %d of %d",
1262             (int) actual, optHdr.depsLength);
1263         goto bail;
1264     }
1265 
1266     /*
1267      * Verify simple items.
1268      */
1269     const u1* ptr;
1270     u4 val;
1271 
1272     ptr = depData;
1273     val = read4LE(&ptr);
1274     if (sourceAvail && val != modWhen) {
1275         LOGI("DexOpt: source file mod time mismatch (%08x vs %08x)",
1276             val, modWhen);
1277         goto bail;
1278     }
1279     val = read4LE(&ptr);
1280     if (sourceAvail && val != crc) {
1281         LOGI("DexOpt: source file CRC mismatch (%08x vs %08x)", val, crc);
1282         goto bail;
1283     }
1284     val = read4LE(&ptr);
1285     if (val != DALVIK_VM_BUILD) {
1286         LOGD("DexOpt: VM build version mismatch (%d vs %d)",
1287             val, DALVIK_VM_BUILD);
1288         goto bail;
1289     }
1290 
1291     /*
1292      * Verify dependencies on other cached DEX files.  It must match
1293      * exactly with what is currently defined in the bootclasspath.
1294      */
1295     ClassPathEntry* cpe;
1296     u4 numDeps;
1297 
1298     numDeps = read4LE(&ptr);
1299     LOGV("+++ DexOpt: numDeps = %d", numDeps);
1300     for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1301         const char* cacheFileName =
1302             dvmPathToAbsolutePortion(getCacheFileName(cpe));
1303         assert(cacheFileName != NULL); /* guaranteed by Class.c */
1304 
1305         const u1* signature = getSignature(cpe);
1306         size_t len = strlen(cacheFileName) +1;
1307         u4 storedStrLen;
1308 
1309         if (numDeps == 0) {
1310             /* more entries in bootclasspath than in deps list */
1311             LOGI("DexOpt: not all deps represented");
1312             goto bail;
1313         }
1314 
1315         storedStrLen = read4LE(&ptr);
1316         if (len != storedStrLen ||
1317             strcmp(cacheFileName, (const char*) ptr) != 0)
1318         {
1319             LOGI("DexOpt: mismatch dep name: '%s' vs. '%s'",
1320                 cacheFileName, ptr);
1321             goto bail;
1322         }
1323 
1324         ptr += storedStrLen;
1325 
1326         if (memcmp(signature, ptr, kSHA1DigestLen) != 0) {
1327             LOGI("DexOpt: mismatch dep signature for '%s'", cacheFileName);
1328             goto bail;
1329         }
1330         ptr += kSHA1DigestLen;
1331 
1332         LOGV("DexOpt: dep match on '%s'", cacheFileName);
1333 
1334         numDeps--;
1335     }
1336 
1337     if (numDeps != 0) {
1338         /* more entries in deps list than in classpath */
1339         LOGI("DexOpt: Some deps went away");
1340         goto bail;
1341     }
1342 
1343     // consumed all data and no more?
1344     if (ptr != depData + optHdr.depsLength) {
1345         LOGW("DexOpt: Spurious dep data? %d vs %d",
1346             (int) (ptr - depData), optHdr.depsLength);
1347         assert(false);
1348     }
1349 
1350     result = true;
1351 
1352 bail:
1353     free(depData);
1354     return result;
1355 }
1356 
1357 /*
1358  * Write the dependency info to "fd" at the current file position.
1359  */
writeDependencies(int fd,u4 modWhen,u4 crc)1360 static int writeDependencies(int fd, u4 modWhen, u4 crc)
1361 {
1362     u1* buf = NULL;
1363     int result = -1;
1364     ssize_t bufLen;
1365     ClassPathEntry* cpe;
1366     int numDeps;
1367 
1368     /*
1369      * Count up the number of completed entries in the bootclasspath.
1370      */
1371     numDeps = 0;
1372     bufLen = 0;
1373     for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1374         const char* cacheFileName =
1375             dvmPathToAbsolutePortion(getCacheFileName(cpe));
1376         assert(cacheFileName != NULL); /* guaranteed by Class.c */
1377 
1378         LOGV("+++ DexOpt: found dep '%s'", cacheFileName);
1379 
1380         numDeps++;
1381         bufLen += strlen(cacheFileName) +1;
1382     }
1383 
1384     bufLen += 4*4 + numDeps * (4+kSHA1DigestLen);
1385 
1386     buf = (u1*)malloc(bufLen);
1387 
1388     set4LE(buf+0, modWhen);
1389     set4LE(buf+4, crc);
1390     set4LE(buf+8, DALVIK_VM_BUILD);
1391     set4LE(buf+12, numDeps);
1392 
1393     // TODO: do we want to add dvmGetInlineOpsTableLength() here?  Won't
1394     // help us if somebody replaces an existing entry, but it'd catch
1395     // additions/removals.
1396 
1397     u1* ptr = buf + 4*4;
1398     for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1399         const char* cacheFileName =
1400             dvmPathToAbsolutePortion(getCacheFileName(cpe));
1401         assert(cacheFileName != NULL); /* guaranteed by Class.c */
1402 
1403         const u1* signature = getSignature(cpe);
1404         int len = strlen(cacheFileName) +1;
1405 
1406         if (ptr + 4 + len + kSHA1DigestLen > buf + bufLen) {
1407             LOGE("DexOpt: overran buffer");
1408             dvmAbort();
1409         }
1410 
1411         set4LE(ptr, len);
1412         ptr += 4;
1413         memcpy(ptr, cacheFileName, len);
1414         ptr += len;
1415         memcpy(ptr, signature, kSHA1DigestLen);
1416         ptr += kSHA1DigestLen;
1417     }
1418 
1419     assert(ptr == buf + bufLen);
1420 
1421     result = sysWriteFully(fd, buf, bufLen, "DexOpt dep info");
1422 
1423     free(buf);
1424     return result;
1425 }
1426 
1427 
1428 /*
1429  * Write a block of data in "chunk" format.
1430  *
1431  * The chunk header fields are always in "native" byte order.  If "size"
1432  * is not a multiple of 8 bytes, the data area is padded out.
1433  */
writeChunk(int fd,u4 type,const void * data,size_t size)1434 static bool writeChunk(int fd, u4 type, const void* data, size_t size)
1435 {
1436     union {             /* save a syscall by grouping these together */
1437         char raw[8];
1438         struct {
1439             u4 type;
1440             u4 size;
1441         } ts;
1442     } header;
1443 
1444     assert(sizeof(header) == 8);
1445 
1446     LOGV("Writing chunk, type=%.4s size=%d", (char*) &type, size);
1447 
1448     header.ts.type = type;
1449     header.ts.size = (u4) size;
1450     if (sysWriteFully(fd, &header, sizeof(header),
1451             "DexOpt opt chunk header write") != 0)
1452     {
1453         return false;
1454     }
1455 
1456     if (size > 0) {
1457         if (sysWriteFully(fd, data, size, "DexOpt opt chunk write") != 0)
1458             return false;
1459     }
1460 
1461     /* if necessary, pad to 64-bit alignment */
1462     if ((size & 7) != 0) {
1463         int padSize = 8 - (size & 7);
1464         LOGV("size was %d, inserting %d pad bytes", size, padSize);
1465         lseek(fd, padSize, SEEK_CUR);
1466     }
1467 
1468     assert( ((int)lseek(fd, 0, SEEK_CUR) & 7) == 0);
1469 
1470     return true;
1471 }
1472 
1473 /*
1474  * Write opt data.
1475  *
1476  * We have different pieces, some of which may be optional.  To make the
1477  * most effective use of space, we use a "chunk" format, with a 4-byte
1478  * type and a 4-byte length.  We guarantee 64-bit alignment for the data,
1479  * so it can be used directly when the file is mapped for reading.
1480  */
writeOptData(int fd,const DexClassLookup * pClassLookup,const RegisterMapBuilder * pRegMapBuilder)1481 static bool writeOptData(int fd, const DexClassLookup* pClassLookup,
1482     const RegisterMapBuilder* pRegMapBuilder)
1483 {
1484     /* pre-computed class lookup hash table */
1485     if (!writeChunk(fd, (u4) kDexChunkClassLookup,
1486             pClassLookup, pClassLookup->size))
1487     {
1488         return false;
1489     }
1490 
1491     /* register maps (optional) */
1492     if (pRegMapBuilder != NULL) {
1493         if (!writeChunk(fd, (u4) kDexChunkRegisterMaps,
1494                 pRegMapBuilder->data, pRegMapBuilder->size))
1495         {
1496             return false;
1497         }
1498     }
1499 
1500     /* write the end marker */
1501     if (!writeChunk(fd, (u4) kDexChunkEnd, NULL, 0)) {
1502         return false;
1503     }
1504 
1505     return true;
1506 }
1507 
1508 /*
1509  * Compute a checksum on a piece of an open file.
1510  *
1511  * File will be positioned at end of checksummed area.
1512  *
1513  * Returns "true" on success.
1514  */
computeFileChecksum(int fd,off_t start,size_t length,u4 * pSum)1515 static bool computeFileChecksum(int fd, off_t start, size_t length, u4* pSum)
1516 {
1517     unsigned char readBuf[8192];
1518     ssize_t actual;
1519     uLong adler;
1520 
1521     if (lseek(fd, start, SEEK_SET) != start) {
1522         LOGE("Unable to seek to start of checksum area (%ld): %s",
1523             (long) start, strerror(errno));
1524         return false;
1525     }
1526 
1527     adler = adler32(0L, Z_NULL, 0);
1528 
1529     while (length != 0) {
1530         size_t wanted = (length < sizeof(readBuf)) ? length : sizeof(readBuf);
1531         actual = read(fd, readBuf, wanted);
1532         if (actual <= 0) {
1533             LOGE("Read failed (%d) while computing checksum (len=%zu): %s",
1534                 (int) actual, length, strerror(errno));
1535             return false;
1536         }
1537 
1538         adler = adler32(adler, readBuf, actual);
1539 
1540         length -= actual;
1541     }
1542 
1543     *pSum = adler;
1544     return true;
1545 }
1546 
1547 /*
1548  * Update the Adler-32 checksum stored in the DEX file.  This covers the
1549  * swapped and optimized DEX data, but does not include the opt header
1550  * or optimized data.
1551  */
updateChecksum(u1 * addr,int len,DexHeader * pHeader)1552 static void updateChecksum(u1* addr, int len, DexHeader* pHeader)
1553 {
1554     /*
1555      * Rewrite the checksum.  We leave the SHA-1 signature alone.
1556      */
1557     uLong adler = adler32(0L, Z_NULL, 0);
1558     const int nonSum = sizeof(pHeader->magic) + sizeof(pHeader->checksum);
1559 
1560     adler = adler32(adler, addr + nonSum, len - nonSum);
1561     pHeader->checksum = adler;
1562 }
1563