blob: 519cdc22cbabe1b5b11ce27cbe71d9b18f738b71 [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
Brian Carlstrom53d6ff42011-09-23 10:45:07 -0700387DexFile::~DexFile() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700388
Brian Carlstromf615a612011-07-23 12:50:34 -0700389bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700390 InitMembers();
391 if (!IsMagicValid()) {
392 return false;
393 }
394 InitIndex();
395 return true;
396}
397
Brian Carlstromf615a612011-07-23 12:50:34 -0700398void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700399 const byte* b = base_;
400 header_ = reinterpret_cast<const Header*>(b);
401 const Header* h = header_;
402 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
403 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
404 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
405 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
406 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
407 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
408}
409
Brian Carlstromf615a612011-07-23 12:50:34 -0700410bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700411 return CheckMagic(header_->magic_);
412}
413
Brian Carlstromf615a612011-07-23 12:50:34 -0700414bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700415 CHECK(magic != NULL);
416 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700417 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700418 << " " << magic[0]
419 << " " << magic[1]
420 << " " << magic[2]
421 << " " << magic[3];
422 return false;
423 }
424 const byte* version = &magic[sizeof(kDexMagic)];
425 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700426 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700427 << " " << version[0]
428 << " " << version[1]
429 << " " << version[2]
430 << " " << version[3];
431 return false;
432 }
433 return true;
434}
435
Brian Carlstromf615a612011-07-23 12:50:34 -0700436void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700437 CHECK_EQ(index_.size(), 0U);
438 for (size_t i = 0; i < NumClassDefs(); ++i) {
439 const ClassDef& class_def = GetClassDef(i);
440 const char* descriptor = GetClassDescriptor(class_def);
441 index_[descriptor] = &class_def;
442 }
443}
444
Brian Carlstromf615a612011-07-23 12:50:34 -0700445const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700446 Index::const_iterator it = index_.find(descriptor);
447 if (it == index_.end()) {
448 return NULL;
449 } else {
450 return it->second;
451 }
452}
453
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700454// Materializes the method descriptor for a method prototype. Method
455// descriptors are not stored directly in the dex file. Instead, one
456// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700457std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
458 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700459 const ProtoId& proto_id = GetProtoId(proto_idx);
460 std::string descriptor;
461 descriptor.push_back('(');
462 const TypeList* type_list = GetProtoParameters(proto_id);
463 size_t parameter_length = 0;
464 if (type_list != NULL) {
465 // A non-zero number of arguments. Append the type names.
466 for (size_t i = 0; i < type_list->Size(); ++i) {
467 const TypeItem& type_item = type_list->GetTypeItem(i);
468 uint32_t type_idx = type_item.type_idx_;
469 int32_t type_length;
470 const char* name = dexStringByTypeIdx(type_idx, &type_length);
471 parameter_length += type_length;
472 descriptor.append(name);
473 }
474 }
475 descriptor.push_back(')');
476 uint32_t return_type_idx = proto_id.return_type_idx_;
477 int32_t return_type_length;
478 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
479 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700480 if (unicode_length != NULL) {
481 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
482 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700483 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700484}
485
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700486// Read a signed integer. "zwidth" is the zero-based byte count.
487static int32_t ReadSignedInt(const byte* ptr, int zwidth)
488{
489 int32_t val = 0;
490 for (int i = zwidth; i >= 0; --i) {
491 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
492 }
493 val >>= (3 - zwidth) * 8;
494 return val;
495}
496
497// Read an unsigned integer. "zwidth" is the zero-based byte count,
498// "fill_on_right" indicates which side we want to zero-fill from.
499static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
500 bool fill_on_right) {
501 uint32_t val = 0;
502 if (!fill_on_right) {
503 for (int i = zwidth; i >= 0; --i) {
504 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
505 }
506 val >>= (3 - zwidth) * 8;
507 } else {
508 for (int i = zwidth; i >= 0; --i) {
509 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
510 }
511 }
512 return val;
513}
514
515// Read a signed long. "zwidth" is the zero-based byte count.
516static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
517 int64_t val = 0;
518 for (int i = zwidth; i >= 0; --i) {
519 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
520 }
521 val >>= (7 - zwidth) * 8;
522 return val;
523}
524
525// Read an unsigned long. "zwidth" is the zero-based byte count,
526// "fill_on_right" indicates which side we want to zero-fill from.
527static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
528 bool fill_on_right) {
529 uint64_t val = 0;
530 if (!fill_on_right) {
531 for (int i = zwidth; i >= 0; --i) {
532 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
533 }
534 val >>= (7 - zwidth) * 8;
535 } else {
536 for (int i = zwidth; i >= 0; --i) {
537 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
538 }
539 }
540 return val;
541}
542
Brian Carlstromf615a612011-07-23 12:50:34 -0700543DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
544 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700545 const byte* ptr = *stream;
546 byte value_type = *ptr++;
547 byte value_arg = value_type >> kEncodedValueArgShift;
548 size_t width = value_arg + 1; // assume and correct later
549 int type = value_type & kEncodedValueTypeMask;
550 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700551 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700552 int32_t b = ReadSignedInt(ptr, value_arg);
553 CHECK(IsInt(8, b));
554 value->i = b;
555 break;
556 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700557 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700558 int32_t s = ReadSignedInt(ptr, value_arg);
559 CHECK(IsInt(16, s));
560 value->i = s;
561 break;
562 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700563 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700564 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
565 CHECK(IsUint(16, c));
566 value->i = c;
567 break;
568 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700569 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700570 value->i = ReadSignedInt(ptr, value_arg);
571 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700572 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700573 value->j = ReadSignedLong(ptr, value_arg);
574 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700575 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700576 value->i = ReadUnsignedInt(ptr, value_arg, true);
577 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700578 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700579 value->j = ReadUnsignedLong(ptr, value_arg, true);
580 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700581 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700582 value->i = (value_arg != 0);
583 width = 0;
584 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700585 case DexFile::kString:
586 case DexFile::kType:
587 case DexFile::kMethod:
588 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700589 value->i = ReadUnsignedInt(ptr, value_arg, false);
590 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700591 case DexFile::kField:
592 case DexFile::kArray:
593 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700594 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700595 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700596 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700597 value->i = 0;
598 width = 0;
599 break;
600 default:
601 LOG(FATAL) << "Unreached";
602 }
603 ptr += width;
604 *stream = ptr;
605 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700606}
607
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700608String* DexFile::dexArtStringById(int32_t idx) const {
609 if (idx == -1) {
610 return NULL;
611 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700612 return String::AllocFromModifiedUtf8(dexStringById(idx));
613}
614
615int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700616 // For native method, lineno should be -2 to indicate it is native. Note that
617 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700618 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700619 return -2;
620 }
621
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700622 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700623 DCHECK(code_item != NULL);
624
625 // A method with no line number info should return -1
626 LineNumFromPcContext context(rel_pc, -1);
627 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
628 return context.line_num_;
629}
630
631void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
632 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
633 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
634 uint32_t line = DecodeUnsignedLeb128(&stream);
635 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
636 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
637 uint32_t address = 0;
638
639 if (!method->IsStatic()) {
640 local_in_reg[arg_reg].name_ = String::AllocFromModifiedUtf8("this");
641 local_in_reg[arg_reg].descriptor_ = method->GetDeclaringClass()->GetDescriptor();
642 local_in_reg[arg_reg].signature_ = NULL;
643 local_in_reg[arg_reg].start_address_ = 0;
644 local_in_reg[arg_reg].is_live_ = true;
645 arg_reg++;
646 }
647
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648 ParameterIterator *it = GetParameterIterator(GetProtoId(method->GetProtoIdx()));
Shih-wei Liao195487c2011-08-20 13:29:04 -0700649 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
650 if (arg_reg >= code_item->registers_size_) {
651 LOG(FATAL) << "invalid stream";
652 return;
653 }
654
655 String* descriptor = String::AllocFromModifiedUtf8(it->GetDescriptor());
656 String* name = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
657
658 local_in_reg[arg_reg].name_ = name;
659 local_in_reg[arg_reg].descriptor_ = descriptor;
660 local_in_reg[arg_reg].signature_ = NULL;
661 local_in_reg[arg_reg].start_address_ = address;
662 local_in_reg[arg_reg].is_live_ = true;
663 switch (descriptor->CharAt(0)) {
664 case 'D':
665 case 'J':
666 arg_reg += 2;
667 break;
668 default:
669 arg_reg += 1;
670 break;
671 }
672 }
673
674 if (it->HasNext()) {
675 LOG(FATAL) << "invalid stream";
676 return;
677 }
678
679 for (;;) {
680 uint8_t opcode = *stream++;
681 uint8_t adjopcode = opcode - DBG_FIRST_SPECIAL;
682 uint16_t reg;
683
684
685 switch (opcode) {
686 case DBG_END_SEQUENCE:
687 return;
688
689 case DBG_ADVANCE_PC:
690 address += DecodeUnsignedLeb128(&stream);
691 break;
692
693 case DBG_ADVANCE_LINE:
694 line += DecodeUnsignedLeb128(&stream);
695 break;
696
697 case DBG_START_LOCAL:
698 case DBG_START_LOCAL_EXTENDED:
699 reg = DecodeUnsignedLeb128(&stream);
700 if (reg > code_item->registers_size_) {
701 LOG(FATAL) << "invalid stream";
702 return;
703 }
704
705 // Emit what was previously there, if anything
706 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
707
708 local_in_reg[reg].name_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
709 local_in_reg[reg].descriptor_ = dexArtStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
710 if (opcode == DBG_START_LOCAL_EXTENDED) {
711 local_in_reg[reg].signature_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
712 } else {
713 local_in_reg[reg].signature_ = NULL;
714 }
715 local_in_reg[reg].start_address_ = address;
716 local_in_reg[reg].is_live_ = true;
717 break;
718
719 case DBG_END_LOCAL:
720 reg = DecodeUnsignedLeb128(&stream);
721 if (reg > code_item->registers_size_) {
722 LOG(FATAL) << "invalid stream";
723 return;
724 }
725
726 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
727 local_in_reg[reg].is_live_ = false;
728 break;
729
730 case DBG_RESTART_LOCAL:
731 reg = DecodeUnsignedLeb128(&stream);
732 if (reg > code_item->registers_size_) {
733 LOG(FATAL) << "invalid stream";
734 return;
735 }
736
737 if (local_in_reg[reg].name_ == NULL
738 || local_in_reg[reg].descriptor_ == NULL) {
739 LOG(FATAL) << "invalid stream";
740 return;
741 }
742
743 // If the register is live, the "restart" is superfluous,
744 // and we don't want to mess with the existing start address.
745 if (!local_in_reg[reg].is_live_) {
746 local_in_reg[reg].start_address_ = address;
747 local_in_reg[reg].is_live_ = true;
748 }
749 break;
750
751 case DBG_SET_PROLOGUE_END:
752 case DBG_SET_EPILOGUE_BEGIN:
753 case DBG_SET_FILE:
754 break;
755
756 default:
757 address += adjopcode / DBG_LINE_RANGE;
758 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
759
760 if (posCb != NULL) {
761 if (posCb(cnxt, address, line)) {
762 // early exit
763 return;
764 }
765 }
766 break;
767 }
768 }
769}
770
Carl Shapiro1fb86202011-06-27 17:43:13 -0700771} // namespace art