OSDN Git Service

Fix debug statements.
[android-x86/dalvik.git] / vm / analysis / DexPrepare.c
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 <zlib.h>
33
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/file.h>
39 #include <sys/wait.h>
40 #include <fcntl.h>
41 #include <errno.h>
42
43
44 /* fwd */
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,
49     bool doOpt);
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);
57
58
59 /*
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.
64  *
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
70  * memory-mapped file.
71  *
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.
77  *
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.
81  */
82 int dvmOpenCachedDexFile(const char* fileName, const char* cacheFileName,
83     u4 modWhen, u4 crc, bool isBootstrap, bool* pNewFile, bool createIfMissing)
84 {
85     int fd, cc;
86     struct stat fdStat, fileStat;
87     bool readOnly = false;
88
89     *pNewFile = false;
90
91 retry:
92     /*
93      * Try to open the cache file.  If we've been asked to,
94      * create it if it doesn't exist.
95      */
96     fd = createIfMissing ? open(cacheFileName, O_CREAT|O_RDWR, 0644) : -1;
97     if (fd < 0) {
98         fd = open(cacheFileName, O_RDONLY, 0);
99         if (fd < 0) {
100             if (createIfMissing) {
101                 LOGE("Can't open dex cache '%s': %s\n",
102                     cacheFileName, strerror(errno));
103             }
104             return fd;
105         }
106         readOnly = true;
107     }
108
109     /*
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.
113      */
114     int oldStatus;
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);
119     if (cc != 0) {
120         LOGD("DexOpt: sleeping on flock(%s)\n", cacheFileName);
121         cc = flock(fd, LOCK_EX);
122     }
123     dvmChangeStatus(NULL, oldStatus);
124     if (cc != 0) {
125         LOGE("Can't lock dex cache '%s': %d\n", cacheFileName, cc);
126         close(fd);
127         return -1;
128     }
129     LOGV("DexOpt:  locked cache file\n");
130
131     /*
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.)
137      */
138     cc = fstat(fd, &fdStat);
139     if (cc != 0) {
140         LOGE("Can't stat open file '%s'\n", cacheFileName);
141         LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
142         goto close_fail;
143     }
144     cc = stat(cacheFileName, &fileStat);
145     if (cc != 0 ||
146         fdStat.st_dev != fileStat.st_dev || fdStat.st_ino != fileStat.st_ino)
147     {
148         LOGD("DexOpt: our open cache file is stale; sleeping and retrying\n");
149         LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
150         flock(fd, LOCK_UN);
151         close(fd);
152         usleep(250 * 1000);     /* if something is hosed, don't peg machine */
153         goto retry;
154     }
155
156     /*
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.
162      */
163     if (fdStat.st_size == 0) {
164         if (readOnly) {
165             LOGW("DexOpt: file has zero length and isn't writable\n");
166             goto close_fail;
167         }
168         cc = dexOptCreateEmptyHeader(fd);
169         if (cc != 0)
170             goto close_fail;
171         *pNewFile = true;
172         LOGV("DexOpt: successfully initialized new cache file\n");
173     } else {
174         bool expectVerify, expectOpt;
175
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)*/
181             expectVerify = true;
182
183         if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
184             expectOpt = false;
185         else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
186             expectOpt = expectVerify;
187         else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
188             expectOpt = true;
189
190         LOGV("checking deps, expecting vfy=%d opt=%d\n",
191             expectVerify, expectOpt);
192
193         if (!dvmCheckOptHeaderAndDependencies(fd, true, modWhen, crc,
194                 expectVerify, expectOpt))
195         {
196             if (readOnly) {
197                 /*
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,
201                  * give up now.
202                  */
203                 if (createIfMissing) {
204                     LOGW("Cached DEX '%s' (%s) is stale and not writable\n",
205                         fileName, cacheFileName);
206                 }
207                 goto close_fail;
208             }
209
210             /*
211              * If we truncate the existing file before unlinking it, any
212              * process that has it mapped will fail when it tries to touch
213              * the pages.
214              *
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.
223              *
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.
230              */
231             LOGD("ODEX file is stale or bad; removing and retrying (%s)\n",
232                 cacheFileName);
233             if (ftruncate(fd, 0) != 0) {
234                 LOGW("Warning: unable to truncate cache file '%s': %s\n",
235                     cacheFileName, strerror(errno));
236                 /* keep going */
237             }
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 */
242             }
243             LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
244             flock(fd, LOCK_UN);
245             close(fd);
246             goto retry;
247         } else {
248             LOGV("DexOpt: good deps in cache file\n");
249         }
250     }
251
252     assert(fd >= 0);
253     return fd;
254
255 close_fail:
256     flock(fd, LOCK_UN);
257     close(fd);
258     return -1;
259 }
260
261 /*
262  * Unlock the file descriptor.
263  *
264  * Returns "true" on success.
265  */
266 bool dvmUnlockCachedDexFile(int fd)
267 {
268     LOGVV("DexOpt: unlocking cache file fd=%d\n", fd);
269     return (flock(fd, LOCK_UN) == 0);
270 }
271
272
273 /*
274  * Given a descriptor for a file with DEX data in it, produce an
275  * optimized version.
276  *
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
279  * here.
280  *
281  * "fileName" is only used for debug output.  "modWhen" and "crc" are stored
282  * in the dependency set.
283  *
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.
290  *
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.
294  *
295  * Returns "true" on success.  All data will have been written to "fd".
296  */
297 bool dvmOptimizeDexFile(int fd, off_t dexOffset, long dexLength,
298     const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
299 {
300     const char* lastPart = strrchr(fileName, '/');
301     if (lastPart != NULL)
302         lastPart++;
303     else
304         lastPart = fileName;
305
306     LOGD("DexOpt: --- BEGIN '%s' (bootstrap=%d) ---\n", lastPart, isBootstrap);
307
308     pid_t pid;
309
310     /*
311      * This could happen if something in our bootclasspath, which we thought
312      * was all optimized, got rejected.
313      */
314     if (gDvm.optimizing) {
315         LOGW("Rejecting recursive optimization attempt on '%s'\n", fileName);
316         return false;
317     }
318
319     pid = fork();
320     if (pid == 0) {
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];
332         char* execFile;
333         char* androidRoot;
334         int flags;
335
336         /* change process groups, so we don't clash with ProcessManager */
337         setpgid(0, 0);
338
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";
344         }
345         execFile = malloc(strlen(androidRoot) + strlen(kDexOptBin) + 1);
346         strcpy(execFile, androidRoot);
347         strcat(execFile, kDexOptBin);
348
349         /*
350          * Create arg vector.
351          */
352         int curArg = 0;
353
354         if (kUseValgrind) {
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);
362         }
363         argv[curArg++] = execFile;
364
365         argv[curArg++] = "--dex";
366
367         sprintf(values[2], "%d", DALVIK_VM_BUILD);
368         argv[curArg++] = values[2];
369
370         sprintf(values[3], "%d", fd);
371         argv[curArg++] = values[3];
372
373         sprintf(values[4], "%d", (int) dexOffset);
374         argv[curArg++] = values[4];
375
376         sprintf(values[5], "%d", (int) dexLength);
377         argv[curArg++] = values[5];
378
379         argv[curArg++] = (char*)fileName;
380
381         sprintf(values[7], "%d", (int) modWhen);
382         argv[curArg++] = values[7];
383
384         sprintf(values[8], "%d", (int) crc);
385         argv[curArg++] = values[8];
386
387         flags = 0;
388         if (gDvm.dexOptMode != OPTIMIZE_MODE_NONE) {
389             flags |= DEXOPT_OPT_ENABLED;
390             if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)
391                 flags |= DEXOPT_OPT_ALL;
392         }
393         if (gDvm.classVerifyMode != VERIFY_MODE_NONE) {
394             flags |= DEXOPT_VERIFY_ENABLED;
395             if (gDvm.classVerifyMode == VERIFY_MODE_ALL)
396                 flags |= DEXOPT_VERIFY_ALL;
397         }
398         if (isBootstrap)
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];
404
405         assert(((!kUseValgrind && curArg == kFixedArgCount) ||
406                ((kUseValgrind && curArg == kFixedArgCount+kValgrindArgCount))));
407
408         ClassPathEntry* cpe;
409         for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
410             argv[curArg++] = cpe->fileName;
411         }
412         assert(curArg == argc);
413
414         argv[curArg] = NULL;
415
416         if (kUseValgrind)
417             execv(kValgrinder, argv);
418         else
419             execv(execFile, argv);
420
421         LOGE("execv '%s'%s failed: %s\n", execFile,
422             kUseValgrind ? " [valgrind]" : "", strerror(errno));
423         exit(1);
424     } else {
425         LOGV("DexOpt: waiting for verify+opt, pid=%d\n", (int) pid);
426         int status;
427         pid_t gotPid;
428         int oldStatus;
429
430         /*
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.
433          */
434         oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
435         while (true) {
436             gotPid = waitpid(pid, &status, 0);
437             if (gotPid == -1 && errno == EINTR) {
438                 LOGD("waitpid interrupted, retrying\n");
439             } else {
440                 break;
441             }
442         }
443         dvmChangeStatus(NULL, oldStatus);
444         if (gotPid != pid) {
445             LOGE("waitpid failed: wanted %d, got %d: %s\n",
446                 (int) pid, (int) gotPid, strerror(errno));
447             return false;
448         }
449
450         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
451             LOGD("DexOpt: --- END '%s' (success) ---\n", lastPart);
452             return true;
453         } else {
454             LOGW("DexOpt: --- END '%s' --- status=0x%04x, process failed\n",
455                 lastPart, status);
456             return false;
457         }
458     }
459 }
460
461 /*
462  * Do the actual optimization.  This is executed in the dexopt process.
463  *
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.)
471  *
472  * Returns "true" on success.
473  */
474 bool dvmContinueOptimization(int fd, off_t dexOffset, long dexLength,
475     const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
476 {
477     DexClassLookup* pClassLookup = NULL;
478     RegisterMapBuilder* pRegMapBuilder = NULL;
479     u4 headerFlags = 0;
480
481     assert(gDvm.optimizing);
482
483     LOGV("Continuing optimization (%s, isb=%d)\n", fileName, isBootstrap);
484
485     assert(dexOffset >= 0);
486
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");
490         return false;
491     }
492     if (dexOffset < (int) sizeof(DexOptHeader)) {
493         LOGE("not enough room for opt header\n");
494         return false;
495     }
496
497     bool result = false;
498
499     /*
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.
503      */
504     gDvm.optimizingBootstrapClass = isBootstrap;
505
506     {
507         /*
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.
511          */
512         bool success;
513         void* mapAddr;
514         mapAddr = mmap(NULL, dexOffset + dexLength, PROT_READ|PROT_WRITE,
515                     MAP_SHARED, fd, 0);
516         if (mapAddr == MAP_FAILED) {
517             LOGE("unable to mmap DEX cache: %s\n", strerror(errno));
518             goto bail;
519         }
520
521         /*
522          * Rewrite the file.  Byte reordering, structure realigning,
523          * class verification, and bytecode optimization are all performed
524          * here.
525          *
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.
529          *
530          * This sets "headerFlags" and creates the class lookup table as
531          * part of doing the processing.
532          */
533         success = rewriteDex(((u1*) mapAddr) + dexOffset, dexLength,
534                     &headerFlags, &pClassLookup);
535
536         if (success) {
537             DvmDex* pDvmDex = NULL;
538             u1* dexAddr = ((u1*) mapAddr) + dexOffset;
539
540             if (dvmDexFileOpenPartial(dexAddr, dexLength, &pDvmDex) != 0) {
541                 LOGE("Unable to create DexFile\n");
542                 success = false;
543             } else {
544                 /*
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.
548                  */
549                 if (gDvm.generateRegisterMaps) {
550                     pRegMapBuilder = dvmGenerateRegisterMaps(pDvmDex);
551                     if (pRegMapBuilder == NULL) {
552                         LOGE("Failed generating register maps\n");
553                         success = false;
554                     }
555                 }
556
557                 DexHeader* pHeader = (DexHeader*)pDvmDex->pHeader;
558                 updateChecksum(dexAddr, dexLength, pHeader);
559
560                 dvmDexFileFree(pDvmDex);
561             }
562         }
563
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
568         }
569 #if 1
570         /*
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.
575          */
576         if (munmap(mapAddr, dexOffset + dexLength) != 0) {
577             LOGE("munmap failed: %s\n", strerror(errno));
578             goto bail;
579         }
580 #endif
581
582         if (!success)
583             goto bail;
584     }
585
586     /* get start offset, and adjust deps start for 64-bit alignment */
587     off_t depsOffset, optOffset, endOffset, adjOffset;
588     int depsLength, optLength;
589     u4 optChecksum;
590
591     depsOffset = lseek(fd, 0, SEEK_END);
592     if (depsOffset < 0) {
593         LOGE("lseek to EOF failed: %s\n", strerror(errno));
594         goto bail;
595     }
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);
602     }
603
604     /*
605      * Append the dependency list.
606      */
607     if (writeDependencies(fd, modWhen, crc) != 0) {
608         LOGW("Failed writing dependencies\n");
609         goto bail;
610     }
611
612     /* compute deps length, then adjust opt start for 64-bit alignment */
613     optOffset = lseek(fd, 0, SEEK_END);
614     depsLength = optOffset - depsOffset;
615
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);
622     }
623
624     /*
625      * Append any optimized pre-computed data structures.
626      */
627     if (!writeOptData(fd, pClassLookup, pRegMapBuilder)) {
628         LOGW("Failed writing opt data\n");
629         goto bail;
630     }
631
632     endOffset = lseek(fd, 0, SEEK_END);
633     optLength = endOffset - optOffset;
634
635     /* compute checksum from start of deps to end of opt area */
636     if (!computeFileChecksum(fd, depsOffset,
637             (optOffset+optLength) - depsOffset, &optChecksum))
638     {
639         goto bail;
640     }
641
642     /*
643      * Output the "opt" header with all values filled in and a correct
644      * magic number.
645      */
646     DexOptHeader optHdr;
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;
656
657     optHdr.flags = headerFlags;
658     optHdr.checksum = optChecksum;
659
660     fsync(fd);      /* ensure previous writes go before header is written */
661
662     lseek(fd, 0, SEEK_SET);
663     if (sysWriteFully(fd, &optHdr, sizeof(optHdr), "DexOpt opt header") != 0)
664         goto bail;
665
666     LOGV("Successfully wrote DEX header\n");
667     result = true;
668
669     //dvmRegisterMapDumpStats();
670
671 bail:
672     dvmFreeRegisterMapBuilder(pRegMapBuilder);
673     free(pClassLookup);
674     return result;
675 }
676
677
678 /*
679  * Perform in-place rewrites on a memory-mapped DEX file.
680  *
681  * This happens in a short-lived child process, so we can go nutty with
682  * loading classes and allocating memory.
683  */
684 static bool rewriteDex(u1* addr, int len, u4* pHeaderFlags,
685     DexClassLookup** ppClassLookup)
686 {
687     u8 prepWhen, loadWhen, verifyOptWhen;
688     DvmDex* pDvmDex = NULL;
689     bool doVerify, doOpt;
690     bool result = false;
691
692     *pHeaderFlags = 0;
693
694     /* if the DEX is in the wrong byte order, swap it now */
695     if (dexSwapAndVerify(addr, len) != 0)
696         goto bail;
697 #if __BYTE_ORDER != __LITTLE_ENDIAN
698     *pHeaderFlags |= DEX_OPT_FLAG_BIG;
699 #endif
700
701     if (gDvm.classVerifyMode == VERIFY_MODE_NONE)
702         doVerify = false;
703     else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE)
704         doVerify = !gDvm.optimizingBootstrapClass;
705     else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/
706         doVerify = true;
707
708     if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
709         doOpt = false;
710     else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
711         doOpt = doVerify;
712     else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
713         doOpt = true;
714
715     /* TODO: decide if this is actually useful */
716     if (doVerify)
717         *pHeaderFlags |= DEX_FLAG_VERIFIED;
718     if (doOpt)
719         *pHeaderFlags |= DEX_OPT_FLAG_FIELDS | DEX_OPT_FLAG_INVOCATIONS;
720
721     /*
722      * Now that the DEX file can be read directly, create a DexFile struct
723      * for it.
724      */
725     if (dvmDexFileOpenPartial(addr, len, &pDvmDex) != 0) {
726         LOGE("Unable to create DexFile\n");
727         goto bail;
728     }
729
730     /*
731      * Create the class lookup table.  This will eventually be appended
732      * to the end of the .odex.
733      */
734     *ppClassLookup = dexCreateClassLookup(pDvmDex->pDexFile);
735     if (*ppClassLookup == NULL)
736         goto bail;
737
738     /*
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.
741      */
742     if (!doVerify && !doOpt) {
743         result = true;
744         goto bail;
745     }
746
747     /* this is needed for the next part */
748     pDvmDex->pDexFile->pClassLookup = *ppClassLookup;
749
750     prepWhen = dvmGetRelativeTimeUsec();
751
752     /*
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).
755      */
756     if (!loadAllClasses(pDvmDex))
757         goto bail;
758     loadWhen = dvmGetRelativeTimeUsec();
759
760     /*
761      * Verify and optimize all classes in the DEX file (command-line
762      * options permitting).
763      *
764      * This is best-effort, so there's really no way for dexopt to
765      * fail at this point.
766      */
767     verifyAndOptimizeClasses(pDvmDex->pDexFile, doVerify, doOpt);
768     verifyOptWhen = dvmGetRelativeTimeUsec();
769
770     const char* msgStr = "???";
771     if (doVerify && doOpt)
772         msgStr = "verify+opt";
773     else if (doVerify)
774         msgStr = "verify";
775     else if (doOpt)
776         msgStr = "opt";
777     LOGD("DexOpt: load %dms, %s %dms\n",
778         (int) (loadWhen - prepWhen) / 1000,
779         msgStr,
780         (int) (verifyOptWhen - loadWhen) / 1000);
781
782     result = true;
783
784 bail:
785     /* free up storage */
786     dvmDexFileFree(pDvmDex);
787
788     return result;
789 }
790
791 /*
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.
796  *
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.
801  *
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.
805  *
806  * This returns "false" if the world is too screwed up to do anything
807  * useful at all.
808  */
809 static bool loadAllClasses(DvmDex* pDvmDex)
810 {
811     u4 count = pDvmDex->pDexFile->pHeader->classDefsSize;
812     u4 idx;
813     int loaded = 0;
814
815     LOGV("DexOpt: +++ trying to load %d classes\n", count);
816
817     dvmSetBootPathExtraDex(pDvmDex);
818
819     /*
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.)
826      */
827     if (dvmFindSystemClass("Ljava/lang/Class;") == NULL) {
828         LOGE("ERROR: java.lang.Class does not exist!\n");
829         return false;
830     }
831
832     for (idx = 0; idx < count; idx++) {
833         const DexClassDef* pClassDef;
834         const char* classDescriptor;
835         ClassObject* newClass;
836
837         pClassDef = dexGetClassDef(pDvmDex->pDexFile, idx);
838         classDescriptor =
839             dexStringByTypeIdx(pDvmDex->pDexFile, pClassDef->classIdx);
840
841         LOGV("+++  loading '%s'", classDescriptor);
842         //newClass = dvmDefineClass(pDexFile, classDescriptor,
843         //        NULL);
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) {
849             /*
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.
853              */
854             LOGD("DexOpt: '%s' has an earlier definition; blocking out\n",
855                 classDescriptor);
856             SET_CLASS_FLAG(newClass, CLASS_MULTIPLE_DEFS);
857         } else {
858             loaded++;
859         }
860     }
861     LOGV("DexOpt: +++ successfully loaded %d classes\n", loaded);
862
863     dvmSetBootPathExtraDex(NULL);
864     return true;
865 }
866
867 /*
868  * Verify and/or optimize all classes that were successfully loaded from
869  * this DEX file.
870  */
871 static void verifyAndOptimizeClasses(DexFile* pDexFile, bool doVerify,
872     bool doOpt)
873 {
874     u4 count = pDexFile->pHeader->classDefsSize;
875     u4 idx;
876
877     /*
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.
881      *
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.
885      */
886     if (doOpt) {
887         gDvm.inlineSubs = dvmCreateInlineSubsTable();
888         if (gDvm.inlineSubs == NULL)
889             return;
890     }
891
892     for (idx = 0; idx < count; idx++) {
893         const DexClassDef* pClassDef;
894         const char* classDescriptor;
895         ClassObject* clazz;
896
897         pClassDef = dexGetClassDef(pDexFile, idx);
898         classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
899
900         /* all classes are loaded into the bootstrap class loader */
901         clazz = dvmLookupClass(classDescriptor, NULL, false);
902         if (clazz != NULL) {
903             verifyAndOptimizeClass(pDexFile, clazz, pClassDef, doVerify, doOpt);
904
905         } else {
906             // TODO: log when in verbose mode
907             LOGV("DexOpt: not optimizing unavailable class '%s'\n",
908                 classDescriptor);
909         }
910     }
911
912     if (gDvm.inlineSubs != NULL) {
913         dvmFreeInlineSubsTable(gDvm.inlineSubs);
914         gDvm.inlineSubs = NULL;
915     }
916 }
917
918 /*
919  * Verify and/or optimize a specific class.
920  */
921 static void verifyAndOptimizeClass(DexFile* pDexFile, ClassObject* clazz,
922     const DexClassDef* pClassDef, bool doVerify, bool doOpt)
923 {
924     const char* classDescriptor;
925     bool verified = false;
926
927     if (clazz->pDvmDex->pDexFile != pDexFile) {
928         /*
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.
934          */
935         LOGD("DexOpt: not verifying/optimizing '%s': multiple definitions\n",
936             clazz->descriptor);
937         return;
938     }
939
940     classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
941
942     /*
943      * First, try to verify it.
944      */
945     if (doVerify) {
946         if (dvmVerifyClass(clazz)) {
947             /*
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.
951              */
952             assert((clazz->accessFlags & JAVA_FLAGS_MASK) ==
953                 pClassDef->accessFlags);
954             ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISPREVERIFIED;
955             verified = true;
956         } else {
957             // TODO: log when in verbose mode
958             LOGV("DexOpt: '%s' failed verification\n", classDescriptor);
959         }
960     }
961
962     if (doOpt) {
963         if (!verified && gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED) {
964             LOGV("DexOpt: not optimizing '%s': not verified\n",
965                 classDescriptor);
966         } else {
967             dvmOptimizeClass(clazz, false);
968
969             /* set the flag whether or not we actually changed anything */
970             ((DexClassDef*)pClassDef)->accessFlags |= CLASS_ISOPTIMIZED;
971         }
972     }
973 }
974
975
976 /*
977  * Get the cache file name from a ClassPathEntry.
978  */
979 static const char* getCacheFileName(const ClassPathEntry* cpe)
980 {
981     switch (cpe->kind) {
982     case kCpeJar:
983         return dvmGetJarFileCacheFileName((JarFile*) cpe->ptr);
984     case kCpeDex:
985         return dvmGetRawDexFileCacheFileName((RawDexFile*) cpe->ptr);
986     default:
987         LOGE("DexOpt: unexpected cpe kind %d\n", cpe->kind);
988         dvmAbort();
989         return NULL;
990     }
991 }
992
993 /*
994  * Get the SHA-1 signature.
995  */
996 static const u1* getSignature(const ClassPathEntry* cpe)
997 {
998     DvmDex* pDvmDex;
999
1000     switch (cpe->kind) {
1001     case kCpeJar:
1002         pDvmDex = dvmGetJarFileDex((JarFile*) cpe->ptr);
1003         break;
1004     case kCpeDex:
1005         pDvmDex = dvmGetRawDexFileDex((RawDexFile*) cpe->ptr);
1006         break;
1007     default:
1008         LOGE("unexpected cpe kind %d\n", cpe->kind);
1009         dvmAbort();
1010         pDvmDex = NULL;         // make gcc happy
1011     }
1012
1013     assert(pDvmDex != NULL);
1014     return pDvmDex->pDexFile->pHeader->signature;
1015 }
1016
1017
1018 /*
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
1028  *
1029  * If this changes, update DEX_OPT_MAGIC_VERS.
1030  */
1031 static const size_t kMinDepSize = 4 * 4;
1032 static const size_t kMaxDepSize = 4 * 4 + 2048;     // sanity check
1033
1034 /*
1035  * Read the "opt" header, verify it, then read the dependencies section
1036  * and verify that data as well.
1037  *
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.
1042  *
1043  * On successful return, the file will be seeked immediately past the
1044  * "opt" header.
1045  */
1046 bool dvmCheckOptHeaderAndDependencies(int fd, bool sourceAvail, u4 modWhen,
1047     u4 crc, bool expectVerify, bool expectOpt)
1048 {
1049     DexOptHeader optHdr;
1050     u1* depData = NULL;
1051     const u1* magic;
1052     off_t posn;
1053     int result = false;
1054     ssize_t actual;
1055
1056     /*
1057      * Start at the start.  The "opt" header, when present, will always be
1058      * the first thing in the file.
1059      */
1060     if (lseek(fd, 0, SEEK_SET) != 0) {
1061         LOGE("DexOpt: failed to seek to start of file: %s\n", strerror(errno));
1062         goto bail;
1063     }
1064
1065     /*
1066      * Read and do trivial verification on the opt header.  The header is
1067      * always in host byte order.
1068      */
1069     actual = read(fd, &optHdr, sizeof(optHdr));
1070     if (actual < 0) {
1071         LOGE("DexOpt: failed reading opt header: %s\n", strerror(errno));
1072         goto bail;
1073     } else if (actual != sizeof(optHdr)) {
1074         LOGE("DexOpt: failed reading opt header (got %d of %zd)\n",
1075             (int) actual, sizeof(optHdr));
1076         goto bail;
1077     }
1078
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");
1083         goto bail;
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]);
1088         goto bail;
1089     }
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]);
1093         goto bail;
1094     }
1095     if (optHdr.depsLength < kMinDepSize || optHdr.depsLength > kMaxDepSize) {
1096         LOGW("DexOpt: weird deps length %d, bailing\n", optHdr.depsLength);
1097         goto bail;
1098     }
1099
1100     /*
1101      * Do the header flags match up with what we want?
1102      *
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.
1109      *
1110      * (This is also of limited value when !sourceAvail.)
1111      *
1112      * So, for now, we essentially ignore "expectVerify" and "expectOpt"
1113      * by limiting the match mask.
1114      *
1115      * The only thing we really can't handle is incorrect byte-ordering.
1116      */
1117     const u4 matchMask = DEX_OPT_FLAG_BIG;
1118     u4 expectedFlags = 0;
1119 #if __BYTE_ORDER != __LITTLE_ENDIAN
1120     expectedFlags |= DEX_OPT_FLAG_BIG;
1121 #endif
1122     if (expectVerify)
1123         expectedFlags |= DEX_FLAG_VERIFIED;
1124     if (expectOpt)
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);
1129         goto bail;
1130     }
1131
1132     posn = lseek(fd, optHdr.depsOffset, SEEK_SET);
1133     if (posn < 0) {
1134         LOGW("DexOpt: seek to deps failed: %s\n", strerror(errno));
1135         goto bail;
1136     }
1137
1138     /*
1139      * Read all of the dependency stuff into memory.
1140      */
1141     depData = (u1*) malloc(optHdr.depsLength);
1142     if (depData == NULL) {
1143         LOGW("DexOpt: unable to allocate %d bytes for deps\n",
1144             optHdr.depsLength);
1145         goto bail;
1146     }
1147     actual = read(fd, depData, optHdr.depsLength);
1148     if (actual < 0) {
1149         LOGW("DexOpt: failed reading deps: %s\n", strerror(errno));
1150         goto bail;
1151     } else if (actual != (ssize_t) optHdr.depsLength) {
1152         LOGW("DexOpt: failed reading deps: got %d of %d\n",
1153             (int) actual, optHdr.depsLength);
1154         goto bail;
1155     }
1156
1157     /*
1158      * Verify simple items.
1159      */
1160     const u1* ptr;
1161     u4 val;
1162
1163     ptr = depData;
1164     val = read4LE(&ptr);
1165     if (sourceAvail && val != modWhen) {
1166         LOGI("DexOpt: source file mod time mismatch (%08x vs %08x)\n",
1167             val, modWhen);
1168         goto bail;
1169     }
1170     val = read4LE(&ptr);
1171     if (sourceAvail && val != crc) {
1172         LOGI("DexOpt: source file CRC mismatch (%08x vs %08x)\n", val, crc);
1173         goto bail;
1174     }
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);
1179         goto bail;
1180     }
1181
1182     /*
1183      * Verify dependencies on other cached DEX files.  It must match
1184      * exactly with what is currently defined in the bootclasspath.
1185      */
1186     ClassPathEntry* cpe;
1187     u4 numDeps;
1188
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 */
1195
1196         const u1* signature = getSignature(cpe);
1197         size_t len = strlen(cacheFileName) +1;
1198         u4 storedStrLen;
1199
1200         if (numDeps == 0) {
1201             /* more entries in bootclasspath than in deps list */
1202             LOGI("DexOpt: not all deps represented\n");
1203             goto bail;
1204         }
1205
1206         storedStrLen = read4LE(&ptr);
1207         if (len != storedStrLen ||
1208             strcmp(cacheFileName, (const char*) ptr) != 0)
1209         {
1210             LOGI("DexOpt: mismatch dep name: '%s' vs. '%s'\n",
1211                 cacheFileName, ptr);
1212             goto bail;
1213         }
1214
1215         ptr += storedStrLen;
1216
1217         if (memcmp(signature, ptr, kSHA1DigestLen) != 0) {
1218             LOGI("DexOpt: mismatch dep signature for '%s'\n", cacheFileName);
1219             goto bail;
1220         }
1221         ptr += kSHA1DigestLen;
1222
1223         LOGV("DexOpt: dep match on '%s'\n", cacheFileName);
1224
1225         numDeps--;
1226     }
1227
1228     if (numDeps != 0) {
1229         /* more entries in deps list than in classpath */
1230         LOGI("DexOpt: Some deps went away\n");
1231         goto bail;
1232     }
1233
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);
1238         assert(false);
1239     }
1240
1241     result = true;
1242
1243 bail:
1244     free(depData);
1245     return result;
1246 }
1247
1248 /*
1249  * Write the dependency info to "fd" at the current file position.
1250  */
1251 static int writeDependencies(int fd, u4 modWhen, u4 crc)
1252 {
1253     u1* buf = NULL;
1254     int result = -1;
1255     ssize_t bufLen;
1256     ClassPathEntry* cpe;
1257     int numDeps;
1258
1259     /*
1260      * Count up the number of completed entries in the bootclasspath.
1261      */
1262     numDeps = 0;
1263     bufLen = 0;
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 */
1268
1269         LOGV("+++ DexOpt: found dep '%s'\n", cacheFileName);
1270
1271         numDeps++;
1272         bufLen += strlen(cacheFileName) +1;
1273     }
1274
1275     bufLen += 4*4 + numDeps * (4+kSHA1DigestLen);
1276
1277     buf = malloc(bufLen);
1278
1279     set4LE(buf+0, modWhen);
1280     set4LE(buf+4, crc);
1281     set4LE(buf+8, DALVIK_VM_BUILD);
1282     set4LE(buf+12, numDeps);
1283
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.
1287
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 */
1293
1294         const u1* signature = getSignature(cpe);
1295         int len = strlen(cacheFileName) +1;
1296
1297         if (ptr + 4 + len + kSHA1DigestLen > buf + bufLen) {
1298             LOGE("DexOpt: overran buffer\n");
1299             dvmAbort();
1300         }
1301
1302         set4LE(ptr, len);
1303         ptr += 4;
1304         memcpy(ptr, cacheFileName, len);
1305         ptr += len;
1306         memcpy(ptr, signature, kSHA1DigestLen);
1307         ptr += kSHA1DigestLen;
1308     }
1309
1310     assert(ptr == buf + bufLen);
1311
1312     result = sysWriteFully(fd, buf, bufLen, "DexOpt dep info");
1313
1314     free(buf);
1315     return result;
1316 }
1317
1318
1319 /*
1320  * Write a block of data in "chunk" format.
1321  *
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.
1324  */
1325 static bool writeChunk(int fd, u4 type, const void* data, size_t size)
1326 {
1327     union {             /* save a syscall by grouping these together */
1328         char raw[8];
1329         struct {
1330             u4 type;
1331             u4 size;
1332         } ts;
1333     } header;
1334
1335     assert(sizeof(header) == 8);
1336
1337     LOGV("Writing chunk, type=%.4s size=%d\n", (char*) &type, size);
1338
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)
1343     {
1344         return false;
1345     }
1346
1347     if (size > 0) {
1348         if (sysWriteFully(fd, data, size, "DexOpt opt chunk write") != 0)
1349             return false;
1350     }
1351
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);
1357     }
1358
1359     assert( ((int)lseek(fd, 0, SEEK_CUR) & 7) == 0);
1360
1361     return true;
1362 }
1363
1364 /*
1365  * Write opt data.
1366  *
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.
1371  */
1372 static bool writeOptData(int fd, const DexClassLookup* pClassLookup,
1373     const RegisterMapBuilder* pRegMapBuilder)
1374 {
1375     /* pre-computed class lookup hash table */
1376     if (!writeChunk(fd, (u4) kDexChunkClassLookup,
1377             pClassLookup, pClassLookup->size))
1378     {
1379         return false;
1380     }
1381
1382     /* register maps (optional) */
1383     if (pRegMapBuilder != NULL) {
1384         if (!writeChunk(fd, (u4) kDexChunkRegisterMaps,
1385                 pRegMapBuilder->data, pRegMapBuilder->size))
1386         {
1387             return false;
1388         }
1389     }
1390
1391     /* write the end marker */
1392     if (!writeChunk(fd, (u4) kDexChunkEnd, NULL, 0)) {
1393         return false;
1394     }
1395
1396     return true;
1397 }
1398
1399 /*
1400  * Compute a checksum on a piece of an open file.
1401  *
1402  * File will be positioned at end of checksummed area.
1403  *
1404  * Returns "true" on success.
1405  */
1406 static bool computeFileChecksum(int fd, off_t start, size_t length, u4* pSum)
1407 {
1408     unsigned char readBuf[8192];
1409     ssize_t actual;
1410     uLong adler;
1411
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));
1415         return false;
1416     }
1417
1418     adler = adler32(0L, Z_NULL, 0);
1419
1420     while (length != 0) {
1421         size_t wanted = (length < sizeof(readBuf)) ? length : sizeof(readBuf);
1422         actual = read(fd, readBuf, wanted);
1423         if (actual <= 0) {
1424             LOGE("Read failed (%d) while computing checksum (len=%zu): %s\n",
1425                 (int) actual, length, strerror(errno));
1426             return false;
1427         }
1428
1429         adler = adler32(adler, readBuf, actual);
1430
1431         length -= actual;
1432     }
1433
1434     *pSum = adler;
1435     return true;
1436 }
1437
1438 /*
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.
1442  */
1443 static void updateChecksum(u1* addr, int len, DexHeader* pHeader)
1444 {
1445     /*
1446      * Rewrite the checksum.  We leave the SHA-1 signature alone.
1447      */
1448     uLong adler = adler32(0L, Z_NULL, 0);
1449     const int nonSum = sizeof(pHeader->magic) + sizeof(pHeader->checksum);
1450
1451     adler = adler32(adler, addr + nonSum, len - nonSum);
1452     pHeader->checksum = adler;
1453 }