blob: 2a59ee301214686ab43662f8bb9707ed89921008 [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
Elliott Hughes90a33692011-08-30 13:27:07 -070028#include <map>
29
30#include "UniquePtr.h"
Ian Rogers0571d352011-11-03 19:51:38 -070031#include "class_linker.h"
jeffhao10037c82012-01-23 15:06:23 -080032#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070034#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "logging.h"
36#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070037#include "os.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070038#include "stringprintf.h"
39#include "thread.h"
Ian Rogers0571d352011-11-03 19:51:38 -070040#include "utf.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070041#include "utils.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)) {
77 UniquePtr<const DexFile> dex_file(DexFile::OpenFile(filename, "", false));
78 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
146 if (!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
238 jclass c = env->FindClass("com/android/dex/Dex");
239 if (c == NULL) {
240 return NULL;
241 }
242
243 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
244 if (mid == NULL) {
245 return NULL;
246 }
247
248 jvalue args[1];
249 args[0].l = byte_buffer;
250 jobject local = env->CallStaticObjectMethodA(c, mid, args);
251 if (local == NULL) {
252 return NULL;
253 }
254
255 dex_object_ = env->NewGlobalRef(local);
256 return dex_object_;
257}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700258
Brian Carlstromf615a612011-07-23 12:50:34 -0700259bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700260 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800261 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700262 return false;
263 }
264 InitIndex();
265 return true;
266}
267
Brian Carlstromf615a612011-07-23 12:50:34 -0700268void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800269 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700270 header_ = reinterpret_cast<const Header*>(b);
271 const Header* h = header_;
272 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
273 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
274 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
275 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
276 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
277 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
jeffhaof6174e82012-01-31 16:14:17 -0800278 DCHECK_EQ(size_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700279}
280
jeffhao10037c82012-01-23 15:06:23 -0800281bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800282 CHECK(header_->magic_ != NULL) << GetLocation();
283 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800284 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800285 << " " << header_->magic_[0]
286 << " " << header_->magic_[1]
287 << " " << header_->magic_[2]
288 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700289 return false;
290 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800291 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800292 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800293 << " " << header_->magic_[4]
294 << " " << header_->magic_[5]
295 << " " << header_->magic_[6]
296 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700297 return false;
298 }
299 return true;
300}
301
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800302bool DexFile::IsMagicValid(const byte* magic) {
303 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
304}
305
306bool DexFile::IsVersionValid(const byte* magic) {
307 const byte* version = &magic[sizeof(kDexMagic)];
308 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
309}
310
Ian Rogersd81871c2011-10-03 13:57:23 -0700311uint32_t DexFile::GetVersion() const {
312 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
313 return atoi(version);
314}
315
Ian Rogers0571d352011-11-03 19:51:38 -0700316int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800317 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700318 return DecodeUnsignedLeb128(&ptr);
319}
320
321// Returns a pointer to the UTF-8 string data referred to by the given string_id.
322const char* DexFile::GetStringDataAndLength(const StringId& string_id, int32_t* length) const {
Ian Rogers7b0c5b42012-02-16 15:29:07 -0800323 DCHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800324 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700325 *length = DecodeUnsignedLeb128(&ptr);
326 return reinterpret_cast<const char*>(ptr);
327}
328
Brian Carlstromf615a612011-07-23 12:50:34 -0700329void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800330 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700331 for (size_t i = 0; i < NumClassDefs(); ++i) {
332 const ClassDef& class_def = GetClassDef(i);
333 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700334 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700335 }
336}
337
Brian Carlstrome24fa612011-09-29 00:53:55 -0700338bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700339 Index::const_iterator it = index_.find(descriptor);
340 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700341 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700342 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700343 idx = it->second;
344 return true;
345}
346
347const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
348 uint32_t idx;
349 if (FindClassDefIndex(descriptor, idx)) {
350 return &GetClassDef(idx);
351 }
352 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700353}
354
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800355const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
356 const DexFile::StringId& name,
357 const DexFile::TypeId& type) const {
358 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
359 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
360 const uint32_t name_idx = GetIndexForStringId(name);
361 const uint16_t type_idx = GetIndexForTypeId(type);
362 uint32_t lo = 0;
363 uint32_t hi = NumFieldIds() - 1;
364 while (hi >= lo) {
365 uint32_t mid = (hi + lo) / 2;
366 const DexFile::FieldId& field = GetFieldId(mid);
367 if (class_idx > field.class_idx_) {
368 lo = mid + 1;
369 } else if (class_idx < field.class_idx_) {
370 hi = mid - 1;
371 } else {
372 if (name_idx > field.name_idx_) {
373 lo = mid + 1;
374 } else if (name_idx < field.name_idx_) {
375 hi = mid - 1;
376 } else {
377 if (type_idx > field.type_idx_) {
378 lo = mid + 1;
379 } else if (type_idx < field.type_idx_) {
380 hi = mid - 1;
381 } else {
382 return &field;
383 }
384 }
385 }
386 }
387 return NULL;
388}
389
390const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700391 const DexFile::StringId& name,
392 const DexFile::ProtoId& signature) const {
393 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800394 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700395 const uint32_t name_idx = GetIndexForStringId(name);
396 const uint16_t proto_idx = GetIndexForProtoId(signature);
397 uint32_t lo = 0;
398 uint32_t hi = NumMethodIds() - 1;
399 while (hi >= lo) {
400 uint32_t mid = (hi + lo) / 2;
401 const DexFile::MethodId& method = GetMethodId(mid);
402 if (class_idx > method.class_idx_) {
403 lo = mid + 1;
404 } else if (class_idx < method.class_idx_) {
405 hi = mid - 1;
406 } else {
407 if (name_idx > method.name_idx_) {
408 lo = mid + 1;
409 } else if (name_idx < method.name_idx_) {
410 hi = mid - 1;
411 } else {
412 if (proto_idx > method.proto_idx_) {
413 lo = mid + 1;
414 } else if (proto_idx < method.proto_idx_) {
415 hi = mid - 1;
416 } else {
417 return &method;
418 }
419 }
420 }
421 }
422 return NULL;
423}
424
425const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
426 uint32_t lo = 0;
427 uint32_t hi = NumStringIds() - 1;
428 while (hi >= lo) {
429 uint32_t mid = (hi + lo) / 2;
430 int32_t length;
431 const DexFile::StringId& str_id = GetStringId(mid);
432 const char* str = GetStringDataAndLength(str_id, &length);
433 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
434 if (compare > 0) {
435 lo = mid + 1;
436 } else if (compare < 0) {
437 hi = mid - 1;
438 } else {
439 return &str_id;
440 }
441 }
442 return NULL;
443}
444
445const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
446 uint32_t lo = 0;
447 uint32_t hi = NumTypeIds() - 1;
448 while (hi >= lo) {
449 uint32_t mid = (hi + lo) / 2;
450 const TypeId& type_id = GetTypeId(mid);
451 if (string_idx > type_id.descriptor_idx_) {
452 lo = mid + 1;
453 } else if (string_idx < type_id.descriptor_idx_) {
454 hi = mid - 1;
455 } else {
456 return &type_id;
457 }
458 }
459 return NULL;
460}
461
462const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800463 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700464 uint32_t lo = 0;
465 uint32_t hi = NumProtoIds() - 1;
466 while (hi >= lo) {
467 uint32_t mid = (hi + lo) / 2;
468 const DexFile::ProtoId& proto = GetProtoId(mid);
469 int compare = return_type_idx - proto.return_type_idx_;
470 if (compare == 0) {
471 DexFileParameterIterator it(*this, proto);
472 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800473 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
474 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700475 it.Next();
476 i++;
477 }
478 if (compare == 0) {
479 if (it.HasNext()) {
480 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800481 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700482 compare = 1;
483 }
484 }
485 }
486 if (compare > 0) {
487 lo = mid + 1;
488 } else if (compare < 0) {
489 hi = mid - 1;
490 } else {
491 return &proto;
492 }
493 }
494 return NULL;
495}
496
497// Given a signature place the type ids into the given vector
498bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
499 const std::string& signature) const {
500 if (signature[0] != '(') {
501 return false;
502 }
503 size_t offset = 1;
504 size_t end = signature.size();
505 bool process_return = false;
506 while (offset < end) {
507 char c = signature[offset];
508 offset++;
509 if (c == ')') {
510 process_return = true;
511 continue;
512 }
513 std::string descriptor;
514 descriptor += c;
515 while (c == '[') { // process array prefix
516 if (offset >= end) { // expect some descriptor following [
517 return false;
518 }
519 c = signature[offset];
520 offset++;
521 descriptor += c;
522 }
523 if (c == 'L') { // process type descriptors
524 do {
525 if (offset >= end) { // unexpected early termination of descriptor
526 return false;
527 }
528 c = signature[offset];
529 offset++;
530 descriptor += c;
531 } while (c != ';');
532 }
533 const DexFile::StringId* string_id = FindStringId(descriptor);
534 if (string_id == NULL) {
535 return false;
536 }
537 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
538 if (type_id == NULL) {
539 return false;
540 }
541 uint16_t type_idx = GetIndexForTypeId(*type_id);
542 if (!process_return) {
543 param_type_idxs->push_back(type_idx);
544 } else {
545 *return_type_idx = type_idx;
546 return offset == end; // return true if the signature had reached a sensible end
547 }
548 }
549 return false; // failed to correctly parse return type
550}
551
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700552// Materializes the method descriptor for a method prototype. Method
553// descriptors are not stored directly in the dex file. Instead, one
554// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700555std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700556 const ProtoId& proto_id = GetProtoId(proto_idx);
557 std::string descriptor;
558 descriptor.push_back('(');
559 const TypeList* type_list = GetProtoParameters(proto_id);
560 size_t parameter_length = 0;
561 if (type_list != NULL) {
562 // A non-zero number of arguments. Append the type names.
563 for (size_t i = 0; i < type_list->Size(); ++i) {
564 const TypeItem& type_item = type_list->GetTypeItem(i);
565 uint32_t type_idx = type_item.type_idx_;
566 int32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700567 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700568 parameter_length += type_length;
569 descriptor.append(name);
570 }
571 }
572 descriptor.push_back(')');
573 uint32_t return_type_idx = proto_id.return_type_idx_;
574 int32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700575 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700576 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700577 if (unicode_length != NULL) {
578 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
579 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700580 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700581}
582
Carl Shapiro1fb86202011-06-27 17:43:13 -0700583
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800584int32_t DexFile::GetLineNumFromPC(const Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700585 // For native method, lineno should be -2 to indicate it is native. Note that
586 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700588 return -2;
589 }
590
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700591 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800592 DCHECK(code_item != NULL) << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700593
594 // A method with no line number info should return -1
595 LineNumFromPcContext context(rel_pc, -1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800596 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
597 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700598 return context.line_num_;
599}
600
Ian Rogers0571d352011-11-03 19:51:38 -0700601int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800602 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700603 // Note: Signed type is important for max and min.
604 int32_t min = 0;
605 int32_t max = tries_size - 1;
606
607 while (max >= min) {
608 int32_t mid = (min + max) / 2;
609 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
610 uint32_t start = pTry->start_addr_;
611 if (address < start) {
612 max = mid - 1;
613 } else {
614 uint32_t end = start + pTry->insn_count_;
615 if (address >= end) {
616 min = mid + 1;
617 } else { // We have a winner!
618 return (int32_t) pTry->handler_off_;
619 }
620 }
621 }
622 // No match.
623 return -1;
624}
625
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800626void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700627 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
628 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700629 uint32_t line = DecodeUnsignedLeb128(&stream);
630 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
631 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
632 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700633 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700634
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800635 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700636 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800637 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700638 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800639 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800640 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700641 local_in_reg[arg_reg].start_address_ = 0;
642 local_in_reg[arg_reg].is_live_ = true;
643 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700644 arg_reg++;
645 }
646
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700648 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700649 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700650 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800651 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700652 return;
653 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800654 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700655 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800656 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700657 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700658 local_in_reg[arg_reg].name_ = name;
659 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800660 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700661 local_in_reg[arg_reg].start_address_ = address;
662 local_in_reg[arg_reg].is_live_ = true;
663 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700664 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700665 case 'D':
666 case 'J':
667 arg_reg += 2;
668 break;
669 default:
670 arg_reg += 1;
671 break;
672 }
673 }
674
Ian Rogers0571d352011-11-03 19:51:38 -0700675 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800676 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700677 return;
678 }
679
680 for (;;) {
681 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700682 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700683 uint16_t name_idx;
684 uint16_t descriptor_idx;
685 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700686
Shih-wei Liao195487c2011-08-20 13:29:04 -0700687 switch (opcode) {
688 case DBG_END_SEQUENCE:
689 return;
690
691 case DBG_ADVANCE_PC:
692 address += DecodeUnsignedLeb128(&stream);
693 break;
694
695 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700696 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700697 break;
698
699 case DBG_START_LOCAL:
700 case DBG_START_LOCAL_EXTENDED:
701 reg = DecodeUnsignedLeb128(&stream);
702 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700703 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800704 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700705 return;
706 }
707
jeffhaof8728872011-10-28 19:11:13 -0700708 name_idx = DecodeUnsignedLeb128P1(&stream);
709 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
710 if (opcode == DBG_START_LOCAL_EXTENDED) {
711 signature_idx = DecodeUnsignedLeb128P1(&stream);
712 }
713
Shih-wei Liao195487c2011-08-20 13:29:04 -0700714 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700715 if (need_locals) {
716 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700717
Ian Rogers0571d352011-11-03 19:51:38 -0700718 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
719 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700720 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700721 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700722 }
723 local_in_reg[reg].start_address_ = address;
724 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700725 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700726 break;
727
728 case DBG_END_LOCAL:
729 reg = DecodeUnsignedLeb128(&stream);
730 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700731 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800732 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700733 return;
734 }
735
Elliott Hughes30646832011-10-13 16:59:46 -0700736 if (need_locals) {
737 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
738 local_in_reg[reg].is_live_ = false;
739 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700740 break;
741
742 case DBG_RESTART_LOCAL:
743 reg = DecodeUnsignedLeb128(&stream);
744 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700745 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800746 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700747 return;
748 }
749
Elliott Hughes30646832011-10-13 16:59:46 -0700750 if (need_locals) {
751 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800752 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700753 return;
754 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700755
Elliott Hughes30646832011-10-13 16:59:46 -0700756 // If the register is live, the "restart" is superfluous,
757 // and we don't want to mess with the existing start address.
758 if (!local_in_reg[reg].is_live_) {
759 local_in_reg[reg].start_address_ = address;
760 local_in_reg[reg].is_live_ = true;
761 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700762 }
763 break;
764
765 case DBG_SET_PROLOGUE_END:
766 case DBG_SET_EPILOGUE_BEGIN:
767 case DBG_SET_FILE:
768 break;
769
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700770 default: {
771 int adjopcode = opcode - DBG_FIRST_SPECIAL;
772
Shih-wei Liao195487c2011-08-20 13:29:04 -0700773 address += adjopcode / DBG_LINE_RANGE;
774 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
775
776 if (posCb != NULL) {
777 if (posCb(cnxt, address, line)) {
778 // early exit
779 return;
780 }
781 }
782 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700783 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700784 }
785 }
786}
787
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800788void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700789 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
790 void* cnxt) const {
791 const byte* stream = GetDebugInfoStream(code_item);
792 LocalInfo local_in_reg[code_item->registers_size_];
793
794 if (stream != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800795 DecodeDebugInfo0(code_item, is_static, method_idx, posCb, local_cb, cnxt, stream, local_in_reg);
Ian Rogers0571d352011-11-03 19:51:38 -0700796 }
797 for (int reg = 0; reg < code_item->registers_size_; reg++) {
798 InvokeLocalCbIfLive(cnxt, reg, code_item->insns_size_in_code_units_, local_in_reg, local_cb);
799 }
800}
801
802bool DexFile::LineNumForPcCb(void* cnxt, uint32_t address, uint32_t line_num) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800803 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(cnxt);
Ian Rogers0571d352011-11-03 19:51:38 -0700804
805 // We know that this callback will be called in
806 // ascending address order, so keep going until we find
807 // a match or we've just gone past it.
808 if (address > context->address_) {
809 // The line number from the previous positions callback
810 // wil be the final result.
811 return true;
812 } else {
813 context->line_num_ = line_num;
814 return address == context->address_;
815 }
816}
817
818// Decodes the header section from the class data bytes.
819void ClassDataItemIterator::ReadClassDataHeader() {
820 CHECK(ptr_pos_ != NULL);
821 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
822 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
823 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
824 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
825}
826
827void ClassDataItemIterator::ReadClassDataField() {
828 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
829 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
830}
831
832void ClassDataItemIterator::ReadClassDataMethod() {
833 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
834 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
835 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
836}
837
838// Read a signed integer. "zwidth" is the zero-based byte count.
839static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
840 int32_t val = 0;
841 for (int i = zwidth; i >= 0; --i) {
842 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
843 }
844 val >>= (3 - zwidth) * 8;
845 return val;
846}
847
848// Read an unsigned integer. "zwidth" is the zero-based byte count,
849// "fill_on_right" indicates which side we want to zero-fill from.
850static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
851 uint32_t val = 0;
852 if (!fill_on_right) {
853 for (int i = zwidth; i >= 0; --i) {
854 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
855 }
856 val >>= (3 - zwidth) * 8;
857 } else {
858 for (int i = zwidth; i >= 0; --i) {
859 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
860 }
861 }
862 return val;
863}
864
865// Read a signed long. "zwidth" is the zero-based byte count.
866static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
867 int64_t val = 0;
868 for (int i = zwidth; i >= 0; --i) {
869 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
870 }
871 val >>= (7 - zwidth) * 8;
872 return val;
873}
874
875// Read an unsigned long. "zwidth" is the zero-based byte count,
876// "fill_on_right" indicates which side we want to zero-fill from.
877static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
878 uint64_t val = 0;
879 if (!fill_on_right) {
880 for (int i = zwidth; i >= 0; --i) {
881 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
882 }
883 val >>= (7 - zwidth) * 8;
884 } else {
885 for (int i = zwidth; i >= 0; --i) {
886 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
887 }
888 }
889 return val;
890}
891
892EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
893 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
894 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
895 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
896 if (ptr_ == NULL) {
897 array_size_ = 0;
898 } else {
899 array_size_ = DecodeUnsignedLeb128(&ptr_);
900 }
901 if (array_size_ > 0) {
902 Next();
903 }
904}
905
906void EncodedStaticFieldValueIterator::Next() {
907 pos_++;
908 if (pos_ >= array_size_) {
909 return;
910 }
911 byte value_type = *ptr_++;
912 byte value_arg = value_type >> kEncodedValueArgShift;
913 size_t width = value_arg + 1; // assume and correct later
914 type_ = value_type & kEncodedValueTypeMask;
915 switch (type_) {
916 case kBoolean:
917 jval_.i = (value_arg != 0) ? 1 : 0;
918 width = 0;
919 break;
920 case kByte:
921 jval_.i = ReadSignedInt(ptr_, value_arg);
922 CHECK(IsInt(8, jval_.i));
923 break;
924 case kShort:
925 jval_.i = ReadSignedInt(ptr_, value_arg);
926 CHECK(IsInt(16, jval_.i));
927 break;
928 case kChar:
929 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
930 CHECK(IsUint(16, jval_.i));
931 break;
932 case kInt:
933 jval_.i = ReadSignedInt(ptr_, value_arg);
934 break;
935 case kLong:
936 jval_.j = ReadSignedLong(ptr_, value_arg);
937 break;
938 case kFloat:
939 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
940 break;
941 case kDouble:
942 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
943 break;
944 case kString:
945 case kType:
946 case kMethod:
947 case kEnum:
948 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
949 break;
950 case kField:
951 case kArray:
952 case kAnnotation:
953 UNIMPLEMENTED(FATAL) << ": type " << type_;
954 break;
955 case kNull:
956 jval_.l = NULL;
957 width = 0;
958 break;
959 default:
960 LOG(FATAL) << "Unreached";
961 }
962 ptr_ += width;
963}
964
965void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
966 switch (type_) {
967 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
968 case kByte: field->SetByte(NULL, jval_.b); break;
969 case kShort: field->SetShort(NULL, jval_.s); break;
970 case kChar: field->SetChar(NULL, jval_.c); break;
971 case kInt: field->SetInt(NULL, jval_.i); break;
972 case kLong: field->SetLong(NULL, jval_.j); break;
973 case kFloat: field->SetFloat(NULL, jval_.f); break;
974 case kDouble: field->SetDouble(NULL, jval_.d); break;
975 case kNull: field->SetObject(NULL, NULL); break;
976 case kString: {
977 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
978 field->SetObject(NULL, resolved);
979 break;
980 }
981 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
982 }
983}
984
985CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
986 handler_.address_ = -1;
987 int32_t offset = -1;
988
989 // Short-circuit the overwhelmingly common cases.
990 switch (code_item.tries_size_) {
991 case 0:
992 break;
993 case 1: {
994 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
995 uint32_t start = tries->start_addr_;
996 if (address >= start) {
997 uint32_t end = start + tries->insn_count_;
998 if (address < end) {
999 offset = tries->handler_off_;
1000 }
1001 }
1002 break;
1003 }
1004 default:
1005 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
1006 }
1007 if (offset >= 0) {
1008 const byte* handler_data = DexFile::GetCatchHandlerData(code_item, offset);
1009 Init(handler_data);
1010 } else {
1011 // Not found, initialize as empty
1012 current_data_ = NULL;
1013 remaining_count_ = -1;
1014 catch_all_ = false;
1015 DCHECK(!HasNext());
1016 }
1017}
1018
1019void CatchHandlerIterator::Init(const byte* handler_data) {
1020 current_data_ = handler_data;
1021 remaining_count_ = DecodeSignedLeb128(&current_data_);
1022
1023 // If remaining_count_ is non-positive, then it is the negative of
1024 // the number of catch types, and the catches are followed by a
1025 // catch-all handler.
1026 if (remaining_count_ <= 0) {
1027 catch_all_ = true;
1028 remaining_count_ = -remaining_count_;
1029 } else {
1030 catch_all_ = false;
1031 }
1032 Next();
1033}
1034
1035void CatchHandlerIterator::Next() {
1036 if (remaining_count_ > 0) {
1037 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1038 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1039 remaining_count_--;
1040 return;
1041 }
1042
1043 if (catch_all_) {
1044 handler_.type_idx_ = DexFile::kDexNoIndex16;
1045 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1046 catch_all_ = false;
1047 return;
1048 }
1049
1050 // no more handler
1051 remaining_count_ = -1;
1052}
1053
Carl Shapiro1fb86202011-06-27 17:43:13 -07001054} // namespace art