blob: d420043e1c44707b4121cc58e91c65546fe78a49 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
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 * Convert the output from "dx" into a locally-optimized DEX file.
19 *
20 * TODO: the format of the optimized header is currently "whatever we
21 * happen to write", since the VM that writes it is by definition the same
22 * as the VM that reads it. Still, it should be better documented and
23 * more rigorously structured.
24 */
25#include "Dalvik.h"
26#include "libdex/InstrUtils.h"
27#include "libdex/OptInvocation.h"
The Android Open Source Project99409882009-03-18 22:20:24 -070028#include "analysis/RegisterMap.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080029
30#include <zlib.h>
31
32#include <stdlib.h>
33#include <unistd.h>
34#include <sys/mman.h>
35#include <sys/stat.h>
36#include <sys/file.h>
37#include <sys/wait.h>
38#include <fcntl.h>
39#include <errno.h>
40
41/*
42 * Virtual/direct calls to "method" are replaced with an execute-inline
43 * instruction with index "idx".
44 */
45typedef struct InlineSub {
46 Method* method;
47 int inlineIdx;
48} InlineSub;
49
50
51/* fwd */
52static int writeDependencies(int fd, u4 modWhen, u4 crc);
53static bool writeAuxData(int fd, const DexClassLookup* pClassLookup,\
The Android Open Source Project99409882009-03-18 22:20:24 -070054 const IndexMapSet* pIndexMapSet, const RegisterMapBuilder* pRegMapBuilder);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080055static void logFailedWrite(size_t expected, ssize_t actual, const char* msg,
56 int err);
57
58static bool rewriteDex(u1* addr, int len, bool doVerify, bool doOpt,\
59 u4* pHeaderFlags, DexClassLookup** ppClassLookup);
60static void updateChecksum(u1* addr, int len, DexHeader* pHeader);
61static bool loadAllClasses(DvmDex* pDvmDex);
62static void optimizeLoadedClasses(DexFile* pDexFile);
63static void optimizeClass(ClassObject* clazz, const InlineSub* inlineSubs);
64static bool optimizeMethod(Method* method, const InlineSub* inlineSubs);
65static void rewriteInstField(Method* method, u2* insns, OpCode newOpc);
66static bool rewriteVirtualInvoke(Method* method, u2* insns, OpCode newOpc);
67static bool rewriteDirectInvoke(Method* method, u2* insns);
68static bool rewriteExecuteInline(Method* method, u2* insns,
69 MethodType methodType, const InlineSub* inlineSubs);
70
71
72/*
73 * Return the fd of an open file in the DEX file cache area. If the cache
74 * file doesn't exist or is out of date, this will remove the old entry,
75 * create a new one (writing only the file header), and return with the
76 * "new file" flag set.
77 *
78 * It's possible to execute from an unoptimized DEX file directly,
79 * assuming the byte ordering and structure alignment is correct, but
80 * disadvantageous because some significant optimizations are not possible.
81 * It's not generally possible to do the same from an uncompressed Jar
82 * file entry, because we have to guarantee 32-bit alignment in the
83 * memory-mapped file.
84 *
85 * For a Jar/APK file (a zip archive with "classes.dex" inside), "modWhen"
86 * and "crc32" come from the Zip directory entry. For a stand-alone DEX
87 * file, it's the modification date of the file and the Adler32 from the
88 * DEX header (which immediately follows the magic). If these don't
89 * match what's stored in the opt header, we reject the file immediately.
90 *
91 * On success, the file descriptor will be positioned just past the "opt"
92 * file header, and will be locked with flock. "*pCachedName" will point
93 * to newly-allocated storage.
94 */
95int dvmOpenCachedDexFile(const char* fileName, const char* cacheFileName,
96 u4 modWhen, u4 crc, bool isBootstrap, bool* pNewFile, bool createIfMissing)
97{
98 int fd, cc;
99 struct stat fdStat, fileStat;
100 bool readOnly = false;
101
102 *pNewFile = false;
103
104retry:
105 /*
106 * Try to open the cache file. If we've been asked to,
107 * create it if it doesn't exist.
108 */
109 fd = createIfMissing ? open(cacheFileName, O_CREAT|O_RDWR, 0644) : -1;
110 if (fd < 0) {
111 fd = open(cacheFileName, O_RDONLY, 0);
112 if (fd < 0) {
113 if (createIfMissing) {
114 LOGE("Can't open dex cache '%s': %s\n",
115 cacheFileName, strerror(errno));
116 }
117 return fd;
118 }
119 readOnly = true;
120 }
121
122 /*
123 * Grab an exclusive lock on the cache file. If somebody else is
124 * working on it, we'll block here until they complete. Because
125 * we're waiting on an external resource, we go into VMWAIT mode.
126 */
127 int oldStatus;
128 LOGV("DexOpt: locking cache file %s (fd=%d, boot=%d)\n",
129 cacheFileName, fd, isBootstrap);
130 oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
131 cc = flock(fd, LOCK_EX | LOCK_NB);
132 if (cc != 0) {
133 LOGD("DexOpt: sleeping on flock(%s)\n", cacheFileName);
134 cc = flock(fd, LOCK_EX);
135 }
136 dvmChangeStatus(NULL, oldStatus);
137 if (cc != 0) {
138 LOGE("Can't lock dex cache '%s': %d\n", cacheFileName, cc);
139 close(fd);
140 return -1;
141 }
142 LOGV("DexOpt: locked cache file\n");
143
144 /*
145 * Check to see if the fd we opened and locked matches the file in
146 * the filesystem. If they don't, then somebody else unlinked ours
147 * and created a new file, and we need to use that one instead. (If
148 * we caught them between the unlink and the create, we'll get an
149 * ENOENT from the file stat.)
150 */
151 cc = fstat(fd, &fdStat);
152 if (cc != 0) {
153 LOGE("Can't stat open file '%s'\n", cacheFileName);
154 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
155 goto close_fail;
156 }
157 cc = stat(cacheFileName, &fileStat);
158 if (cc != 0 ||
159 fdStat.st_dev != fileStat.st_dev || fdStat.st_ino != fileStat.st_ino)
160 {
161 LOGD("DexOpt: our open cache file is stale; sleeping and retrying\n");
162 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
163 flock(fd, LOCK_UN);
164 close(fd);
165 usleep(250 * 1000); /* if something is hosed, don't peg machine */
166 goto retry;
167 }
168
169 /*
170 * We have the correct file open and locked. If the file size is zero,
171 * then it was just created by us, and we want to fill in some fields
172 * in the "opt" header and set "*pNewFile". Otherwise, we want to
173 * verify that the fields in the header match our expectations, and
174 * reset the file if they don't.
175 */
176 if (fdStat.st_size == 0) {
177 if (readOnly) {
178 LOGW("DexOpt: file has zero length and isn't writable\n");
179 goto close_fail;
180 }
181 cc = dexOptCreateEmptyHeader(fd);
182 if (cc != 0)
183 goto close_fail;
184 *pNewFile = true;
185 LOGV("DexOpt: successfully initialized new cache file\n");
186 } else {
187 bool expectVerify, expectOpt;
188
189 if (gDvm.classVerifyMode == VERIFY_MODE_NONE)
190 expectVerify = false;
191 else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE)
192 expectVerify = !isBootstrap;
193 else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/
194 expectVerify = true;
195
196 if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
197 expectOpt = false;
198 else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
199 expectOpt = expectVerify;
200 else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
201 expectOpt = true;
202
203 LOGV("checking deps, expecting vfy=%d opt=%d\n",
204 expectVerify, expectOpt);
205
206 if (!dvmCheckOptHeaderAndDependencies(fd, true, modWhen, crc,
207 expectVerify, expectOpt))
208 {
209 if (readOnly) {
210 /*
211 * We could unlink and rewrite the file if we own it or
212 * the "sticky" bit isn't set on the directory. However,
213 * we're not able to truncate it, which spoils things. So,
214 * give up now.
215 */
216 if (createIfMissing) {
217 LOGW("Cached DEX '%s' (%s) is stale and not writable\n",
218 fileName, cacheFileName);
219 }
220 goto close_fail;
221 }
222
223 /*
224 * If we truncate the existing file before unlinking it, any
225 * process that has it mapped will fail when it tries to touch
226 * the pages.
227 *
228 * This is very important. The zygote process will have the
229 * boot DEX files (core, framework, etc.) mapped early. If
230 * (say) core.dex gets updated, and somebody launches an app
231 * that uses App.dex, then App.dex gets reoptimized because it's
232 * dependent upon the boot classes. However, dexopt will be
233 * using the *new* core.dex to do the optimizations, while the
234 * app will actually be running against the *old* core.dex
235 * because it starts from zygote.
236 *
237 * Even without zygote, it's still possible for a class loader
238 * to pull in an APK that was optimized against an older set
239 * of DEX files. We must ensure that everything fails when a
240 * boot DEX gets updated, and for general "why aren't my
241 * changes doing anything" purposes its best if we just make
242 * everything crash when a DEX they're using gets updated.
243 */
244 LOGD("Stale deps in cache file; removing and retrying\n");
245 if (ftruncate(fd, 0) != 0) {
246 LOGW("Warning: unable to truncate cache file '%s': %s\n",
247 cacheFileName, strerror(errno));
248 /* keep going */
249 }
250 if (unlink(cacheFileName) != 0) {
251 LOGW("Warning: unable to remove cache file '%s': %d %s\n",
252 cacheFileName, errno, strerror(errno));
253 /* keep going; permission failure should probably be fatal */
254 }
255 LOGVV("DexOpt: unlocking cache file %s\n", cacheFileName);
256 flock(fd, LOCK_UN);
257 close(fd);
258 goto retry;
259 } else {
260 LOGV("DexOpt: good deps in cache file\n");
261 }
262 }
263
264 assert(fd >= 0);
265 return fd;
266
267close_fail:
268 flock(fd, LOCK_UN);
269 close(fd);
270 return -1;
271}
272
273/*
274 * Unlock the file descriptor.
275 *
276 * Returns "true" on success.
277 */
278bool dvmUnlockCachedDexFile(int fd)
279{
280 LOGVV("DexOpt: unlocking cache file fd=%d\n", fd);
281 return (flock(fd, LOCK_UN) == 0);
282}
283
284
285/*
286 * Given a descriptor for a file with DEX data in it, produce an
287 * optimized version.
288 *
289 * The file pointed to by "fd" is expected to be a locked shared resource
290 * (or private); we make no efforts to enforce multi-process correctness
291 * here.
292 *
293 * "fileName" is only used for debug output. "modWhen" and "crc" are stored
294 * in the dependency set.
295 *
296 * The "isBootstrap" flag determines how the optimizer and verifier handle
297 * package-scope access checks. When optimizing, we only load the bootstrap
298 * class DEX files and the target DEX, so the flag determines whether the
299 * target DEX classes are given a (synthetic) non-NULL classLoader pointer.
300 * This only really matters if the target DEX contains classes that claim to
301 * be in the same package as bootstrap classes.
302 *
303 * The optimizer will need to load every class in the target DEX file.
304 * This is generally undesirable, so we start a subprocess to do the
305 * work and wait for it to complete.
306 *
307 * Returns "true" on success. All data will have been written to "fd".
308 */
309bool dvmOptimizeDexFile(int fd, off_t dexOffset, long dexLength,
310 const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
311{
312 const char* lastPart = strrchr(fileName, '/');
313 if (lastPart != NULL)
314 lastPart++;
315 else
316 lastPart = fileName;
317
318 /*
319 * For basic optimizations (byte-swapping and structure aligning) we
320 * don't need to fork(). It looks like fork+exec is causing problems
321 * with gdb on our bewildered Linux distro, so in some situations we
322 * want to avoid this.
323 *
324 * For optimization and/or verification, we need to load all the classes.
325 *
326 * We don't check gDvm.generateRegisterMaps, since that is dependent
327 * upon the verifier state.
328 */
329 if (gDvm.classVerifyMode == VERIFY_MODE_NONE &&
330 (gDvm.dexOptMode == OPTIMIZE_MODE_NONE ||
331 gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED))
332 {
333 LOGD("DexOpt: --- BEGIN (quick) '%s' ---\n", lastPart);
334 return dvmContinueOptimization(fd, dexOffset, dexLength,
335 fileName, modWhen, crc, isBootstrap);
336 }
337
338
339 LOGD("DexOpt: --- BEGIN '%s' (bootstrap=%d) ---\n", lastPart, isBootstrap);
340
341 pid_t pid;
342
343 /*
344 * This could happen if something in our bootclasspath, which we thought
345 * was all optimized, got rejected.
346 */
347 if (gDvm.optimizing) {
348 LOGW("Rejecting recursive optimization attempt on '%s'\n", fileName);
349 return false;
350 }
351
352 pid = fork();
353 if (pid == 0) {
354 static const int kUseValgrind = 0;
355 static const char* kDexOptBin = "/bin/dexopt";
356 static const char* kValgrinder = "/usr/bin/valgrind";
357 static const int kFixedArgCount = 10;
358 static const int kValgrindArgCount = 5;
359 static const int kMaxIntLen = 12; // '-'+10dig+'\0' -OR- 0x+8dig
360 int bcpSize = dvmGetBootPathSize();
361 int argc = kFixedArgCount + bcpSize
362 + (kValgrindArgCount * kUseValgrind);
363 char* argv[argc+1]; // last entry is NULL
364 char values[argc][kMaxIntLen];
365 char* execFile;
366 char* androidRoot;
367 int flags;
368
Andy McFadden074afd62009-04-08 12:51:10 -0700369 /* change process groups, so we don't clash with ProcessManager */
370 setpgid(0, 0);
371
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800372 /* full path to optimizer */
373 androidRoot = getenv("ANDROID_ROOT");
374 if (androidRoot == NULL) {
375 LOGW("ANDROID_ROOT not set, defaulting to /system\n");
376 androidRoot = "/system";
377 }
378 execFile = malloc(strlen(androidRoot) + strlen(kDexOptBin) + 1);
379 strcpy(execFile, androidRoot);
380 strcat(execFile, kDexOptBin);
381
382 /*
383 * Create arg vector.
384 */
385 int curArg = 0;
386
387 if (kUseValgrind) {
388 /* probably shouldn't ship the hard-coded path */
389 argv[curArg++] = (char*)kValgrinder;
390 argv[curArg++] = "--tool=memcheck";
391 argv[curArg++] = "--leak-check=yes"; // check for leaks too
392 argv[curArg++] = "--leak-resolution=med"; // increase from 2 to 4
393 argv[curArg++] = "--num-callers=16"; // default is 12
394 assert(curArg == kValgrindArgCount);
395 }
396 argv[curArg++] = execFile;
397
398 argv[curArg++] = "--dex";
399
400 sprintf(values[2], "%d", DALVIK_VM_BUILD);
401 argv[curArg++] = values[2];
402
403 sprintf(values[3], "%d", fd);
404 argv[curArg++] = values[3];
405
406 sprintf(values[4], "%d", (int) dexOffset);
407 argv[curArg++] = values[4];
408
409 sprintf(values[5], "%d", (int) dexLength);
410 argv[curArg++] = values[5];
411
412 argv[curArg++] = (char*)fileName;
413
414 sprintf(values[7], "%d", (int) modWhen);
415 argv[curArg++] = values[7];
416
417 sprintf(values[8], "%d", (int) crc);
418 argv[curArg++] = values[8];
419
420 flags = 0;
421 if (gDvm.dexOptMode != OPTIMIZE_MODE_NONE) {
422 flags |= DEXOPT_OPT_ENABLED;
423 if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)
424 flags |= DEXOPT_OPT_ALL;
425 }
426 if (gDvm.classVerifyMode != VERIFY_MODE_NONE) {
427 flags |= DEXOPT_VERIFY_ENABLED;
428 if (gDvm.classVerifyMode == VERIFY_MODE_ALL)
429 flags |= DEXOPT_VERIFY_ALL;
430 }
431 if (isBootstrap)
432 flags |= DEXOPT_IS_BOOTSTRAP;
433 if (gDvm.generateRegisterMaps)
434 flags |= DEXOPT_GEN_REGISTER_MAP;
435 sprintf(values[9], "%d", flags);
436 argv[curArg++] = values[9];
437
438 assert(((!kUseValgrind && curArg == kFixedArgCount) ||
439 ((kUseValgrind && curArg == kFixedArgCount+kValgrindArgCount))));
440
441 ClassPathEntry* cpe;
442 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
443 argv[curArg++] = cpe->fileName;
444 }
445 assert(curArg == argc);
446
447 argv[curArg] = NULL;
448
449 if (kUseValgrind)
450 execv(kValgrinder, argv);
451 else
452 execv(execFile, argv);
453
454 LOGE("execv '%s'%s failed: %s\n", execFile,
455 kUseValgrind ? " [valgrind]" : "", strerror(errno));
456 exit(1);
457 } else {
458 LOGV("DexOpt: waiting for verify+opt, pid=%d\n", (int) pid);
459 int status;
460 pid_t gotPid;
461 int oldStatus;
462
463 /*
464 * Wait for the optimization process to finish. We go into VMWAIT
465 * mode here so GC suspension won't have to wait for us.
466 */
467 oldStatus = dvmChangeStatus(NULL, THREAD_VMWAIT);
468 while (true) {
469 gotPid = waitpid(pid, &status, 0);
470 if (gotPid == -1 && errno == EINTR) {
471 LOGD("waitpid interrupted, retrying\n");
472 } else {
473 break;
474 }
475 }
476 dvmChangeStatus(NULL, oldStatus);
477 if (gotPid != pid) {
478 LOGE("waitpid failed: wanted %d, got %d: %s\n",
479 (int) pid, (int) gotPid, strerror(errno));
480 return false;
481 }
482
483 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
484 LOGD("DexOpt: --- END '%s' (success) ---\n", lastPart);
485 return true;
486 } else {
487 LOGW("DexOpt: --- END '%s' --- status=0x%04x, process failed\n",
488 lastPart, status);
489 return false;
490 }
491 }
492}
493
494/*
495 * Do the actual optimization. This is called directly for "minimal"
496 * optimization, or from a newly-created process for "full" optimization.
497 *
498 * For best use of disk/memory, we want to extract once and perform
499 * optimizations in place. If the file has to expand or contract
500 * to match local structure padding/alignment expectations, we want
501 * to do the rewrite as part of the extract, rather than extracting
502 * into a temp file and slurping it back out. (The structure alignment
503 * is currently correct for all platforms, and this isn't expected to
504 * change, so we should be okay with having it already extracted.)
505 *
506 * Returns "true" on success.
507 */
508bool dvmContinueOptimization(int fd, off_t dexOffset, long dexLength,
509 const char* fileName, u4 modWhen, u4 crc, bool isBootstrap)
510{
511 DexClassLookup* pClassLookup = NULL;
512 IndexMapSet* pIndexMapSet = NULL;
The Android Open Source Project99409882009-03-18 22:20:24 -0700513 RegisterMapBuilder* pRegMapBuilder = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800514 bool doVerify, doOpt;
515 u4 headerFlags = 0;
516
517 if (gDvm.classVerifyMode == VERIFY_MODE_NONE)
518 doVerify = false;
519 else if (gDvm.classVerifyMode == VERIFY_MODE_REMOTE)
520 doVerify = !isBootstrap;
521 else /*if (gDvm.classVerifyMode == VERIFY_MODE_ALL)*/
522 doVerify = true;
523
524 if (gDvm.dexOptMode == OPTIMIZE_MODE_NONE)
525 doOpt = false;
526 else if (gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
527 doOpt = doVerify;
528 else /*if (gDvm.dexOptMode == OPTIMIZE_MODE_ALL)*/
529 doOpt = true;
530
531 LOGV("Continuing optimization (%s, isb=%d, vfy=%d, opt=%d)\n",
532 fileName, isBootstrap, doVerify, doOpt);
533
534 assert(dexOffset >= 0);
535
536 /* quick test so we don't blow up on empty file */
537 if (dexLength < (int) sizeof(DexHeader)) {
538 LOGE("too small to be DEX\n");
539 return false;
540 }
541 if (dexOffset < (int) sizeof(DexOptHeader)) {
542 LOGE("not enough room for opt header\n");
543 return false;
544 }
545
546 bool result = false;
547
548 /*
549 * Drop this into a global so we don't have to pass it around. We could
550 * also add a field to DexFile, but since it only pertains to DEX
551 * creation that probably doesn't make sense.
552 */
553 gDvm.optimizingBootstrapClass = isBootstrap;
554
555 {
556 /*
557 * Map the entire file (so we don't have to worry about page
558 * alignment). The expectation is that the output file contains
559 * our DEX data plus room for a small header.
560 */
561 bool success;
562 void* mapAddr;
563 mapAddr = mmap(NULL, dexOffset + dexLength, PROT_READ|PROT_WRITE,
564 MAP_SHARED, fd, 0);
565 if (mapAddr == MAP_FAILED) {
566 LOGE("unable to mmap DEX cache: %s\n", strerror(errno));
567 goto bail;
568 }
569
570 /*
571 * Rewrite the file. Byte reordering, structure realigning,
572 * class verification, and bytecode optimization are all performed
573 * here.
The Android Open Source Project99409882009-03-18 22:20:24 -0700574 *
575 * In theory the file could change size and bits could shift around.
576 * In practice this would be annoying to deal with, so the file
577 * layout is designed so that it can always be rewritten in place.
578 *
579 * This sets "headerFlags" and creates the class lookup table as
580 * part of doing the processing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800581 */
582 success = rewriteDex(((u1*) mapAddr) + dexOffset, dexLength,
583 doVerify, doOpt, &headerFlags, &pClassLookup);
584
585 if (success) {
586 DvmDex* pDvmDex = NULL;
587 u1* dexAddr = ((u1*) mapAddr) + dexOffset;
588
589 if (dvmDexFileOpenPartial(dexAddr, dexLength, &pDvmDex) != 0) {
590 LOGE("Unable to create DexFile\n");
The Android Open Source Project99409882009-03-18 22:20:24 -0700591 success = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800592 } else {
593 /*
594 * If configured to do so, scan the instructions, looking
595 * for ways to reduce the size of the resolved-constant table.
596 * This is done post-optimization, across the instructions
597 * in all methods in all classes (even the ones that failed
598 * to load).
599 */
600 pIndexMapSet = dvmRewriteConstants(pDvmDex);
601
The Android Open Source Project99409882009-03-18 22:20:24 -0700602 /*
603 * If configured to do so, generate a full set of register
604 * maps for all verified classes.
605 */
606 if (gDvm.generateRegisterMaps) {
607 pRegMapBuilder = dvmGenerateRegisterMaps(pDvmDex);
608 if (pRegMapBuilder == NULL) {
609 LOGE("Failed generating register maps\n");
610 success = false;
611 }
612 }
613
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800614 updateChecksum(dexAddr, dexLength,
615 (DexHeader*) pDvmDex->pHeader);
616
617 dvmDexFileFree(pDvmDex);
618 }
619 }
620
621 /* unmap the read-write version, forcing writes to disk */
622 if (msync(mapAddr, dexOffset + dexLength, MS_SYNC) != 0) {
623 LOGW("msync failed: %s\n", strerror(errno));
624 // weird, but keep going
625 }
626#if 1
627 /*
628 * This causes clean shutdown to fail, because we have loaded classes
629 * that point into it. For the optimizer this isn't a problem,
630 * because it's more efficient for the process to simply exit.
631 * Exclude this code when doing clean shutdown for valgrind.
632 */
633 if (munmap(mapAddr, dexOffset + dexLength) != 0) {
634 LOGE("munmap failed: %s\n", strerror(errno));
635 goto bail;
636 }
637#endif
638
639 if (!success)
640 goto bail;
641 }
642
643 /* get start offset, and adjust deps start for 64-bit alignment */
644 off_t depsOffset, auxOffset, endOffset, adjOffset;
645 int depsLength, auxLength;
646
647 depsOffset = lseek(fd, 0, SEEK_END);
648 if (depsOffset < 0) {
649 LOGE("lseek to EOF failed: %s\n", strerror(errno));
650 goto bail;
651 }
652 adjOffset = (depsOffset + 7) & ~(0x07);
653 if (adjOffset != depsOffset) {
654 LOGV("Adjusting deps start from %d to %d\n",
655 (int) depsOffset, (int) adjOffset);
656 depsOffset = adjOffset;
657 lseek(fd, depsOffset, SEEK_SET);
658 }
659
660 /*
661 * Append the dependency list.
662 */
663 if (writeDependencies(fd, modWhen, crc) != 0) {
664 LOGW("Failed writing dependencies\n");
665 goto bail;
666 }
667
The Android Open Source Project99409882009-03-18 22:20:24 -0700668 /* compute deps length, then adjust aux start for 64-bit alignment */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800669 auxOffset = lseek(fd, 0, SEEK_END);
670 depsLength = auxOffset - depsOffset;
671
672 adjOffset = (auxOffset + 7) & ~(0x07);
673 if (adjOffset != auxOffset) {
674 LOGV("Adjusting aux start from %d to %d\n",
675 (int) auxOffset, (int) adjOffset);
676 auxOffset = adjOffset;
677 lseek(fd, auxOffset, SEEK_SET);
678 }
679
680 /*
681 * Append any auxillary pre-computed data structures.
682 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700683 if (!writeAuxData(fd, pClassLookup, pIndexMapSet, pRegMapBuilder)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800684 LOGW("Failed writing aux data\n");
685 goto bail;
686 }
687
688 endOffset = lseek(fd, 0, SEEK_END);
689 auxLength = endOffset - auxOffset;
690
691 /*
692 * Output the "opt" header with all values filled in and a correct
693 * magic number.
694 */
695 DexOptHeader optHdr;
696 memset(&optHdr, 0xff, sizeof(optHdr));
697 memcpy(optHdr.magic, DEX_OPT_MAGIC, 4);
698 memcpy(optHdr.magic+4, DEX_OPT_MAGIC_VERS, 4);
699 optHdr.dexOffset = (u4) dexOffset;
700 optHdr.dexLength = (u4) dexLength;
701 optHdr.depsOffset = (u4) depsOffset;
702 optHdr.depsLength = (u4) depsLength;
703 optHdr.auxOffset = (u4) auxOffset;
704 optHdr.auxLength = (u4) auxLength;
705
706 optHdr.flags = headerFlags;
707
708 ssize_t actual;
709 lseek(fd, 0, SEEK_SET);
710 actual = write(fd, &optHdr, sizeof(optHdr));
711 if (actual != sizeof(optHdr)) {
712 logFailedWrite(sizeof(optHdr), actual, "opt header", errno);
713 goto bail;
714 }
715
716 LOGV("Successfully wrote DEX header\n");
717 result = true;
718
The Android Open Source Project99409882009-03-18 22:20:24 -0700719 //dvmRegisterMapDumpStats();
720
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800721bail:
722 dvmFreeIndexMapSet(pIndexMapSet);
The Android Open Source Project99409882009-03-18 22:20:24 -0700723 dvmFreeRegisterMapBuilder(pRegMapBuilder);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800724 free(pClassLookup);
725 return result;
726}
727
728
729/*
730 * Get the cache file name from a ClassPathEntry.
731 */
732static const char* getCacheFileName(const ClassPathEntry* cpe)
733{
734 switch (cpe->kind) {
735 case kCpeJar:
736 return dvmGetJarFileCacheFileName((JarFile*) cpe->ptr);
737 case kCpeDex:
738 return dvmGetRawDexFileCacheFileName((RawDexFile*) cpe->ptr);
739 default:
740 LOGE("DexOpt: unexpected cpe kind %d\n", cpe->kind);
741 dvmAbort();
742 return NULL;
743 }
744}
745
746/*
747 * Get the SHA-1 signature.
748 */
749static const u1* getSignature(const ClassPathEntry* cpe)
750{
751 DvmDex* pDvmDex;
752
753 switch (cpe->kind) {
754 case kCpeJar:
755 pDvmDex = dvmGetJarFileDex((JarFile*) cpe->ptr);
756 break;
757 case kCpeDex:
758 pDvmDex = dvmGetRawDexFileDex((RawDexFile*) cpe->ptr);
759 break;
760 default:
761 LOGE("unexpected cpe kind %d\n", cpe->kind);
762 dvmAbort();
763 pDvmDex = NULL; // make gcc happy
764 }
765
766 assert(pDvmDex != NULL);
767 return pDvmDex->pDexFile->pHeader->signature;
768}
769
770
771/*
772 * Dependency layout:
773 * 4b Source file modification time, in seconds since 1970 UTC
774 * 4b CRC-32 from Zip entry, or Adler32 from source DEX header
775 * 4b Dalvik VM build number
776 * 4b Number of dependency entries that follow
777 * Dependency entries:
778 * 4b Name length (including terminating null)
779 * var Full path of cache entry (null terminated)
780 * 20b SHA-1 signature from source DEX file
781 *
782 * If this changes, update DEX_OPT_MAGIC_VERS.
783 */
784static const size_t kMinDepSize = 4 * 4;
785static const size_t kMaxDepSize = 4 * 4 + 1024; // sanity check
786
787/*
788 * Read the "opt" header, verify it, then read the dependencies section
789 * and verify that data as well.
790 *
791 * If "sourceAvail" is "true", this will verify that "modWhen" and "crc"
792 * match up with what is stored in the header. If they don't, we reject
793 * the file so that it can be recreated from the updated original. If
794 * "sourceAvail" isn't set, e.g. for a .odex file, we ignore these arguments.
795 *
796 * On successful return, the file will be seeked immediately past the
797 * "opt" header.
798 */
799bool dvmCheckOptHeaderAndDependencies(int fd, bool sourceAvail, u4 modWhen,
800 u4 crc, bool expectVerify, bool expectOpt)
801{
802 DexOptHeader optHdr;
803 u1* depData = NULL;
804 const u1* magic;
805 off_t posn;
806 int result = false;
807 ssize_t actual;
808
809 /*
810 * Start at the start. The "opt" header, when present, will always be
811 * the first thing in the file.
812 */
813 if (lseek(fd, 0, SEEK_SET) != 0) {
814 LOGE("DexOpt: failed to seek to start of file: %s\n", strerror(errno));
815 goto bail;
816 }
817
818 /*
819 * Read and do trivial verification on the opt header. The header is
820 * always in host byte order.
821 */
822 if (read(fd, &optHdr, sizeof(optHdr)) != sizeof(optHdr)) {
823 LOGE("DexOpt: failed reading opt header: %s\n", strerror(errno));
824 goto bail;
825 }
826
827 magic = optHdr.magic;
828 if (memcmp(magic, DEX_OPT_MAGIC, 4) != 0) {
829 /* not a DEX file, or previous attempt was interrupted */
830 LOGD("DexOpt: incorrect opt magic number (0x%02x %02x %02x %02x)\n",
831 magic[0], magic[1], magic[2], magic[3]);
832 goto bail;
833 }
834 if (memcmp(magic+4, DEX_OPT_MAGIC_VERS, 4) != 0) {
835 LOGW("DexOpt: stale opt version (0x%02x %02x %02x %02x)\n",
836 magic[4], magic[5], magic[6], magic[7]);
837 goto bail;
838 }
839 if (optHdr.depsLength < kMinDepSize || optHdr.depsLength > kMaxDepSize) {
840 LOGW("DexOpt: weird deps length %d, bailing\n", optHdr.depsLength);
841 goto bail;
842 }
843
844 /*
845 * Do the header flags match up with what we want?
846 *
847 * This is useful because it allows us to automatically regenerate
848 * a file when settings change (e.g. verification is now mandatory),
849 * but can cause difficulties if the bootstrap classes we depend upon
850 * were handled differently than the current options specify. We get
851 * upset because they're not verified or optimized, but we're not able
852 * to regenerate them because the installer won't let us.
853 *
854 * (This is also of limited value when !sourceAvail.)
855 *
856 * So, for now, we essentially ignore "expectVerify" and "expectOpt"
857 * by limiting the match mask.
858 *
859 * The only thing we really can't handle is incorrect byte-ordering.
860 */
861 const u4 matchMask = DEX_OPT_FLAG_BIG;
862 u4 expectedFlags = 0;
863#if __BYTE_ORDER != __LITTLE_ENDIAN
864 expectedFlags |= DEX_OPT_FLAG_BIG;
865#endif
866 if (expectVerify)
867 expectedFlags |= DEX_FLAG_VERIFIED;
868 if (expectOpt)
869 expectedFlags |= DEX_OPT_FLAG_FIELDS | DEX_OPT_FLAG_INVOCATIONS;
870 if ((expectedFlags & matchMask) != (optHdr.flags & matchMask)) {
871 LOGI("DexOpt: header flag mismatch (0x%02x vs 0x%02x, mask=0x%02x)\n",
872 expectedFlags, optHdr.flags, matchMask);
873 goto bail;
874 }
875
876 posn = lseek(fd, optHdr.depsOffset, SEEK_SET);
877 if (posn < 0) {
878 LOGW("DexOpt: seek to deps failed: %s\n", strerror(errno));
879 goto bail;
880 }
881
882 /*
883 * Read all of the dependency stuff into memory.
884 */
885 depData = (u1*) malloc(optHdr.depsLength);
886 if (depData == NULL) {
887 LOGW("DexOpt: unable to allocate %d bytes for deps\n",
888 optHdr.depsLength);
889 goto bail;
890 }
891 actual = read(fd, depData, optHdr.depsLength);
892 if (actual != (ssize_t) optHdr.depsLength) {
893 LOGW("DexOpt: failed reading deps: %d of %d (err=%s)\n",
894 (int) actual, optHdr.depsLength, strerror(errno));
895 goto bail;
896 }
897
898 /*
899 * Verify simple items.
900 */
901 const u1* ptr;
902 u4 val;
903
904 ptr = depData;
905 val = read4LE(&ptr);
906 if (sourceAvail && val != modWhen) {
907 LOGI("DexOpt: source file mod time mismatch (%08x vs %08x)\n",
908 val, modWhen);
909 goto bail;
910 }
911 val = read4LE(&ptr);
912 if (sourceAvail && val != crc) {
913 LOGI("DexOpt: source file CRC mismatch (%08x vs %08x)\n", val, crc);
914 goto bail;
915 }
916 val = read4LE(&ptr);
917 if (val != DALVIK_VM_BUILD) {
918 LOGI("DexOpt: VM build mismatch (%d vs %d)\n", val, DALVIK_VM_BUILD);
919 goto bail;
920 }
921
922 /*
923 * Verify dependencies on other cached DEX files. It must match
924 * exactly with what is currently defined in the bootclasspath.
925 */
926 ClassPathEntry* cpe;
927 u4 numDeps;
928
929 numDeps = read4LE(&ptr);
930 LOGV("+++ DexOpt: numDeps = %d\n", numDeps);
931 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
932 const char* cacheFileName = getCacheFileName(cpe);
933 const u1* signature = getSignature(cpe);
934 size_t len = strlen(cacheFileName) +1;
935 u4 storedStrLen;
936
937 if (numDeps == 0) {
938 /* more entries in bootclasspath than in deps list */
939 LOGI("DexOpt: not all deps represented\n");
940 goto bail;
941 }
942
943 storedStrLen = read4LE(&ptr);
944 if (len != storedStrLen ||
945 strcmp(cacheFileName, (const char*) ptr) != 0)
946 {
947 LOGI("DexOpt: mismatch dep name: '%s' vs. '%s'\n",
948 cacheFileName, ptr);
949 goto bail;
950 }
951
952 ptr += storedStrLen;
953
954 if (memcmp(signature, ptr, kSHA1DigestLen) != 0) {
955 LOGI("DexOpt: mismatch dep signature for '%s'\n", cacheFileName);
956 goto bail;
957 }
958 ptr += kSHA1DigestLen;
959
960 LOGV("DexOpt: dep match on '%s'\n", cacheFileName);
961
962 numDeps--;
963 }
964
965 if (numDeps != 0) {
966 /* more entries in deps list than in classpath */
967 LOGI("DexOpt: Some deps went away\n");
968 goto bail;
969 }
970
971 // consumed all data and no more?
972 if (ptr != depData + optHdr.depsLength) {
973 LOGW("DexOpt: Spurious dep data? %d vs %d\n",
974 (int) (ptr - depData), optHdr.depsLength);
975 assert(false);
976 }
977
978 result = true;
979
980bail:
981 free(depData);
982 return result;
983}
984
985/*
986 * Write the dependency info to "fd" at the current file position.
987 */
988static int writeDependencies(int fd, u4 modWhen, u4 crc)
989{
990 u1* buf = NULL;
991 ssize_t actual;
992 int result = -1;
993 ssize_t bufLen;
994 ClassPathEntry* cpe;
995 int i, numDeps;
996
997 /*
998 * Count up the number of completed entries in the bootclasspath.
999 */
1000 numDeps = 0;
1001 bufLen = 0;
1002 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1003 const char* cacheFileName = getCacheFileName(cpe);
1004 LOGV("+++ DexOpt: found dep '%s'\n", cacheFileName);
1005
1006 numDeps++;
1007 bufLen += strlen(cacheFileName) +1;
1008 }
1009
1010 bufLen += 4*4 + numDeps * (4+kSHA1DigestLen);
1011
1012 buf = malloc(bufLen);
1013
1014 set4LE(buf+0, modWhen);
1015 set4LE(buf+4, crc);
1016 set4LE(buf+8, DALVIK_VM_BUILD);
1017 set4LE(buf+12, numDeps);
1018
1019 // TODO: do we want to add dvmGetInlineOpsTableLength() here? Won't
1020 // help us if somebody replaces an existing entry, but it'd catch
1021 // additions/removals.
1022
1023 u1* ptr = buf + 4*4;
1024 for (cpe = gDvm.bootClassPath; cpe->ptr != NULL; cpe++) {
1025 const char* cacheFileName = getCacheFileName(cpe);
1026 const u1* signature = getSignature(cpe);
1027 int len = strlen(cacheFileName) +1;
1028
1029 if (ptr + 4 + len + kSHA1DigestLen > buf + bufLen) {
1030 LOGE("DexOpt: overran buffer\n");
1031 dvmAbort();
1032 }
1033
1034 set4LE(ptr, len);
1035 ptr += 4;
1036 memcpy(ptr, cacheFileName, len);
1037 ptr += len;
1038 memcpy(ptr, signature, kSHA1DigestLen);
1039 ptr += kSHA1DigestLen;
1040 }
1041
1042 assert(ptr == buf + bufLen);
1043
1044 actual = write(fd, buf, bufLen);
1045 if (actual != bufLen) {
1046 result = (errno != 0) ? errno : -1;
1047 logFailedWrite(bufLen, actual, "dep info", errno);
1048 } else {
1049 result = 0;
1050 }
1051
1052 free(buf);
1053 return result;
1054}
1055
1056
1057/*
1058 * Write a block of data in "chunk" format.
1059 *
1060 * The chunk header fields are always in "native" byte order. If "size"
1061 * is not a multiple of 8 bytes, the data area is padded out.
1062 */
1063static bool writeChunk(int fd, u4 type, const void* data, size_t size)
1064{
1065 ssize_t actual;
1066 union { /* save a syscall by grouping these together */
1067 char raw[8];
1068 struct {
1069 u4 type;
1070 u4 size;
1071 } ts;
1072 } header;
1073
1074 assert(sizeof(header) == 8);
1075
1076 LOGV("Writing chunk, type=%.4s size=%d\n", (char*) &type, size);
1077
1078 header.ts.type = type;
1079 header.ts.size = (u4) size;
1080 actual = write(fd, &header, sizeof(header));
1081 if (actual != sizeof(header)) {
1082 logFailedWrite(size, actual, "aux chunk header write", errno);
1083 return false;
1084 }
1085
1086 if (size > 0) {
1087 actual = write(fd, data, size);
1088 if (actual != (ssize_t) size) {
1089 logFailedWrite(size, actual, "aux chunk write", errno);
1090 return false;
1091 }
1092 }
1093
1094 /* if necessary, pad to 64-bit alignment */
1095 if ((size & 7) != 0) {
1096 int padSize = 8 - (size & 7);
1097 LOGV("size was %d, inserting %d pad bytes\n", size, padSize);
1098 lseek(fd, padSize, SEEK_CUR);
1099 }
1100
1101 assert( ((int)lseek(fd, 0, SEEK_CUR) & 7) == 0);
1102
1103 return true;
1104}
1105
1106/*
1107 * Write aux data.
1108 *
1109 * We have different pieces, some of which may be optional. To make the
1110 * most effective use of space, we use a "chunk" format, with a 4-byte
1111 * type and a 4-byte length. We guarantee 64-bit alignment for the data,
1112 * so it can be used directly when the file is mapped for reading.
1113 */
1114static bool writeAuxData(int fd, const DexClassLookup* pClassLookup,
The Android Open Source Project99409882009-03-18 22:20:24 -07001115 const IndexMapSet* pIndexMapSet, const RegisterMapBuilder* pRegMapBuilder)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001116{
1117 /* pre-computed class lookup hash table */
The Android Open Source Project99409882009-03-18 22:20:24 -07001118 if (!writeChunk(fd, (u4) kDexChunkClassLookup,
1119 pClassLookup, pClassLookup->size))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001120 {
1121 return false;
1122 }
1123
1124 /* remapped constants (optional) */
1125 if (pIndexMapSet != NULL) {
The Android Open Source Project99409882009-03-18 22:20:24 -07001126 if (!writeChunk(fd, pIndexMapSet->chunkType,
1127 pIndexMapSet->chunkData, pIndexMapSet->chunkDataLen))
1128 {
1129 return false;
1130 }
1131 }
1132
1133 /* register maps (optional) */
1134 if (pRegMapBuilder != NULL) {
1135 if (!writeChunk(fd, (u4) kDexChunkRegisterMaps,
1136 pRegMapBuilder->data, pRegMapBuilder->size))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001137 {
1138 return false;
1139 }
1140 }
1141
1142 /* write the end marker */
1143 if (!writeChunk(fd, (u4) kDexChunkEnd, NULL, 0)) {
1144 return false;
1145 }
1146
1147 return true;
1148}
1149
1150/*
1151 * Log a failed write.
1152 */
1153static void logFailedWrite(size_t expected, ssize_t actual, const char* msg,
1154 int err)
1155{
1156 LOGE("Write failed: %s (%d of %d): %s\n",
1157 msg, (int)actual, (int)expected, strerror(err));
1158}
1159
1160
1161/*
1162 * ===========================================================================
1163 * Optimizations
1164 * ===========================================================================
1165 */
1166
1167/*
1168 * Perform in-place rewrites on a memory-mapped DEX file.
1169 *
1170 * This happens in a short-lived child process, so we can go nutty with
1171 * loading classes and allocating memory.
1172 */
1173static bool rewriteDex(u1* addr, int len, bool doVerify, bool doOpt,
1174 u4* pHeaderFlags, DexClassLookup** ppClassLookup)
1175{
1176 u8 prepWhen, loadWhen, verifyWhen, optWhen;
1177 DvmDex* pDvmDex = NULL;
1178 bool result = false;
1179
1180 *pHeaderFlags = 0;
1181
1182 LOGV("+++ swapping bytes\n");
1183 if (dexFixByteOrdering(addr, len) != 0)
1184 goto bail;
1185#if __BYTE_ORDER != __LITTLE_ENDIAN
1186 *pHeaderFlags |= DEX_OPT_FLAG_BIG;
1187#endif
1188
1189 /*
1190 * Now that the DEX file can be read directly, create a DexFile for it.
1191 */
1192 if (dvmDexFileOpenPartial(addr, len, &pDvmDex) != 0) {
1193 LOGE("Unable to create DexFile\n");
1194 goto bail;
1195 }
1196
1197 /*
1198 * Create the class lookup table.
1199 */
1200 //startWhen = dvmGetRelativeTimeUsec();
1201 *ppClassLookup = dexCreateClassLookup(pDvmDex->pDexFile);
1202 if (*ppClassLookup == NULL)
1203 goto bail;
1204
1205 /*
1206 * Bail out early if they don't want The Works. The current implementation
1207 * doesn't fork a new process if this flag isn't set, so we really don't
1208 * want to continue on with the crazy class loading.
1209 */
1210 if (!doVerify && !doOpt) {
1211 result = true;
1212 goto bail;
1213 }
1214
1215 /* this is needed for the next part */
1216 pDvmDex->pDexFile->pClassLookup = *ppClassLookup;
1217
1218 prepWhen = dvmGetRelativeTimeUsec();
1219
1220 /*
1221 * Load all classes found in this DEX file. If they fail to load for
1222 * some reason, they won't get verified (which is as it should be).
1223 */
1224 if (!loadAllClasses(pDvmDex))
1225 goto bail;
1226 loadWhen = dvmGetRelativeTimeUsec();
1227
1228 /*
1229 * Verify all classes in the DEX file. Export the "is verified" flag
1230 * to the DEX file we're creating.
1231 */
1232 if (doVerify) {
1233 dvmVerifyAllClasses(pDvmDex->pDexFile);
1234 *pHeaderFlags |= DEX_FLAG_VERIFIED;
1235 }
1236 verifyWhen = dvmGetRelativeTimeUsec();
1237
1238 /*
1239 * Optimize the classes we successfully loaded. If the opt mode is
1240 * OPTIMIZE_MODE_VERIFIED, each class must have been successfully
1241 * verified or we'll skip it.
1242 */
1243#ifndef PROFILE_FIELD_ACCESS
1244 if (doOpt) {
1245 optimizeLoadedClasses(pDvmDex->pDexFile);
1246 *pHeaderFlags |= DEX_OPT_FLAG_FIELDS | DEX_OPT_FLAG_INVOCATIONS;
1247 }
1248#endif
1249 optWhen = dvmGetRelativeTimeUsec();
1250
1251 LOGD("DexOpt: load %dms, verify %dms, opt %dms\n",
1252 (int) (loadWhen - prepWhen) / 1000,
1253 (int) (verifyWhen - loadWhen) / 1000,
1254 (int) (optWhen - verifyWhen) / 1000);
1255
1256 result = true;
1257
1258bail:
1259 /* free up storage */
1260 dvmDexFileFree(pDvmDex);
1261
1262 return result;
1263}
1264
1265/*
1266 * Update the Adler-32 checksum stored in the DEX file. This covers the
1267 * swapped and optimized DEX data, but does not include the opt header
1268 * or auxillary data.
1269 */
1270static void updateChecksum(u1* addr, int len, DexHeader* pHeader)
1271{
1272 /*
1273 * Rewrite the checksum. We leave the SHA-1 signature alone.
1274 */
1275 uLong adler = adler32(0L, Z_NULL, 0);
1276 const int nonSum = sizeof(pHeader->magic) + sizeof(pHeader->checksum);
1277
1278 adler = adler32(adler, addr + nonSum, len - nonSum);
1279 pHeader->checksum = adler;
1280}
1281
1282/*
1283 * Try to load all classes in the specified DEX. If they have some sort
1284 * of broken dependency, e.g. their superclass lives in a different DEX
1285 * that wasn't previously loaded into the bootstrap class path, loading
1286 * will fail. This is the desired behavior.
1287 *
1288 * We have no notion of class loader at this point, so we load all of
1289 * the classes with the bootstrap class loader. It turns out this has
1290 * exactly the behavior we want, and has no ill side effects because we're
1291 * running in a separate process and anything we load here will be forgotten.
1292 *
1293 * We set the CLASS_MULTIPLE_DEFS flag here if we see multiple definitions.
1294 * This works because we only call here as part of optimization / pre-verify,
1295 * not during verification as part of loading a class into a running VM.
1296 *
1297 * This returns "false" if the world is too screwed up to do anything
1298 * useful at all.
1299 */
1300static bool loadAllClasses(DvmDex* pDvmDex)
1301{
1302 u4 count = pDvmDex->pDexFile->pHeader->classDefsSize;
1303 u4 idx;
1304 int loaded = 0;
1305
1306 LOGV("DexOpt: +++ trying to load %d classes\n", count);
1307
1308 dvmSetBootPathExtraDex(pDvmDex);
1309
1310 /*
1311 * We have some circularity issues with Class and Object that are most
1312 * easily avoided by ensuring that Object is never the first thing we
1313 * try to find. Take care of that here. (We only need to do this when
1314 * loading classes from the DEX file that contains Object, and only
1315 * when Object comes first in the list, but it costs very little to
1316 * do it in all cases.)
1317 */
1318 if (dvmFindSystemClass("Ljava/lang/Class;") == NULL) {
1319 LOGE("ERROR: java.lang.Class does not exist!\n");
1320 return false;
1321 }
1322
1323 for (idx = 0; idx < count; idx++) {
1324 const DexClassDef* pClassDef;
1325 const char* classDescriptor;
1326 ClassObject* newClass;
1327
1328 pClassDef = dexGetClassDef(pDvmDex->pDexFile, idx);
1329 classDescriptor =
1330 dexStringByTypeIdx(pDvmDex->pDexFile, pClassDef->classIdx);
1331
1332 LOGV("+++ loading '%s'", classDescriptor);
1333 //newClass = dvmDefineClass(pDexFile, classDescriptor,
1334 // NULL);
1335 newClass = dvmFindSystemClassNoInit(classDescriptor);
1336 if (newClass == NULL) {
1337 LOGV("DexOpt: failed loading '%s'\n", classDescriptor);
1338 dvmClearOptException(dvmThreadSelf());
1339 } else if (newClass->pDvmDex != pDvmDex) {
1340 /*
1341 * We don't load the new one, and we tag the first one found
1342 * with the "multiple def" flag so the resolver doesn't try
1343 * to make it available.
1344 */
1345 LOGD("DexOpt: '%s' has an earlier definition; blocking out\n",
1346 classDescriptor);
1347 SET_CLASS_FLAG(newClass, CLASS_MULTIPLE_DEFS);
1348 } else {
1349 loaded++;
1350 }
1351 }
1352 LOGV("DexOpt: +++ successfully loaded %d classes\n", loaded);
1353
1354 dvmSetBootPathExtraDex(NULL);
1355 return true;
1356}
1357
1358
1359/*
1360 * Create a table of inline substitutions.
1361 *
1362 * TODO: this is currently just a linear array. We will want to put this
1363 * into a hash table as the list size increases.
1364 */
1365static InlineSub* createInlineSubsTable(void)
1366{
1367 const InlineOperation* ops = dvmGetInlineOpsTable();
1368 const int count = dvmGetInlineOpsTableLength();
1369 InlineSub* table;
1370 Method* method;
1371 ClassObject* clazz;
1372 int i, tableIndex;
1373
1374 /*
1375 * Allocate for optimism: one slot per entry, plus an end-of-list marker.
1376 */
1377 table = malloc(sizeof(InlineSub) * (count+1));
1378
1379 tableIndex = 0;
1380 for (i = 0; i < count; i++) {
1381 clazz = dvmFindClassNoInit(ops[i].classDescriptor, NULL);
1382 if (clazz == NULL) {
1383 LOGV("DexOpt: can't inline for class '%s': not found\n",
1384 ops[i].classDescriptor);
1385 dvmClearOptException(dvmThreadSelf());
1386 } else {
1387 /*
1388 * Method could be virtual or direct. Try both. Don't use
1389 * the "hier" versions.
1390 */
1391 method = dvmFindDirectMethodByDescriptor(clazz, ops[i].methodName,
1392 ops[i].methodSignature);
1393 if (method == NULL)
1394 method = dvmFindVirtualMethodByDescriptor(clazz, ops[i].methodName,
1395 ops[i].methodSignature);
1396 if (method == NULL) {
1397 LOGW("DexOpt: can't inline %s.%s %s: method not found\n",
1398 ops[i].classDescriptor, ops[i].methodName,
1399 ops[i].methodSignature);
1400 } else {
1401 if (!dvmIsFinalClass(clazz) && !dvmIsFinalMethod(method)) {
1402 LOGW("DexOpt: WARNING: inline op on non-final class/method "
1403 "%s.%s\n",
1404 clazz->descriptor, method->name);
1405 /* fail? */
1406 }
1407 if (dvmIsSynchronizedMethod(method) ||
1408 dvmIsDeclaredSynchronizedMethod(method))
1409 {
1410 LOGW("DexOpt: WARNING: inline op on synchronized method "
1411 "%s.%s\n",
1412 clazz->descriptor, method->name);
1413 /* fail? */
1414 }
1415
1416 table[tableIndex].method = method;
1417 table[tableIndex].inlineIdx = i;
1418 tableIndex++;
1419
1420 LOGV("DexOpt: will inline %d: %s.%s %s\n", i,
1421 ops[i].classDescriptor, ops[i].methodName,
1422 ops[i].methodSignature);
1423 }
1424 }
1425 }
1426
1427 /* mark end of table */
1428 table[tableIndex].method = NULL;
1429 LOGV("DexOpt: inline table has %d entries\n", tableIndex);
1430
1431 return table;
1432}
1433
1434/*
1435 * Run through all classes that were successfully loaded from this DEX
1436 * file and optimize their code sections.
1437 */
1438static void optimizeLoadedClasses(DexFile* pDexFile)
1439{
1440 u4 count = pDexFile->pHeader->classDefsSize;
1441 u4 idx;
1442 InlineSub* inlineSubs = NULL;
1443
1444 LOGV("DexOpt: +++ optimizing up to %d classes\n", count);
1445 assert(gDvm.dexOptMode != OPTIMIZE_MODE_NONE);
1446
1447 inlineSubs = createInlineSubsTable();
1448
1449 for (idx = 0; idx < count; idx++) {
1450 const DexClassDef* pClassDef;
1451 const char* classDescriptor;
1452 ClassObject* clazz;
1453
1454 pClassDef = dexGetClassDef(pDexFile, idx);
1455 classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
1456
1457 /* all classes are loaded into the bootstrap class loader */
1458 clazz = dvmLookupClass(classDescriptor, NULL, false);
1459 if (clazz != NULL) {
1460 if ((pClassDef->accessFlags & CLASS_ISPREVERIFIED) == 0 &&
1461 gDvm.dexOptMode == OPTIMIZE_MODE_VERIFIED)
1462 {
1463 LOGV("DexOpt: not optimizing '%s': not verified\n",
1464 classDescriptor);
1465 } else if (clazz->pDvmDex->pDexFile != pDexFile) {
1466 /* shouldn't be here -- verifier should have caught */
1467 LOGD("DexOpt: not optimizing '%s': multiple definitions\n",
1468 classDescriptor);
1469 } else {
1470 optimizeClass(clazz, inlineSubs);
1471
1472 /* set the flag whether or not we actually did anything */
1473 ((DexClassDef*)pClassDef)->accessFlags |=
1474 CLASS_ISOPTIMIZED;
1475 }
1476 } else {
1477 LOGV("DexOpt: not optimizing unavailable class '%s'\n",
1478 classDescriptor);
1479 }
1480 }
1481
1482 free(inlineSubs);
1483}
1484
1485/*
1486 * Optimize the specified class.
1487 */
1488static void optimizeClass(ClassObject* clazz, const InlineSub* inlineSubs)
1489{
1490 int i;
1491
1492 for (i = 0; i < clazz->directMethodCount; i++) {
1493 if (!optimizeMethod(&clazz->directMethods[i], inlineSubs))
1494 goto fail;
1495 }
1496 for (i = 0; i < clazz->virtualMethodCount; i++) {
1497 if (!optimizeMethod(&clazz->virtualMethods[i], inlineSubs))
1498 goto fail;
1499 }
1500
1501 return;
1502
1503fail:
1504 LOGV("DexOpt: ceasing optimization attempts on %s\n", clazz->descriptor);
1505}
1506
1507/*
1508 * Optimize instructions in a method.
1509 *
1510 * Returns "true" if all went well, "false" if we bailed out early when
1511 * something failed.
1512 */
1513static bool optimizeMethod(Method* method, const InlineSub* inlineSubs)
1514{
1515 u4 insnsSize;
1516 u2* insns;
1517 u2 inst;
1518
1519 if (dvmIsNativeMethod(method) || dvmIsAbstractMethod(method))
1520 return true;
1521
1522 insns = (u2*) method->insns;
1523 assert(insns != NULL);
1524 insnsSize = dvmGetMethodInsnsSize(method);
1525
1526 while (insnsSize > 0) {
1527 int width;
1528
1529 inst = *insns & 0xff;
1530
1531 switch (inst) {
1532 case OP_IGET:
1533 case OP_IGET_BOOLEAN:
1534 case OP_IGET_BYTE:
1535 case OP_IGET_CHAR:
1536 case OP_IGET_SHORT:
1537 rewriteInstField(method, insns, OP_IGET_QUICK);
1538 break;
1539 case OP_IGET_WIDE:
1540 rewriteInstField(method, insns, OP_IGET_WIDE_QUICK);
1541 break;
1542 case OP_IGET_OBJECT:
1543 rewriteInstField(method, insns, OP_IGET_OBJECT_QUICK);
1544 break;
1545 case OP_IPUT:
1546 case OP_IPUT_BOOLEAN:
1547 case OP_IPUT_BYTE:
1548 case OP_IPUT_CHAR:
1549 case OP_IPUT_SHORT:
1550 rewriteInstField(method, insns, OP_IPUT_QUICK);
1551 break;
1552 case OP_IPUT_WIDE:
1553 rewriteInstField(method, insns, OP_IPUT_WIDE_QUICK);
1554 break;
1555 case OP_IPUT_OBJECT:
1556 rewriteInstField(method, insns, OP_IPUT_OBJECT_QUICK);
1557 break;
1558
1559 case OP_INVOKE_VIRTUAL:
1560 if (!rewriteExecuteInline(method, insns, METHOD_VIRTUAL,inlineSubs))
1561 {
1562 if (!rewriteVirtualInvoke(method, insns, OP_INVOKE_VIRTUAL_QUICK))
1563 return false;
1564 }
1565 break;
1566 case OP_INVOKE_VIRTUAL_RANGE:
1567 if (!rewriteVirtualInvoke(method, insns, OP_INVOKE_VIRTUAL_QUICK_RANGE))
1568 return false;
1569 break;
1570 case OP_INVOKE_SUPER:
1571 if (!rewriteVirtualInvoke(method, insns, OP_INVOKE_SUPER_QUICK))
1572 return false;
1573 break;
1574 case OP_INVOKE_SUPER_RANGE:
1575 if (!rewriteVirtualInvoke(method, insns, OP_INVOKE_SUPER_QUICK_RANGE))
1576 return false;
1577 break;
1578
1579 case OP_INVOKE_DIRECT:
1580 if (!rewriteExecuteInline(method, insns, METHOD_DIRECT, inlineSubs))
1581 {
1582 if (!rewriteDirectInvoke(method, insns))
1583 return false;
1584 }
1585 break;
1586 case OP_INVOKE_STATIC:
1587 rewriteExecuteInline(method, insns, METHOD_STATIC, inlineSubs);
1588 break;
1589
1590 default:
1591 // ignore this instruction
1592 ;
1593 }
1594
1595 if (*insns == kPackedSwitchSignature) {
1596 width = 4 + insns[1] * 2;
1597 } else if (*insns == kSparseSwitchSignature) {
1598 width = 2 + insns[1] * 4;
1599 } else if (*insns == kArrayDataSignature) {
1600 u2 elemWidth = insns[1];
1601 u4 len = insns[2] | (((u4)insns[3]) << 16);
1602 width = 4 + (elemWidth * len + 1) / 2;
1603 } else {
1604 width = dexGetInstrWidth(gDvm.instrWidth, inst);
1605 }
1606 assert(width > 0);
1607
1608 insns += width;
1609 insnsSize -= width;
1610 }
1611
1612 assert(insnsSize == 0);
1613 return true;
1614}
1615
1616
1617/*
1618 * If "referrer" and "resClass" don't come from the same DEX file, and
1619 * the DEX we're working on is not destined for the bootstrap class path,
1620 * tweak the class loader so package-access checks work correctly.
1621 *
1622 * Only do this if we're doing pre-verification or optimization.
1623 */
1624static void tweakLoader(ClassObject* referrer, ClassObject* resClass)
1625{
1626 if (!gDvm.optimizing)
1627 return;
1628 assert(referrer->classLoader == NULL);
1629 assert(resClass->classLoader == NULL);
1630
1631 if (!gDvm.optimizingBootstrapClass) {
1632 /* class loader for an array class comes from element type */
1633 if (dvmIsArrayClass(resClass))
1634 resClass = resClass->elementClass;
1635 if (referrer->pDvmDex != resClass->pDvmDex)
1636 resClass->classLoader = (Object*) 0xdead3333;
1637 }
1638}
1639
1640/*
1641 * Undo the effects of tweakLoader.
1642 */
1643static void untweakLoader(ClassObject* referrer, ClassObject* resClass)
1644{
1645 if (!gDvm.optimizing || gDvm.optimizingBootstrapClass)
1646 return;
1647
1648 if (dvmIsArrayClass(resClass))
1649 resClass = resClass->elementClass;
1650 resClass->classLoader = NULL;
1651}
1652
1653
1654/*
1655 * Alternate version of dvmResolveClass for use with verification and
1656 * optimization. Performs access checks on every resolve, and refuses
1657 * to acknowledge the existence of classes defined in more than one DEX
1658 * file.
1659 *
1660 * Exceptions caused by failures are cleared before returning.
Andy McFadden62a75162009-04-17 17:23:37 -07001661 *
1662 * On failure, returns NULL, and sets *pFailure if pFailure is not NULL.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001663 */
Andy McFadden62a75162009-04-17 17:23:37 -07001664ClassObject* dvmOptResolveClass(ClassObject* referrer, u4 classIdx,
1665 VerifyError* pFailure)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001666{
1667 DvmDex* pDvmDex = referrer->pDvmDex;
1668 ClassObject* resClass;
1669
1670 /*
1671 * Check the table first. If not there, do the lookup by name.
1672 */
1673 resClass = dvmDexGetResolvedClass(pDvmDex, classIdx);
1674 if (resClass == NULL) {
1675 const char* className = dexStringByTypeIdx(pDvmDex->pDexFile, classIdx);
1676 if (className[0] != '\0' && className[1] == '\0') {
1677 /* primitive type */
1678 resClass = dvmFindPrimitiveClass(className[0]);
1679 } else {
1680 resClass = dvmFindClassNoInit(className, referrer->classLoader);
1681 }
1682 if (resClass == NULL) {
1683 /* not found, exception should be raised */
1684 LOGV("DexOpt: class %d (%s) not found\n",
1685 classIdx,
1686 dexStringByTypeIdx(pDvmDex->pDexFile, classIdx));
1687 dvmClearOptException(dvmThreadSelf());
Andy McFadden62a75162009-04-17 17:23:37 -07001688 if (pFailure != NULL)
1689 *pFailure = VERIFY_ERROR_NO_CLASS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001690 return NULL;
1691 }
1692
1693 /*
1694 * Add it to the resolved table so we're faster on the next lookup.
1695 */
1696 dvmDexSetResolvedClass(pDvmDex, classIdx, resClass);
1697 }
1698
1699 /* multiple definitions? */
1700 if (IS_CLASS_FLAG_SET(resClass, CLASS_MULTIPLE_DEFS)) {
1701 LOGI("DexOpt: not resolving ambiguous class '%s'\n",
1702 resClass->descriptor);
Andy McFadden62a75162009-04-17 17:23:37 -07001703 if (pFailure != NULL)
1704 *pFailure = VERIFY_ERROR_NO_CLASS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001705 return NULL;
1706 }
1707
1708 /* access allowed? */
1709 tweakLoader(referrer, resClass);
1710 bool allowed = dvmCheckClassAccess(referrer, resClass);
1711 untweakLoader(referrer, resClass);
1712 if (!allowed) {
1713 LOGW("DexOpt: resolve class illegal access: %s -> %s\n",
1714 referrer->descriptor, resClass->descriptor);
Andy McFadden62a75162009-04-17 17:23:37 -07001715 if (pFailure != NULL)
1716 *pFailure = VERIFY_ERROR_ACCESS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001717 return NULL;
1718 }
1719
1720 return resClass;
1721}
1722
1723/*
1724 * Alternate version of dvmResolveInstField().
Andy McFadden62a75162009-04-17 17:23:37 -07001725 *
1726 * On failure, returns NULL, and sets *pFailure if pFailure is not NULL.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001727 */
Andy McFadden62a75162009-04-17 17:23:37 -07001728InstField* dvmOptResolveInstField(ClassObject* referrer, u4 ifieldIdx,
1729 VerifyError* pFailure)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001730{
1731 DvmDex* pDvmDex = referrer->pDvmDex;
1732 InstField* resField;
1733
1734 resField = (InstField*) dvmDexGetResolvedField(pDvmDex, ifieldIdx);
1735 if (resField == NULL) {
1736 const DexFieldId* pFieldId;
1737 ClassObject* resClass;
1738
1739 pFieldId = dexGetFieldId(pDvmDex->pDexFile, ifieldIdx);
1740
1741 /*
1742 * Find the field's class.
1743 */
Andy McFadden62a75162009-04-17 17:23:37 -07001744 resClass = dvmOptResolveClass(referrer, pFieldId->classIdx, pFailure);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001745 if (resClass == NULL) {
1746 //dvmClearOptException(dvmThreadSelf());
1747 assert(!dvmCheckException(dvmThreadSelf()));
Andy McFadden62a75162009-04-17 17:23:37 -07001748 if (pFailure != NULL)
1749 *pFailure = VERIFY_ERROR_NO_FIELD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001750 return NULL;
1751 }
1752
1753 resField = dvmFindInstanceFieldHier(resClass,
1754 dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx),
1755 dexStringByTypeIdx(pDvmDex->pDexFile, pFieldId->typeIdx));
1756 if (resField == NULL) {
1757 LOGD("DexOpt: couldn't find field %s.%s\n",
1758 resClass->descriptor,
1759 dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx));
Andy McFadden62a75162009-04-17 17:23:37 -07001760 if (pFailure != NULL)
1761 *pFailure = VERIFY_ERROR_NO_FIELD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001762 return NULL;
1763 }
1764
1765 /*
1766 * Add it to the resolved table so we're faster on the next lookup.
1767 */
1768 dvmDexSetResolvedField(pDvmDex, ifieldIdx, (Field*) resField);
1769 }
1770
1771 /* access allowed? */
1772 tweakLoader(referrer, resField->field.clazz);
1773 bool allowed = dvmCheckFieldAccess(referrer, (Field*)resField);
1774 untweakLoader(referrer, resField->field.clazz);
1775 if (!allowed) {
1776 LOGI("DexOpt: access denied from %s to field %s.%s\n",
1777 referrer->descriptor, resField->field.clazz->descriptor,
1778 resField->field.name);
Andy McFadden62a75162009-04-17 17:23:37 -07001779 if (pFailure != NULL)
1780 *pFailure = VERIFY_ERROR_ACCESS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001781 return NULL;
1782 }
1783
1784 return resField;
1785}
1786
1787/*
1788 * Alternate version of dvmResolveStaticField().
1789 *
1790 * Does not force initialization of the resolved field's class.
Andy McFadden62a75162009-04-17 17:23:37 -07001791 *
1792 * On failure, returns NULL, and sets *pFailure if pFailure is not NULL.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001793 */
Andy McFadden62a75162009-04-17 17:23:37 -07001794StaticField* dvmOptResolveStaticField(ClassObject* referrer, u4 sfieldIdx,
1795 VerifyError* pFailure)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001796{
1797 DvmDex* pDvmDex = referrer->pDvmDex;
1798 StaticField* resField;
1799
1800 resField = (StaticField*)dvmDexGetResolvedField(pDvmDex, sfieldIdx);
1801 if (resField == NULL) {
1802 const DexFieldId* pFieldId;
1803 ClassObject* resClass;
1804
1805 pFieldId = dexGetFieldId(pDvmDex->pDexFile, sfieldIdx);
1806
1807 /*
1808 * Find the field's class.
1809 */
Andy McFadden62a75162009-04-17 17:23:37 -07001810 resClass = dvmOptResolveClass(referrer, pFieldId->classIdx, pFailure);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001811 if (resClass == NULL) {
1812 //dvmClearOptException(dvmThreadSelf());
1813 assert(!dvmCheckException(dvmThreadSelf()));
Andy McFadden62a75162009-04-17 17:23:37 -07001814 if (pFailure != NULL)
1815 *pFailure = VERIFY_ERROR_NO_FIELD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001816 return NULL;
1817 }
1818
1819 resField = dvmFindStaticFieldHier(resClass,
1820 dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx),
1821 dexStringByTypeIdx(pDvmDex->pDexFile, pFieldId->typeIdx));
1822 if (resField == NULL) {
1823 LOGD("DexOpt: couldn't find static field\n");
Andy McFadden62a75162009-04-17 17:23:37 -07001824 if (pFailure != NULL)
1825 *pFailure = VERIFY_ERROR_NO_FIELD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001826 return NULL;
1827 }
1828
1829 /*
1830 * Add it to the resolved table so we're faster on the next lookup.
1831 *
1832 * We can only do this if we're in "dexopt", because the presence
1833 * of a valid value in the resolution table implies that the class
1834 * containing the static field has been initialized.
1835 */
1836 if (gDvm.optimizing)
1837 dvmDexSetResolvedField(pDvmDex, sfieldIdx, (Field*) resField);
1838 }
1839
1840 /* access allowed? */
1841 tweakLoader(referrer, resField->field.clazz);
1842 bool allowed = dvmCheckFieldAccess(referrer, (Field*)resField);
1843 untweakLoader(referrer, resField->field.clazz);
1844 if (!allowed) {
1845 LOGI("DexOpt: access denied from %s to field %s.%s\n",
1846 referrer->descriptor, resField->field.clazz->descriptor,
1847 resField->field.name);
Andy McFadden62a75162009-04-17 17:23:37 -07001848 if (pFailure != NULL)
1849 *pFailure = VERIFY_ERROR_ACCESS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001850 return NULL;
1851 }
1852
1853 return resField;
1854}
1855
1856
1857/*
1858 * Rewrite an iget/iput instruction. These all have the form:
1859 * op vA, vB, field@CCCC
1860 *
1861 * Where vA holds the value, vB holds the object reference, and CCCC is
1862 * the field reference constant pool offset. We want to replace CCCC
1863 * with the byte offset from the start of the object.
1864 *
1865 * "clazz" is the referring class. We need this because we verify
1866 * access rights here.
1867 */
1868static void rewriteInstField(Method* method, u2* insns, OpCode newOpc)
1869{
1870 ClassObject* clazz = method->clazz;
1871 u2 fieldIdx = insns[1];
1872 InstField* field;
1873 int byteOffset;
1874
Andy McFadden62a75162009-04-17 17:23:37 -07001875 field = dvmOptResolveInstField(clazz, fieldIdx, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001876 if (field == NULL) {
1877 LOGI("DexOpt: unable to optimize field ref 0x%04x at 0x%02x in %s.%s\n",
1878 fieldIdx, (int) (insns - method->insns), clazz->descriptor,
1879 method->name);
1880 return;
1881 }
1882
1883 if (field->byteOffset >= 65536) {
1884 LOGI("DexOpt: field offset exceeds 64K (%d)\n", field->byteOffset);
1885 return;
1886 }
1887
1888 insns[0] = (insns[0] & 0xff00) | (u2) newOpc;
1889 insns[1] = (u2) field->byteOffset;
1890 LOGVV("DexOpt: rewrote access to %s.%s --> %d\n",
1891 field->field.clazz->descriptor, field->field.name,
1892 field->byteOffset);
1893}
1894
1895/*
1896 * Alternate version of dvmResolveMethod().
1897 *
1898 * Doesn't throw exceptions, and checks access on every lookup.
Andy McFadden62a75162009-04-17 17:23:37 -07001899 *
1900 * On failure, returns NULL, and sets *pFailure if pFailure is not NULL.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001901 */
1902Method* dvmOptResolveMethod(ClassObject* referrer, u4 methodIdx,
Andy McFadden62a75162009-04-17 17:23:37 -07001903 MethodType methodType, VerifyError* pFailure)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001904{
1905 DvmDex* pDvmDex = referrer->pDvmDex;
1906 Method* resMethod;
1907
1908 assert(methodType != METHOD_INTERFACE);
1909
1910 LOGVV("--- resolving method %u (referrer=%s)\n", methodIdx,
1911 referrer->descriptor);
1912
1913 resMethod = dvmDexGetResolvedMethod(pDvmDex, methodIdx);
1914 if (resMethod == NULL) {
1915 const DexMethodId* pMethodId;
1916 ClassObject* resClass;
1917
1918 pMethodId = dexGetMethodId(pDvmDex->pDexFile, methodIdx);
1919
Andy McFadden62a75162009-04-17 17:23:37 -07001920 resClass = dvmOptResolveClass(referrer, pMethodId->classIdx, pFailure);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001921 if (resClass == NULL) {
1922 /* can't find the class that the method is a part of */
1923 LOGV("DexOpt: can't find called method's class (?.%s)\n",
1924 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx));
Andy McFadden62a75162009-04-17 17:23:37 -07001925 if (pFailure != NULL)
1926 *pFailure = VERIFY_ERROR_NO_METHOD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001927 return NULL;
1928 }
1929 if (dvmIsInterfaceClass(resClass)) {
1930 /* method is part of an interface; this is wrong method for that */
1931 LOGW("DexOpt: method is in an interface\n");
Andy McFadden62a75162009-04-17 17:23:37 -07001932 if (pFailure != NULL)
1933 *pFailure = VERIFY_ERROR_GENERIC;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001934 return NULL;
1935 }
1936
1937 /*
1938 * We need to chase up the class hierarchy to find methods defined
1939 * in super-classes. (We only want to check the current class
1940 * if we're looking for a constructor.)
1941 */
1942 DexProto proto;
1943 dexProtoSetFromMethodId(&proto, pDvmDex->pDexFile, pMethodId);
1944
1945 if (methodType == METHOD_DIRECT) {
1946 resMethod = dvmFindDirectMethod(resClass,
1947 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx), &proto);
1948 } else if (methodType == METHOD_STATIC) {
1949 resMethod = dvmFindDirectMethodHier(resClass,
1950 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx), &proto);
1951 } else {
1952 resMethod = dvmFindVirtualMethodHier(resClass,
1953 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx), &proto);
1954 }
1955
1956 if (resMethod == NULL) {
1957 LOGV("DexOpt: couldn't find method '%s'\n",
1958 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx));
Andy McFadden62a75162009-04-17 17:23:37 -07001959 if (pFailure != NULL)
1960 *pFailure = VERIFY_ERROR_NO_METHOD;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001961 return NULL;
1962 }
1963
1964 /* see if this is a pure-abstract method */
1965 if (dvmIsAbstractMethod(resMethod) && !dvmIsAbstractClass(resClass)) {
1966 LOGW("DexOpt: pure-abstract method '%s' in %s\n",
1967 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx),
1968 resClass->descriptor);
Andy McFadden62a75162009-04-17 17:23:37 -07001969 if (pFailure != NULL)
1970 *pFailure = VERIFY_ERROR_GENERIC;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001971 return NULL;
1972 }
1973
1974 /*
1975 * Add it to the resolved table so we're faster on the next lookup.
1976 *
1977 * We can only do this for static methods if we're not in "dexopt",
1978 * because the presence of a valid value in the resolution table
1979 * implies that the class containing the static field has been
1980 * initialized.
1981 */
1982 if (methodType != METHOD_STATIC || gDvm.optimizing)
1983 dvmDexSetResolvedMethod(pDvmDex, methodIdx, resMethod);
1984 }
1985
1986 LOGVV("--- found method %d (%s.%s)\n",
1987 methodIdx, resMethod->clazz->descriptor, resMethod->name);
1988
1989 /* access allowed? */
1990 tweakLoader(referrer, resMethod->clazz);
1991 bool allowed = dvmCheckMethodAccess(referrer, resMethod);
1992 untweakLoader(referrer, resMethod->clazz);
1993 if (!allowed) {
1994 IF_LOGI() {
1995 char* desc = dexProtoCopyMethodDescriptor(&resMethod->prototype);
1996 LOGI("DexOpt: illegal method access (call %s.%s %s from %s)\n",
1997 resMethod->clazz->descriptor, resMethod->name, desc,
1998 referrer->descriptor);
1999 free(desc);
2000 }
Andy McFadden62a75162009-04-17 17:23:37 -07002001 if (pFailure != NULL)
2002 *pFailure = VERIFY_ERROR_ACCESS;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002003 return NULL;
2004 }
2005
2006 return resMethod;
2007}
2008
2009/*
2010 * Rewrite invoke-virtual, invoke-virtual/range, invoke-super, and
2011 * invoke-super/range. These all have the form:
2012 * op vAA, meth@BBBB, reg stuff @CCCC
2013 *
2014 * We want to replace the method constant pool index BBBB with the
2015 * vtable index.
2016 */
2017static bool rewriteVirtualInvoke(Method* method, u2* insns, OpCode newOpc)
2018{
2019 ClassObject* clazz = method->clazz;
2020 Method* baseMethod;
2021 u2 methodIdx = insns[1];
2022
Andy McFadden62a75162009-04-17 17:23:37 -07002023 baseMethod = dvmOptResolveMethod(clazz, methodIdx, METHOD_VIRTUAL, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002024 if (baseMethod == NULL) {
2025 LOGD("DexOpt: unable to optimize virt call 0x%04x at 0x%02x in %s.%s\n",
2026 methodIdx,
2027 (int) (insns - method->insns), clazz->descriptor,
2028 method->name);
2029 return false;
2030 }
2031
2032 assert((insns[0] & 0xff) == OP_INVOKE_VIRTUAL ||
2033 (insns[0] & 0xff) == OP_INVOKE_VIRTUAL_RANGE ||
2034 (insns[0] & 0xff) == OP_INVOKE_SUPER ||
2035 (insns[0] & 0xff) == OP_INVOKE_SUPER_RANGE);
2036
2037 /*
2038 * Note: Method->methodIndex is a u2 and is range checked during the
2039 * initial load.
2040 */
2041 insns[0] = (insns[0] & 0xff00) | (u2) newOpc;
2042 insns[1] = baseMethod->methodIndex;
2043
2044 //LOGI("DexOpt: rewrote call to %s.%s --> %s.%s\n",
2045 // method->clazz->descriptor, method->name,
2046 // baseMethod->clazz->descriptor, baseMethod->name);
2047
2048 return true;
2049}
2050
2051/*
2052 * Rewrite invoke-direct, which has the form:
2053 * op vAA, meth@BBBB, reg stuff @CCCC
2054 *
2055 * There isn't a lot we can do to make this faster, but in some situations
2056 * we can make it go away entirely.
2057 *
2058 * This must only be used when the invoked method does nothing and has
2059 * no return value (the latter being very important for verification).
2060 */
2061static bool rewriteDirectInvoke(Method* method, u2* insns)
2062{
2063 ClassObject* clazz = method->clazz;
2064 Method* calledMethod;
2065 u2 methodIdx = insns[1];
2066
Andy McFadden62a75162009-04-17 17:23:37 -07002067 calledMethod = dvmOptResolveMethod(clazz, methodIdx, METHOD_DIRECT, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002068 if (calledMethod == NULL) {
2069 LOGD("DexOpt: unable to opt direct call 0x%04x at 0x%02x in %s.%s\n",
2070 methodIdx,
2071 (int) (insns - method->insns), clazz->descriptor,
2072 method->name);
2073 return false;
2074 }
2075
2076 /* TODO: verify that java.lang.Object() is actually empty! */
2077 if (calledMethod->clazz == gDvm.classJavaLangObject &&
2078 dvmCompareNameDescriptorAndMethod("<init>", "()V", calledMethod) == 0)
2079 {
2080 /*
2081 * Replace with "empty" instruction. DO NOT disturb anything
2082 * else about it, as we want it to function the same as
2083 * OP_INVOKE_DIRECT when debugging is enabled.
2084 */
2085 assert((insns[0] & 0xff) == OP_INVOKE_DIRECT);
2086 insns[0] = (insns[0] & 0xff00) | (u2) OP_INVOKE_DIRECT_EMPTY;
2087
2088 //LOGI("DexOpt: marked-empty call to %s.%s --> %s.%s\n",
2089 // method->clazz->descriptor, method->name,
2090 // calledMethod->clazz->descriptor, calledMethod->name);
2091 }
2092
2093 return true;
2094}
2095
2096/*
2097 * Resolve an interface method reference.
2098 *
Andy McFadden62a75162009-04-17 17:23:37 -07002099 * No method access check here -- interface methods are always public.
2100 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002101 * Returns NULL if the method was not found. Does not throw an exception.
2102 */
2103Method* dvmOptResolveInterfaceMethod(ClassObject* referrer, u4 methodIdx)
2104{
2105 DvmDex* pDvmDex = referrer->pDvmDex;
2106 Method* resMethod;
2107 int i;
2108
2109 LOGVV("--- resolving interface method %d (referrer=%s)\n",
2110 methodIdx, referrer->descriptor);
2111
2112 resMethod = dvmDexGetResolvedMethod(pDvmDex, methodIdx);
2113 if (resMethod == NULL) {
2114 const DexMethodId* pMethodId;
2115 ClassObject* resClass;
2116
2117 pMethodId = dexGetMethodId(pDvmDex->pDexFile, methodIdx);
2118
Andy McFadden62a75162009-04-17 17:23:37 -07002119 resClass = dvmOptResolveClass(referrer, pMethodId->classIdx, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002120 if (resClass == NULL) {
2121 /* can't find the class that the method is a part of */
2122 dvmClearOptException(dvmThreadSelf());
2123 return NULL;
2124 }
2125 if (!dvmIsInterfaceClass(resClass)) {
2126 /* whoops */
2127 LOGI("Interface method not part of interface class\n");
2128 return NULL;
2129 }
2130
2131 const char* methodName =
2132 dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx);
2133 DexProto proto;
2134 dexProtoSetFromMethodId(&proto, pDvmDex->pDexFile, pMethodId);
2135
2136 LOGVV("+++ looking for '%s' '%s' in resClass='%s'\n",
2137 methodName, methodSig, resClass->descriptor);
2138 resMethod = dvmFindVirtualMethod(resClass, methodName, &proto);
2139 if (resMethod == NULL) {
2140 /* scan superinterfaces and superclass interfaces */
2141 LOGVV("+++ did not resolve immediately\n");
2142 for (i = 0; i < resClass->iftableCount; i++) {
2143 resMethod = dvmFindVirtualMethod(resClass->iftable[i].clazz,
2144 methodName, &proto);
2145 if (resMethod != NULL)
2146 break;
2147 }
2148
2149 if (resMethod == NULL) {
2150 LOGVV("+++ unable to resolve method %s\n", methodName);
2151 return NULL;
2152 }
2153 } else {
2154 LOGVV("+++ resolved immediately: %s (%s %d)\n", resMethod->name,
2155 resMethod->clazz->descriptor, (u4) resMethod->methodIndex);
2156 }
2157
2158 /* we're expecting this to be abstract */
2159 if (!dvmIsAbstractMethod(resMethod)) {
2160 char* desc = dexProtoCopyMethodDescriptor(&resMethod->prototype);
2161 LOGW("Found non-abstract interface method %s.%s %s\n",
2162 resMethod->clazz->descriptor, resMethod->name, desc);
2163 free(desc);
2164 return NULL;
2165 }
2166
2167 /*
2168 * Add it to the resolved table so we're faster on the next lookup.
2169 */
2170 dvmDexSetResolvedMethod(pDvmDex, methodIdx, resMethod);
2171 }
2172
2173 LOGVV("--- found interface method %d (%s.%s)\n",
2174 methodIdx, resMethod->clazz->descriptor, resMethod->name);
2175
2176 /* interface methods are always public; no need to check access */
2177
2178 return resMethod;
2179}
2180/*
2181 * See if the method being called can be rewritten as an inline operation.
2182 * Works for invoke-virtual, invoke-direct, and invoke-static.
2183 *
2184 * Returns "true" if we replace it.
2185 */
2186static bool rewriteExecuteInline(Method* method, u2* insns,
2187 MethodType methodType, const InlineSub* inlineSubs)
2188{
2189 ClassObject* clazz = method->clazz;
2190 Method* calledMethod;
2191 u2 methodIdx = insns[1];
2192
2193 //return false;
2194
Andy McFadden62a75162009-04-17 17:23:37 -07002195 calledMethod = dvmOptResolveMethod(clazz, methodIdx, methodType, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002196 if (calledMethod == NULL) {
2197 LOGV("+++ DexOpt inline: can't find %d\n", methodIdx);
2198 return false;
2199 }
2200
2201 while (inlineSubs->method != NULL) {
2202 /*
2203 if (extra) {
2204 LOGI("comparing %p vs %p %s.%s %s\n",
2205 inlineSubs->method, calledMethod,
2206 inlineSubs->method->clazz->descriptor,
2207 inlineSubs->method->name,
2208 inlineSubs->method->signature);
2209 }
2210 */
2211 if (inlineSubs->method == calledMethod) {
2212 assert((insns[0] & 0xff) == OP_INVOKE_DIRECT ||
2213 (insns[0] & 0xff) == OP_INVOKE_STATIC ||
2214 (insns[0] & 0xff) == OP_INVOKE_VIRTUAL);
2215 insns[0] = (insns[0] & 0xff00) | (u2) OP_EXECUTE_INLINE;
2216 insns[1] = (u2) inlineSubs->inlineIdx;
2217
2218 //LOGI("DexOpt: execute-inline %s.%s --> %s.%s\n",
2219 // method->clazz->descriptor, method->name,
2220 // calledMethod->clazz->descriptor, calledMethod->name);
2221 return true;
2222 }
2223
2224 inlineSubs++;
2225 }
2226
2227 return false;
2228}
2229