blob: 71fd5a76d06ab2798dbecda599bbb0c5320b88f6 [file] [log] [blame]
Carl Shapiro1fb86202011-06-27 17:43:13 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07004
5#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -07006#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -07007#include <stdio.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07008#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -07009#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070010#include <sys/mman.h>
11#include <sys/stat.h>
12#include <sys/types.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070013
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <map>
15
16#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "globals.h"
18#include "logging.h"
19#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070020#include "os.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include "stringprintf.h"
22#include "thread.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070025
26namespace art {
27
Brian Carlstromf615a612011-07-23 12:50:34 -070028const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
29const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070030
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070031DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070032 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070033 for (size_t i = 0; i != class_path.size(); ++i) {
34 const DexFile* dex_file = class_path[i];
35 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
36 if (dex_class_def != NULL) {
37 return ClassPathEntry(dex_file, dex_class_def);
38 }
39 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070040 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070041 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
42 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070043}
44
Brian Carlstrom16192862011-09-12 17:50:06 -070045const DexFile* DexFile::Open(const std::string& filename,
46 const std::string& strip_location_prefix) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070047 if (filename.size() < 4) {
48 LOG(WARNING) << "Ignoring short classpath entry '" << filename << "'";
49 return NULL;
50 }
51 std::string suffix(filename.substr(filename.size() - 4));
52 if (suffix == ".zip" || suffix == ".jar" || suffix == ".apk") {
Brian Carlstrom16192862011-09-12 17:50:06 -070053 return DexFile::OpenZip(filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070054 } else {
Brian Carlstrom16192862011-09-12 17:50:06 -070055 return DexFile::OpenFile(filename, filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070056 }
57}
58
Brian Carlstromf615a612011-07-23 12:50:34 -070059DexFile::Closer::~Closer() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070060
Brian Carlstromf615a612011-07-23 12:50:34 -070061DexFile::MmapCloser::MmapCloser(void* addr, size_t length) : addr_(addr), length_(length) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070062 CHECK(addr != NULL);
63}
Brian Carlstromf615a612011-07-23 12:50:34 -070064DexFile::MmapCloser::~MmapCloser() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070065 if (munmap(addr_, length_) == -1) {
66 PLOG(INFO) << "munmap failed";
67 }
68}
69
Brian Carlstromf615a612011-07-23 12:50:34 -070070DexFile::PtrCloser::PtrCloser(byte* addr) : addr_(addr) {}
71DexFile::PtrCloser::~PtrCloser() { delete[] addr_; }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070072
Brian Carlstrom16192862011-09-12 17:50:06 -070073const DexFile* DexFile::OpenFile(const std::string& filename,
74 const std::string& original_location,
75 const std::string& strip_location_prefix) {
76 StringPiece location = original_location;
77 if (!location.starts_with(strip_location_prefix)) {
78 LOG(ERROR) << filename << " does not start with " << strip_location_prefix;
79 return NULL;
80 }
81 location.remove_prefix(strip_location_prefix.size());
Brian Carlstromb0460ea2011-07-29 10:08:05 -070082 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070083 if (fd == -1) {
84 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
85 return NULL;
86 }
87 struct stat sbuf;
88 memset(&sbuf, 0, sizeof(sbuf));
89 if (fstat(fd, &sbuf) == -1) {
90 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
91 close(fd);
92 return NULL;
93 }
94 size_t length = sbuf.st_size;
95 void* addr = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0);
96 if (addr == MAP_FAILED) {
97 PLOG(ERROR) << "mmap \"" << filename << "\" failed";
98 close(fd);
99 return NULL;
100 }
101 close(fd);
102 byte* dex_file = reinterpret_cast<byte*>(addr);
103 Closer* closer = new MmapCloser(addr, length);
Brian Carlstrom16192862011-09-12 17:50:06 -0700104 return Open(dex_file, length, location.ToString(), closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700105}
106
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700107static const char* kClassesDex = "classes.dex";
108
109class LockedFd {
110 public:
111 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
112 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
113 if (fd == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700114 PLOG(ERROR) << "Failed to open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700115 return NULL;
116 }
117 fchmod(fd, mode);
118
119 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
120 int result = flock(fd, LOCK_EX | LOCK_NB);
121 if (result == -1) {
122 LOG(WARNING) << "sleeping while locking file " << name;
123 result = flock(fd, LOCK_EX);
124 }
125 if (result == -1 ) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700126 PLOG(ERROR) << "Failed to lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700127 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700128 return NULL;
129 }
130 return new LockedFd(fd);
131 }
132
133 int GetFd() const {
134 return fd_;
135 }
136
137 ~LockedFd() {
138 if (fd_ != -1) {
139 int result = flock(fd_, LOCK_UN);
140 if (result == -1) {
141 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
142 }
143 close(fd_);
144 }
145 }
146
147 private:
148 LockedFd(int fd) : fd_(fd) {}
149
150 int fd_;
151};
152
153class TmpFile {
154 public:
155 TmpFile(const std::string name) : name_(name) {}
156 ~TmpFile() {
157 unlink(name_.c_str());
158 }
159 private:
160 const std::string name_;
161};
162
163// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700164const DexFile* DexFile::OpenZip(const std::string& filename,
165 const std::string& strip_location_prefix) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700166
167 // First, look for a ".dex" alongside the jar file. It will have
168 // the same name/path except for the extension.
169
170 // Example filename = dir/foo.jar
171 std::string adjacent_dex_filename(filename);
172 size_t found = adjacent_dex_filename.find_last_of(".");
173 if (found == std::string::npos) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700174 LOG(ERROR) << "No . in filename" << filename;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700175 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700176 }
177 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
178 adjacent_dex_filename.end(),
179 ".dex");
180 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700181 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700182 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename,
183 filename,
184 strip_location_prefix);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700185 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700186 // We don't verify anything in this case, because we aren't in
187 // the cache and typically the file is in the readonly /system
188 // area, so if something is wrong, there is nothing we can do.
189 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700190 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700191 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700192 }
193
194 char resolved[PATH_MAX];
195 char* absolute_path = realpath(filename.c_str(), resolved);
196 if (absolute_path == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700197 LOG(ERROR) << "Failed to create absolute path for " << filename
198 << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700199 return NULL;
200 }
201 std::string cache_file(absolute_path+1); // skip leading slash
202 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
203 cache_file.push_back('@');
204 cache_file.append(kClassesDex);
205 // Example cache_file = parent@dir@foo.jar@classes.dex
206
207 const char* data_root = getenv("ANDROID_DATA");
208 if (data_root == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700209 if (OS::DirectoryExists("/data")) {
210 data_root = "/data";
211 } else {
212 data_root = "/tmp";
213 }
214 }
215 if (!OS::DirectoryExists(data_root)) {
216 LOG(ERROR) << "Failed to find ANDROID_DATA directory " << data_root;
217 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700218 }
219
Brian Carlstrom16192862011-09-12 17:50:06 -0700220 std::string art_cache = StringPrintf("%s/art-cache", data_root);
221
222 if (!OS::DirectoryExists(art_cache.c_str())) {
223 if (StringPiece(art_cache).starts_with("/tmp/")) {
224 int result = mkdir(art_cache.c_str(), 0700);
225 if (result != 0) {
226 LOG(ERROR) << "Failed to create art-cache directory " << art_cache;
227 return NULL;
228 }
229 } else {
230 LOG(ERROR) << "Failed to find art-cache directory " << art_cache;
231 return NULL;
232 }
233 }
234
235 std::string cache_path_tmp = StringPrintf("%s/%s", art_cache.c_str(), cache_file.c_str());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700236 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
237
Elliott Hughes90a33692011-08-30 13:27:07 -0700238 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
239 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700240 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700241 return NULL;
242 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700243 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
244 if (zip_entry.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700245 LOG(ERROR) << "Failed to find classes.dex within " << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700246 return NULL;
247 }
248
249 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
250 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
251
252 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700253 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700254 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path,
255 filename,
256 strip_location_prefix);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700257 if (cached_dex_file != NULL) {
258 return cached_dex_file;
259 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700260 }
261
262 // Try to open the temporary cache file, grabbing an exclusive
263 // lock. If somebody else is working on it, we'll block here until
264 // they complete. Because we're waiting on an external resource,
265 // we go into native mode.
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700266 // Note that current_thread can be NULL if we're parsing the bootclasspath
267 // during JNI_CreateJavaVM.
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700268 Thread* current_thread = Thread::Current();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700269 Thread::State old(Thread::kUnknown);
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700270 if (current_thread != NULL) {
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700271 old = current_thread->SetState(Thread::kNative);
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700272 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700273 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700274 if (current_thread != NULL) {
275 current_thread->SetState(old);
276 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700277 if (fd.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700278 return NULL;
279 }
280
281 // Check to see if the fd we opened and locked matches the file in
282 // the filesystem. If they don't, then somebody else unlinked
283 // ours and created a new file, and we need to use that one
284 // instead. (If we caught them between the unlink and the create,
285 // we'll get an ENOENT from the file stat.)
286 struct stat fd_stat;
287 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
288 if (fd_stat_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700289 PLOG(ERROR) << "Failed to stat open file '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700290 return NULL;
291 }
292 struct stat file_stat;
293 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
294 if (file_stat_result == -1 ||
295 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
296 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
297 usleep(250 * 1000); // if something is hosed, don't peg machine
298 continue;
299 }
300
301 // We have the correct file open and locked. Extract classes.dex
302 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700303 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
304 if (file.get() == NULL) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700305 return NULL;
306 }
307 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700308 if (!success) {
309 return NULL;
310 }
311
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700312 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700313
314 // Compute checksum and compare to zip. If things look okay, rename from tmp.
315 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
316 if (lseek_result == -1) {
317 return NULL;
318 }
319 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700320 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
321 if (buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700322 return NULL;
323 }
324 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
325 while (true) {
326 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700327 if (bytes_read == -1) {
328 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
329 return NULL;
330 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700331 if (bytes_read == 0) {
332 break;
333 }
334 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
335 }
336 if (computed_crc != zip_entry->GetCrc32()) {
337 return NULL;
338 }
339 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
340 if (rename_result == -1) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700341 PLOG(ERROR) << "Failed to install dex cache file '" << cache_path << "'"
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700342 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700343 unlink(cache_path.c_str());
344 }
345 }
346 // NOTREACHED
347}
348
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700349const DexFile* DexFile::OpenPtr(byte* ptr, size_t length, const std::string& location) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700350 CHECK(ptr != NULL);
Brian Carlstromf615a612011-07-23 12:50:34 -0700351 DexFile::Closer* closer = new PtrCloser(ptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700352 return Open(ptr, length, location, closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700353}
354
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700355const DexFile* DexFile::Open(const byte* dex_bytes, size_t length,
356 const std::string& location, Closer* closer) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700357 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, closer));
Brian Carlstromf615a612011-07-23 12:50:34 -0700358 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700359 return NULL;
360 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700361 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700362 }
363}
364
Brian Carlstromf615a612011-07-23 12:50:34 -0700365DexFile::~DexFile() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700366
Brian Carlstromf615a612011-07-23 12:50:34 -0700367bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700368 InitMembers();
369 if (!IsMagicValid()) {
370 return false;
371 }
372 InitIndex();
373 return true;
374}
375
Brian Carlstromf615a612011-07-23 12:50:34 -0700376void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700377 const byte* b = base_;
378 header_ = reinterpret_cast<const Header*>(b);
379 const Header* h = header_;
380 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
381 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
382 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
383 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
384 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
385 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
386}
387
Brian Carlstromf615a612011-07-23 12:50:34 -0700388bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700389 return CheckMagic(header_->magic_);
390}
391
Brian Carlstromf615a612011-07-23 12:50:34 -0700392bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700393 CHECK(magic != NULL);
394 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700395 LOG(ERROR) << "Unrecognized magic number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700396 << " " << magic[0]
397 << " " << magic[1]
398 << " " << magic[2]
399 << " " << magic[3];
400 return false;
401 }
402 const byte* version = &magic[sizeof(kDexMagic)];
403 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700404 LOG(ERROR) << "Unrecognized version number:"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700405 << " " << version[0]
406 << " " << version[1]
407 << " " << version[2]
408 << " " << version[3];
409 return false;
410 }
411 return true;
412}
413
Brian Carlstromf615a612011-07-23 12:50:34 -0700414void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700415 CHECK_EQ(index_.size(), 0U);
416 for (size_t i = 0; i < NumClassDefs(); ++i) {
417 const ClassDef& class_def = GetClassDef(i);
418 const char* descriptor = GetClassDescriptor(class_def);
419 index_[descriptor] = &class_def;
420 }
421}
422
Brian Carlstromf615a612011-07-23 12:50:34 -0700423const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700424 CHECK(descriptor != NULL);
425 Index::const_iterator it = index_.find(descriptor);
426 if (it == index_.end()) {
427 return NULL;
428 } else {
429 return it->second;
430 }
431}
432
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700433// Materializes the method descriptor for a method prototype. Method
434// descriptors are not stored directly in the dex file. Instead, one
435// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700436std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
437 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700438 const ProtoId& proto_id = GetProtoId(proto_idx);
439 std::string descriptor;
440 descriptor.push_back('(');
441 const TypeList* type_list = GetProtoParameters(proto_id);
442 size_t parameter_length = 0;
443 if (type_list != NULL) {
444 // A non-zero number of arguments. Append the type names.
445 for (size_t i = 0; i < type_list->Size(); ++i) {
446 const TypeItem& type_item = type_list->GetTypeItem(i);
447 uint32_t type_idx = type_item.type_idx_;
448 int32_t type_length;
449 const char* name = dexStringByTypeIdx(type_idx, &type_length);
450 parameter_length += type_length;
451 descriptor.append(name);
452 }
453 }
454 descriptor.push_back(')');
455 uint32_t return_type_idx = proto_id.return_type_idx_;
456 int32_t return_type_length;
457 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
458 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700459 if (unicode_length != NULL) {
460 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
461 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700462 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700463}
464
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700465// Read a signed integer. "zwidth" is the zero-based byte count.
466static int32_t ReadSignedInt(const byte* ptr, int zwidth)
467{
468 int32_t val = 0;
469 for (int i = zwidth; i >= 0; --i) {
470 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
471 }
472 val >>= (3 - zwidth) * 8;
473 return val;
474}
475
476// Read an unsigned integer. "zwidth" is the zero-based byte count,
477// "fill_on_right" indicates which side we want to zero-fill from.
478static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
479 bool fill_on_right) {
480 uint32_t val = 0;
481 if (!fill_on_right) {
482 for (int i = zwidth; i >= 0; --i) {
483 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
484 }
485 val >>= (3 - zwidth) * 8;
486 } else {
487 for (int i = zwidth; i >= 0; --i) {
488 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
489 }
490 }
491 return val;
492}
493
494// Read a signed long. "zwidth" is the zero-based byte count.
495static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
496 int64_t val = 0;
497 for (int i = zwidth; i >= 0; --i) {
498 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
499 }
500 val >>= (7 - zwidth) * 8;
501 return val;
502}
503
504// Read an unsigned long. "zwidth" is the zero-based byte count,
505// "fill_on_right" indicates which side we want to zero-fill from.
506static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
507 bool fill_on_right) {
508 uint64_t val = 0;
509 if (!fill_on_right) {
510 for (int i = zwidth; i >= 0; --i) {
511 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
512 }
513 val >>= (7 - zwidth) * 8;
514 } else {
515 for (int i = zwidth; i >= 0; --i) {
516 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
517 }
518 }
519 return val;
520}
521
Brian Carlstromf615a612011-07-23 12:50:34 -0700522DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
523 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700524 const byte* ptr = *stream;
525 byte value_type = *ptr++;
526 byte value_arg = value_type >> kEncodedValueArgShift;
527 size_t width = value_arg + 1; // assume and correct later
528 int type = value_type & kEncodedValueTypeMask;
529 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700530 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700531 int32_t b = ReadSignedInt(ptr, value_arg);
532 CHECK(IsInt(8, b));
533 value->i = b;
534 break;
535 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700536 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537 int32_t s = ReadSignedInt(ptr, value_arg);
538 CHECK(IsInt(16, s));
539 value->i = s;
540 break;
541 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700542 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700543 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
544 CHECK(IsUint(16, c));
545 value->i = c;
546 break;
547 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700548 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700549 value->i = ReadSignedInt(ptr, value_arg);
550 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700551 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700552 value->j = ReadSignedLong(ptr, value_arg);
553 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700554 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700555 value->i = ReadUnsignedInt(ptr, value_arg, true);
556 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700557 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700558 value->j = ReadUnsignedLong(ptr, value_arg, true);
559 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700560 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700561 value->i = (value_arg != 0);
562 width = 0;
563 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700564 case DexFile::kString:
565 case DexFile::kType:
566 case DexFile::kMethod:
567 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700568 value->i = ReadUnsignedInt(ptr, value_arg, false);
569 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700570 case DexFile::kField:
571 case DexFile::kArray:
572 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700573 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700574 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700575 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700576 value->i = 0;
577 width = 0;
578 break;
579 default:
580 LOG(FATAL) << "Unreached";
581 }
582 ptr += width;
583 *stream = ptr;
584 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700585}
586
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700587String* DexFile::dexArtStringById(int32_t idx) const {
588 if (idx == -1) {
589 return NULL;
590 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700591 return String::AllocFromModifiedUtf8(dexStringById(idx));
592}
593
594int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700595 // For native method, lineno should be -2 to indicate it is native. Note that
596 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700597 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700598 return -2;
599 }
600
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700601 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao195487c2011-08-20 13:29:04 -0700602 DCHECK(code_item != NULL);
603
604 // A method with no line number info should return -1
605 LineNumFromPcContext context(rel_pc, -1);
606 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
607 return context.line_num_;
608}
609
610void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
611 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
612 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
613 uint32_t line = DecodeUnsignedLeb128(&stream);
614 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
615 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
616 uint32_t address = 0;
617
618 if (!method->IsStatic()) {
619 local_in_reg[arg_reg].name_ = String::AllocFromModifiedUtf8("this");
620 local_in_reg[arg_reg].descriptor_ = method->GetDeclaringClass()->GetDescriptor();
621 local_in_reg[arg_reg].signature_ = NULL;
622 local_in_reg[arg_reg].start_address_ = 0;
623 local_in_reg[arg_reg].is_live_ = true;
624 arg_reg++;
625 }
626
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700627 ParameterIterator *it = GetParameterIterator(GetProtoId(method->GetProtoIdx()));
Shih-wei Liao195487c2011-08-20 13:29:04 -0700628 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
629 if (arg_reg >= code_item->registers_size_) {
630 LOG(FATAL) << "invalid stream";
631 return;
632 }
633
634 String* descriptor = String::AllocFromModifiedUtf8(it->GetDescriptor());
635 String* name = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
636
637 local_in_reg[arg_reg].name_ = name;
638 local_in_reg[arg_reg].descriptor_ = descriptor;
639 local_in_reg[arg_reg].signature_ = NULL;
640 local_in_reg[arg_reg].start_address_ = address;
641 local_in_reg[arg_reg].is_live_ = true;
642 switch (descriptor->CharAt(0)) {
643 case 'D':
644 case 'J':
645 arg_reg += 2;
646 break;
647 default:
648 arg_reg += 1;
649 break;
650 }
651 }
652
653 if (it->HasNext()) {
654 LOG(FATAL) << "invalid stream";
655 return;
656 }
657
658 for (;;) {
659 uint8_t opcode = *stream++;
660 uint8_t adjopcode = opcode - DBG_FIRST_SPECIAL;
661 uint16_t reg;
662
663
664 switch (opcode) {
665 case DBG_END_SEQUENCE:
666 return;
667
668 case DBG_ADVANCE_PC:
669 address += DecodeUnsignedLeb128(&stream);
670 break;
671
672 case DBG_ADVANCE_LINE:
673 line += DecodeUnsignedLeb128(&stream);
674 break;
675
676 case DBG_START_LOCAL:
677 case DBG_START_LOCAL_EXTENDED:
678 reg = DecodeUnsignedLeb128(&stream);
679 if (reg > code_item->registers_size_) {
680 LOG(FATAL) << "invalid stream";
681 return;
682 }
683
684 // Emit what was previously there, if anything
685 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
686
687 local_in_reg[reg].name_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
688 local_in_reg[reg].descriptor_ = dexArtStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
689 if (opcode == DBG_START_LOCAL_EXTENDED) {
690 local_in_reg[reg].signature_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
691 } else {
692 local_in_reg[reg].signature_ = NULL;
693 }
694 local_in_reg[reg].start_address_ = address;
695 local_in_reg[reg].is_live_ = true;
696 break;
697
698 case DBG_END_LOCAL:
699 reg = DecodeUnsignedLeb128(&stream);
700 if (reg > code_item->registers_size_) {
701 LOG(FATAL) << "invalid stream";
702 return;
703 }
704
705 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
706 local_in_reg[reg].is_live_ = false;
707 break;
708
709 case DBG_RESTART_LOCAL:
710 reg = DecodeUnsignedLeb128(&stream);
711 if (reg > code_item->registers_size_) {
712 LOG(FATAL) << "invalid stream";
713 return;
714 }
715
716 if (local_in_reg[reg].name_ == NULL
717 || local_in_reg[reg].descriptor_ == NULL) {
718 LOG(FATAL) << "invalid stream";
719 return;
720 }
721
722 // If the register is live, the "restart" is superfluous,
723 // and we don't want to mess with the existing start address.
724 if (!local_in_reg[reg].is_live_) {
725 local_in_reg[reg].start_address_ = address;
726 local_in_reg[reg].is_live_ = true;
727 }
728 break;
729
730 case DBG_SET_PROLOGUE_END:
731 case DBG_SET_EPILOGUE_BEGIN:
732 case DBG_SET_FILE:
733 break;
734
735 default:
736 address += adjopcode / DBG_LINE_RANGE;
737 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
738
739 if (posCb != NULL) {
740 if (posCb(cnxt, address, line)) {
741 // early exit
742 return;
743 }
744 }
745 break;
746 }
747 }
748}
749
Carl Shapiro1fb86202011-06-27 17:43:13 -0700750} // namespace art