blob: 208479ee5174977e59f4e1caf6c9b9042a5b71b0 [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>
Ian Rogersd81871c2011-10-03 13:57:23 -07008#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07009#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070010#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070011#include <sys/mman.h>
12#include <sys/stat.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070013
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <map>
15
16#include "UniquePtr.h"
Ian Rogers0571d352011-11-03 19:51:38 -070017#include "class_linker.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070019#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "logging.h"
21#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070022#include "os.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070023#include "stringprintf.h"
24#include "thread.h"
Ian Rogers0571d352011-11-03 19:51:38 -070025#include "utf.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070026#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070027#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070028
29namespace art {
30
Brian Carlstromf615a612011-07-23 12:50:34 -070031const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
32const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070033
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070034DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070035 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070036 for (size_t i = 0; i != class_path.size(); ++i) {
37 const DexFile* dex_file = class_path[i];
38 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
39 if (dex_class_def != NULL) {
40 return ClassPathEntry(dex_file, dex_class_def);
41 }
42 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070043 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070044 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
45 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070046}
47
Brian Carlstrom78128a62011-09-15 17:21:19 -070048void DexFile::OpenDexFiles(std::vector<const char*>& dex_filenames,
49 std::vector<const DexFile*>& dex_files,
50 const std::string& strip_location_prefix) {
51 for (size_t i = 0; i < dex_filenames.size(); i++) {
52 const char* dex_filename = dex_filenames[i];
53 const DexFile* dex_file = Open(dex_filename, strip_location_prefix);
54 if (dex_file == NULL) {
55 fprintf(stderr, "could not open .dex from file %s\n", dex_filename);
56 exit(EXIT_FAILURE);
57 }
58 dex_files.push_back(dex_file);
59 }
60}
61
Brian Carlstrom16192862011-09-12 17:50:06 -070062const DexFile* DexFile::Open(const std::string& filename,
63 const std::string& strip_location_prefix) {
jeffhao262bf462011-10-20 18:36:32 -070064 if (IsValidZipFilename(filename)) {
Brian Carlstrom16192862011-09-12 17:50:06 -070065 return DexFile::OpenZip(filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070066 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -070067 if (!IsValidDexFilename(filename)) {
68 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
69 }
70 return DexFile::OpenFile(filename, filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070071}
72
jeffhaob4df5142011-09-19 20:25:32 -070073void DexFile::ChangePermissions(int prot) const {
Brian Carlstrom33f741e2011-10-03 11:24:05 -070074 if (mprotect(mem_map_->GetAddress(), mem_map_->GetLength(), prot) != 0) {
jeffhaob4df5142011-09-19 20:25:32 -070075 PLOG(FATAL) << "Failed to change dex file permissions to " << prot;
76 }
77}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070078
Brian Carlstrom16192862011-09-12 17:50:06 -070079const DexFile* DexFile::OpenFile(const std::string& filename,
80 const std::string& original_location,
81 const std::string& strip_location_prefix) {
82 StringPiece location = original_location;
83 if (!location.starts_with(strip_location_prefix)) {
84 LOG(ERROR) << filename << " does not start with " << strip_location_prefix;
85 return NULL;
86 }
87 location.remove_prefix(strip_location_prefix.size());
Brian Carlstromb0460ea2011-07-29 10:08:05 -070088 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070089 if (fd == -1) {
90 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
91 return NULL;
92 }
93 struct stat sbuf;
94 memset(&sbuf, 0, sizeof(sbuf));
95 if (fstat(fd, &sbuf) == -1) {
96 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
97 close(fd);
98 return NULL;
99 }
100 size_t length = sbuf.st_size;
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700101 UniquePtr<MemMap> map(MemMap::Map(length, PROT_READ, MAP_PRIVATE, fd, 0));
102 if (map.get() == NULL) {
103 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700104 close(fd);
105 return NULL;
106 }
107 close(fd);
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700108 byte* dex_file = map->GetAddress();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700109 return OpenMemory(dex_file, length, location.ToString(), map.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700110}
111
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700112const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700113
114class LockedFd {
115 public:
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700116 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700117 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
118 if (fd == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700119 PLOG(ERROR) << "Failed to open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700120 return NULL;
121 }
122 fchmod(fd, mode);
123
124 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
125 int result = flock(fd, LOCK_EX | LOCK_NB);
126 if (result == -1) {
127 LOG(WARNING) << "sleeping while locking file " << name;
128 result = flock(fd, LOCK_EX);
129 }
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700130 if (result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700131 PLOG(ERROR) << "Failed to lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700132 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700133 return NULL;
134 }
135 return new LockedFd(fd);
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700136 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700137
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700138 int GetFd() const {
139 return fd_;
140 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700141
142 ~LockedFd() {
143 if (fd_ != -1) {
144 int result = flock(fd_, LOCK_UN);
145 if (result == -1) {
146 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
147 }
148 close(fd_);
149 }
150 }
151
152 private:
Elliott Hughesa51a3dd2011-10-17 15:19:26 -0700153 explicit LockedFd(int fd) : fd_(fd) {}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700154
155 int fd_;
156};
157
158class TmpFile {
159 public:
Elliott Hughesa51a3dd2011-10-17 15:19:26 -0700160 explicit TmpFile(const std::string& name) : name_(name) {}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700161 ~TmpFile() {
162 unlink(name_.c_str());
163 }
164 private:
165 const std::string name_;
166};
167
168// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700169const DexFile* DexFile::OpenZip(const std::string& filename,
170 const std::string& strip_location_prefix) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700171 // First, look for a ".dex" alongside the jar file. It will have
172 // the same name/path except for the extension.
173
174 // Example filename = dir/foo.jar
175 std::string adjacent_dex_filename(filename);
176 size_t found = adjacent_dex_filename.find_last_of(".");
177 if (found == std::string::npos) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700178 LOG(ERROR) << "No . in filename" << filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700179 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700180 }
181 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
182 adjacent_dex_filename.end(),
183 ".dex");
184 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700185 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700186 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename,
187 filename,
188 strip_location_prefix);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700189 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700190 // We don't verify anything in this case, because we aren't in
191 // the cache and typically the file is in the readonly /system
192 // area, so if something is wrong, there is nothing we can do.
193 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700194 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700195 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700196 }
197
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700198 UniquePtr<char[]> resolved(new char[PATH_MAX]);
199 char* absolute_path = realpath(filename.c_str(), resolved.get());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700200 if (absolute_path == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700201 LOG(ERROR) << "Failed to create absolute path for " << filename
202 << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700203 return NULL;
204 }
jeffhao262bf462011-10-20 18:36:32 -0700205 std::string cache_path_tmp(GetArtCacheFilenameOrDie(absolute_path));
206 cache_path_tmp.push_back('@');
207 cache_path_tmp.append(kClassesDex);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700208 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
209
Elliott Hughes90a33692011-08-30 13:27:07 -0700210 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
211 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700212 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700213 return NULL;
214 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700215 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
216 if (zip_entry.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700217 LOG(ERROR) << "Failed to find classes.dex within " << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700218 return NULL;
219 }
220
221 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
222 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
223
224 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700225 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700226 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path,
227 filename,
228 strip_location_prefix);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700229 if (cached_dex_file != NULL) {
230 return cached_dex_file;
231 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700232 }
233
234 // Try to open the temporary cache file, grabbing an exclusive
235 // lock. If somebody else is working on it, we'll block here until
236 // they complete. Because we're waiting on an external resource,
237 // we go into native mode.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700238 // Note that self can be NULL if we're parsing the bootclasspath
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700239 // during JNI_CreateJavaVM.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700240 Thread* self = Thread::Current();
241 UniquePtr<ScopedThreadStateChange> state_changer;
242 if (self != NULL) {
243 state_changer.reset(new ScopedThreadStateChange(self, Thread::kNative));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700244 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700245 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700246 state_changer.reset(NULL);
Elliott Hughes90a33692011-08-30 13:27:07 -0700247 if (fd.get() == NULL) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700248 PLOG(ERROR) << "Failed to lock file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700249 return NULL;
250 }
251
252 // Check to see if the fd we opened and locked matches the file in
253 // the filesystem. If they don't, then somebody else unlinked
254 // ours and created a new file, and we need to use that one
255 // instead. (If we caught them between the unlink and the create,
256 // we'll get an ENOENT from the file stat.)
257 struct stat fd_stat;
258 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
259 if (fd_stat_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700260 PLOG(ERROR) << "Failed to stat open file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700261 return NULL;
262 }
263 struct stat file_stat;
264 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
265 if (file_stat_result == -1 ||
266 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
267 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
268 usleep(250 * 1000); // if something is hosed, don't peg machine
269 continue;
270 }
271
272 // We have the correct file open and locked. Extract classes.dex
273 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700274 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
275 if (file.get() == NULL) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700276 LOG(ERROR) << "Failed to create file for '" << cache_path_tmp << "'";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700277 return NULL;
278 }
279 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700280 if (!success) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700281 LOG(ERROR) << "Failed to extract classes.dex to '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700282 return NULL;
283 }
284
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700285 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700286
287 // Compute checksum and compare to zip. If things look okay, rename from tmp.
288 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
289 if (lseek_result == -1) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700290 PLOG(ERROR) << "Failed to seek to start of '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700291 return NULL;
292 }
293 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700294 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
295 if (buf.get() == NULL) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700296 LOG(ERROR) << "Failed to allocate buffer to checksum '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297 return NULL;
298 }
299 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
300 while (true) {
301 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700302 if (bytes_read == -1) {
303 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
304 return NULL;
305 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700306 if (bytes_read == 0) {
307 break;
308 }
309 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
310 }
311 if (computed_crc != zip_entry->GetCrc32()) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700312 LOG(ERROR) << "Failed to validate checksum for '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700313 return NULL;
314 }
315 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
316 if (rename_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700317 PLOG(ERROR) << "Failed to install dex cache file '" << cache_path << "'"
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700318 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700319 unlink(cache_path.c_str());
320 }
321 }
322 // NOTREACHED
323}
324
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700325const DexFile* DexFile::OpenMemory(const byte* dex_bytes, size_t length,
326 const std::string& location, MemMap* mem_map) {
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700327 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700328 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700329 return NULL;
330 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700331 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700332 }
333}
334
Jesse Wilson6bf19152011-09-29 13:12:33 -0400335DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700336 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
337 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
338 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
339 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400340}
341
342jobject DexFile::GetDexObject(JNIEnv* env) const {
343 MutexLock mu(dex_object_lock_);
344 if (dex_object_ != NULL) {
345 return dex_object_;
346 }
347
348 void* address = const_cast<void*>(reinterpret_cast<const void*>(base_));
349 jobject byte_buffer = env->NewDirectByteBuffer(address, length_);
350 if (byte_buffer == NULL) {
351 return NULL;
352 }
353
354 jclass c = env->FindClass("com/android/dex/Dex");
355 if (c == NULL) {
356 return NULL;
357 }
358
359 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
360 if (mid == NULL) {
361 return NULL;
362 }
363
364 jvalue args[1];
365 args[0].l = byte_buffer;
366 jobject local = env->CallStaticObjectMethodA(c, mid, args);
367 if (local == NULL) {
368 return NULL;
369 }
370
371 dex_object_ = env->NewGlobalRef(local);
372 return dex_object_;
373}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700374
Brian Carlstromf615a612011-07-23 12:50:34 -0700375bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700376 InitMembers();
377 if (!IsMagicValid()) {
378 return false;
379 }
380 InitIndex();
381 return true;
382}
383
Brian Carlstromf615a612011-07-23 12:50:34 -0700384void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700385 const byte* b = base_;
386 header_ = reinterpret_cast<const Header*>(b);
387 const Header* h = header_;
388 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
389 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
390 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
391 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
392 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
393 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
394}
395
Brian Carlstromf615a612011-07-23 12:50:34 -0700396bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700397 return CheckMagic(header_->magic_);
398}
399
Brian Carlstromf615a612011-07-23 12:50:34 -0700400bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700401 CHECK(magic != NULL);
402 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700403 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700404 << " " << magic[0]
405 << " " << magic[1]
406 << " " << magic[2]
407 << " " << magic[3];
408 return false;
409 }
410 const byte* version = &magic[sizeof(kDexMagic)];
411 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700412 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700413 << " " << version[0]
414 << " " << version[1]
415 << " " << version[2]
416 << " " << version[3];
417 return false;
418 }
419 return true;
420}
421
Ian Rogersd81871c2011-10-03 13:57:23 -0700422uint32_t DexFile::GetVersion() const {
423 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
424 return atoi(version);
425}
426
Ian Rogers0571d352011-11-03 19:51:38 -0700427int32_t DexFile::GetStringLength(const StringId& string_id) const {
428 const byte* ptr = base_ + string_id.string_data_off_;
429 return DecodeUnsignedLeb128(&ptr);
430}
431
432// Returns a pointer to the UTF-8 string data referred to by the given string_id.
433const char* DexFile::GetStringDataAndLength(const StringId& string_id, int32_t* length) const {
434 CHECK(length != NULL);
435 const byte* ptr = base_ + string_id.string_data_off_;
436 *length = DecodeUnsignedLeb128(&ptr);
437 return reinterpret_cast<const char*>(ptr);
438}
439
Brian Carlstromf615a612011-07-23 12:50:34 -0700440void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700441 CHECK_EQ(index_.size(), 0U);
442 for (size_t i = 0; i < NumClassDefs(); ++i) {
443 const ClassDef& class_def = GetClassDef(i);
444 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700445 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700446 }
447}
448
Brian Carlstrome24fa612011-09-29 00:53:55 -0700449bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700450 Index::const_iterator it = index_.find(descriptor);
451 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700452 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700453 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700454 idx = it->second;
455 return true;
456}
457
458const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
459 uint32_t idx;
460 if (FindClassDefIndex(descriptor, idx)) {
461 return &GetClassDef(idx);
462 }
463 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700464}
465
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800466const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
467 const DexFile::StringId& name,
468 const DexFile::TypeId& type) const {
469 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
470 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
471 const uint32_t name_idx = GetIndexForStringId(name);
472 const uint16_t type_idx = GetIndexForTypeId(type);
473 uint32_t lo = 0;
474 uint32_t hi = NumFieldIds() - 1;
475 while (hi >= lo) {
476 uint32_t mid = (hi + lo) / 2;
477 const DexFile::FieldId& field = GetFieldId(mid);
478 if (class_idx > field.class_idx_) {
479 lo = mid + 1;
480 } else if (class_idx < field.class_idx_) {
481 hi = mid - 1;
482 } else {
483 if (name_idx > field.name_idx_) {
484 lo = mid + 1;
485 } else if (name_idx < field.name_idx_) {
486 hi = mid - 1;
487 } else {
488 if (type_idx > field.type_idx_) {
489 lo = mid + 1;
490 } else if (type_idx < field.type_idx_) {
491 hi = mid - 1;
492 } else {
493 return &field;
494 }
495 }
496 }
497 }
498 return NULL;
499}
500
501const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700502 const DexFile::StringId& name,
503 const DexFile::ProtoId& signature) const {
504 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800505 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700506 const uint32_t name_idx = GetIndexForStringId(name);
507 const uint16_t proto_idx = GetIndexForProtoId(signature);
508 uint32_t lo = 0;
509 uint32_t hi = NumMethodIds() - 1;
510 while (hi >= lo) {
511 uint32_t mid = (hi + lo) / 2;
512 const DexFile::MethodId& method = GetMethodId(mid);
513 if (class_idx > method.class_idx_) {
514 lo = mid + 1;
515 } else if (class_idx < method.class_idx_) {
516 hi = mid - 1;
517 } else {
518 if (name_idx > method.name_idx_) {
519 lo = mid + 1;
520 } else if (name_idx < method.name_idx_) {
521 hi = mid - 1;
522 } else {
523 if (proto_idx > method.proto_idx_) {
524 lo = mid + 1;
525 } else if (proto_idx < method.proto_idx_) {
526 hi = mid - 1;
527 } else {
528 return &method;
529 }
530 }
531 }
532 }
533 return NULL;
534}
535
536const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
537 uint32_t lo = 0;
538 uint32_t hi = NumStringIds() - 1;
539 while (hi >= lo) {
540 uint32_t mid = (hi + lo) / 2;
541 int32_t length;
542 const DexFile::StringId& str_id = GetStringId(mid);
543 const char* str = GetStringDataAndLength(str_id, &length);
544 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
545 if (compare > 0) {
546 lo = mid + 1;
547 } else if (compare < 0) {
548 hi = mid - 1;
549 } else {
550 return &str_id;
551 }
552 }
553 return NULL;
554}
555
556const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
557 uint32_t lo = 0;
558 uint32_t hi = NumTypeIds() - 1;
559 while (hi >= lo) {
560 uint32_t mid = (hi + lo) / 2;
561 const TypeId& type_id = GetTypeId(mid);
562 if (string_idx > type_id.descriptor_idx_) {
563 lo = mid + 1;
564 } else if (string_idx < type_id.descriptor_idx_) {
565 hi = mid - 1;
566 } else {
567 return &type_id;
568 }
569 }
570 return NULL;
571}
572
573const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
574 const std::vector<uint16_t>& signature_type_ids) const {
575 uint32_t lo = 0;
576 uint32_t hi = NumProtoIds() - 1;
577 while (hi >= lo) {
578 uint32_t mid = (hi + lo) / 2;
579 const DexFile::ProtoId& proto = GetProtoId(mid);
580 int compare = return_type_idx - proto.return_type_idx_;
581 if (compare == 0) {
582 DexFileParameterIterator it(*this, proto);
583 size_t i = 0;
584 while (it.HasNext() && i < signature_type_ids.size() && compare == 0) {
585 compare = signature_type_ids[i] - it.GetTypeId();
586 it.Next();
587 i++;
588 }
589 if (compare == 0) {
590 if (it.HasNext()) {
591 compare = -1;
592 } else if (i < signature_type_ids.size()) {
593 compare = 1;
594 }
595 }
596 }
597 if (compare > 0) {
598 lo = mid + 1;
599 } else if (compare < 0) {
600 hi = mid - 1;
601 } else {
602 return &proto;
603 }
604 }
605 return NULL;
606}
607
608// Given a signature place the type ids into the given vector
609bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
610 const std::string& signature) const {
611 if (signature[0] != '(') {
612 return false;
613 }
614 size_t offset = 1;
615 size_t end = signature.size();
616 bool process_return = false;
617 while (offset < end) {
618 char c = signature[offset];
619 offset++;
620 if (c == ')') {
621 process_return = true;
622 continue;
623 }
624 std::string descriptor;
625 descriptor += c;
626 while (c == '[') { // process array prefix
627 if (offset >= end) { // expect some descriptor following [
628 return false;
629 }
630 c = signature[offset];
631 offset++;
632 descriptor += c;
633 }
634 if (c == 'L') { // process type descriptors
635 do {
636 if (offset >= end) { // unexpected early termination of descriptor
637 return false;
638 }
639 c = signature[offset];
640 offset++;
641 descriptor += c;
642 } while (c != ';');
643 }
644 const DexFile::StringId* string_id = FindStringId(descriptor);
645 if (string_id == NULL) {
646 return false;
647 }
648 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
649 if (type_id == NULL) {
650 return false;
651 }
652 uint16_t type_idx = GetIndexForTypeId(*type_id);
653 if (!process_return) {
654 param_type_idxs->push_back(type_idx);
655 } else {
656 *return_type_idx = type_idx;
657 return offset == end; // return true if the signature had reached a sensible end
658 }
659 }
660 return false; // failed to correctly parse return type
661}
662
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700663// Materializes the method descriptor for a method prototype. Method
664// descriptors are not stored directly in the dex file. Instead, one
665// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700666std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700667 const ProtoId& proto_id = GetProtoId(proto_idx);
668 std::string descriptor;
669 descriptor.push_back('(');
670 const TypeList* type_list = GetProtoParameters(proto_id);
671 size_t parameter_length = 0;
672 if (type_list != NULL) {
673 // A non-zero number of arguments. Append the type names.
674 for (size_t i = 0; i < type_list->Size(); ++i) {
675 const TypeItem& type_item = type_list->GetTypeItem(i);
676 uint32_t type_idx = type_item.type_idx_;
677 int32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700678 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700679 parameter_length += type_length;
680 descriptor.append(name);
681 }
682 }
683 descriptor.push_back(')');
684 uint32_t return_type_idx = proto_id.return_type_idx_;
685 int32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700686 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700687 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700688 if (unicode_length != NULL) {
689 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
690 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700691 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700692}
693
Carl Shapiro1fb86202011-06-27 17:43:13 -0700694
Shih-wei Liao195487c2011-08-20 13:29:04 -0700695int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700696 // For native method, lineno should be -2 to indicate it is native. Note that
697 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700698 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700699 return -2;
700 }
701
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700702 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700703 DCHECK(code_item != NULL);
704
705 // A method with no line number info should return -1
706 LineNumFromPcContext context(rel_pc, -1);
Ian Rogers0571d352011-11-03 19:51:38 -0700707 DecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700708 return context.line_num_;
709}
710
Ian Rogers0571d352011-11-03 19:51:38 -0700711int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
712 uint32_t address){
713 // Note: Signed type is important for max and min.
714 int32_t min = 0;
715 int32_t max = tries_size - 1;
716
717 while (max >= min) {
718 int32_t mid = (min + max) / 2;
719 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
720 uint32_t start = pTry->start_addr_;
721 if (address < start) {
722 max = mid - 1;
723 } else {
724 uint32_t end = start + pTry->insn_count_;
725 if (address >= end) {
726 min = mid + 1;
727 } else { // We have a winner!
728 return (int32_t) pTry->handler_off_;
729 }
730 }
731 }
732 // No match.
733 return -1;
734}
735
736void DexFile::DecodeDebugInfo0(const CodeItem* code_item, const Method* method,
737 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
738 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700739 uint32_t line = DecodeUnsignedLeb128(&stream);
740 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
741 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
742 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700743 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700744
745 if (!method->IsStatic()) {
Elliott Hughes30646832011-10-13 16:59:46 -0700746 if (need_locals) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700747 std::string descriptor = method->GetDeclaringClass()->GetDescriptor()->ToModifiedUtf8();
748 const ClassDef* class_def = FindClassDef(descriptor);
749 CHECK(class_def != NULL) << descriptor;
750 local_in_reg[arg_reg].name_ = "this";
751 local_in_reg[arg_reg].descriptor_ = GetClassDescriptor(*class_def);
Elliott Hughes30646832011-10-13 16:59:46 -0700752 local_in_reg[arg_reg].start_address_ = 0;
753 local_in_reg[arg_reg].is_live_ = true;
754 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700755 arg_reg++;
756 }
757
Ian Rogers0571d352011-11-03 19:51:38 -0700758 DexFileParameterIterator it(*this, GetProtoId(method->GetProtoIdx()));
759 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700760 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700761 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
762 << " >= " << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700763 return;
764 }
Elliott Hughes30646832011-10-13 16:59:46 -0700765 int32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700766 const char* descriptor = it.GetDescriptor();
Elliott Hughes30646832011-10-13 16:59:46 -0700767 if (need_locals) {
Ian Rogers0571d352011-11-03 19:51:38 -0700768 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700769 local_in_reg[arg_reg].name_ = name;
770 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes30646832011-10-13 16:59:46 -0700771 local_in_reg[arg_reg].start_address_ = address;
772 local_in_reg[arg_reg].is_live_ = true;
773 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700774 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700775 case 'D':
776 case 'J':
777 arg_reg += 2;
778 break;
779 default:
780 arg_reg += 1;
781 break;
782 }
783 }
784
Ian Rogers0571d352011-11-03 19:51:38 -0700785 if (it.HasNext()) {
jeffhaof8728872011-10-28 19:11:13 -0700786 LOG(ERROR) << "invalid stream - problem with parameter iterator";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700787 return;
788 }
789
790 for (;;) {
791 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700792 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700793 uint16_t name_idx;
794 uint16_t descriptor_idx;
795 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700796
Shih-wei Liao195487c2011-08-20 13:29:04 -0700797 switch (opcode) {
798 case DBG_END_SEQUENCE:
799 return;
800
801 case DBG_ADVANCE_PC:
802 address += DecodeUnsignedLeb128(&stream);
803 break;
804
805 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700806 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700807 break;
808
809 case DBG_START_LOCAL:
810 case DBG_START_LOCAL_EXTENDED:
811 reg = DecodeUnsignedLeb128(&stream);
812 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700813 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
814 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700815 return;
816 }
817
jeffhaof8728872011-10-28 19:11:13 -0700818 name_idx = DecodeUnsignedLeb128P1(&stream);
819 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
820 if (opcode == DBG_START_LOCAL_EXTENDED) {
821 signature_idx = DecodeUnsignedLeb128P1(&stream);
822 }
823
Shih-wei Liao195487c2011-08-20 13:29:04 -0700824 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700825 if (need_locals) {
826 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700827
Ian Rogers0571d352011-11-03 19:51:38 -0700828 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
829 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700830 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700831 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700832 }
833 local_in_reg[reg].start_address_ = address;
834 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700835 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700836 break;
837
838 case DBG_END_LOCAL:
839 reg = DecodeUnsignedLeb128(&stream);
840 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700841 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
842 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700843 return;
844 }
845
Elliott Hughes30646832011-10-13 16:59:46 -0700846 if (need_locals) {
847 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
848 local_in_reg[reg].is_live_ = false;
849 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700850 break;
851
852 case DBG_RESTART_LOCAL:
853 reg = DecodeUnsignedLeb128(&stream);
854 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700855 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
856 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700857 return;
858 }
859
Elliott Hughes30646832011-10-13 16:59:46 -0700860 if (need_locals) {
861 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
jeffhaof8728872011-10-28 19:11:13 -0700862 LOG(ERROR) << "invalid stream - no name or descriptor";
Elliott Hughes30646832011-10-13 16:59:46 -0700863 return;
864 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700865
Elliott Hughes30646832011-10-13 16:59:46 -0700866 // If the register is live, the "restart" is superfluous,
867 // and we don't want to mess with the existing start address.
868 if (!local_in_reg[reg].is_live_) {
869 local_in_reg[reg].start_address_ = address;
870 local_in_reg[reg].is_live_ = true;
871 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700872 }
873 break;
874
875 case DBG_SET_PROLOGUE_END:
876 case DBG_SET_EPILOGUE_BEGIN:
877 case DBG_SET_FILE:
878 break;
879
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700880 default: {
881 int adjopcode = opcode - DBG_FIRST_SPECIAL;
882
Shih-wei Liao195487c2011-08-20 13:29:04 -0700883 address += adjopcode / DBG_LINE_RANGE;
884 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
885
886 if (posCb != NULL) {
887 if (posCb(cnxt, address, line)) {
888 // early exit
889 return;
890 }
891 }
892 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700893 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700894 }
895 }
896}
897
Ian Rogers0571d352011-11-03 19:51:38 -0700898void DexFile::DecodeDebugInfo(const CodeItem* code_item, const art::Method* method,
899 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
900 void* cnxt) const {
901 const byte* stream = GetDebugInfoStream(code_item);
902 LocalInfo local_in_reg[code_item->registers_size_];
903
904 if (stream != NULL) {
905 DecodeDebugInfo0(code_item, method, posCb, local_cb, cnxt, stream, local_in_reg);
906 }
907 for (int reg = 0; reg < code_item->registers_size_; reg++) {
908 InvokeLocalCbIfLive(cnxt, reg, code_item->insns_size_in_code_units_, local_in_reg, local_cb);
909 }
910}
911
912bool DexFile::LineNumForPcCb(void* cnxt, uint32_t address, uint32_t line_num) {
913 LineNumFromPcContext* context = (LineNumFromPcContext*) cnxt;
914
915 // We know that this callback will be called in
916 // ascending address order, so keep going until we find
917 // a match or we've just gone past it.
918 if (address > context->address_) {
919 // The line number from the previous positions callback
920 // wil be the final result.
921 return true;
922 } else {
923 context->line_num_ = line_num;
924 return address == context->address_;
925 }
926}
927
928// Decodes the header section from the class data bytes.
929void ClassDataItemIterator::ReadClassDataHeader() {
930 CHECK(ptr_pos_ != NULL);
931 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
932 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
933 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
934 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
935}
936
937void ClassDataItemIterator::ReadClassDataField() {
938 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
939 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
940}
941
942void ClassDataItemIterator::ReadClassDataMethod() {
943 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
944 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
945 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
946}
947
948// Read a signed integer. "zwidth" is the zero-based byte count.
949static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
950 int32_t val = 0;
951 for (int i = zwidth; i >= 0; --i) {
952 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
953 }
954 val >>= (3 - zwidth) * 8;
955 return val;
956}
957
958// Read an unsigned integer. "zwidth" is the zero-based byte count,
959// "fill_on_right" indicates which side we want to zero-fill from.
960static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
961 uint32_t val = 0;
962 if (!fill_on_right) {
963 for (int i = zwidth; i >= 0; --i) {
964 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
965 }
966 val >>= (3 - zwidth) * 8;
967 } else {
968 for (int i = zwidth; i >= 0; --i) {
969 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
970 }
971 }
972 return val;
973}
974
975// Read a signed long. "zwidth" is the zero-based byte count.
976static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
977 int64_t val = 0;
978 for (int i = zwidth; i >= 0; --i) {
979 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
980 }
981 val >>= (7 - zwidth) * 8;
982 return val;
983}
984
985// Read an unsigned long. "zwidth" is the zero-based byte count,
986// "fill_on_right" indicates which side we want to zero-fill from.
987static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
988 uint64_t val = 0;
989 if (!fill_on_right) {
990 for (int i = zwidth; i >= 0; --i) {
991 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
992 }
993 val >>= (7 - zwidth) * 8;
994 } else {
995 for (int i = zwidth; i >= 0; --i) {
996 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
997 }
998 }
999 return val;
1000}
1001
1002EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1003 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
1004 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
1005 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
1006 if (ptr_ == NULL) {
1007 array_size_ = 0;
1008 } else {
1009 array_size_ = DecodeUnsignedLeb128(&ptr_);
1010 }
1011 if (array_size_ > 0) {
1012 Next();
1013 }
1014}
1015
1016void EncodedStaticFieldValueIterator::Next() {
1017 pos_++;
1018 if (pos_ >= array_size_) {
1019 return;
1020 }
1021 byte value_type = *ptr_++;
1022 byte value_arg = value_type >> kEncodedValueArgShift;
1023 size_t width = value_arg + 1; // assume and correct later
1024 type_ = value_type & kEncodedValueTypeMask;
1025 switch (type_) {
1026 case kBoolean:
1027 jval_.i = (value_arg != 0) ? 1 : 0;
1028 width = 0;
1029 break;
1030 case kByte:
1031 jval_.i = ReadSignedInt(ptr_, value_arg);
1032 CHECK(IsInt(8, jval_.i));
1033 break;
1034 case kShort:
1035 jval_.i = ReadSignedInt(ptr_, value_arg);
1036 CHECK(IsInt(16, jval_.i));
1037 break;
1038 case kChar:
1039 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1040 CHECK(IsUint(16, jval_.i));
1041 break;
1042 case kInt:
1043 jval_.i = ReadSignedInt(ptr_, value_arg);
1044 break;
1045 case kLong:
1046 jval_.j = ReadSignedLong(ptr_, value_arg);
1047 break;
1048 case kFloat:
1049 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1050 break;
1051 case kDouble:
1052 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1053 break;
1054 case kString:
1055 case kType:
1056 case kMethod:
1057 case kEnum:
1058 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1059 break;
1060 case kField:
1061 case kArray:
1062 case kAnnotation:
1063 UNIMPLEMENTED(FATAL) << ": type " << type_;
1064 break;
1065 case kNull:
1066 jval_.l = NULL;
1067 width = 0;
1068 break;
1069 default:
1070 LOG(FATAL) << "Unreached";
1071 }
1072 ptr_ += width;
1073}
1074
1075void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
1076 switch (type_) {
1077 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
1078 case kByte: field->SetByte(NULL, jval_.b); break;
1079 case kShort: field->SetShort(NULL, jval_.s); break;
1080 case kChar: field->SetChar(NULL, jval_.c); break;
1081 case kInt: field->SetInt(NULL, jval_.i); break;
1082 case kLong: field->SetLong(NULL, jval_.j); break;
1083 case kFloat: field->SetFloat(NULL, jval_.f); break;
1084 case kDouble: field->SetDouble(NULL, jval_.d); break;
1085 case kNull: field->SetObject(NULL, NULL); break;
1086 case kString: {
1087 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
1088 field->SetObject(NULL, resolved);
1089 break;
1090 }
1091 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1092 }
1093}
1094
1095CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1096 handler_.address_ = -1;
1097 int32_t offset = -1;
1098
1099 // Short-circuit the overwhelmingly common cases.
1100 switch (code_item.tries_size_) {
1101 case 0:
1102 break;
1103 case 1: {
1104 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1105 uint32_t start = tries->start_addr_;
1106 if (address >= start) {
1107 uint32_t end = start + tries->insn_count_;
1108 if (address < end) {
1109 offset = tries->handler_off_;
1110 }
1111 }
1112 break;
1113 }
1114 default:
1115 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
1116 }
1117 if (offset >= 0) {
1118 const byte* handler_data = DexFile::GetCatchHandlerData(code_item, offset);
1119 Init(handler_data);
1120 } else {
1121 // Not found, initialize as empty
1122 current_data_ = NULL;
1123 remaining_count_ = -1;
1124 catch_all_ = false;
1125 DCHECK(!HasNext());
1126 }
1127}
1128
1129void CatchHandlerIterator::Init(const byte* handler_data) {
1130 current_data_ = handler_data;
1131 remaining_count_ = DecodeSignedLeb128(&current_data_);
1132
1133 // If remaining_count_ is non-positive, then it is the negative of
1134 // the number of catch types, and the catches are followed by a
1135 // catch-all handler.
1136 if (remaining_count_ <= 0) {
1137 catch_all_ = true;
1138 remaining_count_ = -remaining_count_;
1139 } else {
1140 catch_all_ = false;
1141 }
1142 Next();
1143}
1144
1145void CatchHandlerIterator::Next() {
1146 if (remaining_count_ > 0) {
1147 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1148 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1149 remaining_count_--;
1150 return;
1151 }
1152
1153 if (catch_all_) {
1154 handler_.type_idx_ = DexFile::kDexNoIndex16;
1155 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1156 catch_all_ = false;
1157 return;
1158 }
1159
1160 // no more handler
1161 remaining_count_ = -1;
1162}
1163
Carl Shapiro1fb86202011-06-27 17:43:13 -07001164} // namespace art