blob: f18b21556ef2fd10d7b6258a88e1b0b4b3ddfa36 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/mman.h>
26#include <sys/stat.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070027
Ian Rogers0571d352011-11-03 19:51:38 -070028#include "class_linker.h"
jeffhao10037c82012-01-23 15:06:23 -080029#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070031#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "logging.h"
33#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070034#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070035#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070036#include "stringprintf.h"
37#include "thread.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070038#include "UniquePtr.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "utf.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070040#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070041#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070042#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070043
44namespace art {
45
Brian Carlstromf615a612011-07-23 12:50:34 -070046const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
47const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070048
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070049DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070050 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070051 for (size_t i = 0; i != class_path.size(); ++i) {
52 const DexFile* dex_file = class_path[i];
53 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
54 if (dex_class_def != NULL) {
55 return ClassPathEntry(dex_file, dex_class_def);
56 }
57 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070058 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070059 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
60 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070061}
62
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063bool DexFile::GetChecksum(const std::string& filename, uint32_t& checksum) {
64 if (IsValidZipFilename(filename)) {
65 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
66 if (zip_archive.get() == NULL) {
67 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070068 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080069 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
70 if (zip_entry.get() == NULL) {
71 return false;
72 }
73 checksum = zip_entry->GetCrc32();
74 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -070075 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080076 if (IsValidDexFilename(filename)) {
Brian Carlstrom1db858a2012-03-11 22:44:45 -070077 UniquePtr<const DexFile> dex_file(DexFile::OpenFile(filename, filename, false));
Brian Carlstrom5b332c82012-02-01 15:02:31 -080078 if (dex_file.get() == NULL) {
79 return false;
80 }
81 checksum = dex_file->GetHeader().checksum_;
82 return true;
83 }
84 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070085}
86
Brian Carlstrom16192862011-09-12 17:50:06 -070087const DexFile* DexFile::Open(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -080088 const std::string& location) {
jeffhao262bf462011-10-20 18:36:32 -070089 if (IsValidZipFilename(filename)) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080090 return DexFile::OpenZip(filename, location);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070091 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -070092 if (!IsValidDexFilename(filename)) {
93 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
94 }
Brian Carlstroma004aa92012-02-08 18:05:09 -080095 return DexFile::OpenFile(filename, location, true);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070096}
97
jeffhaob4df5142011-09-19 20:25:32 -070098void DexFile::ChangePermissions(int prot) const {
Ian Rogers30fab402012-01-23 15:43:46 -080099 if (mprotect(mem_map_->Begin(), mem_map_->Size(), prot) != 0) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800100 PLOG(FATAL) << "Failed to change dex file permissions to " << prot << " for " << GetLocation();
jeffhaob4df5142011-09-19 20:25:32 -0700101 }
102}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700103
Brian Carlstrom16192862011-09-12 17:50:06 -0700104const DexFile* DexFile::OpenFile(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800105 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800106 bool verify) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800107 CHECK(!location.empty()) << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700108 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700109 if (fd == -1) {
110 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
111 return NULL;
112 }
113 struct stat sbuf;
114 memset(&sbuf, 0, sizeof(sbuf));
115 if (fstat(fd, &sbuf) == -1) {
116 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
117 close(fd);
118 return NULL;
119 }
Ian Rogers7cfb93e2012-01-17 19:46:36 -0800120 if (S_ISDIR(sbuf.st_mode)) {
121 LOG(ERROR) << "attempt to mmap directory \"" << filename << "\"";
122 return NULL;
123 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700124 size_t length = sbuf.st_size;
Brian Carlstrom89521892011-12-07 22:05:07 -0800125 UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0));
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700126 if (map.get() == NULL) {
127 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700128 close(fd);
129 return NULL;
130 }
131 close(fd);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800132
133 if (map->Size() < sizeof(DexFile::Header)) {
134 LOG(ERROR) << "Failed to open dex file '" << filename << "' that is too short to have a header";
135 return NULL;
136 }
137
138 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
139
140 const DexFile* dex_file = OpenMemory(location, dex_header->checksum_, map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800141 if (dex_file == NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800142 LOG(ERROR) << "Failed to open dex file '" << filename << "' from memory";
jeffhao54c1ceb2012-02-01 11:45:32 -0800143 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800144 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800145
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700146 if (verify && !DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800147 LOG(ERROR) << "Failed to verify dex file '" << filename << "'";
jeffhao54c1ceb2012-02-01 11:45:32 -0800148 return NULL;
149 }
150
jeffhaof6174e82012-01-31 16:14:17 -0800151 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700152}
153
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700154const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700155
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700156// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700157const DexFile* DexFile::OpenZip(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800158 const std::string& location) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700159 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
160 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700161 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700162 return NULL;
163 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800164 return DexFile::Open(*zip_archive.get(), location);
165}
166
167const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800168 CHECK(!location.empty());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800169 UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex));
Elliott Hughes90a33692011-08-30 13:27:07 -0700170 if (zip_entry.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800171 LOG(ERROR) << "Failed to find classes.dex within " << location;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700172 return NULL;
173 }
174
Brian Carlstrom89521892011-12-07 22:05:07 -0800175 uint32_t length = zip_entry->GetUncompressedLength();
Elliott Hughes850162c2012-01-12 18:46:43 -0800176 std::string name("classes.dex extracted in memory from ");
177 name += location;
178 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(), NULL, length, PROT_READ | PROT_WRITE));
Brian Carlstrom89521892011-12-07 22:05:07 -0800179 if (map.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800180 LOG(ERROR) << "mmap classes.dex for \"" << location << "\" failed";
Brian Carlstrom89521892011-12-07 22:05:07 -0800181 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700182 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800183
184 // Extract classes.dex
185 bool success = zip_entry->ExtractToMemory(*map.get());
186 if (!success) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800187 LOG(ERROR) << "Failed to extract classes.dex from '" << location << "' to memory";
Brian Carlstrom89521892011-12-07 22:05:07 -0800188 return NULL;
189 }
190
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800191 const DexFile* dex_file = OpenMemory(location, zip_entry->GetCrc32(), map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800192 if (dex_file == NULL) {
193 LOG(ERROR) << "Failed to open dex file '" << location << "' from memory";
194 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800195 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800196
197 if (!DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
198 LOG(ERROR) << "Failed to verify dex file '" << location << "'";
199 return NULL;
200 }
201
jeffhaof6174e82012-01-31 16:14:17 -0800202 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700203}
204
Brian Carlstrom89521892011-12-07 22:05:07 -0800205const DexFile* DexFile::OpenMemory(const byte* base,
jeffhaof6174e82012-01-31 16:14:17 -0800206 size_t size,
Brian Carlstrom89521892011-12-07 22:05:07 -0800207 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800208 uint32_t location_checksum,
Brian Carlstrom89521892011-12-07 22:05:07 -0800209 MemMap* mem_map) {
210 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800211 UniquePtr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700212 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700213 return NULL;
214 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700215 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700216 }
217}
218
Jesse Wilson6bf19152011-09-29 13:12:33 -0400219DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700220 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
221 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
222 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
223 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400224}
225
226jobject DexFile::GetDexObject(JNIEnv* env) const {
227 MutexLock mu(dex_object_lock_);
228 if (dex_object_ != NULL) {
229 return dex_object_;
230 }
231
Ian Rogers30fab402012-01-23 15:43:46 -0800232 void* address = const_cast<void*>(reinterpret_cast<const void*>(begin_));
jeffhaof6174e82012-01-31 16:14:17 -0800233 jobject byte_buffer = env->NewDirectByteBuffer(address, size_);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400234 if (byte_buffer == NULL) {
235 return NULL;
236 }
237
Jesse Wilson6bf19152011-09-29 13:12:33 -0400238 jvalue args[1];
239 args[0].l = byte_buffer;
Elliott Hugheseac76672012-05-24 21:56:51 -0700240 jobject local = env->CallStaticObjectMethodA(WellKnownClasses::com_android_dex_Dex,
241 WellKnownClasses::com_android_dex_Dex_create,
242 args);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400243 if (local == NULL) {
244 return NULL;
245 }
246
247 dex_object_ = env->NewGlobalRef(local);
248 return dex_object_;
249}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700250
Brian Carlstromf615a612011-07-23 12:50:34 -0700251bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700252 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800253 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700254 return false;
255 }
256 InitIndex();
257 return true;
258}
259
Brian Carlstromf615a612011-07-23 12:50:34 -0700260void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800261 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700262 header_ = reinterpret_cast<const Header*>(b);
263 const Header* h = header_;
264 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
265 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
266 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
267 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
268 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
269 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
jeffhaof6174e82012-01-31 16:14:17 -0800270 DCHECK_EQ(size_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700271}
272
jeffhao10037c82012-01-23 15:06:23 -0800273bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800274 CHECK(header_->magic_ != NULL) << GetLocation();
275 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800276 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800277 << " " << header_->magic_[0]
278 << " " << header_->magic_[1]
279 << " " << header_->magic_[2]
280 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700281 return false;
282 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800283 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800284 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800285 << " " << header_->magic_[4]
286 << " " << header_->magic_[5]
287 << " " << header_->magic_[6]
288 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700289 return false;
290 }
291 return true;
292}
293
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800294bool DexFile::IsMagicValid(const byte* magic) {
295 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
296}
297
298bool DexFile::IsVersionValid(const byte* magic) {
299 const byte* version = &magic[sizeof(kDexMagic)];
300 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
301}
302
Ian Rogersd81871c2011-10-03 13:57:23 -0700303uint32_t DexFile::GetVersion() const {
304 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
305 return atoi(version);
306}
307
Ian Rogers0571d352011-11-03 19:51:38 -0700308int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800309 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700310 return DecodeUnsignedLeb128(&ptr);
311}
312
313// Returns a pointer to the UTF-8 string data referred to by the given string_id.
Elliott Hughes45651fd2012-02-21 15:48:20 -0800314const char* DexFile::GetStringDataAndLength(const StringId& string_id, uint32_t* length) const {
Ian Rogers7b0c5b42012-02-16 15:29:07 -0800315 DCHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800316 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700317 *length = DecodeUnsignedLeb128(&ptr);
318 return reinterpret_cast<const char*>(ptr);
319}
320
Brian Carlstromf615a612011-07-23 12:50:34 -0700321void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800322 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700323 for (size_t i = 0; i < NumClassDefs(); ++i) {
324 const ClassDef& class_def = GetClassDef(i);
325 const char* descriptor = GetClassDescriptor(class_def);
Elliott Hughesa0e18062012-04-13 15:59:59 -0700326 index_.Put(descriptor, i);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700327 }
328}
329
Brian Carlstrome24fa612011-09-29 00:53:55 -0700330bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700331 Index::const_iterator it = index_.find(descriptor);
332 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700333 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700334 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700335 idx = it->second;
336 return true;
337}
338
339const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
340 uint32_t idx;
341 if (FindClassDefIndex(descriptor, idx)) {
342 return &GetClassDef(idx);
343 }
344 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700345}
346
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800347const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
348 const DexFile::StringId& name,
349 const DexFile::TypeId& type) const {
350 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
351 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
352 const uint32_t name_idx = GetIndexForStringId(name);
353 const uint16_t type_idx = GetIndexForTypeId(type);
354 uint32_t lo = 0;
355 uint32_t hi = NumFieldIds() - 1;
356 while (hi >= lo) {
357 uint32_t mid = (hi + lo) / 2;
358 const DexFile::FieldId& field = GetFieldId(mid);
359 if (class_idx > field.class_idx_) {
360 lo = mid + 1;
361 } else if (class_idx < field.class_idx_) {
362 hi = mid - 1;
363 } else {
364 if (name_idx > field.name_idx_) {
365 lo = mid + 1;
366 } else if (name_idx < field.name_idx_) {
367 hi = mid - 1;
368 } else {
369 if (type_idx > field.type_idx_) {
370 lo = mid + 1;
371 } else if (type_idx < field.type_idx_) {
372 hi = mid - 1;
373 } else {
374 return &field;
375 }
376 }
377 }
378 }
379 return NULL;
380}
381
382const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700383 const DexFile::StringId& name,
384 const DexFile::ProtoId& signature) const {
385 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800386 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700387 const uint32_t name_idx = GetIndexForStringId(name);
388 const uint16_t proto_idx = GetIndexForProtoId(signature);
389 uint32_t lo = 0;
390 uint32_t hi = NumMethodIds() - 1;
391 while (hi >= lo) {
392 uint32_t mid = (hi + lo) / 2;
393 const DexFile::MethodId& method = GetMethodId(mid);
394 if (class_idx > method.class_idx_) {
395 lo = mid + 1;
396 } else if (class_idx < method.class_idx_) {
397 hi = mid - 1;
398 } else {
399 if (name_idx > method.name_idx_) {
400 lo = mid + 1;
401 } else if (name_idx < method.name_idx_) {
402 hi = mid - 1;
403 } else {
404 if (proto_idx > method.proto_idx_) {
405 lo = mid + 1;
406 } else if (proto_idx < method.proto_idx_) {
407 hi = mid - 1;
408 } else {
409 return &method;
410 }
411 }
412 }
413 }
414 return NULL;
415}
416
417const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
418 uint32_t lo = 0;
419 uint32_t hi = NumStringIds() - 1;
420 while (hi >= lo) {
421 uint32_t mid = (hi + lo) / 2;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800422 uint32_t length;
Ian Rogers0571d352011-11-03 19:51:38 -0700423 const DexFile::StringId& str_id = GetStringId(mid);
424 const char* str = GetStringDataAndLength(str_id, &length);
425 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
426 if (compare > 0) {
427 lo = mid + 1;
428 } else if (compare < 0) {
429 hi = mid - 1;
430 } else {
431 return &str_id;
432 }
433 }
434 return NULL;
435}
436
437const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
438 uint32_t lo = 0;
439 uint32_t hi = NumTypeIds() - 1;
440 while (hi >= lo) {
441 uint32_t mid = (hi + lo) / 2;
442 const TypeId& type_id = GetTypeId(mid);
443 if (string_idx > type_id.descriptor_idx_) {
444 lo = mid + 1;
445 } else if (string_idx < type_id.descriptor_idx_) {
446 hi = mid - 1;
447 } else {
448 return &type_id;
449 }
450 }
451 return NULL;
452}
453
454const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800455 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700456 uint32_t lo = 0;
457 uint32_t hi = NumProtoIds() - 1;
458 while (hi >= lo) {
459 uint32_t mid = (hi + lo) / 2;
460 const DexFile::ProtoId& proto = GetProtoId(mid);
461 int compare = return_type_idx - proto.return_type_idx_;
462 if (compare == 0) {
463 DexFileParameterIterator it(*this, proto);
464 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800465 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
466 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700467 it.Next();
468 i++;
469 }
470 if (compare == 0) {
471 if (it.HasNext()) {
472 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800473 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700474 compare = 1;
475 }
476 }
477 }
478 if (compare > 0) {
479 lo = mid + 1;
480 } else if (compare < 0) {
481 hi = mid - 1;
482 } else {
483 return &proto;
484 }
485 }
486 return NULL;
487}
488
489// Given a signature place the type ids into the given vector
490bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
491 const std::string& signature) const {
492 if (signature[0] != '(') {
493 return false;
494 }
495 size_t offset = 1;
496 size_t end = signature.size();
497 bool process_return = false;
498 while (offset < end) {
499 char c = signature[offset];
500 offset++;
501 if (c == ')') {
502 process_return = true;
503 continue;
504 }
505 std::string descriptor;
506 descriptor += c;
507 while (c == '[') { // process array prefix
508 if (offset >= end) { // expect some descriptor following [
509 return false;
510 }
511 c = signature[offset];
512 offset++;
513 descriptor += c;
514 }
515 if (c == 'L') { // process type descriptors
516 do {
517 if (offset >= end) { // unexpected early termination of descriptor
518 return false;
519 }
520 c = signature[offset];
521 offset++;
522 descriptor += c;
523 } while (c != ';');
524 }
525 const DexFile::StringId* string_id = FindStringId(descriptor);
526 if (string_id == NULL) {
527 return false;
528 }
529 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
530 if (type_id == NULL) {
531 return false;
532 }
533 uint16_t type_idx = GetIndexForTypeId(*type_id);
534 if (!process_return) {
535 param_type_idxs->push_back(type_idx);
536 } else {
537 *return_type_idx = type_idx;
538 return offset == end; // return true if the signature had reached a sensible end
539 }
540 }
541 return false; // failed to correctly parse return type
542}
543
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700544// Materializes the method descriptor for a method prototype. Method
545// descriptors are not stored directly in the dex file. Instead, one
546// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700547std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700548 const ProtoId& proto_id = GetProtoId(proto_idx);
549 std::string descriptor;
550 descriptor.push_back('(');
551 const TypeList* type_list = GetProtoParameters(proto_id);
552 size_t parameter_length = 0;
553 if (type_list != NULL) {
554 // A non-zero number of arguments. Append the type names.
555 for (size_t i = 0; i < type_list->Size(); ++i) {
556 const TypeItem& type_item = type_list->GetTypeItem(i);
557 uint32_t type_idx = type_item.type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800558 uint32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700559 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700560 parameter_length += type_length;
561 descriptor.append(name);
562 }
563 }
564 descriptor.push_back(')');
565 uint32_t return_type_idx = proto_id.return_type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800566 uint32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700567 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700568 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700569 if (unicode_length != NULL) {
570 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
571 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700572 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700573}
574
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800575int32_t DexFile::GetLineNumFromPC(const Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700576 // For native method, lineno should be -2 to indicate it is native. Note that
577 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700579 return -2;
580 }
581
TDYa127c8dc1012012-04-19 07:03:33 -0700582 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800583 DCHECK(code_item != NULL) << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700584
585 // A method with no line number info should return -1
586 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700587 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800588 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700589 return context.line_num_;
590}
591
Ian Rogers0571d352011-11-03 19:51:38 -0700592int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800593 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700594 // Note: Signed type is important for max and min.
595 int32_t min = 0;
596 int32_t max = tries_size - 1;
597
598 while (max >= min) {
599 int32_t mid = (min + max) / 2;
600 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
601 uint32_t start = pTry->start_addr_;
602 if (address < start) {
603 max = mid - 1;
604 } else {
605 uint32_t end = start + pTry->insn_count_;
606 if (address >= end) {
607 min = mid + 1;
608 } else { // We have a winner!
609 return (int32_t) pTry->handler_off_;
610 }
611 }
612 }
613 // No match.
614 return -1;
615}
616
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800617void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800618 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
619 void* context, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700620 uint32_t line = DecodeUnsignedLeb128(&stream);
621 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
622 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
623 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700624 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700625
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800626 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700627 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800628 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700629 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800630 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800631 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700632 local_in_reg[arg_reg].start_address_ = 0;
633 local_in_reg[arg_reg].is_live_ = true;
634 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700635 arg_reg++;
636 }
637
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800638 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700639 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700640 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700641 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800642 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700643 return;
644 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800645 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700646 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800647 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700648 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700649 local_in_reg[arg_reg].name_ = name;
650 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800651 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700652 local_in_reg[arg_reg].start_address_ = address;
653 local_in_reg[arg_reg].is_live_ = true;
654 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700655 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700656 case 'D':
657 case 'J':
658 arg_reg += 2;
659 break;
660 default:
661 arg_reg += 1;
662 break;
663 }
664 }
665
Ian Rogers0571d352011-11-03 19:51:38 -0700666 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800667 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700668 return;
669 }
670
671 for (;;) {
672 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700673 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700674 uint16_t name_idx;
675 uint16_t descriptor_idx;
676 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700677
Shih-wei Liao195487c2011-08-20 13:29:04 -0700678 switch (opcode) {
679 case DBG_END_SEQUENCE:
680 return;
681
682 case DBG_ADVANCE_PC:
683 address += DecodeUnsignedLeb128(&stream);
684 break;
685
686 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700687 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700688 break;
689
690 case DBG_START_LOCAL:
691 case DBG_START_LOCAL_EXTENDED:
692 reg = DecodeUnsignedLeb128(&stream);
693 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700694 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800695 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700696 return;
697 }
698
jeffhaof8728872011-10-28 19:11:13 -0700699 name_idx = DecodeUnsignedLeb128P1(&stream);
700 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
701 if (opcode == DBG_START_LOCAL_EXTENDED) {
702 signature_idx = DecodeUnsignedLeb128P1(&stream);
703 }
704
Shih-wei Liao195487c2011-08-20 13:29:04 -0700705 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700706 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800707 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700708
Ian Rogers0571d352011-11-03 19:51:38 -0700709 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
710 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700711 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700712 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700713 }
714 local_in_reg[reg].start_address_ = address;
715 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700716 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700717 break;
718
719 case DBG_END_LOCAL:
720 reg = DecodeUnsignedLeb128(&stream);
721 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700722 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800723 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700724 return;
725 }
726
Elliott Hughes30646832011-10-13 16:59:46 -0700727 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800728 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700729 local_in_reg[reg].is_live_ = false;
730 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700731 break;
732
733 case DBG_RESTART_LOCAL:
734 reg = DecodeUnsignedLeb128(&stream);
735 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700736 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800737 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700738 return;
739 }
740
Elliott Hughes30646832011-10-13 16:59:46 -0700741 if (need_locals) {
742 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800743 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700744 return;
745 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700746
Elliott Hughes30646832011-10-13 16:59:46 -0700747 // If the register is live, the "restart" is superfluous,
748 // and we don't want to mess with the existing start address.
749 if (!local_in_reg[reg].is_live_) {
750 local_in_reg[reg].start_address_ = address;
751 local_in_reg[reg].is_live_ = true;
752 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700753 }
754 break;
755
756 case DBG_SET_PROLOGUE_END:
757 case DBG_SET_EPILOGUE_BEGIN:
758 case DBG_SET_FILE:
759 break;
760
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700761 default: {
762 int adjopcode = opcode - DBG_FIRST_SPECIAL;
763
Shih-wei Liao195487c2011-08-20 13:29:04 -0700764 address += adjopcode / DBG_LINE_RANGE;
765 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
766
Elliott Hughes2435a572012-02-17 16:07:41 -0800767 if (position_cb != NULL) {
768 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700769 // early exit
770 return;
771 }
772 }
773 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700774 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700775 }
776 }
777}
778
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800779void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800780 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
781 void* context) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700782 const byte* stream = GetDebugInfoStream(code_item);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700783 UniquePtr<LocalInfo[]> local_in_reg(local_cb != NULL ? new LocalInfo[code_item->registers_size_] : NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700784 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700785 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700786 }
787 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700788 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700789 }
790}
791
Elliott Hughes2435a572012-02-17 16:07:41 -0800792bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
793 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700794
795 // We know that this callback will be called in
796 // ascending address order, so keep going until we find
797 // a match or we've just gone past it.
798 if (address > context->address_) {
799 // The line number from the previous positions callback
800 // wil be the final result.
801 return true;
802 } else {
803 context->line_num_ = line_num;
804 return address == context->address_;
805 }
806}
807
808// Decodes the header section from the class data bytes.
809void ClassDataItemIterator::ReadClassDataHeader() {
810 CHECK(ptr_pos_ != NULL);
811 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
812 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
813 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
814 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
815}
816
817void ClassDataItemIterator::ReadClassDataField() {
818 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
819 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700820 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700821 LOG(WARNING) << "Duplicate field " << PrettyField(GetMemberIndex(), dex_file_)
822 << " in " << dex_file_.GetLocation();
823 }
Ian Rogers0571d352011-11-03 19:51:38 -0700824}
825
826void ClassDataItemIterator::ReadClassDataMethod() {
827 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
828 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
829 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700830 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700831 LOG(WARNING) << "Duplicate method " << PrettyMethod(GetMemberIndex(), dex_file_)
832 << " in " << dex_file_.GetLocation();
833 }
Ian Rogers0571d352011-11-03 19:51:38 -0700834}
835
836// Read a signed integer. "zwidth" is the zero-based byte count.
837static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
838 int32_t val = 0;
839 for (int i = zwidth; i >= 0; --i) {
840 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
841 }
842 val >>= (3 - zwidth) * 8;
843 return val;
844}
845
846// Read an unsigned integer. "zwidth" is the zero-based byte count,
847// "fill_on_right" indicates which side we want to zero-fill from.
848static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
849 uint32_t val = 0;
850 if (!fill_on_right) {
851 for (int i = zwidth; i >= 0; --i) {
852 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
853 }
854 val >>= (3 - zwidth) * 8;
855 } else {
856 for (int i = zwidth; i >= 0; --i) {
857 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
858 }
859 }
860 return val;
861}
862
863// Read a signed long. "zwidth" is the zero-based byte count.
864static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
865 int64_t val = 0;
866 for (int i = zwidth; i >= 0; --i) {
867 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
868 }
869 val >>= (7 - zwidth) * 8;
870 return val;
871}
872
873// Read an unsigned long. "zwidth" is the zero-based byte count,
874// "fill_on_right" indicates which side we want to zero-fill from.
875static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
876 uint64_t val = 0;
877 if (!fill_on_right) {
878 for (int i = zwidth; i >= 0; --i) {
879 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
880 }
881 val >>= (7 - zwidth) * 8;
882 } else {
883 for (int i = zwidth; i >= 0; --i) {
884 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
885 }
886 }
887 return val;
888}
889
890EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
891 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
892 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
893 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
894 if (ptr_ == NULL) {
895 array_size_ = 0;
896 } else {
897 array_size_ = DecodeUnsignedLeb128(&ptr_);
898 }
899 if (array_size_ > 0) {
900 Next();
901 }
902}
903
904void EncodedStaticFieldValueIterator::Next() {
905 pos_++;
906 if (pos_ >= array_size_) {
907 return;
908 }
909 byte value_type = *ptr_++;
910 byte value_arg = value_type >> kEncodedValueArgShift;
911 size_t width = value_arg + 1; // assume and correct later
912 type_ = value_type & kEncodedValueTypeMask;
913 switch (type_) {
914 case kBoolean:
915 jval_.i = (value_arg != 0) ? 1 : 0;
916 width = 0;
917 break;
918 case kByte:
919 jval_.i = ReadSignedInt(ptr_, value_arg);
920 CHECK(IsInt(8, jval_.i));
921 break;
922 case kShort:
923 jval_.i = ReadSignedInt(ptr_, value_arg);
924 CHECK(IsInt(16, jval_.i));
925 break;
926 case kChar:
927 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
928 CHECK(IsUint(16, jval_.i));
929 break;
930 case kInt:
931 jval_.i = ReadSignedInt(ptr_, value_arg);
932 break;
933 case kLong:
934 jval_.j = ReadSignedLong(ptr_, value_arg);
935 break;
936 case kFloat:
937 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
938 break;
939 case kDouble:
940 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
941 break;
942 case kString:
943 case kType:
944 case kMethod:
945 case kEnum:
946 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
947 break;
948 case kField:
949 case kArray:
950 case kAnnotation:
951 UNIMPLEMENTED(FATAL) << ": type " << type_;
952 break;
953 case kNull:
954 jval_.l = NULL;
955 width = 0;
956 break;
957 default:
958 LOG(FATAL) << "Unreached";
959 }
960 ptr_ += width;
961}
962
963void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
964 switch (type_) {
965 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
966 case kByte: field->SetByte(NULL, jval_.b); break;
967 case kShort: field->SetShort(NULL, jval_.s); break;
968 case kChar: field->SetChar(NULL, jval_.c); break;
969 case kInt: field->SetInt(NULL, jval_.i); break;
970 case kLong: field->SetLong(NULL, jval_.j); break;
971 case kFloat: field->SetFloat(NULL, jval_.f); break;
972 case kDouble: field->SetDouble(NULL, jval_.d); break;
973 case kNull: field->SetObject(NULL, NULL); break;
974 case kString: {
975 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
976 field->SetObject(NULL, resolved);
977 break;
978 }
979 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
980 }
981}
982
983CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
984 handler_.address_ = -1;
985 int32_t offset = -1;
986
987 // Short-circuit the overwhelmingly common cases.
988 switch (code_item.tries_size_) {
989 case 0:
990 break;
991 case 1: {
992 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
993 uint32_t start = tries->start_addr_;
994 if (address >= start) {
995 uint32_t end = start + tries->insn_count_;
996 if (address < end) {
997 offset = tries->handler_off_;
998 }
999 }
1000 break;
1001 }
1002 default:
1003 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
1004 }
Logan Chien736df022012-04-27 16:25:57 +08001005 Init(code_item, offset);
1006}
1007
1008CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1009 const DexFile::TryItem& try_item) {
1010 handler_.address_ = -1;
1011 Init(code_item, try_item.handler_off_);
1012}
1013
1014void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1015 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001016 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001017 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001018 } else {
1019 // Not found, initialize as empty
1020 current_data_ = NULL;
1021 remaining_count_ = -1;
1022 catch_all_ = false;
1023 DCHECK(!HasNext());
1024 }
1025}
1026
1027void CatchHandlerIterator::Init(const byte* handler_data) {
1028 current_data_ = handler_data;
1029 remaining_count_ = DecodeSignedLeb128(&current_data_);
1030
1031 // If remaining_count_ is non-positive, then it is the negative of
1032 // the number of catch types, and the catches are followed by a
1033 // catch-all handler.
1034 if (remaining_count_ <= 0) {
1035 catch_all_ = true;
1036 remaining_count_ = -remaining_count_;
1037 } else {
1038 catch_all_ = false;
1039 }
1040 Next();
1041}
1042
1043void CatchHandlerIterator::Next() {
1044 if (remaining_count_ > 0) {
1045 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1046 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1047 remaining_count_--;
1048 return;
1049 }
1050
1051 if (catch_all_) {
1052 handler_.type_idx_ = DexFile::kDexNoIndex16;
1053 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1054 catch_all_ = false;
1055 return;
1056 }
1057
1058 // no more handler
1059 remaining_count_ = -1;
1060}
1061
Carl Shapiro1fb86202011-06-27 17:43:13 -07001062} // namespace art