blob: d437a3fc9c06a99fddca89449411114e132bdcd5 [file] [log] [blame]
Carl Shapiro1fb86202011-06-27 17:43:13 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07004
5#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -07006#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -07007#include <stdio.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07008#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -07009#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070010#include <sys/mman.h>
11#include <sys/stat.h>
12#include <sys/types.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070013
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <map>
15
16#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "globals.h"
18#include "logging.h"
19#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070020#include "os.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include "stringprintf.h"
22#include "thread.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070025
26namespace art {
27
Brian Carlstromf615a612011-07-23 12:50:34 -070028const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
29const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070030
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070031DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070032 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070033 for (size_t i = 0; i != class_path.size(); ++i) {
34 const DexFile* dex_file = class_path[i];
35 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
36 if (dex_class_def != NULL) {
37 return ClassPathEntry(dex_file, dex_class_def);
38 }
39 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070040 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070041 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
42 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070043}
44
Brian Carlstrom78128a62011-09-15 17:21:19 -070045void DexFile::OpenDexFiles(std::vector<const char*>& dex_filenames,
46 std::vector<const DexFile*>& dex_files,
47 const std::string& strip_location_prefix) {
48 for (size_t i = 0; i < dex_filenames.size(); i++) {
49 const char* dex_filename = dex_filenames[i];
50 const DexFile* dex_file = Open(dex_filename, strip_location_prefix);
51 if (dex_file == NULL) {
52 fprintf(stderr, "could not open .dex from file %s\n", dex_filename);
53 exit(EXIT_FAILURE);
54 }
55 dex_files.push_back(dex_file);
56 }
57}
58
Brian Carlstrom16192862011-09-12 17:50:06 -070059const DexFile* DexFile::Open(const std::string& filename,
60 const std::string& strip_location_prefix) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070061 if (filename.size() < 4) {
62 LOG(WARNING) << "Ignoring short classpath entry '" << filename << "'";
63 return NULL;
64 }
65 std::string suffix(filename.substr(filename.size() - 4));
66 if (suffix == ".zip" || suffix == ".jar" || suffix == ".apk") {
Brian Carlstrom16192862011-09-12 17:50:06 -070067 return DexFile::OpenZip(filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070068 } else {
Brian Carlstrom16192862011-09-12 17:50:06 -070069 return DexFile::OpenFile(filename, filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070070 }
71}
72
jeffhaob4df5142011-09-19 20:25:32 -070073void DexFile::ChangePermissions(int prot) const {
74 closer_->ChangePermissions(prot);
75}
76
Brian Carlstromf615a612011-07-23 12:50:34 -070077DexFile::Closer::~Closer() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070078
Brian Carlstromf615a612011-07-23 12:50:34 -070079DexFile::MmapCloser::MmapCloser(void* addr, size_t length) : addr_(addr), length_(length) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070080 CHECK(addr != NULL);
81}
Brian Carlstromf615a612011-07-23 12:50:34 -070082DexFile::MmapCloser::~MmapCloser() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070083 if (munmap(addr_, length_) == -1) {
84 PLOG(INFO) << "munmap failed";
85 }
86}
jeffhaob4df5142011-09-19 20:25:32 -070087void DexFile::MmapCloser::ChangePermissions(int prot) {
88 if (mprotect(addr_, length_, prot) != 0) {
89 PLOG(FATAL) << "Failed to change dex file permissions to " << prot;
90 }
91}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070092
Brian Carlstromf615a612011-07-23 12:50:34 -070093DexFile::PtrCloser::PtrCloser(byte* addr) : addr_(addr) {}
94DexFile::PtrCloser::~PtrCloser() { delete[] addr_; }
jeffhaob4df5142011-09-19 20:25:32 -070095void DexFile::PtrCloser::ChangePermissions(int prot) {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070096
Brian Carlstrom16192862011-09-12 17:50:06 -070097const DexFile* DexFile::OpenFile(const std::string& filename,
98 const std::string& original_location,
99 const std::string& strip_location_prefix) {
100 StringPiece location = original_location;
101 if (!location.starts_with(strip_location_prefix)) {
102 LOG(ERROR) << filename << " does not start with " << strip_location_prefix;
103 return NULL;
104 }
105 location.remove_prefix(strip_location_prefix.size());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700106 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700107 if (fd == -1) {
108 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
109 return NULL;
110 }
111 struct stat sbuf;
112 memset(&sbuf, 0, sizeof(sbuf));
113 if (fstat(fd, &sbuf) == -1) {
114 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
115 close(fd);
116 return NULL;
117 }
118 size_t length = sbuf.st_size;
jeffhaob4df5142011-09-19 20:25:32 -0700119 void* addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700120 if (addr == MAP_FAILED) {
121 PLOG(ERROR) << "mmap \"" << filename << "\" failed";
122 close(fd);
123 return NULL;
124 }
125 close(fd);
126 byte* dex_file = reinterpret_cast<byte*>(addr);
127 Closer* closer = new MmapCloser(addr, length);
Brian Carlstrom16192862011-09-12 17:50:06 -0700128 return Open(dex_file, length, location.ToString(), closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700129}
130
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700131static const char* kClassesDex = "classes.dex";
132
133class LockedFd {
134 public:
135 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
136 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
137 if (fd == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700138 PLOG(ERROR) << "Failed to open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700139 return NULL;
140 }
141 fchmod(fd, mode);
142
143 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
144 int result = flock(fd, LOCK_EX | LOCK_NB);
145 if (result == -1) {
146 LOG(WARNING) << "sleeping while locking file " << name;
147 result = flock(fd, LOCK_EX);
148 }
149 if (result == -1 ) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700150 PLOG(ERROR) << "Failed to lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700151 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700152 return NULL;
153 }
154 return new LockedFd(fd);
155 }
156
157 int GetFd() const {
158 return fd_;
159 }
160
161 ~LockedFd() {
162 if (fd_ != -1) {
163 int result = flock(fd_, LOCK_UN);
164 if (result == -1) {
165 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
166 }
167 close(fd_);
168 }
169 }
170
171 private:
172 LockedFd(int fd) : fd_(fd) {}
173
174 int fd_;
175};
176
177class TmpFile {
178 public:
179 TmpFile(const std::string name) : name_(name) {}
180 ~TmpFile() {
181 unlink(name_.c_str());
182 }
183 private:
184 const std::string name_;
185};
186
187// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700188const DexFile* DexFile::OpenZip(const std::string& filename,
189 const std::string& strip_location_prefix) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700190
191 // First, look for a ".dex" alongside the jar file. It will have
192 // the same name/path except for the extension.
193
194 // Example filename = dir/foo.jar
195 std::string adjacent_dex_filename(filename);
196 size_t found = adjacent_dex_filename.find_last_of(".");
197 if (found == std::string::npos) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700198 LOG(ERROR) << "No . in filename" << filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700199 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700200 }
201 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
202 adjacent_dex_filename.end(),
203 ".dex");
204 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700205 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700206 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename,
207 filename,
208 strip_location_prefix);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700209 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700210 // We don't verify anything in this case, because we aren't in
211 // the cache and typically the file is in the readonly /system
212 // area, so if something is wrong, there is nothing we can do.
213 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700214 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700215 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700216 }
217
218 char resolved[PATH_MAX];
219 char* absolute_path = realpath(filename.c_str(), resolved);
220 if (absolute_path == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700221 LOG(ERROR) << "Failed to create absolute path for " << filename
222 << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700223 return NULL;
224 }
225 std::string cache_file(absolute_path+1); // skip leading slash
226 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
227 cache_file.push_back('@');
228 cache_file.append(kClassesDex);
229 // Example cache_file = parent@dir@foo.jar@classes.dex
230
231 const char* data_root = getenv("ANDROID_DATA");
232 if (data_root == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700233 if (OS::DirectoryExists("/data")) {
234 data_root = "/data";
235 } else {
236 data_root = "/tmp";
237 }
238 }
239 if (!OS::DirectoryExists(data_root)) {
240 LOG(ERROR) << "Failed to find ANDROID_DATA directory " << data_root;
241 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700242 }
243
Brian Carlstrom16192862011-09-12 17:50:06 -0700244 std::string art_cache = StringPrintf("%s/art-cache", data_root);
245
246 if (!OS::DirectoryExists(art_cache.c_str())) {
247 if (StringPiece(art_cache).starts_with("/tmp/")) {
248 int result = mkdir(art_cache.c_str(), 0700);
249 if (result != 0) {
Elliott Hughes380fac02011-09-16 16:01:07 -0700250 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
Brian Carlstrom16192862011-09-12 17:50:06 -0700251 return NULL;
252 }
253 } else {
Elliott Hughes380fac02011-09-16 16:01:07 -0700254 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
Brian Carlstrom16192862011-09-12 17:50:06 -0700255 return NULL;
256 }
257 }
258
259 std::string cache_path_tmp = StringPrintf("%s/%s", art_cache.c_str(), cache_file.c_str());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700260 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
261
Elliott Hughes90a33692011-08-30 13:27:07 -0700262 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
263 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700264 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700265 return NULL;
266 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700267 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
268 if (zip_entry.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700269 LOG(ERROR) << "Failed to find classes.dex within " << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700270 return NULL;
271 }
272
273 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
274 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
275
276 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700277 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700278 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path,
279 filename,
280 strip_location_prefix);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700281 if (cached_dex_file != NULL) {
282 return cached_dex_file;
283 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700284 }
285
286 // Try to open the temporary cache file, grabbing an exclusive
287 // lock. If somebody else is working on it, we'll block here until
288 // they complete. Because we're waiting on an external resource,
289 // we go into native mode.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700290 // Note that self can be NULL if we're parsing the bootclasspath
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700291 // during JNI_CreateJavaVM.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700292 Thread* self = Thread::Current();
293 UniquePtr<ScopedThreadStateChange> state_changer;
294 if (self != NULL) {
295 state_changer.reset(new ScopedThreadStateChange(self, Thread::kNative));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700296 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700297 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700298 state_changer.reset(NULL);
Elliott Hughes90a33692011-08-30 13:27:07 -0700299 if (fd.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700300 return NULL;
301 }
302
303 // Check to see if the fd we opened and locked matches the file in
304 // the filesystem. If they don't, then somebody else unlinked
305 // ours and created a new file, and we need to use that one
306 // instead. (If we caught them between the unlink and the create,
307 // we'll get an ENOENT from the file stat.)
308 struct stat fd_stat;
309 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
310 if (fd_stat_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700311 PLOG(ERROR) << "Failed to stat open file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700312 return NULL;
313 }
314 struct stat file_stat;
315 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
316 if (file_stat_result == -1 ||
317 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
318 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
319 usleep(250 * 1000); // if something is hosed, don't peg machine
320 continue;
321 }
322
323 // We have the correct file open and locked. Extract classes.dex
324 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700325 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
326 if (file.get() == NULL) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700327 return NULL;
328 }
329 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700330 if (!success) {
331 return NULL;
332 }
333
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700334 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700335
336 // Compute checksum and compare to zip. If things look okay, rename from tmp.
337 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
338 if (lseek_result == -1) {
339 return NULL;
340 }
341 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700342 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
343 if (buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700344 return NULL;
345 }
346 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
347 while (true) {
348 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700349 if (bytes_read == -1) {
350 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
351 return NULL;
352 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700353 if (bytes_read == 0) {
354 break;
355 }
356 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
357 }
358 if (computed_crc != zip_entry->GetCrc32()) {
359 return NULL;
360 }
361 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
362 if (rename_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700363 PLOG(ERROR) << "Failed to install dex cache file '" << cache_path << "'"
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700364 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700365 unlink(cache_path.c_str());
366 }
367 }
368 // NOTREACHED
369}
370
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700371const DexFile* DexFile::OpenPtr(byte* ptr, size_t length, const std::string& location) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700372 CHECK(ptr != NULL);
Brian Carlstromf615a612011-07-23 12:50:34 -0700373 DexFile::Closer* closer = new PtrCloser(ptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700374 return Open(ptr, length, location, closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700375}
376
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700377const DexFile* DexFile::Open(const byte* dex_bytes, size_t length,
378 const std::string& location, Closer* closer) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700379 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, closer));
Brian Carlstromf615a612011-07-23 12:50:34 -0700380 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700381 return NULL;
382 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700383 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700384 }
385}
386
Jesse Wilson6bf19152011-09-29 13:12:33 -0400387DexFile::~DexFile() {
388 if (dex_object_ != NULL) {
389 UNIMPLEMENTED(WARNING) << "leaked a global reference to an com.android.dex.Dex instance";
390 }
391}
392
393jobject DexFile::GetDexObject(JNIEnv* env) const {
394 MutexLock mu(dex_object_lock_);
395 if (dex_object_ != NULL) {
396 return dex_object_;
397 }
398
399 void* address = const_cast<void*>(reinterpret_cast<const void*>(base_));
400 jobject byte_buffer = env->NewDirectByteBuffer(address, length_);
401 if (byte_buffer == NULL) {
402 return NULL;
403 }
404
405 jclass c = env->FindClass("com/android/dex/Dex");
406 if (c == NULL) {
407 return NULL;
408 }
409
410 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
411 if (mid == NULL) {
412 return NULL;
413 }
414
415 jvalue args[1];
416 args[0].l = byte_buffer;
417 jobject local = env->CallStaticObjectMethodA(c, mid, args);
418 if (local == NULL) {
419 return NULL;
420 }
421
422 dex_object_ = env->NewGlobalRef(local);
423 return dex_object_;
424}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700425
Brian Carlstromf615a612011-07-23 12:50:34 -0700426bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700427 InitMembers();
428 if (!IsMagicValid()) {
429 return false;
430 }
431 InitIndex();
432 return true;
433}
434
Brian Carlstromf615a612011-07-23 12:50:34 -0700435void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700436 const byte* b = base_;
437 header_ = reinterpret_cast<const Header*>(b);
438 const Header* h = header_;
439 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
440 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
441 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
442 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
443 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
444 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
445}
446
Brian Carlstromf615a612011-07-23 12:50:34 -0700447bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700448 return CheckMagic(header_->magic_);
449}
450
Brian Carlstromf615a612011-07-23 12:50:34 -0700451bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700452 CHECK(magic != NULL);
453 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700454 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700455 << " " << magic[0]
456 << " " << magic[1]
457 << " " << magic[2]
458 << " " << magic[3];
459 return false;
460 }
461 const byte* version = &magic[sizeof(kDexMagic)];
462 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700463 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700464 << " " << version[0]
465 << " " << version[1]
466 << " " << version[2]
467 << " " << version[3];
468 return false;
469 }
470 return true;
471}
472
Brian Carlstromf615a612011-07-23 12:50:34 -0700473void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700474 CHECK_EQ(index_.size(), 0U);
475 for (size_t i = 0; i < NumClassDefs(); ++i) {
476 const ClassDef& class_def = GetClassDef(i);
477 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700478 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700479 }
480}
481
Brian Carlstrome24fa612011-09-29 00:53:55 -0700482bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700483 Index::const_iterator it = index_.find(descriptor);
484 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700485 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700486 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700487 idx = it->second;
488 return true;
489}
490
491const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
492 uint32_t idx;
493 if (FindClassDefIndex(descriptor, idx)) {
494 return &GetClassDef(idx);
495 }
496 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700497}
498
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700499// Materializes the method descriptor for a method prototype. Method
500// descriptors are not stored directly in the dex file. Instead, one
501// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700502std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
503 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700504 const ProtoId& proto_id = GetProtoId(proto_idx);
505 std::string descriptor;
506 descriptor.push_back('(');
507 const TypeList* type_list = GetProtoParameters(proto_id);
508 size_t parameter_length = 0;
509 if (type_list != NULL) {
510 // A non-zero number of arguments. Append the type names.
511 for (size_t i = 0; i < type_list->Size(); ++i) {
512 const TypeItem& type_item = type_list->GetTypeItem(i);
513 uint32_t type_idx = type_item.type_idx_;
514 int32_t type_length;
515 const char* name = dexStringByTypeIdx(type_idx, &type_length);
516 parameter_length += type_length;
517 descriptor.append(name);
518 }
519 }
520 descriptor.push_back(')');
521 uint32_t return_type_idx = proto_id.return_type_idx_;
522 int32_t return_type_length;
523 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
524 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700525 if (unicode_length != NULL) {
526 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
527 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700528 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700529}
530
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700531// Read a signed integer. "zwidth" is the zero-based byte count.
532static int32_t ReadSignedInt(const byte* ptr, int zwidth)
533{
534 int32_t val = 0;
535 for (int i = zwidth; i >= 0; --i) {
536 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
537 }
538 val >>= (3 - zwidth) * 8;
539 return val;
540}
541
542// Read an unsigned integer. "zwidth" is the zero-based byte count,
543// "fill_on_right" indicates which side we want to zero-fill from.
544static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
545 bool fill_on_right) {
546 uint32_t val = 0;
547 if (!fill_on_right) {
548 for (int i = zwidth; i >= 0; --i) {
549 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
550 }
551 val >>= (3 - zwidth) * 8;
552 } else {
553 for (int i = zwidth; i >= 0; --i) {
554 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
555 }
556 }
557 return val;
558}
559
560// Read a signed long. "zwidth" is the zero-based byte count.
561static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
562 int64_t val = 0;
563 for (int i = zwidth; i >= 0; --i) {
564 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
565 }
566 val >>= (7 - zwidth) * 8;
567 return val;
568}
569
570// Read an unsigned long. "zwidth" is the zero-based byte count,
571// "fill_on_right" indicates which side we want to zero-fill from.
572static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
573 bool fill_on_right) {
574 uint64_t val = 0;
575 if (!fill_on_right) {
576 for (int i = zwidth; i >= 0; --i) {
577 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
578 }
579 val >>= (7 - zwidth) * 8;
580 } else {
581 for (int i = zwidth; i >= 0; --i) {
582 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
583 }
584 }
585 return val;
586}
587
Brian Carlstromf615a612011-07-23 12:50:34 -0700588DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
589 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700590 const byte* ptr = *stream;
591 byte value_type = *ptr++;
592 byte value_arg = value_type >> kEncodedValueArgShift;
593 size_t width = value_arg + 1; // assume and correct later
594 int type = value_type & kEncodedValueTypeMask;
595 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700596 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700597 int32_t b = ReadSignedInt(ptr, value_arg);
598 CHECK(IsInt(8, b));
599 value->i = b;
600 break;
601 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700602 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700603 int32_t s = ReadSignedInt(ptr, value_arg);
604 CHECK(IsInt(16, s));
605 value->i = s;
606 break;
607 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700608 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700609 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
610 CHECK(IsUint(16, c));
611 value->i = c;
612 break;
613 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700614 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700615 value->i = ReadSignedInt(ptr, value_arg);
616 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700617 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700618 value->j = ReadSignedLong(ptr, value_arg);
619 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700620 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700621 value->i = ReadUnsignedInt(ptr, value_arg, true);
622 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700623 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700624 value->j = ReadUnsignedLong(ptr, value_arg, true);
625 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700626 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700627 value->i = (value_arg != 0);
628 width = 0;
629 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700630 case DexFile::kString:
631 case DexFile::kType:
632 case DexFile::kMethod:
633 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700634 value->i = ReadUnsignedInt(ptr, value_arg, false);
635 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700636 case DexFile::kField:
637 case DexFile::kArray:
638 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700639 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700640 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700641 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700642 value->i = 0;
643 width = 0;
644 break;
645 default:
646 LOG(FATAL) << "Unreached";
647 }
648 ptr += width;
649 *stream = ptr;
650 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700651}
652
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700653String* DexFile::dexArtStringById(int32_t idx) const {
654 if (idx == -1) {
655 return NULL;
656 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700657 return String::AllocFromModifiedUtf8(dexStringById(idx));
658}
659
660int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700661 // For native method, lineno should be -2 to indicate it is native. Note that
662 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700663 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700664 return -2;
665 }
666
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700668 DCHECK(code_item != NULL);
669
670 // A method with no line number info should return -1
671 LineNumFromPcContext context(rel_pc, -1);
672 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
673 return context.line_num_;
674}
675
676void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
677 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
678 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
679 uint32_t line = DecodeUnsignedLeb128(&stream);
680 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
681 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
682 uint32_t address = 0;
683
684 if (!method->IsStatic()) {
685 local_in_reg[arg_reg].name_ = String::AllocFromModifiedUtf8("this");
686 local_in_reg[arg_reg].descriptor_ = method->GetDeclaringClass()->GetDescriptor();
687 local_in_reg[arg_reg].signature_ = NULL;
688 local_in_reg[arg_reg].start_address_ = 0;
689 local_in_reg[arg_reg].is_live_ = true;
690 arg_reg++;
691 }
692
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700693 ParameterIterator *it = GetParameterIterator(GetProtoId(method->GetProtoIdx()));
Shih-wei Liao195487c2011-08-20 13:29:04 -0700694 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
695 if (arg_reg >= code_item->registers_size_) {
696 LOG(FATAL) << "invalid stream";
697 return;
698 }
699
700 String* descriptor = String::AllocFromModifiedUtf8(it->GetDescriptor());
701 String* name = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
702
703 local_in_reg[arg_reg].name_ = name;
704 local_in_reg[arg_reg].descriptor_ = descriptor;
705 local_in_reg[arg_reg].signature_ = NULL;
706 local_in_reg[arg_reg].start_address_ = address;
707 local_in_reg[arg_reg].is_live_ = true;
708 switch (descriptor->CharAt(0)) {
709 case 'D':
710 case 'J':
711 arg_reg += 2;
712 break;
713 default:
714 arg_reg += 1;
715 break;
716 }
717 }
718
719 if (it->HasNext()) {
720 LOG(FATAL) << "invalid stream";
721 return;
722 }
723
724 for (;;) {
725 uint8_t opcode = *stream++;
726 uint8_t adjopcode = opcode - DBG_FIRST_SPECIAL;
727 uint16_t reg;
728
729
730 switch (opcode) {
731 case DBG_END_SEQUENCE:
732 return;
733
734 case DBG_ADVANCE_PC:
735 address += DecodeUnsignedLeb128(&stream);
736 break;
737
738 case DBG_ADVANCE_LINE:
739 line += DecodeUnsignedLeb128(&stream);
740 break;
741
742 case DBG_START_LOCAL:
743 case DBG_START_LOCAL_EXTENDED:
744 reg = DecodeUnsignedLeb128(&stream);
745 if (reg > code_item->registers_size_) {
746 LOG(FATAL) << "invalid stream";
747 return;
748 }
749
750 // Emit what was previously there, if anything
751 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
752
753 local_in_reg[reg].name_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
754 local_in_reg[reg].descriptor_ = dexArtStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
755 if (opcode == DBG_START_LOCAL_EXTENDED) {
756 local_in_reg[reg].signature_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
757 } else {
758 local_in_reg[reg].signature_ = NULL;
759 }
760 local_in_reg[reg].start_address_ = address;
761 local_in_reg[reg].is_live_ = true;
762 break;
763
764 case DBG_END_LOCAL:
765 reg = DecodeUnsignedLeb128(&stream);
766 if (reg > code_item->registers_size_) {
767 LOG(FATAL) << "invalid stream";
768 return;
769 }
770
771 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
772 local_in_reg[reg].is_live_ = false;
773 break;
774
775 case DBG_RESTART_LOCAL:
776 reg = DecodeUnsignedLeb128(&stream);
777 if (reg > code_item->registers_size_) {
778 LOG(FATAL) << "invalid stream";
779 return;
780 }
781
782 if (local_in_reg[reg].name_ == NULL
783 || local_in_reg[reg].descriptor_ == NULL) {
784 LOG(FATAL) << "invalid stream";
785 return;
786 }
787
788 // If the register is live, the "restart" is superfluous,
789 // and we don't want to mess with the existing start address.
790 if (!local_in_reg[reg].is_live_) {
791 local_in_reg[reg].start_address_ = address;
792 local_in_reg[reg].is_live_ = true;
793 }
794 break;
795
796 case DBG_SET_PROLOGUE_END:
797 case DBG_SET_EPILOGUE_BEGIN:
798 case DBG_SET_FILE:
799 break;
800
801 default:
802 address += adjopcode / DBG_LINE_RANGE;
803 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
804
805 if (posCb != NULL) {
806 if (posCb(cnxt, address, line)) {
807 // early exit
808 return;
809 }
810 }
811 break;
812 }
813 }
814}
815
Carl Shapiro1fb86202011-06-27 17:43:13 -0700816} // namespace art