blob: 7a41845b788442ba4ba9ec977b70380ed406f097 [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>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include <map>
14
15#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "globals.h"
17#include "logging.h"
18#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070019#include "os.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070020#include "stringprintf.h"
21#include "thread.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070022#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070023#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070024
25namespace art {
26
Brian Carlstromf615a612011-07-23 12:50:34 -070027const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
28const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070030DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070031 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070032 for (size_t i = 0; i != class_path.size(); ++i) {
33 const DexFile* dex_file = class_path[i];
34 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
35 if (dex_class_def != NULL) {
36 return ClassPathEntry(dex_file, dex_class_def);
37 }
38 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070039 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070040 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
41 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070042}
43
Brian Carlstrom78128a62011-09-15 17:21:19 -070044void DexFile::OpenDexFiles(std::vector<const char*>& dex_filenames,
45 std::vector<const DexFile*>& dex_files,
46 const std::string& strip_location_prefix) {
47 for (size_t i = 0; i < dex_filenames.size(); i++) {
48 const char* dex_filename = dex_filenames[i];
49 const DexFile* dex_file = Open(dex_filename, strip_location_prefix);
50 if (dex_file == NULL) {
51 fprintf(stderr, "could not open .dex from file %s\n", dex_filename);
52 exit(EXIT_FAILURE);
53 }
54 dex_files.push_back(dex_file);
55 }
56}
57
Brian Carlstrom16192862011-09-12 17:50:06 -070058const DexFile* DexFile::Open(const std::string& filename,
59 const std::string& strip_location_prefix) {
jeffhao262bf462011-10-20 18:36:32 -070060 if (IsValidZipFilename(filename)) {
Brian Carlstrom16192862011-09-12 17:50:06 -070061 return DexFile::OpenZip(filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070062 } else {
jeffhao262bf462011-10-20 18:36:32 -070063 if (!IsValidDexFilename(filename)) {
64 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
65 }
Brian Carlstrom16192862011-09-12 17:50:06 -070066 return DexFile::OpenFile(filename, filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070067 }
68}
69
jeffhaob4df5142011-09-19 20:25:32 -070070void DexFile::ChangePermissions(int prot) const {
Brian Carlstrom33f741e2011-10-03 11:24:05 -070071 if (mprotect(mem_map_->GetAddress(), mem_map_->GetLength(), prot) != 0) {
jeffhaob4df5142011-09-19 20:25:32 -070072 PLOG(FATAL) << "Failed to change dex file permissions to " << prot;
73 }
74}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070075
Brian Carlstrom16192862011-09-12 17:50:06 -070076const DexFile* DexFile::OpenFile(const std::string& filename,
77 const std::string& original_location,
78 const std::string& strip_location_prefix) {
79 StringPiece location = original_location;
80 if (!location.starts_with(strip_location_prefix)) {
81 LOG(ERROR) << filename << " does not start with " << strip_location_prefix;
82 return NULL;
83 }
84 location.remove_prefix(strip_location_prefix.size());
Brian Carlstromb0460ea2011-07-29 10:08:05 -070085 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070086 if (fd == -1) {
87 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
88 return NULL;
89 }
90 struct stat sbuf;
91 memset(&sbuf, 0, sizeof(sbuf));
92 if (fstat(fd, &sbuf) == -1) {
93 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
94 close(fd);
95 return NULL;
96 }
97 size_t length = sbuf.st_size;
Brian Carlstrom33f741e2011-10-03 11:24:05 -070098 UniquePtr<MemMap> map(MemMap::Map(length, PROT_READ, MAP_PRIVATE, fd, 0));
99 if (map.get() == NULL) {
100 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700101 close(fd);
102 return NULL;
103 }
104 close(fd);
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700105 byte* dex_file = map->GetAddress();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700106 return OpenMemory(dex_file, length, location.ToString(), map.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700107}
108
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700109const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700110
111class LockedFd {
112 public:
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700113 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700114 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
115 if (fd == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700116 PLOG(ERROR) << "Failed to open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700117 return NULL;
118 }
119 fchmod(fd, mode);
120
121 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
122 int result = flock(fd, LOCK_EX | LOCK_NB);
123 if (result == -1) {
124 LOG(WARNING) << "sleeping while locking file " << name;
125 result = flock(fd, LOCK_EX);
126 }
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700127 if (result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700128 PLOG(ERROR) << "Failed to lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700129 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700130 return NULL;
131 }
132 return new LockedFd(fd);
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700133 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700134
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700135 int GetFd() const {
136 return fd_;
137 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700138
139 ~LockedFd() {
140 if (fd_ != -1) {
141 int result = flock(fd_, LOCK_UN);
142 if (result == -1) {
143 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
144 }
145 close(fd_);
146 }
147 }
148
149 private:
Elliott Hughesa51a3dd2011-10-17 15:19:26 -0700150 explicit LockedFd(int fd) : fd_(fd) {}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700151
152 int fd_;
153};
154
155class TmpFile {
156 public:
Elliott Hughesa51a3dd2011-10-17 15:19:26 -0700157 explicit TmpFile(const std::string& name) : name_(name) {}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700158 ~TmpFile() {
159 unlink(name_.c_str());
160 }
161 private:
162 const std::string name_;
163};
164
165// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700166const DexFile* DexFile::OpenZip(const std::string& filename,
167 const std::string& strip_location_prefix) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700168 // First, look for a ".dex" alongside the jar file. It will have
169 // the same name/path except for the extension.
170
171 // Example filename = dir/foo.jar
172 std::string adjacent_dex_filename(filename);
173 size_t found = adjacent_dex_filename.find_last_of(".");
174 if (found == std::string::npos) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700175 LOG(ERROR) << "No . in filename" << filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700176 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700177 }
178 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
179 adjacent_dex_filename.end(),
180 ".dex");
181 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700182 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700183 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename,
184 filename,
185 strip_location_prefix);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700186 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700187 // We don't verify anything in this case, because we aren't in
188 // the cache and typically the file is in the readonly /system
189 // area, so if something is wrong, there is nothing we can do.
190 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700191 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700192 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700193 }
194
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700195 UniquePtr<char[]> resolved(new char[PATH_MAX]);
196 char* absolute_path = realpath(filename.c_str(), resolved.get());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700197 if (absolute_path == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700198 LOG(ERROR) << "Failed to create absolute path for " << filename
199 << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700200 return NULL;
201 }
jeffhao262bf462011-10-20 18:36:32 -0700202 std::string cache_path_tmp(GetArtCacheFilenameOrDie(absolute_path));
203 cache_path_tmp.push_back('@');
204 cache_path_tmp.append(kClassesDex);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700205 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
206
Elliott Hughes90a33692011-08-30 13:27:07 -0700207 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
208 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700209 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700210 return NULL;
211 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700212 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
213 if (zip_entry.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700214 LOG(ERROR) << "Failed to find classes.dex within " << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700215 return NULL;
216 }
217
218 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
219 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
220
221 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700222 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700223 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path,
224 filename,
225 strip_location_prefix);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700226 if (cached_dex_file != NULL) {
227 return cached_dex_file;
228 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700229 }
230
231 // Try to open the temporary cache file, grabbing an exclusive
232 // lock. If somebody else is working on it, we'll block here until
233 // they complete. Because we're waiting on an external resource,
234 // we go into native mode.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700235 // Note that self can be NULL if we're parsing the bootclasspath
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700236 // during JNI_CreateJavaVM.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700237 Thread* self = Thread::Current();
238 UniquePtr<ScopedThreadStateChange> state_changer;
239 if (self != NULL) {
240 state_changer.reset(new ScopedThreadStateChange(self, Thread::kNative));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700241 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700242 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700243 state_changer.reset(NULL);
Elliott Hughes90a33692011-08-30 13:27:07 -0700244 if (fd.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700245 return NULL;
246 }
247
248 // Check to see if the fd we opened and locked matches the file in
249 // the filesystem. If they don't, then somebody else unlinked
250 // ours and created a new file, and we need to use that one
251 // instead. (If we caught them between the unlink and the create,
252 // we'll get an ENOENT from the file stat.)
253 struct stat fd_stat;
254 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
255 if (fd_stat_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700256 PLOG(ERROR) << "Failed to stat open file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700257 return NULL;
258 }
259 struct stat file_stat;
260 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
261 if (file_stat_result == -1 ||
262 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
263 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
264 usleep(250 * 1000); // if something is hosed, don't peg machine
265 continue;
266 }
267
268 // We have the correct file open and locked. Extract classes.dex
269 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700270 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
271 if (file.get() == NULL) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700272 return NULL;
273 }
274 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700275 if (!success) {
276 return NULL;
277 }
278
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700279 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700280
281 // Compute checksum and compare to zip. If things look okay, rename from tmp.
282 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
283 if (lseek_result == -1) {
284 return NULL;
285 }
286 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700287 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
288 if (buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700289 return NULL;
290 }
291 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
292 while (true) {
293 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700294 if (bytes_read == -1) {
295 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
296 return NULL;
297 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700298 if (bytes_read == 0) {
299 break;
300 }
301 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
302 }
303 if (computed_crc != zip_entry->GetCrc32()) {
304 return NULL;
305 }
306 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
307 if (rename_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700308 PLOG(ERROR) << "Failed to install dex cache file '" << cache_path << "'"
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700309 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700310 unlink(cache_path.c_str());
311 }
312 }
313 // NOTREACHED
314}
315
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700316const DexFile* DexFile::OpenMemory(const byte* dex_bytes, size_t length,
317 const std::string& location, MemMap* mem_map) {
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700318 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700319 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700320 return NULL;
321 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700322 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700323 }
324}
325
Jesse Wilson6bf19152011-09-29 13:12:33 -0400326DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700327 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
328 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
329 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
330 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400331}
332
333jobject DexFile::GetDexObject(JNIEnv* env) const {
334 MutexLock mu(dex_object_lock_);
335 if (dex_object_ != NULL) {
336 return dex_object_;
337 }
338
339 void* address = const_cast<void*>(reinterpret_cast<const void*>(base_));
340 jobject byte_buffer = env->NewDirectByteBuffer(address, length_);
341 if (byte_buffer == NULL) {
342 return NULL;
343 }
344
345 jclass c = env->FindClass("com/android/dex/Dex");
346 if (c == NULL) {
347 return NULL;
348 }
349
350 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
351 if (mid == NULL) {
352 return NULL;
353 }
354
355 jvalue args[1];
356 args[0].l = byte_buffer;
357 jobject local = env->CallStaticObjectMethodA(c, mid, args);
358 if (local == NULL) {
359 return NULL;
360 }
361
362 dex_object_ = env->NewGlobalRef(local);
363 return dex_object_;
364}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700365
Brian Carlstromf615a612011-07-23 12:50:34 -0700366bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700367 InitMembers();
368 if (!IsMagicValid()) {
369 return false;
370 }
371 InitIndex();
372 return true;
373}
374
Brian Carlstromf615a612011-07-23 12:50:34 -0700375void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700376 const byte* b = base_;
377 header_ = reinterpret_cast<const Header*>(b);
378 const Header* h = header_;
379 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
380 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
381 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
382 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
383 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
384 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
385}
386
Brian Carlstromf615a612011-07-23 12:50:34 -0700387bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700388 return CheckMagic(header_->magic_);
389}
390
Brian Carlstromf615a612011-07-23 12:50:34 -0700391bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700392 CHECK(magic != NULL);
393 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700394 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700395 << " " << magic[0]
396 << " " << magic[1]
397 << " " << magic[2]
398 << " " << magic[3];
399 return false;
400 }
401 const byte* version = &magic[sizeof(kDexMagic)];
402 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700403 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700404 << " " << version[0]
405 << " " << version[1]
406 << " " << version[2]
407 << " " << version[3];
408 return false;
409 }
410 return true;
411}
412
Brian Carlstromf615a612011-07-23 12:50:34 -0700413void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700414 CHECK_EQ(index_.size(), 0U);
415 for (size_t i = 0; i < NumClassDefs(); ++i) {
416 const ClassDef& class_def = GetClassDef(i);
417 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700418 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700419 }
420}
421
Brian Carlstrome24fa612011-09-29 00:53:55 -0700422bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700423 Index::const_iterator it = index_.find(descriptor);
424 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700425 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700426 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700427 idx = it->second;
428 return true;
429}
430
431const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
432 uint32_t idx;
433 if (FindClassDefIndex(descriptor, idx)) {
434 return &GetClassDef(idx);
435 }
436 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700437}
438
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700439// Materializes the method descriptor for a method prototype. Method
440// descriptors are not stored directly in the dex file. Instead, one
441// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700442std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
443 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700444 const ProtoId& proto_id = GetProtoId(proto_idx);
445 std::string descriptor;
446 descriptor.push_back('(');
447 const TypeList* type_list = GetProtoParameters(proto_id);
448 size_t parameter_length = 0;
449 if (type_list != NULL) {
450 // A non-zero number of arguments. Append the type names.
451 for (size_t i = 0; i < type_list->Size(); ++i) {
452 const TypeItem& type_item = type_list->GetTypeItem(i);
453 uint32_t type_idx = type_item.type_idx_;
454 int32_t type_length;
455 const char* name = dexStringByTypeIdx(type_idx, &type_length);
456 parameter_length += type_length;
457 descriptor.append(name);
458 }
459 }
460 descriptor.push_back(')');
461 uint32_t return_type_idx = proto_id.return_type_idx_;
462 int32_t return_type_length;
463 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
464 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700465 if (unicode_length != NULL) {
466 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
467 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700468 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700469}
470
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700471// Read a signed integer. "zwidth" is the zero-based byte count.
472static int32_t ReadSignedInt(const byte* ptr, int zwidth)
473{
474 int32_t val = 0;
475 for (int i = zwidth; i >= 0; --i) {
476 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
477 }
478 val >>= (3 - zwidth) * 8;
479 return val;
480}
481
482// Read an unsigned integer. "zwidth" is the zero-based byte count,
483// "fill_on_right" indicates which side we want to zero-fill from.
484static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
485 bool fill_on_right) {
486 uint32_t val = 0;
487 if (!fill_on_right) {
488 for (int i = zwidth; i >= 0; --i) {
489 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
490 }
491 val >>= (3 - zwidth) * 8;
492 } else {
493 for (int i = zwidth; i >= 0; --i) {
494 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
495 }
496 }
497 return val;
498}
499
500// Read a signed long. "zwidth" is the zero-based byte count.
501static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
502 int64_t val = 0;
503 for (int i = zwidth; i >= 0; --i) {
504 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
505 }
506 val >>= (7 - zwidth) * 8;
507 return val;
508}
509
510// Read an unsigned long. "zwidth" is the zero-based byte count,
511// "fill_on_right" indicates which side we want to zero-fill from.
512static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
513 bool fill_on_right) {
514 uint64_t val = 0;
515 if (!fill_on_right) {
516 for (int i = zwidth; i >= 0; --i) {
517 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
518 }
519 val >>= (7 - zwidth) * 8;
520 } else {
521 for (int i = zwidth; i >= 0; --i) {
522 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
523 }
524 }
525 return val;
526}
527
Brian Carlstromf615a612011-07-23 12:50:34 -0700528DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
529 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700530 const byte* ptr = *stream;
531 byte value_type = *ptr++;
532 byte value_arg = value_type >> kEncodedValueArgShift;
533 size_t width = value_arg + 1; // assume and correct later
534 int type = value_type & kEncodedValueTypeMask;
535 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700536 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537 int32_t b = ReadSignedInt(ptr, value_arg);
538 CHECK(IsInt(8, b));
539 value->i = b;
540 break;
541 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700542 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700543 int32_t s = ReadSignedInt(ptr, value_arg);
544 CHECK(IsInt(16, s));
545 value->i = s;
546 break;
547 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700548 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700549 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
550 CHECK(IsUint(16, c));
551 value->i = c;
552 break;
553 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700554 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700555 value->i = ReadSignedInt(ptr, value_arg);
556 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700557 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700558 value->j = ReadSignedLong(ptr, value_arg);
559 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700560 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700561 value->i = ReadUnsignedInt(ptr, value_arg, true);
562 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700563 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700564 value->j = ReadUnsignedLong(ptr, value_arg, true);
565 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700566 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700567 value->i = (value_arg != 0);
568 width = 0;
569 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700570 case DexFile::kString:
571 case DexFile::kType:
572 case DexFile::kMethod:
573 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700574 value->i = ReadUnsignedInt(ptr, value_arg, false);
575 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700576 case DexFile::kField:
577 case DexFile::kArray:
578 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700579 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700580 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700581 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700582 value->i = 0;
583 width = 0;
584 break;
585 default:
586 LOG(FATAL) << "Unreached";
587 }
588 ptr += width;
589 *stream = ptr;
590 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700591}
592
Shih-wei Liao195487c2011-08-20 13:29:04 -0700593int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700594 // For native method, lineno should be -2 to indicate it is native. Note that
595 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700596 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700597 return -2;
598 }
599
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700601 DCHECK(code_item != NULL);
602
603 // A method with no line number info should return -1
604 LineNumFromPcContext context(rel_pc, -1);
605 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
606 return context.line_num_;
607}
608
609void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
610 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
611 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
612 uint32_t line = DecodeUnsignedLeb128(&stream);
613 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
614 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
615 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700616 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700617
618 if (!method->IsStatic()) {
Elliott Hughes30646832011-10-13 16:59:46 -0700619 if (need_locals) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700620 std::string descriptor = method->GetDeclaringClass()->GetDescriptor()->ToModifiedUtf8();
621 const ClassDef* class_def = FindClassDef(descriptor);
622 CHECK(class_def != NULL) << descriptor;
623 local_in_reg[arg_reg].name_ = "this";
624 local_in_reg[arg_reg].descriptor_ = GetClassDescriptor(*class_def);
Elliott Hughes30646832011-10-13 16:59:46 -0700625 local_in_reg[arg_reg].start_address_ = 0;
626 local_in_reg[arg_reg].is_live_ = true;
627 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700628 arg_reg++;
629 }
630
Elliott Hughes30646832011-10-13 16:59:46 -0700631 ParameterIterator* it = GetParameterIterator(GetProtoId(method->GetProtoIdx()));
Shih-wei Liao195487c2011-08-20 13:29:04 -0700632 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
633 if (arg_reg >= code_item->registers_size_) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700634 LOG(ERROR) << "invalid stream";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700635 return;
636 }
Elliott Hughes30646832011-10-13 16:59:46 -0700637 int32_t id = DecodeUnsignedLeb128P1(&stream);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700638 const char* descriptor = it->GetDescriptor();
Elliott Hughes30646832011-10-13 16:59:46 -0700639 if (need_locals) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700640 const char* name = dexStringById(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700641 local_in_reg[arg_reg].name_ = name;
642 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes30646832011-10-13 16:59:46 -0700643 local_in_reg[arg_reg].start_address_ = address;
644 local_in_reg[arg_reg].is_live_ = true;
645 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700646 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700647 case 'D':
648 case 'J':
649 arg_reg += 2;
650 break;
651 default:
652 arg_reg += 1;
653 break;
654 }
655 }
656
657 if (it->HasNext()) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700658 LOG(ERROR) << "invalid stream";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700659 return;
660 }
661
662 for (;;) {
663 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700664 uint16_t reg;
665
Shih-wei Liao195487c2011-08-20 13:29:04 -0700666 switch (opcode) {
667 case DBG_END_SEQUENCE:
668 return;
669
670 case DBG_ADVANCE_PC:
671 address += DecodeUnsignedLeb128(&stream);
672 break;
673
674 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700675 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700676 break;
677
678 case DBG_START_LOCAL:
679 case DBG_START_LOCAL_EXTENDED:
680 reg = DecodeUnsignedLeb128(&stream);
681 if (reg > code_item->registers_size_) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700682 LOG(ERROR) << "invalid stream";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700683 return;
684 }
685
686 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700687 if (need_locals) {
688 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700689
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700690 local_in_reg[reg].name_ = dexStringById(DecodeUnsignedLeb128P1(&stream));
691 local_in_reg[reg].descriptor_ = dexStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
Elliott Hughes30646832011-10-13 16:59:46 -0700692 if (opcode == DBG_START_LOCAL_EXTENDED) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700693 local_in_reg[reg].signature_ = dexStringById(DecodeUnsignedLeb128P1(&stream));
Elliott Hughes30646832011-10-13 16:59:46 -0700694 }
695 local_in_reg[reg].start_address_ = address;
696 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700697 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700698 break;
699
700 case DBG_END_LOCAL:
701 reg = DecodeUnsignedLeb128(&stream);
702 if (reg > code_item->registers_size_) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700703 LOG(ERROR) << "invalid stream";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700704 return;
705 }
706
Elliott Hughes30646832011-10-13 16:59:46 -0700707 if (need_locals) {
708 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
709 local_in_reg[reg].is_live_ = false;
710 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700711 break;
712
713 case DBG_RESTART_LOCAL:
714 reg = DecodeUnsignedLeb128(&stream);
715 if (reg > code_item->registers_size_) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700716 LOG(ERROR) << "invalid stream";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700717 return;
718 }
719
Elliott Hughes30646832011-10-13 16:59:46 -0700720 if (need_locals) {
721 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700722 LOG(ERROR) << "invalid stream";
Elliott Hughes30646832011-10-13 16:59:46 -0700723 return;
724 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700725
Elliott Hughes30646832011-10-13 16:59:46 -0700726 // If the register is live, the "restart" is superfluous,
727 // and we don't want to mess with the existing start address.
728 if (!local_in_reg[reg].is_live_) {
729 local_in_reg[reg].start_address_ = address;
730 local_in_reg[reg].is_live_ = true;
731 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700732 }
733 break;
734
735 case DBG_SET_PROLOGUE_END:
736 case DBG_SET_EPILOGUE_BEGIN:
737 case DBG_SET_FILE:
738 break;
739
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700740 default: {
741 int adjopcode = opcode - DBG_FIRST_SPECIAL;
742
Shih-wei Liao195487c2011-08-20 13:29:04 -0700743 address += adjopcode / DBG_LINE_RANGE;
744 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
745
746 if (posCb != NULL) {
747 if (posCb(cnxt, address, line)) {
748 // early exit
749 return;
750 }
751 }
752 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700753 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700754 }
755 }
756}
757
Carl Shapiro1fb86202011-06-27 17:43:13 -0700758} // namespace art