blob: 2b81e72544f07a7e9a2dcf6cbac153b93891f0a9 [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/stat.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070026
Ian Rogers0571d352011-11-03 19:51:38 -070027#include "class_linker.h"
jeffhao10037c82012-01-23 15:06:23 -080028#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070030#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070031#include "logging.h"
32#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070033#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070034#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070035#include "stringprintf.h"
36#include "thread.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070037#include "UniquePtr.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "utf.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070039#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070040#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070041#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070042
43namespace art {
44
Brian Carlstromf615a612011-07-23 12:50:34 -070045const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
46const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070047
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070048DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070049 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070050 for (size_t i = 0; i != class_path.size(); ++i) {
51 const DexFile* dex_file = class_path[i];
52 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
53 if (dex_class_def != NULL) {
54 return ClassPathEntry(dex_file, dex_class_def);
55 }
56 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070057 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070058 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
59 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070060}
61
Brian Carlstrom5b332c82012-02-01 15:02:31 -080062bool DexFile::GetChecksum(const std::string& filename, uint32_t& checksum) {
63 if (IsValidZipFilename(filename)) {
64 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
65 if (zip_archive.get() == NULL) {
66 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070067 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080068 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
69 if (zip_entry.get() == NULL) {
70 return false;
71 }
72 checksum = zip_entry->GetCrc32();
73 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -070074 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080075 if (IsValidDexFilename(filename)) {
Brian Carlstrom1db858a2012-03-11 22:44:45 -070076 UniquePtr<const DexFile> dex_file(DexFile::OpenFile(filename, filename, false));
Brian Carlstrom5b332c82012-02-01 15:02:31 -080077 if (dex_file.get() == NULL) {
78 return false;
79 }
80 checksum = dex_file->GetHeader().checksum_;
81 return true;
82 }
83 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070084}
85
Brian Carlstrom16192862011-09-12 17:50:06 -070086const DexFile* DexFile::Open(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -080087 const std::string& location) {
jeffhao262bf462011-10-20 18:36:32 -070088 if (IsValidZipFilename(filename)) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080089 return DexFile::OpenZip(filename, location);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070090 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -070091 if (!IsValidDexFilename(filename)) {
92 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
93 }
Brian Carlstroma004aa92012-02-08 18:05:09 -080094 return DexFile::OpenFile(filename, location, true);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070095}
96
jeffhaob4df5142011-09-19 20:25:32 -070097void DexFile::ChangePermissions(int prot) const {
Shih-wei Liaoa060ed92012-06-07 09:25:28 -070098 CHECK(mem_map_->Protect(prot)) << GetLocation();
jeffhaob4df5142011-09-19 20:25:32 -070099}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700100
Brian Carlstrom16192862011-09-12 17:50:06 -0700101const DexFile* DexFile::OpenFile(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800102 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800103 bool verify) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800104 CHECK(!location.empty()) << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700105 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700106 if (fd == -1) {
107 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
108 return NULL;
109 }
110 struct stat sbuf;
111 memset(&sbuf, 0, sizeof(sbuf));
112 if (fstat(fd, &sbuf) == -1) {
113 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
114 close(fd);
115 return NULL;
116 }
Ian Rogers7cfb93e2012-01-17 19:46:36 -0800117 if (S_ISDIR(sbuf.st_mode)) {
118 LOG(ERROR) << "attempt to mmap directory \"" << filename << "\"";
119 return NULL;
120 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700121 size_t length = sbuf.st_size;
Brian Carlstrom89521892011-12-07 22:05:07 -0800122 UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0));
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700123 if (map.get() == NULL) {
124 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700125 close(fd);
126 return NULL;
127 }
128 close(fd);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800129
130 if (map->Size() < sizeof(DexFile::Header)) {
131 LOG(ERROR) << "Failed to open dex file '" << filename << "' that is too short to have a header";
132 return NULL;
133 }
134
135 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
136
137 const DexFile* dex_file = OpenMemory(location, dex_header->checksum_, map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800138 if (dex_file == NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800139 LOG(ERROR) << "Failed to open dex file '" << filename << "' from memory";
jeffhao54c1ceb2012-02-01 11:45:32 -0800140 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800141 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800142
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700143 if (verify && !DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800144 LOG(ERROR) << "Failed to verify dex file '" << filename << "'";
jeffhao54c1ceb2012-02-01 11:45:32 -0800145 return NULL;
146 }
147
jeffhaof6174e82012-01-31 16:14:17 -0800148 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700149}
150
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700151const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700152
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700153// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700154const DexFile* DexFile::OpenZip(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800155 const std::string& location) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700156 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
157 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700158 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700159 return NULL;
160 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800161 return DexFile::Open(*zip_archive.get(), location);
162}
163
164const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800165 CHECK(!location.empty());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800166 UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex));
Elliott Hughes90a33692011-08-30 13:27:07 -0700167 if (zip_entry.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800168 LOG(ERROR) << "Failed to find classes.dex within " << location;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700169 return NULL;
170 }
171
Brian Carlstrom89521892011-12-07 22:05:07 -0800172 uint32_t length = zip_entry->GetUncompressedLength();
Elliott Hughes850162c2012-01-12 18:46:43 -0800173 std::string name("classes.dex extracted in memory from ");
174 name += location;
175 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(), NULL, length, PROT_READ | PROT_WRITE));
Brian Carlstrom89521892011-12-07 22:05:07 -0800176 if (map.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800177 LOG(ERROR) << "mmap classes.dex for \"" << location << "\" failed";
Brian Carlstrom89521892011-12-07 22:05:07 -0800178 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700179 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800180
181 // Extract classes.dex
182 bool success = zip_entry->ExtractToMemory(*map.get());
183 if (!success) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800184 LOG(ERROR) << "Failed to extract classes.dex from '" << location << "' to memory";
Brian Carlstrom89521892011-12-07 22:05:07 -0800185 return NULL;
186 }
187
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800188 const DexFile* dex_file = OpenMemory(location, zip_entry->GetCrc32(), map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800189 if (dex_file == NULL) {
190 LOG(ERROR) << "Failed to open dex file '" << location << "' from memory";
191 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800192 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800193
194 if (!DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
195 LOG(ERROR) << "Failed to verify dex file '" << location << "'";
196 return NULL;
197 }
198
jeffhaof6174e82012-01-31 16:14:17 -0800199 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700200}
201
Brian Carlstrom89521892011-12-07 22:05:07 -0800202const DexFile* DexFile::OpenMemory(const byte* base,
jeffhaof6174e82012-01-31 16:14:17 -0800203 size_t size,
Brian Carlstrom89521892011-12-07 22:05:07 -0800204 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800205 uint32_t location_checksum,
Brian Carlstrom89521892011-12-07 22:05:07 -0800206 MemMap* mem_map) {
207 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800208 UniquePtr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700209 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700210 return NULL;
211 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700212 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700213 }
214}
215
Jesse Wilson6bf19152011-09-29 13:12:33 -0400216DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700217 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
218 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
219 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
220 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400221}
222
223jobject DexFile::GetDexObject(JNIEnv* env) const {
224 MutexLock mu(dex_object_lock_);
225 if (dex_object_ != NULL) {
226 return dex_object_;
227 }
228
Ian Rogers30fab402012-01-23 15:43:46 -0800229 void* address = const_cast<void*>(reinterpret_cast<const void*>(begin_));
jeffhaof6174e82012-01-31 16:14:17 -0800230 jobject byte_buffer = env->NewDirectByteBuffer(address, size_);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400231 if (byte_buffer == NULL) {
232 return NULL;
233 }
234
Jesse Wilson6bf19152011-09-29 13:12:33 -0400235 jvalue args[1];
236 args[0].l = byte_buffer;
Elliott Hugheseac76672012-05-24 21:56:51 -0700237 jobject local = env->CallStaticObjectMethodA(WellKnownClasses::com_android_dex_Dex,
238 WellKnownClasses::com_android_dex_Dex_create,
239 args);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400240 if (local == NULL) {
241 return NULL;
242 }
243
244 dex_object_ = env->NewGlobalRef(local);
245 return dex_object_;
246}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700247
Brian Carlstromf615a612011-07-23 12:50:34 -0700248bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700249 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800250 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700251 return false;
252 }
253 InitIndex();
254 return true;
255}
256
Brian Carlstromf615a612011-07-23 12:50:34 -0700257void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800258 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700259 header_ = reinterpret_cast<const Header*>(b);
260 const Header* h = header_;
261 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
262 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
263 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
264 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
265 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
266 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
jeffhaof6174e82012-01-31 16:14:17 -0800267 DCHECK_EQ(size_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700268}
269
jeffhao10037c82012-01-23 15:06:23 -0800270bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800271 CHECK(header_->magic_ != NULL) << GetLocation();
272 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800273 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800274 << " " << header_->magic_[0]
275 << " " << header_->magic_[1]
276 << " " << header_->magic_[2]
277 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700278 return false;
279 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800280 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800281 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800282 << " " << header_->magic_[4]
283 << " " << header_->magic_[5]
284 << " " << header_->magic_[6]
285 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700286 return false;
287 }
288 return true;
289}
290
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800291bool DexFile::IsMagicValid(const byte* magic) {
292 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
293}
294
295bool DexFile::IsVersionValid(const byte* magic) {
296 const byte* version = &magic[sizeof(kDexMagic)];
297 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
298}
299
Ian Rogersd81871c2011-10-03 13:57:23 -0700300uint32_t DexFile::GetVersion() const {
301 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
302 return atoi(version);
303}
304
Ian Rogers0571d352011-11-03 19:51:38 -0700305int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800306 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700307 return DecodeUnsignedLeb128(&ptr);
308}
309
310// Returns a pointer to the UTF-8 string data referred to by the given string_id.
Elliott Hughes45651fd2012-02-21 15:48:20 -0800311const char* DexFile::GetStringDataAndLength(const StringId& string_id, uint32_t* length) const {
Ian Rogers7b0c5b42012-02-16 15:29:07 -0800312 DCHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800313 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700314 *length = DecodeUnsignedLeb128(&ptr);
315 return reinterpret_cast<const char*>(ptr);
316}
317
Brian Carlstromf615a612011-07-23 12:50:34 -0700318void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800319 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700320 for (size_t i = 0; i < NumClassDefs(); ++i) {
321 const ClassDef& class_def = GetClassDef(i);
322 const char* descriptor = GetClassDescriptor(class_def);
Elliott Hughesa0e18062012-04-13 15:59:59 -0700323 index_.Put(descriptor, i);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700324 }
325}
326
Brian Carlstrome24fa612011-09-29 00:53:55 -0700327bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700328 Index::const_iterator it = index_.find(descriptor);
329 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700330 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700331 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700332 idx = it->second;
333 return true;
334}
335
336const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
337 uint32_t idx;
338 if (FindClassDefIndex(descriptor, idx)) {
339 return &GetClassDef(idx);
340 }
341 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700342}
343
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800344const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
345 const DexFile::StringId& name,
346 const DexFile::TypeId& type) const {
347 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
348 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
349 const uint32_t name_idx = GetIndexForStringId(name);
350 const uint16_t type_idx = GetIndexForTypeId(type);
351 uint32_t lo = 0;
352 uint32_t hi = NumFieldIds() - 1;
353 while (hi >= lo) {
354 uint32_t mid = (hi + lo) / 2;
355 const DexFile::FieldId& field = GetFieldId(mid);
356 if (class_idx > field.class_idx_) {
357 lo = mid + 1;
358 } else if (class_idx < field.class_idx_) {
359 hi = mid - 1;
360 } else {
361 if (name_idx > field.name_idx_) {
362 lo = mid + 1;
363 } else if (name_idx < field.name_idx_) {
364 hi = mid - 1;
365 } else {
366 if (type_idx > field.type_idx_) {
367 lo = mid + 1;
368 } else if (type_idx < field.type_idx_) {
369 hi = mid - 1;
370 } else {
371 return &field;
372 }
373 }
374 }
375 }
376 return NULL;
377}
378
379const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700380 const DexFile::StringId& name,
381 const DexFile::ProtoId& signature) const {
382 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800383 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700384 const uint32_t name_idx = GetIndexForStringId(name);
385 const uint16_t proto_idx = GetIndexForProtoId(signature);
386 uint32_t lo = 0;
387 uint32_t hi = NumMethodIds() - 1;
388 while (hi >= lo) {
389 uint32_t mid = (hi + lo) / 2;
390 const DexFile::MethodId& method = GetMethodId(mid);
391 if (class_idx > method.class_idx_) {
392 lo = mid + 1;
393 } else if (class_idx < method.class_idx_) {
394 hi = mid - 1;
395 } else {
396 if (name_idx > method.name_idx_) {
397 lo = mid + 1;
398 } else if (name_idx < method.name_idx_) {
399 hi = mid - 1;
400 } else {
401 if (proto_idx > method.proto_idx_) {
402 lo = mid + 1;
403 } else if (proto_idx < method.proto_idx_) {
404 hi = mid - 1;
405 } else {
406 return &method;
407 }
408 }
409 }
410 }
411 return NULL;
412}
413
414const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
415 uint32_t lo = 0;
416 uint32_t hi = NumStringIds() - 1;
417 while (hi >= lo) {
418 uint32_t mid = (hi + lo) / 2;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800419 uint32_t length;
Ian Rogers0571d352011-11-03 19:51:38 -0700420 const DexFile::StringId& str_id = GetStringId(mid);
421 const char* str = GetStringDataAndLength(str_id, &length);
422 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
423 if (compare > 0) {
424 lo = mid + 1;
425 } else if (compare < 0) {
426 hi = mid - 1;
427 } else {
428 return &str_id;
429 }
430 }
431 return NULL;
432}
433
434const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
435 uint32_t lo = 0;
436 uint32_t hi = NumTypeIds() - 1;
437 while (hi >= lo) {
438 uint32_t mid = (hi + lo) / 2;
439 const TypeId& type_id = GetTypeId(mid);
440 if (string_idx > type_id.descriptor_idx_) {
441 lo = mid + 1;
442 } else if (string_idx < type_id.descriptor_idx_) {
443 hi = mid - 1;
444 } else {
445 return &type_id;
446 }
447 }
448 return NULL;
449}
450
451const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800452 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700453 uint32_t lo = 0;
454 uint32_t hi = NumProtoIds() - 1;
455 while (hi >= lo) {
456 uint32_t mid = (hi + lo) / 2;
457 const DexFile::ProtoId& proto = GetProtoId(mid);
458 int compare = return_type_idx - proto.return_type_idx_;
459 if (compare == 0) {
460 DexFileParameterIterator it(*this, proto);
461 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800462 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
463 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700464 it.Next();
465 i++;
466 }
467 if (compare == 0) {
468 if (it.HasNext()) {
469 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800470 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700471 compare = 1;
472 }
473 }
474 }
475 if (compare > 0) {
476 lo = mid + 1;
477 } else if (compare < 0) {
478 hi = mid - 1;
479 } else {
480 return &proto;
481 }
482 }
483 return NULL;
484}
485
486// Given a signature place the type ids into the given vector
487bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
488 const std::string& signature) const {
489 if (signature[0] != '(') {
490 return false;
491 }
492 size_t offset = 1;
493 size_t end = signature.size();
494 bool process_return = false;
495 while (offset < end) {
496 char c = signature[offset];
497 offset++;
498 if (c == ')') {
499 process_return = true;
500 continue;
501 }
502 std::string descriptor;
503 descriptor += c;
504 while (c == '[') { // process array prefix
505 if (offset >= end) { // expect some descriptor following [
506 return false;
507 }
508 c = signature[offset];
509 offset++;
510 descriptor += c;
511 }
512 if (c == 'L') { // process type descriptors
513 do {
514 if (offset >= end) { // unexpected early termination of descriptor
515 return false;
516 }
517 c = signature[offset];
518 offset++;
519 descriptor += c;
520 } while (c != ';');
521 }
522 const DexFile::StringId* string_id = FindStringId(descriptor);
523 if (string_id == NULL) {
524 return false;
525 }
526 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
527 if (type_id == NULL) {
528 return false;
529 }
530 uint16_t type_idx = GetIndexForTypeId(*type_id);
531 if (!process_return) {
532 param_type_idxs->push_back(type_idx);
533 } else {
534 *return_type_idx = type_idx;
535 return offset == end; // return true if the signature had reached a sensible end
536 }
537 }
538 return false; // failed to correctly parse return type
539}
540
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700541// Materializes the method descriptor for a method prototype. Method
542// descriptors are not stored directly in the dex file. Instead, one
543// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700544std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700545 const ProtoId& proto_id = GetProtoId(proto_idx);
546 std::string descriptor;
547 descriptor.push_back('(');
548 const TypeList* type_list = GetProtoParameters(proto_id);
549 size_t parameter_length = 0;
550 if (type_list != NULL) {
551 // A non-zero number of arguments. Append the type names.
552 for (size_t i = 0; i < type_list->Size(); ++i) {
553 const TypeItem& type_item = type_list->GetTypeItem(i);
554 uint32_t type_idx = type_item.type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800555 uint32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700556 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700557 parameter_length += type_length;
558 descriptor.append(name);
559 }
560 }
561 descriptor.push_back(')');
562 uint32_t return_type_idx = proto_id.return_type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800563 uint32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700564 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700565 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700566 if (unicode_length != NULL) {
567 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
568 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700569 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700570}
571
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800572int32_t DexFile::GetLineNumFromPC(const Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700573 // For native method, lineno should be -2 to indicate it is native. Note that
574 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700576 return -2;
577 }
578
TDYa127c8dc1012012-04-19 07:03:33 -0700579 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Elliott Hughescaf76542012-06-28 16:08:22 -0700580 DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700581
582 // A method with no line number info should return -1
583 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700584 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800585 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700586 return context.line_num_;
587}
588
Ian Rogers0571d352011-11-03 19:51:38 -0700589int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800590 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700591 // Note: Signed type is important for max and min.
592 int32_t min = 0;
593 int32_t max = tries_size - 1;
594
595 while (max >= min) {
596 int32_t mid = (min + max) / 2;
Elliott Hughes24edeb52012-06-18 15:29:46 -0700597 const TryItem* try_item = DexFile::GetTryItems(code_item, mid);
598 uint32_t start = try_item->start_addr_;
Ian Rogers0571d352011-11-03 19:51:38 -0700599 if (address < start) {
600 max = mid - 1;
601 } else {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700602 uint32_t end = start + try_item->insn_count_;
Ian Rogers0571d352011-11-03 19:51:38 -0700603 if (address >= end) {
604 min = mid + 1;
605 } else { // We have a winner!
Elliott Hughes24edeb52012-06-18 15:29:46 -0700606 return (int32_t) try_item->handler_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700607 }
608 }
609 }
610 // No match.
611 return -1;
612}
613
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800614void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800615 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
616 void* context, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700617 uint32_t line = DecodeUnsignedLeb128(&stream);
618 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
619 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
620 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700621 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700622
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800623 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700624 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800625 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700626 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800627 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800628 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700629 local_in_reg[arg_reg].start_address_ = 0;
630 local_in_reg[arg_reg].is_live_ = true;
631 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700632 arg_reg++;
633 }
634
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800635 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700636 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700637 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700638 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800639 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700640 return;
641 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800642 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700643 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800644 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700645 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700646 local_in_reg[arg_reg].name_ = name;
647 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800648 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700649 local_in_reg[arg_reg].start_address_ = address;
650 local_in_reg[arg_reg].is_live_ = true;
651 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700652 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700653 case 'D':
654 case 'J':
655 arg_reg += 2;
656 break;
657 default:
658 arg_reg += 1;
659 break;
660 }
661 }
662
Ian Rogers0571d352011-11-03 19:51:38 -0700663 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800664 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700665 return;
666 }
667
668 for (;;) {
669 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700670 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700671 uint16_t name_idx;
672 uint16_t descriptor_idx;
673 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700674
Shih-wei Liao195487c2011-08-20 13:29:04 -0700675 switch (opcode) {
676 case DBG_END_SEQUENCE:
677 return;
678
679 case DBG_ADVANCE_PC:
680 address += DecodeUnsignedLeb128(&stream);
681 break;
682
683 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700684 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700685 break;
686
687 case DBG_START_LOCAL:
688 case DBG_START_LOCAL_EXTENDED:
689 reg = DecodeUnsignedLeb128(&stream);
690 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700691 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800692 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700693 return;
694 }
695
jeffhaof8728872011-10-28 19:11:13 -0700696 name_idx = DecodeUnsignedLeb128P1(&stream);
697 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
698 if (opcode == DBG_START_LOCAL_EXTENDED) {
699 signature_idx = DecodeUnsignedLeb128P1(&stream);
700 }
701
Shih-wei Liao195487c2011-08-20 13:29:04 -0700702 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700703 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800704 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700705
Ian Rogers0571d352011-11-03 19:51:38 -0700706 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
707 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700708 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700709 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700710 }
711 local_in_reg[reg].start_address_ = address;
712 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700713 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700714 break;
715
716 case DBG_END_LOCAL:
717 reg = DecodeUnsignedLeb128(&stream);
718 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700719 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800720 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700721 return;
722 }
723
Elliott Hughes30646832011-10-13 16:59:46 -0700724 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800725 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700726 local_in_reg[reg].is_live_ = false;
727 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700728 break;
729
730 case DBG_RESTART_LOCAL:
731 reg = DecodeUnsignedLeb128(&stream);
732 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700733 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800734 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700735 return;
736 }
737
Elliott Hughes30646832011-10-13 16:59:46 -0700738 if (need_locals) {
739 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800740 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700741 return;
742 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700743
Elliott Hughes30646832011-10-13 16:59:46 -0700744 // If the register is live, the "restart" is superfluous,
745 // and we don't want to mess with the existing start address.
746 if (!local_in_reg[reg].is_live_) {
747 local_in_reg[reg].start_address_ = address;
748 local_in_reg[reg].is_live_ = true;
749 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700750 }
751 break;
752
753 case DBG_SET_PROLOGUE_END:
754 case DBG_SET_EPILOGUE_BEGIN:
755 case DBG_SET_FILE:
756 break;
757
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700758 default: {
759 int adjopcode = opcode - DBG_FIRST_SPECIAL;
760
Shih-wei Liao195487c2011-08-20 13:29:04 -0700761 address += adjopcode / DBG_LINE_RANGE;
762 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
763
Elliott Hughes2435a572012-02-17 16:07:41 -0800764 if (position_cb != NULL) {
765 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700766 // early exit
767 return;
768 }
769 }
770 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700771 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700772 }
773 }
774}
775
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800776void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800777 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
778 void* context) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700779 const byte* stream = GetDebugInfoStream(code_item);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700780 UniquePtr<LocalInfo[]> local_in_reg(local_cb != NULL ? new LocalInfo[code_item->registers_size_] : NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700781 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700782 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700783 }
784 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700785 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700786 }
787}
788
Elliott Hughes2435a572012-02-17 16:07:41 -0800789bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
790 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700791
792 // We know that this callback will be called in
793 // ascending address order, so keep going until we find
794 // a match or we've just gone past it.
795 if (address > context->address_) {
796 // The line number from the previous positions callback
797 // wil be the final result.
798 return true;
799 } else {
800 context->line_num_ = line_num;
801 return address == context->address_;
802 }
803}
804
805// Decodes the header section from the class data bytes.
806void ClassDataItemIterator::ReadClassDataHeader() {
807 CHECK(ptr_pos_ != NULL);
808 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
809 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
810 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
811 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
812}
813
814void ClassDataItemIterator::ReadClassDataField() {
815 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
816 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700817 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700818 LOG(WARNING) << "Duplicate field " << PrettyField(GetMemberIndex(), dex_file_)
819 << " in " << dex_file_.GetLocation();
820 }
Ian Rogers0571d352011-11-03 19:51:38 -0700821}
822
823void ClassDataItemIterator::ReadClassDataMethod() {
824 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
825 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
826 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700827 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700828 LOG(WARNING) << "Duplicate method " << PrettyMethod(GetMemberIndex(), dex_file_)
829 << " in " << dex_file_.GetLocation();
830 }
Ian Rogers0571d352011-11-03 19:51:38 -0700831}
832
833// Read a signed integer. "zwidth" is the zero-based byte count.
834static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
835 int32_t val = 0;
836 for (int i = zwidth; i >= 0; --i) {
837 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
838 }
839 val >>= (3 - zwidth) * 8;
840 return val;
841}
842
843// Read an unsigned integer. "zwidth" is the zero-based byte count,
844// "fill_on_right" indicates which side we want to zero-fill from.
845static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
846 uint32_t val = 0;
847 if (!fill_on_right) {
848 for (int i = zwidth; i >= 0; --i) {
849 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
850 }
851 val >>= (3 - zwidth) * 8;
852 } else {
853 for (int i = zwidth; i >= 0; --i) {
854 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
855 }
856 }
857 return val;
858}
859
860// Read a signed long. "zwidth" is the zero-based byte count.
861static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
862 int64_t val = 0;
863 for (int i = zwidth; i >= 0; --i) {
864 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
865 }
866 val >>= (7 - zwidth) * 8;
867 return val;
868}
869
870// Read an unsigned long. "zwidth" is the zero-based byte count,
871// "fill_on_right" indicates which side we want to zero-fill from.
872static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
873 uint64_t val = 0;
874 if (!fill_on_right) {
875 for (int i = zwidth; i >= 0; --i) {
876 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
877 }
878 val >>= (7 - zwidth) * 8;
879 } else {
880 for (int i = zwidth; i >= 0; --i) {
881 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
882 }
883 }
884 return val;
885}
886
887EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
Ian Rogersca190662012-06-26 15:45:57 -0700888 DexCache* dex_cache,
889 ClassLinker* linker,
890 const DexFile::ClassDef& class_def)
891 : dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1),
892 type_(0) {
Ian Rogers0571d352011-11-03 19:51:38 -0700893 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