blob: 46fb2dc26d96d9025f5367324ad2c711352f10cb [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
Brian Carlstromf615a612011-07-23 12:50:34 -070073DexFile::Closer::~Closer() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070074
Brian Carlstromf615a612011-07-23 12:50:34 -070075DexFile::MmapCloser::MmapCloser(void* addr, size_t length) : addr_(addr), length_(length) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070076 CHECK(addr != NULL);
77}
Brian Carlstromf615a612011-07-23 12:50:34 -070078DexFile::MmapCloser::~MmapCloser() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070079 if (munmap(addr_, length_) == -1) {
80 PLOG(INFO) << "munmap failed";
81 }
82}
83
Brian Carlstromf615a612011-07-23 12:50:34 -070084DexFile::PtrCloser::PtrCloser(byte* addr) : addr_(addr) {}
85DexFile::PtrCloser::~PtrCloser() { delete[] addr_; }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070086
Brian Carlstrom16192862011-09-12 17:50:06 -070087const DexFile* DexFile::OpenFile(const std::string& filename,
88 const std::string& original_location,
89 const std::string& strip_location_prefix) {
90 StringPiece location = original_location;
91 if (!location.starts_with(strip_location_prefix)) {
92 LOG(ERROR) << filename << " does not start with " << strip_location_prefix;
93 return NULL;
94 }
95 location.remove_prefix(strip_location_prefix.size());
Brian Carlstromb0460ea2011-07-29 10:08:05 -070096 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070097 if (fd == -1) {
98 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
99 return NULL;
100 }
101 struct stat sbuf;
102 memset(&sbuf, 0, sizeof(sbuf));
103 if (fstat(fd, &sbuf) == -1) {
104 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
105 close(fd);
106 return NULL;
107 }
108 size_t length = sbuf.st_size;
109 void* addr = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0);
110 if (addr == MAP_FAILED) {
111 PLOG(ERROR) << "mmap \"" << filename << "\" failed";
112 close(fd);
113 return NULL;
114 }
115 close(fd);
116 byte* dex_file = reinterpret_cast<byte*>(addr);
117 Closer* closer = new MmapCloser(addr, length);
Brian Carlstrom16192862011-09-12 17:50:06 -0700118 return Open(dex_file, length, location.ToString(), closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700119}
120
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700121static const char* kClassesDex = "classes.dex";
122
123class LockedFd {
124 public:
125 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
126 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
127 if (fd == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700128 PLOG(ERROR) << "Failed to open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700129 return NULL;
130 }
131 fchmod(fd, mode);
132
133 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
134 int result = flock(fd, LOCK_EX | LOCK_NB);
135 if (result == -1) {
136 LOG(WARNING) << "sleeping while locking file " << name;
137 result = flock(fd, LOCK_EX);
138 }
139 if (result == -1 ) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700140 PLOG(ERROR) << "Failed to lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700141 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700142 return NULL;
143 }
144 return new LockedFd(fd);
145 }
146
147 int GetFd() const {
148 return fd_;
149 }
150
151 ~LockedFd() {
152 if (fd_ != -1) {
153 int result = flock(fd_, LOCK_UN);
154 if (result == -1) {
155 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
156 }
157 close(fd_);
158 }
159 }
160
161 private:
162 LockedFd(int fd) : fd_(fd) {}
163
164 int fd_;
165};
166
167class TmpFile {
168 public:
169 TmpFile(const std::string name) : name_(name) {}
170 ~TmpFile() {
171 unlink(name_.c_str());
172 }
173 private:
174 const std::string name_;
175};
176
177// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700178const DexFile* DexFile::OpenZip(const std::string& filename,
179 const std::string& strip_location_prefix) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700180
181 // First, look for a ".dex" alongside the jar file. It will have
182 // the same name/path except for the extension.
183
184 // Example filename = dir/foo.jar
185 std::string adjacent_dex_filename(filename);
186 size_t found = adjacent_dex_filename.find_last_of(".");
187 if (found == std::string::npos) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700188 LOG(ERROR) << "No . in filename" << filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700189 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700190 }
191 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
192 adjacent_dex_filename.end(),
193 ".dex");
194 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700195 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700196 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename,
197 filename,
198 strip_location_prefix);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700199 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700200 // We don't verify anything in this case, because we aren't in
201 // the cache and typically the file is in the readonly /system
202 // area, so if something is wrong, there is nothing we can do.
203 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700204 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700205 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700206 }
207
208 char resolved[PATH_MAX];
209 char* absolute_path = realpath(filename.c_str(), resolved);
210 if (absolute_path == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700211 LOG(ERROR) << "Failed to create absolute path for " << filename
212 << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700213 return NULL;
214 }
215 std::string cache_file(absolute_path+1); // skip leading slash
216 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
217 cache_file.push_back('@');
218 cache_file.append(kClassesDex);
219 // Example cache_file = parent@dir@foo.jar@classes.dex
220
221 const char* data_root = getenv("ANDROID_DATA");
222 if (data_root == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700223 if (OS::DirectoryExists("/data")) {
224 data_root = "/data";
225 } else {
226 data_root = "/tmp";
227 }
228 }
229 if (!OS::DirectoryExists(data_root)) {
230 LOG(ERROR) << "Failed to find ANDROID_DATA directory " << data_root;
231 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700232 }
233
Brian Carlstrom16192862011-09-12 17:50:06 -0700234 std::string art_cache = StringPrintf("%s/art-cache", data_root);
235
236 if (!OS::DirectoryExists(art_cache.c_str())) {
237 if (StringPiece(art_cache).starts_with("/tmp/")) {
238 int result = mkdir(art_cache.c_str(), 0700);
239 if (result != 0) {
240 LOG(ERROR) << "Failed to create art-cache directory " << art_cache;
241 return NULL;
242 }
243 } else {
244 LOG(ERROR) << "Failed to find art-cache directory " << art_cache;
245 return NULL;
246 }
247 }
248
249 std::string cache_path_tmp = StringPrintf("%s/%s", art_cache.c_str(), cache_file.c_str());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700250 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
251
Elliott Hughes90a33692011-08-30 13:27:07 -0700252 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
253 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700254 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700255 return NULL;
256 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700257 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
258 if (zip_entry.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700259 LOG(ERROR) << "Failed to find classes.dex within " << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700260 return NULL;
261 }
262
263 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
264 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
265
266 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700267 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700268 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path,
269 filename,
270 strip_location_prefix);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700271 if (cached_dex_file != NULL) {
272 return cached_dex_file;
273 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700274 }
275
276 // Try to open the temporary cache file, grabbing an exclusive
277 // lock. If somebody else is working on it, we'll block here until
278 // they complete. Because we're waiting on an external resource,
279 // we go into native mode.
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700280 // Note that current_thread can be NULL if we're parsing the bootclasspath
281 // during JNI_CreateJavaVM.
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700282 Thread* current_thread = Thread::Current();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700283 Thread::State old(Thread::kUnknown);
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700284 if (current_thread != NULL) {
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700285 old = current_thread->SetState(Thread::kNative);
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700286 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700287 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700288 if (current_thread != NULL) {
289 current_thread->SetState(old);
290 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700291 if (fd.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700292 return NULL;
293 }
294
295 // Check to see if the fd we opened and locked matches the file in
296 // the filesystem. If they don't, then somebody else unlinked
297 // ours and created a new file, and we need to use that one
298 // instead. (If we caught them between the unlink and the create,
299 // we'll get an ENOENT from the file stat.)
300 struct stat fd_stat;
301 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
302 if (fd_stat_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700303 PLOG(ERROR) << "Failed to stat open file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700304 return NULL;
305 }
306 struct stat file_stat;
307 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
308 if (file_stat_result == -1 ||
309 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
310 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
311 usleep(250 * 1000); // if something is hosed, don't peg machine
312 continue;
313 }
314
315 // We have the correct file open and locked. Extract classes.dex
316 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700317 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
318 if (file.get() == NULL) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700319 return NULL;
320 }
321 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700322 if (!success) {
323 return NULL;
324 }
325
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700326 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700327
328 // Compute checksum and compare to zip. If things look okay, rename from tmp.
329 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
330 if (lseek_result == -1) {
331 return NULL;
332 }
333 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700334 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
335 if (buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700336 return NULL;
337 }
338 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
339 while (true) {
340 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700341 if (bytes_read == -1) {
342 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
343 return NULL;
344 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700345 if (bytes_read == 0) {
346 break;
347 }
348 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
349 }
350 if (computed_crc != zip_entry->GetCrc32()) {
351 return NULL;
352 }
353 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
354 if (rename_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700355 PLOG(ERROR) << "Failed to install dex cache file '" << cache_path << "'"
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700356 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700357 unlink(cache_path.c_str());
358 }
359 }
360 // NOTREACHED
361}
362
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700363const DexFile* DexFile::OpenPtr(byte* ptr, size_t length, const std::string& location) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700364 CHECK(ptr != NULL);
Brian Carlstromf615a612011-07-23 12:50:34 -0700365 DexFile::Closer* closer = new PtrCloser(ptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700366 return Open(ptr, length, location, closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700367}
368
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700369const DexFile* DexFile::Open(const byte* dex_bytes, size_t length,
370 const std::string& location, Closer* closer) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700371 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, closer));
Brian Carlstromf615a612011-07-23 12:50:34 -0700372 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700373 return NULL;
374 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700375 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700376 }
377}
378
Brian Carlstromf615a612011-07-23 12:50:34 -0700379DexFile::~DexFile() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700380
Brian Carlstromf615a612011-07-23 12:50:34 -0700381bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700382 InitMembers();
383 if (!IsMagicValid()) {
384 return false;
385 }
386 InitIndex();
387 return true;
388}
389
Brian Carlstromf615a612011-07-23 12:50:34 -0700390void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700391 const byte* b = base_;
392 header_ = reinterpret_cast<const Header*>(b);
393 const Header* h = header_;
394 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
395 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
396 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
397 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
398 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
399 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
400}
401
Brian Carlstromf615a612011-07-23 12:50:34 -0700402bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700403 return CheckMagic(header_->magic_);
404}
405
Brian Carlstromf615a612011-07-23 12:50:34 -0700406bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700407 CHECK(magic != NULL);
408 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700409 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700410 << " " << magic[0]
411 << " " << magic[1]
412 << " " << magic[2]
413 << " " << magic[3];
414 return false;
415 }
416 const byte* version = &magic[sizeof(kDexMagic)];
417 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700418 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700419 << " " << version[0]
420 << " " << version[1]
421 << " " << version[2]
422 << " " << version[3];
423 return false;
424 }
425 return true;
426}
427
Brian Carlstromf615a612011-07-23 12:50:34 -0700428void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700429 CHECK_EQ(index_.size(), 0U);
430 for (size_t i = 0; i < NumClassDefs(); ++i) {
431 const ClassDef& class_def = GetClassDef(i);
432 const char* descriptor = GetClassDescriptor(class_def);
433 index_[descriptor] = &class_def;
434 }
435}
436
Brian Carlstromf615a612011-07-23 12:50:34 -0700437const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700438 CHECK(descriptor != NULL);
439 Index::const_iterator it = index_.find(descriptor);
440 if (it == index_.end()) {
441 return NULL;
442 } else {
443 return it->second;
444 }
445}
446
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700447// Materializes the method descriptor for a method prototype. Method
448// descriptors are not stored directly in the dex file. Instead, one
449// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700450std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
451 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700452 const ProtoId& proto_id = GetProtoId(proto_idx);
453 std::string descriptor;
454 descriptor.push_back('(');
455 const TypeList* type_list = GetProtoParameters(proto_id);
456 size_t parameter_length = 0;
457 if (type_list != NULL) {
458 // A non-zero number of arguments. Append the type names.
459 for (size_t i = 0; i < type_list->Size(); ++i) {
460 const TypeItem& type_item = type_list->GetTypeItem(i);
461 uint32_t type_idx = type_item.type_idx_;
462 int32_t type_length;
463 const char* name = dexStringByTypeIdx(type_idx, &type_length);
464 parameter_length += type_length;
465 descriptor.append(name);
466 }
467 }
468 descriptor.push_back(')');
469 uint32_t return_type_idx = proto_id.return_type_idx_;
470 int32_t return_type_length;
471 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
472 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700473 if (unicode_length != NULL) {
474 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
475 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700476 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700477}
478
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700479// Read a signed integer. "zwidth" is the zero-based byte count.
480static int32_t ReadSignedInt(const byte* ptr, int zwidth)
481{
482 int32_t val = 0;
483 for (int i = zwidth; i >= 0; --i) {
484 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
485 }
486 val >>= (3 - zwidth) * 8;
487 return val;
488}
489
490// Read an unsigned integer. "zwidth" is the zero-based byte count,
491// "fill_on_right" indicates which side we want to zero-fill from.
492static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
493 bool fill_on_right) {
494 uint32_t val = 0;
495 if (!fill_on_right) {
496 for (int i = zwidth; i >= 0; --i) {
497 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
498 }
499 val >>= (3 - zwidth) * 8;
500 } else {
501 for (int i = zwidth; i >= 0; --i) {
502 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
503 }
504 }
505 return val;
506}
507
508// Read a signed long. "zwidth" is the zero-based byte count.
509static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
510 int64_t val = 0;
511 for (int i = zwidth; i >= 0; --i) {
512 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
513 }
514 val >>= (7 - zwidth) * 8;
515 return val;
516}
517
518// Read an unsigned long. "zwidth" is the zero-based byte count,
519// "fill_on_right" indicates which side we want to zero-fill from.
520static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
521 bool fill_on_right) {
522 uint64_t val = 0;
523 if (!fill_on_right) {
524 for (int i = zwidth; i >= 0; --i) {
525 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
526 }
527 val >>= (7 - zwidth) * 8;
528 } else {
529 for (int i = zwidth; i >= 0; --i) {
530 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
531 }
532 }
533 return val;
534}
535
Brian Carlstromf615a612011-07-23 12:50:34 -0700536DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
537 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700538 const byte* ptr = *stream;
539 byte value_type = *ptr++;
540 byte value_arg = value_type >> kEncodedValueArgShift;
541 size_t width = value_arg + 1; // assume and correct later
542 int type = value_type & kEncodedValueTypeMask;
543 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700544 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700545 int32_t b = ReadSignedInt(ptr, value_arg);
546 CHECK(IsInt(8, b));
547 value->i = b;
548 break;
549 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700550 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700551 int32_t s = ReadSignedInt(ptr, value_arg);
552 CHECK(IsInt(16, s));
553 value->i = s;
554 break;
555 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700556 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700557 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
558 CHECK(IsUint(16, c));
559 value->i = c;
560 break;
561 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700562 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700563 value->i = ReadSignedInt(ptr, value_arg);
564 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700565 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700566 value->j = ReadSignedLong(ptr, value_arg);
567 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700568 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700569 value->i = ReadUnsignedInt(ptr, value_arg, true);
570 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700571 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700572 value->j = ReadUnsignedLong(ptr, value_arg, true);
573 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700574 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700575 value->i = (value_arg != 0);
576 width = 0;
577 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700578 case DexFile::kString:
579 case DexFile::kType:
580 case DexFile::kMethod:
581 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700582 value->i = ReadUnsignedInt(ptr, value_arg, false);
583 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700584 case DexFile::kField:
585 case DexFile::kArray:
586 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700587 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700588 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700589 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700590 value->i = 0;
591 width = 0;
592 break;
593 default:
594 LOG(FATAL) << "Unreached";
595 }
596 ptr += width;
597 *stream = ptr;
598 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700599}
600
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700601String* DexFile::dexArtStringById(int32_t idx) const {
602 if (idx == -1) {
603 return NULL;
604 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700605 return String::AllocFromModifiedUtf8(dexStringById(idx));
606}
607
608int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700609 // For native method, lineno should be -2 to indicate it is native. Note that
610 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700611 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700612 return -2;
613 }
614
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700615 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700616 DCHECK(code_item != NULL);
617
618 // A method with no line number info should return -1
619 LineNumFromPcContext context(rel_pc, -1);
620 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
621 return context.line_num_;
622}
623
624void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
625 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
626 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
627 uint32_t line = DecodeUnsignedLeb128(&stream);
628 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
629 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
630 uint32_t address = 0;
631
632 if (!method->IsStatic()) {
633 local_in_reg[arg_reg].name_ = String::AllocFromModifiedUtf8("this");
634 local_in_reg[arg_reg].descriptor_ = method->GetDeclaringClass()->GetDescriptor();
635 local_in_reg[arg_reg].signature_ = NULL;
636 local_in_reg[arg_reg].start_address_ = 0;
637 local_in_reg[arg_reg].is_live_ = true;
638 arg_reg++;
639 }
640
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700641 ParameterIterator *it = GetParameterIterator(GetProtoId(method->GetProtoIdx()));
Shih-wei Liao195487c2011-08-20 13:29:04 -0700642 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
643 if (arg_reg >= code_item->registers_size_) {
644 LOG(FATAL) << "invalid stream";
645 return;
646 }
647
648 String* descriptor = String::AllocFromModifiedUtf8(it->GetDescriptor());
649 String* name = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
650
651 local_in_reg[arg_reg].name_ = name;
652 local_in_reg[arg_reg].descriptor_ = descriptor;
653 local_in_reg[arg_reg].signature_ = NULL;
654 local_in_reg[arg_reg].start_address_ = address;
655 local_in_reg[arg_reg].is_live_ = true;
656 switch (descriptor->CharAt(0)) {
657 case 'D':
658 case 'J':
659 arg_reg += 2;
660 break;
661 default:
662 arg_reg += 1;
663 break;
664 }
665 }
666
667 if (it->HasNext()) {
668 LOG(FATAL) << "invalid stream";
669 return;
670 }
671
672 for (;;) {
673 uint8_t opcode = *stream++;
674 uint8_t adjopcode = opcode - DBG_FIRST_SPECIAL;
675 uint16_t reg;
676
677
678 switch (opcode) {
679 case DBG_END_SEQUENCE:
680 return;
681
682 case DBG_ADVANCE_PC:
683 address += DecodeUnsignedLeb128(&stream);
684 break;
685
686 case DBG_ADVANCE_LINE:
687 line += DecodeUnsignedLeb128(&stream);
688 break;
689
690 case DBG_START_LOCAL:
691 case DBG_START_LOCAL_EXTENDED:
692 reg = DecodeUnsignedLeb128(&stream);
693 if (reg > code_item->registers_size_) {
694 LOG(FATAL) << "invalid stream";
695 return;
696 }
697
698 // Emit what was previously there, if anything
699 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
700
701 local_in_reg[reg].name_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
702 local_in_reg[reg].descriptor_ = dexArtStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
703 if (opcode == DBG_START_LOCAL_EXTENDED) {
704 local_in_reg[reg].signature_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
705 } else {
706 local_in_reg[reg].signature_ = NULL;
707 }
708 local_in_reg[reg].start_address_ = address;
709 local_in_reg[reg].is_live_ = true;
710 break;
711
712 case DBG_END_LOCAL:
713 reg = DecodeUnsignedLeb128(&stream);
714 if (reg > code_item->registers_size_) {
715 LOG(FATAL) << "invalid stream";
716 return;
717 }
718
719 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
720 local_in_reg[reg].is_live_ = false;
721 break;
722
723 case DBG_RESTART_LOCAL:
724 reg = DecodeUnsignedLeb128(&stream);
725 if (reg > code_item->registers_size_) {
726 LOG(FATAL) << "invalid stream";
727 return;
728 }
729
730 if (local_in_reg[reg].name_ == NULL
731 || local_in_reg[reg].descriptor_ == NULL) {
732 LOG(FATAL) << "invalid stream";
733 return;
734 }
735
736 // If the register is live, the "restart" is superfluous,
737 // and we don't want to mess with the existing start address.
738 if (!local_in_reg[reg].is_live_) {
739 local_in_reg[reg].start_address_ = address;
740 local_in_reg[reg].is_live_ = true;
741 }
742 break;
743
744 case DBG_SET_PROLOGUE_END:
745 case DBG_SET_EPILOGUE_BEGIN:
746 case DBG_SET_FILE:
747 break;
748
749 default:
750 address += adjopcode / DBG_LINE_RANGE;
751 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
752
753 if (posCb != NULL) {
754 if (posCb(cnxt, address, line)) {
755 // early exit
756 return;
757 }
758 }
759 break;
760 }
761 }
762}
763
Carl Shapiro1fb86202011-06-27 17:43:13 -0700764} // namespace art