blob: e9a883c9e39b8700373f4e488f42ef10f70a2058 [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 Rogers0571d352011-11-03 19:51:38 -0700466const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& klass,
467 const DexFile::StringId& name,
468 const DexFile::ProtoId& signature) 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(klass);
471 const uint32_t name_idx = GetIndexForStringId(name);
472 const uint16_t proto_idx = GetIndexForProtoId(signature);
473 uint32_t lo = 0;
474 uint32_t hi = NumMethodIds() - 1;
475 while (hi >= lo) {
476 uint32_t mid = (hi + lo) / 2;
477 const DexFile::MethodId& method = GetMethodId(mid);
478 if (class_idx > method.class_idx_) {
479 lo = mid + 1;
480 } else if (class_idx < method.class_idx_) {
481 hi = mid - 1;
482 } else {
483 if (name_idx > method.name_idx_) {
484 lo = mid + 1;
485 } else if (name_idx < method.name_idx_) {
486 hi = mid - 1;
487 } else {
488 if (proto_idx > method.proto_idx_) {
489 lo = mid + 1;
490 } else if (proto_idx < method.proto_idx_) {
491 hi = mid - 1;
492 } else {
493 return &method;
494 }
495 }
496 }
497 }
498 return NULL;
499}
500
501const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
502 uint32_t lo = 0;
503 uint32_t hi = NumStringIds() - 1;
504 while (hi >= lo) {
505 uint32_t mid = (hi + lo) / 2;
506 int32_t length;
507 const DexFile::StringId& str_id = GetStringId(mid);
508 const char* str = GetStringDataAndLength(str_id, &length);
509 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
510 if (compare > 0) {
511 lo = mid + 1;
512 } else if (compare < 0) {
513 hi = mid - 1;
514 } else {
515 return &str_id;
516 }
517 }
518 return NULL;
519}
520
521const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
522 uint32_t lo = 0;
523 uint32_t hi = NumTypeIds() - 1;
524 while (hi >= lo) {
525 uint32_t mid = (hi + lo) / 2;
526 const TypeId& type_id = GetTypeId(mid);
527 if (string_idx > type_id.descriptor_idx_) {
528 lo = mid + 1;
529 } else if (string_idx < type_id.descriptor_idx_) {
530 hi = mid - 1;
531 } else {
532 return &type_id;
533 }
534 }
535 return NULL;
536}
537
538const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
539 const std::vector<uint16_t>& signature_type_ids) const {
540 uint32_t lo = 0;
541 uint32_t hi = NumProtoIds() - 1;
542 while (hi >= lo) {
543 uint32_t mid = (hi + lo) / 2;
544 const DexFile::ProtoId& proto = GetProtoId(mid);
545 int compare = return_type_idx - proto.return_type_idx_;
546 if (compare == 0) {
547 DexFileParameterIterator it(*this, proto);
548 size_t i = 0;
549 while (it.HasNext() && i < signature_type_ids.size() && compare == 0) {
550 compare = signature_type_ids[i] - it.GetTypeId();
551 it.Next();
552 i++;
553 }
554 if (compare == 0) {
555 if (it.HasNext()) {
556 compare = -1;
557 } else if (i < signature_type_ids.size()) {
558 compare = 1;
559 }
560 }
561 }
562 if (compare > 0) {
563 lo = mid + 1;
564 } else if (compare < 0) {
565 hi = mid - 1;
566 } else {
567 return &proto;
568 }
569 }
570 return NULL;
571}
572
573// Given a signature place the type ids into the given vector
574bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
575 const std::string& signature) const {
576 if (signature[0] != '(') {
577 return false;
578 }
579 size_t offset = 1;
580 size_t end = signature.size();
581 bool process_return = false;
582 while (offset < end) {
583 char c = signature[offset];
584 offset++;
585 if (c == ')') {
586 process_return = true;
587 continue;
588 }
589 std::string descriptor;
590 descriptor += c;
591 while (c == '[') { // process array prefix
592 if (offset >= end) { // expect some descriptor following [
593 return false;
594 }
595 c = signature[offset];
596 offset++;
597 descriptor += c;
598 }
599 if (c == 'L') { // process type descriptors
600 do {
601 if (offset >= end) { // unexpected early termination of descriptor
602 return false;
603 }
604 c = signature[offset];
605 offset++;
606 descriptor += c;
607 } while (c != ';');
608 }
609 const DexFile::StringId* string_id = FindStringId(descriptor);
610 if (string_id == NULL) {
611 return false;
612 }
613 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
614 if (type_id == NULL) {
615 return false;
616 }
617 uint16_t type_idx = GetIndexForTypeId(*type_id);
618 if (!process_return) {
619 param_type_idxs->push_back(type_idx);
620 } else {
621 *return_type_idx = type_idx;
622 return offset == end; // return true if the signature had reached a sensible end
623 }
624 }
625 return false; // failed to correctly parse return type
626}
627
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700628// Materializes the method descriptor for a method prototype. Method
629// descriptors are not stored directly in the dex file. Instead, one
630// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700631std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700632 const ProtoId& proto_id = GetProtoId(proto_idx);
633 std::string descriptor;
634 descriptor.push_back('(');
635 const TypeList* type_list = GetProtoParameters(proto_id);
636 size_t parameter_length = 0;
637 if (type_list != NULL) {
638 // A non-zero number of arguments. Append the type names.
639 for (size_t i = 0; i < type_list->Size(); ++i) {
640 const TypeItem& type_item = type_list->GetTypeItem(i);
641 uint32_t type_idx = type_item.type_idx_;
642 int32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700643 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700644 parameter_length += type_length;
645 descriptor.append(name);
646 }
647 }
648 descriptor.push_back(')');
649 uint32_t return_type_idx = proto_id.return_type_idx_;
650 int32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700651 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700652 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700653 if (unicode_length != NULL) {
654 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
655 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700656 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700657}
658
Carl Shapiro1fb86202011-06-27 17:43:13 -0700659
Shih-wei Liao195487c2011-08-20 13:29:04 -0700660int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700661 // For native method, lineno should be -2 to indicate it is native. Note that
662 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700663 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700664 return -2;
665 }
666
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700668 DCHECK(code_item != NULL);
669
670 // A method with no line number info should return -1
671 LineNumFromPcContext context(rel_pc, -1);
Ian Rogers0571d352011-11-03 19:51:38 -0700672 DecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700673 return context.line_num_;
674}
675
Ian Rogers0571d352011-11-03 19:51:38 -0700676int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
677 uint32_t address){
678 // Note: Signed type is important for max and min.
679 int32_t min = 0;
680 int32_t max = tries_size - 1;
681
682 while (max >= min) {
683 int32_t mid = (min + max) / 2;
684 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
685 uint32_t start = pTry->start_addr_;
686 if (address < start) {
687 max = mid - 1;
688 } else {
689 uint32_t end = start + pTry->insn_count_;
690 if (address >= end) {
691 min = mid + 1;
692 } else { // We have a winner!
693 return (int32_t) pTry->handler_off_;
694 }
695 }
696 }
697 // No match.
698 return -1;
699}
700
701void DexFile::DecodeDebugInfo0(const CodeItem* code_item, const Method* method,
702 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
703 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700704 uint32_t line = DecodeUnsignedLeb128(&stream);
705 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
706 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
707 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700708 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700709
710 if (!method->IsStatic()) {
Elliott Hughes30646832011-10-13 16:59:46 -0700711 if (need_locals) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700712 std::string descriptor = method->GetDeclaringClass()->GetDescriptor()->ToModifiedUtf8();
713 const ClassDef* class_def = FindClassDef(descriptor);
714 CHECK(class_def != NULL) << descriptor;
715 local_in_reg[arg_reg].name_ = "this";
716 local_in_reg[arg_reg].descriptor_ = GetClassDescriptor(*class_def);
Elliott Hughes30646832011-10-13 16:59:46 -0700717 local_in_reg[arg_reg].start_address_ = 0;
718 local_in_reg[arg_reg].is_live_ = true;
719 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700720 arg_reg++;
721 }
722
Ian Rogers0571d352011-11-03 19:51:38 -0700723 DexFileParameterIterator it(*this, GetProtoId(method->GetProtoIdx()));
724 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700725 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700726 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
727 << " >= " << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700728 return;
729 }
Elliott Hughes30646832011-10-13 16:59:46 -0700730 int32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700731 const char* descriptor = it.GetDescriptor();
Elliott Hughes30646832011-10-13 16:59:46 -0700732 if (need_locals) {
Ian Rogers0571d352011-11-03 19:51:38 -0700733 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700734 local_in_reg[arg_reg].name_ = name;
735 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes30646832011-10-13 16:59:46 -0700736 local_in_reg[arg_reg].start_address_ = address;
737 local_in_reg[arg_reg].is_live_ = true;
738 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700739 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700740 case 'D':
741 case 'J':
742 arg_reg += 2;
743 break;
744 default:
745 arg_reg += 1;
746 break;
747 }
748 }
749
Ian Rogers0571d352011-11-03 19:51:38 -0700750 if (it.HasNext()) {
jeffhaof8728872011-10-28 19:11:13 -0700751 LOG(ERROR) << "invalid stream - problem with parameter iterator";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700752 return;
753 }
754
755 for (;;) {
756 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700757 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700758 uint16_t name_idx;
759 uint16_t descriptor_idx;
760 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700761
Shih-wei Liao195487c2011-08-20 13:29:04 -0700762 switch (opcode) {
763 case DBG_END_SEQUENCE:
764 return;
765
766 case DBG_ADVANCE_PC:
767 address += DecodeUnsignedLeb128(&stream);
768 break;
769
770 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700771 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700772 break;
773
774 case DBG_START_LOCAL:
775 case DBG_START_LOCAL_EXTENDED:
776 reg = DecodeUnsignedLeb128(&stream);
777 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700778 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
779 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700780 return;
781 }
782
jeffhaof8728872011-10-28 19:11:13 -0700783 name_idx = DecodeUnsignedLeb128P1(&stream);
784 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
785 if (opcode == DBG_START_LOCAL_EXTENDED) {
786 signature_idx = DecodeUnsignedLeb128P1(&stream);
787 }
788
Shih-wei Liao195487c2011-08-20 13:29:04 -0700789 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700790 if (need_locals) {
791 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700792
Ian Rogers0571d352011-11-03 19:51:38 -0700793 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
794 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700795 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700796 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700797 }
798 local_in_reg[reg].start_address_ = address;
799 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700800 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700801 break;
802
803 case DBG_END_LOCAL:
804 reg = DecodeUnsignedLeb128(&stream);
805 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700806 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
807 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700808 return;
809 }
810
Elliott Hughes30646832011-10-13 16:59:46 -0700811 if (need_locals) {
812 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
813 local_in_reg[reg].is_live_ = false;
814 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700815 break;
816
817 case DBG_RESTART_LOCAL:
818 reg = DecodeUnsignedLeb128(&stream);
819 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700820 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
821 << code_item->registers_size_ << ")";
Shih-wei Liao195487c2011-08-20 13:29:04 -0700822 return;
823 }
824
Elliott Hughes30646832011-10-13 16:59:46 -0700825 if (need_locals) {
826 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
jeffhaof8728872011-10-28 19:11:13 -0700827 LOG(ERROR) << "invalid stream - no name or descriptor";
Elliott Hughes30646832011-10-13 16:59:46 -0700828 return;
829 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700830
Elliott Hughes30646832011-10-13 16:59:46 -0700831 // If the register is live, the "restart" is superfluous,
832 // and we don't want to mess with the existing start address.
833 if (!local_in_reg[reg].is_live_) {
834 local_in_reg[reg].start_address_ = address;
835 local_in_reg[reg].is_live_ = true;
836 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700837 }
838 break;
839
840 case DBG_SET_PROLOGUE_END:
841 case DBG_SET_EPILOGUE_BEGIN:
842 case DBG_SET_FILE:
843 break;
844
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700845 default: {
846 int adjopcode = opcode - DBG_FIRST_SPECIAL;
847
Shih-wei Liao195487c2011-08-20 13:29:04 -0700848 address += adjopcode / DBG_LINE_RANGE;
849 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
850
851 if (posCb != NULL) {
852 if (posCb(cnxt, address, line)) {
853 // early exit
854 return;
855 }
856 }
857 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700858 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700859 }
860 }
861}
862
Ian Rogers0571d352011-11-03 19:51:38 -0700863void DexFile::DecodeDebugInfo(const CodeItem* code_item, const art::Method* method,
864 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
865 void* cnxt) const {
866 const byte* stream = GetDebugInfoStream(code_item);
867 LocalInfo local_in_reg[code_item->registers_size_];
868
869 if (stream != NULL) {
870 DecodeDebugInfo0(code_item, method, posCb, local_cb, cnxt, stream, local_in_reg);
871 }
872 for (int reg = 0; reg < code_item->registers_size_; reg++) {
873 InvokeLocalCbIfLive(cnxt, reg, code_item->insns_size_in_code_units_, local_in_reg, local_cb);
874 }
875}
876
877bool DexFile::LineNumForPcCb(void* cnxt, uint32_t address, uint32_t line_num) {
878 LineNumFromPcContext* context = (LineNumFromPcContext*) cnxt;
879
880 // We know that this callback will be called in
881 // ascending address order, so keep going until we find
882 // a match or we've just gone past it.
883 if (address > context->address_) {
884 // The line number from the previous positions callback
885 // wil be the final result.
886 return true;
887 } else {
888 context->line_num_ = line_num;
889 return address == context->address_;
890 }
891}
892
893// Decodes the header section from the class data bytes.
894void ClassDataItemIterator::ReadClassDataHeader() {
895 CHECK(ptr_pos_ != NULL);
896 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
897 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
898 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
899 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
900}
901
902void ClassDataItemIterator::ReadClassDataField() {
903 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
904 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
905}
906
907void ClassDataItemIterator::ReadClassDataMethod() {
908 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
909 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
910 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
911}
912
913// Read a signed integer. "zwidth" is the zero-based byte count.
914static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
915 int32_t val = 0;
916 for (int i = zwidth; i >= 0; --i) {
917 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
918 }
919 val >>= (3 - zwidth) * 8;
920 return val;
921}
922
923// Read an unsigned integer. "zwidth" is the zero-based byte count,
924// "fill_on_right" indicates which side we want to zero-fill from.
925static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
926 uint32_t val = 0;
927 if (!fill_on_right) {
928 for (int i = zwidth; i >= 0; --i) {
929 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
930 }
931 val >>= (3 - zwidth) * 8;
932 } else {
933 for (int i = zwidth; i >= 0; --i) {
934 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
935 }
936 }
937 return val;
938}
939
940// Read a signed long. "zwidth" is the zero-based byte count.
941static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
942 int64_t val = 0;
943 for (int i = zwidth; i >= 0; --i) {
944 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
945 }
946 val >>= (7 - zwidth) * 8;
947 return val;
948}
949
950// Read an unsigned long. "zwidth" is the zero-based byte count,
951// "fill_on_right" indicates which side we want to zero-fill from.
952static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
953 uint64_t val = 0;
954 if (!fill_on_right) {
955 for (int i = zwidth; i >= 0; --i) {
956 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
957 }
958 val >>= (7 - zwidth) * 8;
959 } else {
960 for (int i = zwidth; i >= 0; --i) {
961 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
962 }
963 }
964 return val;
965}
966
967EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
968 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
969 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
970 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
971 if (ptr_ == NULL) {
972 array_size_ = 0;
973 } else {
974 array_size_ = DecodeUnsignedLeb128(&ptr_);
975 }
976 if (array_size_ > 0) {
977 Next();
978 }
979}
980
981void EncodedStaticFieldValueIterator::Next() {
982 pos_++;
983 if (pos_ >= array_size_) {
984 return;
985 }
986 byte value_type = *ptr_++;
987 byte value_arg = value_type >> kEncodedValueArgShift;
988 size_t width = value_arg + 1; // assume and correct later
989 type_ = value_type & kEncodedValueTypeMask;
990 switch (type_) {
991 case kBoolean:
992 jval_.i = (value_arg != 0) ? 1 : 0;
993 width = 0;
994 break;
995 case kByte:
996 jval_.i = ReadSignedInt(ptr_, value_arg);
997 CHECK(IsInt(8, jval_.i));
998 break;
999 case kShort:
1000 jval_.i = ReadSignedInt(ptr_, value_arg);
1001 CHECK(IsInt(16, jval_.i));
1002 break;
1003 case kChar:
1004 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1005 CHECK(IsUint(16, jval_.i));
1006 break;
1007 case kInt:
1008 jval_.i = ReadSignedInt(ptr_, value_arg);
1009 break;
1010 case kLong:
1011 jval_.j = ReadSignedLong(ptr_, value_arg);
1012 break;
1013 case kFloat:
1014 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1015 break;
1016 case kDouble:
1017 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1018 break;
1019 case kString:
1020 case kType:
1021 case kMethod:
1022 case kEnum:
1023 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1024 break;
1025 case kField:
1026 case kArray:
1027 case kAnnotation:
1028 UNIMPLEMENTED(FATAL) << ": type " << type_;
1029 break;
1030 case kNull:
1031 jval_.l = NULL;
1032 width = 0;
1033 break;
1034 default:
1035 LOG(FATAL) << "Unreached";
1036 }
1037 ptr_ += width;
1038}
1039
1040void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
1041 switch (type_) {
1042 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
1043 case kByte: field->SetByte(NULL, jval_.b); break;
1044 case kShort: field->SetShort(NULL, jval_.s); break;
1045 case kChar: field->SetChar(NULL, jval_.c); break;
1046 case kInt: field->SetInt(NULL, jval_.i); break;
1047 case kLong: field->SetLong(NULL, jval_.j); break;
1048 case kFloat: field->SetFloat(NULL, jval_.f); break;
1049 case kDouble: field->SetDouble(NULL, jval_.d); break;
1050 case kNull: field->SetObject(NULL, NULL); break;
1051 case kString: {
1052 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
1053 field->SetObject(NULL, resolved);
1054 break;
1055 }
1056 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1057 }
1058}
1059
1060CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1061 handler_.address_ = -1;
1062 int32_t offset = -1;
1063
1064 // Short-circuit the overwhelmingly common cases.
1065 switch (code_item.tries_size_) {
1066 case 0:
1067 break;
1068 case 1: {
1069 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1070 uint32_t start = tries->start_addr_;
1071 if (address >= start) {
1072 uint32_t end = start + tries->insn_count_;
1073 if (address < end) {
1074 offset = tries->handler_off_;
1075 }
1076 }
1077 break;
1078 }
1079 default:
1080 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
1081 }
1082 if (offset >= 0) {
1083 const byte* handler_data = DexFile::GetCatchHandlerData(code_item, offset);
1084 Init(handler_data);
1085 } else {
1086 // Not found, initialize as empty
1087 current_data_ = NULL;
1088 remaining_count_ = -1;
1089 catch_all_ = false;
1090 DCHECK(!HasNext());
1091 }
1092}
1093
1094void CatchHandlerIterator::Init(const byte* handler_data) {
1095 current_data_ = handler_data;
1096 remaining_count_ = DecodeSignedLeb128(&current_data_);
1097
1098 // If remaining_count_ is non-positive, then it is the negative of
1099 // the number of catch types, and the catches are followed by a
1100 // catch-all handler.
1101 if (remaining_count_ <= 0) {
1102 catch_all_ = true;
1103 remaining_count_ = -remaining_count_;
1104 } else {
1105 catch_all_ = false;
1106 }
1107 Next();
1108}
1109
1110void CatchHandlerIterator::Next() {
1111 if (remaining_count_ > 0) {
1112 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1113 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1114 remaining_count_--;
1115 return;
1116 }
1117
1118 if (catch_all_) {
1119 handler_.type_idx_ = DexFile::kDexNoIndex16;
1120 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1121 catch_all_ = false;
1122 return;
1123 }
1124
1125 // no more handler
1126 remaining_count_ = -1;
1127}
1128
Carl Shapiro1fb86202011-06-27 17:43:13 -07001129} // namespace art