blob: 4b56435284076dc9b32669cc4e6f37a00b46bf2e [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 Carlstromf615a612011-07-23 12:50:34 -070045DexFile::Closer::~Closer() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070046
Brian Carlstromf615a612011-07-23 12:50:34 -070047DexFile::MmapCloser::MmapCloser(void* addr, size_t length) : addr_(addr), length_(length) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070048 CHECK(addr != NULL);
49}
Brian Carlstromf615a612011-07-23 12:50:34 -070050DexFile::MmapCloser::~MmapCloser() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070051 if (munmap(addr_, length_) == -1) {
52 PLOG(INFO) << "munmap failed";
53 }
54}
55
Brian Carlstromf615a612011-07-23 12:50:34 -070056DexFile::PtrCloser::PtrCloser(byte* addr) : addr_(addr) {}
57DexFile::PtrCloser::~PtrCloser() { delete[] addr_; }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070058
Brian Carlstrom9f30b382011-08-28 22:41:38 -070059const DexFile* DexFile::OpenFile(const std::string& filename) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070060 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070061 if (fd == -1) {
62 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
63 return NULL;
64 }
65 struct stat sbuf;
66 memset(&sbuf, 0, sizeof(sbuf));
67 if (fstat(fd, &sbuf) == -1) {
68 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
69 close(fd);
70 return NULL;
71 }
72 size_t length = sbuf.st_size;
73 void* addr = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0);
74 if (addr == MAP_FAILED) {
75 PLOG(ERROR) << "mmap \"" << filename << "\" failed";
76 close(fd);
77 return NULL;
78 }
79 close(fd);
80 byte* dex_file = reinterpret_cast<byte*>(addr);
81 Closer* closer = new MmapCloser(addr, length);
Brian Carlstroma663ea52011-08-19 23:33:41 -070082 return Open(dex_file, length, filename, closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070083}
84
Brian Carlstromb0460ea2011-07-29 10:08:05 -070085static const char* kClassesDex = "classes.dex";
86
87class LockedFd {
88 public:
89 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
90 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
91 if (fd == -1) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070092 PLOG(ERROR) << "Can't open file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -070093 return NULL;
94 }
95 fchmod(fd, mode);
96
97 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
98 int result = flock(fd, LOCK_EX | LOCK_NB);
99 if (result == -1) {
100 LOG(WARNING) << "sleeping while locking file " << name;
101 result = flock(fd, LOCK_EX);
102 }
103 if (result == -1 ) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700104 PLOG(ERROR) << "Can't lock file '" << name << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700105 close(fd);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700106 return NULL;
107 }
108 return new LockedFd(fd);
109 }
110
111 int GetFd() const {
112 return fd_;
113 }
114
115 ~LockedFd() {
116 if (fd_ != -1) {
117 int result = flock(fd_, LOCK_UN);
118 if (result == -1) {
119 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
120 }
121 close(fd_);
122 }
123 }
124
125 private:
126 LockedFd(int fd) : fd_(fd) {}
127
128 int fd_;
129};
130
131class TmpFile {
132 public:
133 TmpFile(const std::string name) : name_(name) {}
134 ~TmpFile() {
135 unlink(name_.c_str());
136 }
137 private:
138 const std::string name_;
139};
140
141// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700142const DexFile* DexFile::OpenZip(const std::string& filename) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700143
144 // First, look for a ".dex" alongside the jar file. It will have
145 // the same name/path except for the extension.
146
147 // Example filename = dir/foo.jar
148 std::string adjacent_dex_filename(filename);
149 size_t found = adjacent_dex_filename.find_last_of(".");
150 if (found == std::string::npos) {
151 LOG(WARNING) << "No . in filename" << filename;
152 }
153 adjacent_dex_filename.replace(adjacent_dex_filename.begin() + found,
154 adjacent_dex_filename.end(),
155 ".dex");
156 // Example adjacent_dex_filename = dir/foo.dex
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700157 if (OS::FileExists(adjacent_dex_filename.c_str())) {
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700158 const DexFile* adjacent_dex_file = DexFile::OpenFile(adjacent_dex_filename);
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700159 if (adjacent_dex_file != NULL) {
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700160 // We don't verify anything in this case, because we aren't in
161 // the cache and typically the file is in the readonly /system
162 // area, so if something is wrong, there is nothing we can do.
163 return adjacent_dex_file;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700164 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700165 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700166 }
167
168 char resolved[PATH_MAX];
169 char* absolute_path = realpath(filename.c_str(), resolved);
170 if (absolute_path == NULL) {
171 LOG(WARNING) << "Could not create absolute path for " << filename
172 << " when looking for classes.dex";
173 return NULL;
174 }
175 std::string cache_file(absolute_path+1); // skip leading slash
176 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
177 cache_file.push_back('@');
178 cache_file.append(kClassesDex);
179 // Example cache_file = parent@dir@foo.jar@classes.dex
180
181 const char* data_root = getenv("ANDROID_DATA");
182 if (data_root == NULL) {
183 data_root = "/data";
184 }
185
186 std::string cache_path_tmp = StringPrintf("%s/art-cache/%s", data_root, cache_file.c_str());
187 // Example cache_path_tmp = /data/art-cache/parent@dir@foo.jar@classes.dex
188
Elliott Hughes90a33692011-08-30 13:27:07 -0700189 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
190 if (zip_archive.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700191 LOG(WARNING) << "Could not open " << filename << " when looking for classes.dex";
192 return NULL;
193 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700194 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
195 if (zip_entry.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700196 LOG(WARNING) << "Could not find classes.dex within " << filename;
197 return NULL;
198 }
199
200 std::string cache_path = StringPrintf("%s.%08x", cache_path_tmp.c_str(), zip_entry->GetCrc32());
201 // Example cache_path = /data/art-cache/parent@dir@foo.jar@classes.dex.1a2b3c4d
202
203 while (true) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700204 if (OS::FileExists(cache_path.c_str())) {
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700205 const DexFile* cached_dex_file = DexFile::OpenFile(cache_path);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700206 if (cached_dex_file != NULL) {
207 return cached_dex_file;
208 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700209 }
210
211 // Try to open the temporary cache file, grabbing an exclusive
212 // lock. If somebody else is working on it, we'll block here until
213 // they complete. Because we're waiting on an external resource,
214 // we go into native mode.
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700215 // Note that current_thread can be NULL if we're parsing the bootclasspath
216 // during JNI_CreateJavaVM.
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700217 Thread* current_thread = Thread::Current();
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700218 Thread::State old;
219 if (current_thread != NULL) {
220 old = current_thread->GetState();
221 current_thread->SetState(Thread::kNative);
222 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700223 UniquePtr<LockedFd> fd(LockedFd::CreateAndLock(cache_path_tmp, 0644));
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700224 if (current_thread != NULL) {
225 current_thread->SetState(old);
226 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700227 if (fd.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700228 return NULL;
229 }
230
231 // Check to see if the fd we opened and locked matches the file in
232 // the filesystem. If they don't, then somebody else unlinked
233 // ours and created a new file, and we need to use that one
234 // instead. (If we caught them between the unlink and the create,
235 // we'll get an ENOENT from the file stat.)
236 struct stat fd_stat;
237 int fd_stat_result = fstat(fd->GetFd(), &fd_stat);
238 if (fd_stat_result == -1) {
239 PLOG(ERROR) << "Can't stat open file '" << cache_path_tmp << "'";
240 return NULL;
241 }
242 struct stat file_stat;
243 int file_stat_result = stat(cache_path_tmp.c_str(), &file_stat);
244 if (file_stat_result == -1 ||
245 fd_stat.st_dev != file_stat.st_dev || fd_stat.st_ino != file_stat.st_ino) {
246 LOG(WARNING) << "our open cache file is stale; sleeping and retrying";
247 usleep(250 * 1000); // if something is hosed, don't peg machine
248 continue;
249 }
250
251 // We have the correct file open and locked. Extract classes.dex
252 TmpFile tmp_file(cache_path_tmp);
Elliott Hughes90a33692011-08-30 13:27:07 -0700253 UniquePtr<File> file(OS::FileFromFd(cache_path_tmp.c_str(), fd->GetFd()));
254 if (file.get() == NULL) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700255 return NULL;
256 }
257 bool success = zip_entry->Extract(*file);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700258 if (!success) {
259 return NULL;
260 }
261
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700262 // TODO: restat and check length against zip_entry->GetUncompressedLength()?
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700263
264 // Compute checksum and compare to zip. If things look okay, rename from tmp.
265 off_t lseek_result = lseek(fd->GetFd(), 0, SEEK_SET);
266 if (lseek_result == -1) {
267 return NULL;
268 }
269 const size_t kBufSize = 32768;
Elliott Hughes90a33692011-08-30 13:27:07 -0700270 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
271 if (buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700272 return NULL;
273 }
274 uint32_t computed_crc = crc32(0L, Z_NULL, 0);
275 while (true) {
276 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd->GetFd(), buf.get(), kBufSize));
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700277 if (bytes_read == -1) {
278 PLOG(ERROR) << "Problem computing CRC of '" << cache_path_tmp << "'";
279 return NULL;
280 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700281 if (bytes_read == 0) {
282 break;
283 }
284 computed_crc = crc32(computed_crc, buf.get(), bytes_read);
285 }
286 if (computed_crc != zip_entry->GetCrc32()) {
287 return NULL;
288 }
289 int rename_result = rename(cache_path_tmp.c_str(), cache_path.c_str());
290 if (rename_result == -1) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700291 PLOG(ERROR) << "Can't install dex cache file '" << cache_path << "'"
292 << " from '" << cache_path_tmp << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700293 unlink(cache_path.c_str());
294 }
295 }
296 // NOTREACHED
297}
298
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700299const DexFile* DexFile::OpenPtr(byte* ptr, size_t length, const std::string& location) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700300 CHECK(ptr != NULL);
Brian Carlstromf615a612011-07-23 12:50:34 -0700301 DexFile::Closer* closer = new PtrCloser(ptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700302 return Open(ptr, length, location, closer);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700303}
304
Brian Carlstrom9f30b382011-08-28 22:41:38 -0700305const DexFile* DexFile::Open(const byte* dex_bytes, size_t length,
306 const std::string& location, Closer* closer) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700307 UniquePtr<DexFile> dex_file(new DexFile(dex_bytes, length, location, closer));
Brian Carlstromf615a612011-07-23 12:50:34 -0700308 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700309 return NULL;
310 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700311 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700312 }
313}
314
Brian Carlstromf615a612011-07-23 12:50:34 -0700315DexFile::~DexFile() {}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700316
Brian Carlstromf615a612011-07-23 12:50:34 -0700317bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700318 InitMembers();
319 if (!IsMagicValid()) {
320 return false;
321 }
322 InitIndex();
323 return true;
324}
325
Brian Carlstromf615a612011-07-23 12:50:34 -0700326void DexFile::InitMembers() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700327 const byte* b = base_;
328 header_ = reinterpret_cast<const Header*>(b);
329 const Header* h = header_;
330 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
331 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
332 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
333 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
334 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
335 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
336}
337
Brian Carlstromf615a612011-07-23 12:50:34 -0700338bool DexFile::IsMagicValid() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700339 return CheckMagic(header_->magic_);
340}
341
Brian Carlstromf615a612011-07-23 12:50:34 -0700342bool DexFile::CheckMagic(const byte* magic) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700343 CHECK(magic != NULL);
344 if (memcmp(magic, kDexMagic, sizeof(kDexMagic)) != 0) {
345 LOG(WARNING) << "Unrecognized magic number:"
346 << " " << magic[0]
347 << " " << magic[1]
348 << " " << magic[2]
349 << " " << magic[3];
350 return false;
351 }
352 const byte* version = &magic[sizeof(kDexMagic)];
353 if (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) != 0) {
354 LOG(WARNING) << "Unrecognized version number:"
355 << " " << version[0]
356 << " " << version[1]
357 << " " << version[2]
358 << " " << version[3];
359 return false;
360 }
361 return true;
362}
363
Brian Carlstromf615a612011-07-23 12:50:34 -0700364void DexFile::InitIndex() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700365 CHECK_EQ(index_.size(), 0U);
366 for (size_t i = 0; i < NumClassDefs(); ++i) {
367 const ClassDef& class_def = GetClassDef(i);
368 const char* descriptor = GetClassDescriptor(class_def);
369 index_[descriptor] = &class_def;
370 }
371}
372
Brian Carlstromf615a612011-07-23 12:50:34 -0700373const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700374 CHECK(descriptor != NULL);
375 Index::const_iterator it = index_.find(descriptor);
376 if (it == index_.end()) {
377 return NULL;
378 } else {
379 return it->second;
380 }
381}
382
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700383// Materializes the method descriptor for a method prototype. Method
384// descriptors are not stored directly in the dex file. Instead, one
385// must assemble the descriptor from references in the prototype.
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700386std::string DexFile::CreateMethodDescriptor(uint32_t proto_idx,
387 int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700388 const ProtoId& proto_id = GetProtoId(proto_idx);
389 std::string descriptor;
390 descriptor.push_back('(');
391 const TypeList* type_list = GetProtoParameters(proto_id);
392 size_t parameter_length = 0;
393 if (type_list != NULL) {
394 // A non-zero number of arguments. Append the type names.
395 for (size_t i = 0; i < type_list->Size(); ++i) {
396 const TypeItem& type_item = type_list->GetTypeItem(i);
397 uint32_t type_idx = type_item.type_idx_;
398 int32_t type_length;
399 const char* name = dexStringByTypeIdx(type_idx, &type_length);
400 parameter_length += type_length;
401 descriptor.append(name);
402 }
403 }
404 descriptor.push_back(')');
405 uint32_t return_type_idx = proto_id.return_type_idx_;
406 int32_t return_type_length;
407 const char* name = dexStringByTypeIdx(return_type_idx, &return_type_length);
408 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700409 if (unicode_length != NULL) {
410 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
411 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700412 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700413}
414
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700415// Read a signed integer. "zwidth" is the zero-based byte count.
416static int32_t ReadSignedInt(const byte* ptr, int zwidth)
417{
418 int32_t val = 0;
419 for (int i = zwidth; i >= 0; --i) {
420 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
421 }
422 val >>= (3 - zwidth) * 8;
423 return val;
424}
425
426// Read an unsigned integer. "zwidth" is the zero-based byte count,
427// "fill_on_right" indicates which side we want to zero-fill from.
428static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth,
429 bool fill_on_right) {
430 uint32_t val = 0;
431 if (!fill_on_right) {
432 for (int i = zwidth; i >= 0; --i) {
433 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
434 }
435 val >>= (3 - zwidth) * 8;
436 } else {
437 for (int i = zwidth; i >= 0; --i) {
438 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
439 }
440 }
441 return val;
442}
443
444// Read a signed long. "zwidth" is the zero-based byte count.
445static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
446 int64_t val = 0;
447 for (int i = zwidth; i >= 0; --i) {
448 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
449 }
450 val >>= (7 - zwidth) * 8;
451 return val;
452}
453
454// Read an unsigned long. "zwidth" is the zero-based byte count,
455// "fill_on_right" indicates which side we want to zero-fill from.
456static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth,
457 bool fill_on_right) {
458 uint64_t val = 0;
459 if (!fill_on_right) {
460 for (int i = zwidth; i >= 0; --i) {
461 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
462 }
463 val >>= (7 - zwidth) * 8;
464 } else {
465 for (int i = zwidth; i >= 0; --i) {
466 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
467 }
468 }
469 return val;
470}
471
Brian Carlstromf615a612011-07-23 12:50:34 -0700472DexFile::ValueType DexFile::ReadEncodedValue(const byte** stream,
473 JValue* value) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700474 const byte* ptr = *stream;
475 byte value_type = *ptr++;
476 byte value_arg = value_type >> kEncodedValueArgShift;
477 size_t width = value_arg + 1; // assume and correct later
478 int type = value_type & kEncodedValueTypeMask;
479 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700480 case DexFile::kByte: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700481 int32_t b = ReadSignedInt(ptr, value_arg);
482 CHECK(IsInt(8, b));
483 value->i = b;
484 break;
485 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700486 case DexFile::kShort: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700487 int32_t s = ReadSignedInt(ptr, value_arg);
488 CHECK(IsInt(16, s));
489 value->i = s;
490 break;
491 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700492 case DexFile::kChar: {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700493 uint32_t c = ReadUnsignedInt(ptr, value_arg, false);
494 CHECK(IsUint(16, c));
495 value->i = c;
496 break;
497 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700498 case DexFile::kInt:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700499 value->i = ReadSignedInt(ptr, value_arg);
500 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700501 case DexFile::kLong:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700502 value->j = ReadSignedLong(ptr, value_arg);
503 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700504 case DexFile::kFloat:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700505 value->i = ReadUnsignedInt(ptr, value_arg, true);
506 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700507 case DexFile::kDouble:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700508 value->j = ReadUnsignedLong(ptr, value_arg, true);
509 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700510 case DexFile::kBoolean:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700511 value->i = (value_arg != 0);
512 width = 0;
513 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700514 case DexFile::kString:
515 case DexFile::kType:
516 case DexFile::kMethod:
517 case DexFile::kEnum:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700518 value->i = ReadUnsignedInt(ptr, value_arg, false);
519 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700520 case DexFile::kField:
521 case DexFile::kArray:
522 case DexFile::kAnnotation:
Elliott Hughes53b61312011-08-12 18:28:20 -0700523 UNIMPLEMENTED(FATAL) << ": type " << type;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700524 break;
Brian Carlstromf615a612011-07-23 12:50:34 -0700525 case DexFile::kNull:
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700526 value->i = 0;
527 width = 0;
528 break;
529 default:
530 LOG(FATAL) << "Unreached";
531 }
532 ptr += width;
533 *stream = ptr;
534 return static_cast<ValueType>(type);
Carl Shapiro1fb86202011-06-27 17:43:13 -0700535}
536
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700537String* DexFile::dexArtStringById(int32_t idx) const {
538 if (idx == -1) {
539 return NULL;
540 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700541 return String::AllocFromModifiedUtf8(dexStringById(idx));
542}
543
544int32_t DexFile::GetLineNumFromPC(const art::Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700545 // For native method, lineno should be -2 to indicate it is native. Note that
546 // "line number == -2" is how libcore tells from StackTraceElement.
547 if (method->code_off_ == 0) {
548 return -2;
549 }
550
Shih-wei Liao195487c2011-08-20 13:29:04 -0700551 const CodeItem* code_item = GetCodeItem(method->code_off_);
552 DCHECK(code_item != NULL);
553
554 // A method with no line number info should return -1
555 LineNumFromPcContext context(rel_pc, -1);
556 dexDecodeDebugInfo(code_item, method, LineNumForPcCb, NULL, &context);
557 return context.line_num_;
558}
559
560void DexFile::dexDecodeDebugInfo0(const CodeItem* code_item, const art::Method* method,
561 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
562 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
563 uint32_t line = DecodeUnsignedLeb128(&stream);
564 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
565 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
566 uint32_t address = 0;
567
568 if (!method->IsStatic()) {
569 local_in_reg[arg_reg].name_ = String::AllocFromModifiedUtf8("this");
570 local_in_reg[arg_reg].descriptor_ = method->GetDeclaringClass()->GetDescriptor();
571 local_in_reg[arg_reg].signature_ = NULL;
572 local_in_reg[arg_reg].start_address_ = 0;
573 local_in_reg[arg_reg].is_live_ = true;
574 arg_reg++;
575 }
576
577 ParameterIterator *it = GetParameterIterator(GetProtoId(method->proto_idx_));
578 for (uint32_t i = 0; i < parameters_size && it->HasNext(); ++i, it->Next()) {
579 if (arg_reg >= code_item->registers_size_) {
580 LOG(FATAL) << "invalid stream";
581 return;
582 }
583
584 String* descriptor = String::AllocFromModifiedUtf8(it->GetDescriptor());
585 String* name = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
586
587 local_in_reg[arg_reg].name_ = name;
588 local_in_reg[arg_reg].descriptor_ = descriptor;
589 local_in_reg[arg_reg].signature_ = NULL;
590 local_in_reg[arg_reg].start_address_ = address;
591 local_in_reg[arg_reg].is_live_ = true;
592 switch (descriptor->CharAt(0)) {
593 case 'D':
594 case 'J':
595 arg_reg += 2;
596 break;
597 default:
598 arg_reg += 1;
599 break;
600 }
601 }
602
603 if (it->HasNext()) {
604 LOG(FATAL) << "invalid stream";
605 return;
606 }
607
608 for (;;) {
609 uint8_t opcode = *stream++;
610 uint8_t adjopcode = opcode - DBG_FIRST_SPECIAL;
611 uint16_t reg;
612
613
614 switch (opcode) {
615 case DBG_END_SEQUENCE:
616 return;
617
618 case DBG_ADVANCE_PC:
619 address += DecodeUnsignedLeb128(&stream);
620 break;
621
622 case DBG_ADVANCE_LINE:
623 line += DecodeUnsignedLeb128(&stream);
624 break;
625
626 case DBG_START_LOCAL:
627 case DBG_START_LOCAL_EXTENDED:
628 reg = DecodeUnsignedLeb128(&stream);
629 if (reg > code_item->registers_size_) {
630 LOG(FATAL) << "invalid stream";
631 return;
632 }
633
634 // Emit what was previously there, if anything
635 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
636
637 local_in_reg[reg].name_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
638 local_in_reg[reg].descriptor_ = dexArtStringByTypeIdx(DecodeUnsignedLeb128P1(&stream));
639 if (opcode == DBG_START_LOCAL_EXTENDED) {
640 local_in_reg[reg].signature_ = dexArtStringById(DecodeUnsignedLeb128P1(&stream));
641 } else {
642 local_in_reg[reg].signature_ = NULL;
643 }
644 local_in_reg[reg].start_address_ = address;
645 local_in_reg[reg].is_live_ = true;
646 break;
647
648 case DBG_END_LOCAL:
649 reg = DecodeUnsignedLeb128(&stream);
650 if (reg > code_item->registers_size_) {
651 LOG(FATAL) << "invalid stream";
652 return;
653 }
654
655 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
656 local_in_reg[reg].is_live_ = false;
657 break;
658
659 case DBG_RESTART_LOCAL:
660 reg = DecodeUnsignedLeb128(&stream);
661 if (reg > code_item->registers_size_) {
662 LOG(FATAL) << "invalid stream";
663 return;
664 }
665
666 if (local_in_reg[reg].name_ == NULL
667 || local_in_reg[reg].descriptor_ == NULL) {
668 LOG(FATAL) << "invalid stream";
669 return;
670 }
671
672 // If the register is live, the "restart" is superfluous,
673 // and we don't want to mess with the existing start address.
674 if (!local_in_reg[reg].is_live_) {
675 local_in_reg[reg].start_address_ = address;
676 local_in_reg[reg].is_live_ = true;
677 }
678 break;
679
680 case DBG_SET_PROLOGUE_END:
681 case DBG_SET_EPILOGUE_BEGIN:
682 case DBG_SET_FILE:
683 break;
684
685 default:
686 address += adjopcode / DBG_LINE_RANGE;
687 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
688
689 if (posCb != NULL) {
690 if (posCb(cnxt, address, line)) {
691 // early exit
692 return;
693 }
694 }
695 break;
696 }
697 }
698}
699
Carl Shapiro1fb86202011-06-27 17:43:13 -0700700} // namespace art