blob: 974f6e52013f38145aaff5e5e2853cb5026c95e3 [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 Carlstromae826982011-11-09 01:33:42 -080063void DexFile::OpenDexFiles(const std::vector<const char*>& dex_filenames,
Brian Carlstrom78128a62011-09-15 17:21:19 -070064 std::vector<const DexFile*>& dex_files,
65 const std::string& strip_location_prefix) {
66 for (size_t i = 0; i < dex_filenames.size(); i++) {
67 const char* dex_filename = dex_filenames[i];
68 const DexFile* dex_file = Open(dex_filename, strip_location_prefix);
69 if (dex_file == NULL) {
70 fprintf(stderr, "could not open .dex from file %s\n", dex_filename);
71 exit(EXIT_FAILURE);
72 }
73 dex_files.push_back(dex_file);
74 }
75}
76
Brian Carlstrom16192862011-09-12 17:50:06 -070077const DexFile* DexFile::Open(const std::string& filename,
78 const std::string& strip_location_prefix) {
jeffhao262bf462011-10-20 18:36:32 -070079 if (IsValidZipFilename(filename)) {
Brian Carlstrom16192862011-09-12 17:50:06 -070080 return DexFile::OpenZip(filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070081 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -070082 if (!IsValidDexFilename(filename)) {
83 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
84 }
85 return DexFile::OpenFile(filename, filename, strip_location_prefix);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070086}
87
jeffhaob4df5142011-09-19 20:25:32 -070088void DexFile::ChangePermissions(int prot) const {
Ian Rogers30fab402012-01-23 15:43:46 -080089 if (mprotect(mem_map_->Begin(), mem_map_->Size(), prot) != 0) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -080090 PLOG(FATAL) << "Failed to change dex file permissions to " << prot << " for " << GetLocation();
jeffhaob4df5142011-09-19 20:25:32 -070091 }
92}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070093
Brian Carlstrom89521892011-12-07 22:05:07 -080094const std::string StripLocationPrefix(const std::string& original_location,
95 const std::string& strip_location_prefix) {
96 StringPiece location = original_location;
97 if (!location.starts_with(strip_location_prefix)) {
98 LOG(ERROR) << location << " does not start with " << strip_location_prefix;
99 return "";
100 }
101 location.remove_prefix(strip_location_prefix.size());
102 return location.ToString();
103}
104
Brian Carlstrom16192862011-09-12 17:50:06 -0700105const DexFile* DexFile::OpenFile(const std::string& filename,
106 const std::string& original_location,
107 const std::string& strip_location_prefix) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800108 std::string location(StripLocationPrefix(original_location, strip_location_prefix));
109 if (location.empty()) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700110 return NULL;
111 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800112
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700113 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700114 if (fd == -1) {
115 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
116 return NULL;
117 }
118 struct stat sbuf;
119 memset(&sbuf, 0, sizeof(sbuf));
120 if (fstat(fd, &sbuf) == -1) {
121 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
122 close(fd);
123 return NULL;
124 }
Ian Rogers7cfb93e2012-01-17 19:46:36 -0800125 if (S_ISDIR(sbuf.st_mode)) {
126 LOG(ERROR) << "attempt to mmap directory \"" << filename << "\"";
127 return NULL;
128 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700129 size_t length = sbuf.st_size;
Brian Carlstrom89521892011-12-07 22:05:07 -0800130 UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0));
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700131 if (map.get() == NULL) {
132 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700133 close(fd);
134 return NULL;
135 }
136 close(fd);
jeffhaof6174e82012-01-31 16:14:17 -0800137 const DexFile* dex_file = OpenMemory(location, map.release());
138 if (dex_file != NULL) {
139 DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size());
140 }
141 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700142}
143
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700144const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700145
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700146// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700147const DexFile* DexFile::OpenZip(const std::string& filename,
148 const std::string& strip_location_prefix) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800149 std::string location(StripLocationPrefix(filename, strip_location_prefix));
150 if (location.empty()) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700152 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700153
Elliott Hughes90a33692011-08-30 13:27:07 -0700154 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
155 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700156 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700157 return NULL;
158 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800159 return DexFile::Open(*zip_archive.get(), location);
160}
161
162const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) {
163 UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex));
Elliott Hughes90a33692011-08-30 13:27:07 -0700164 if (zip_entry.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800165 LOG(ERROR) << "Failed to find classes.dex within " << location;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700166 return NULL;
167 }
168
Brian Carlstrom89521892011-12-07 22:05:07 -0800169 uint32_t length = zip_entry->GetUncompressedLength();
Elliott Hughes850162c2012-01-12 18:46:43 -0800170 std::string name("classes.dex extracted in memory from ");
171 name += location;
172 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(), NULL, length, PROT_READ | PROT_WRITE));
Brian Carlstrom89521892011-12-07 22:05:07 -0800173 if (map.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800174 LOG(ERROR) << "mmap classes.dex for \"" << location << "\" failed";
Brian Carlstrom89521892011-12-07 22:05:07 -0800175 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700176 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800177
178 // Extract classes.dex
179 bool success = zip_entry->ExtractToMemory(*map.get());
180 if (!success) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800181 LOG(ERROR) << "Failed to extract classes.dex from '" << location << "' to memory";
Brian Carlstrom89521892011-12-07 22:05:07 -0800182 return NULL;
183 }
184
jeffhaof6174e82012-01-31 16:14:17 -0800185 const DexFile* dex_file = OpenMemory(location, map.release());
186 if (dex_file != NULL) {
187 DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size());
188 }
189 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700190}
191
Brian Carlstrom89521892011-12-07 22:05:07 -0800192const DexFile* DexFile::OpenMemory(const byte* base,
jeffhaof6174e82012-01-31 16:14:17 -0800193 size_t size,
Brian Carlstrom89521892011-12-07 22:05:07 -0800194 const std::string& location,
195 MemMap* mem_map) {
196 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
jeffhaof6174e82012-01-31 16:14:17 -0800197 UniquePtr<DexFile> dex_file(new DexFile(base, size, location, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700198 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700199 return NULL;
200 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700201 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700202 }
203}
204
Jesse Wilson6bf19152011-09-29 13:12:33 -0400205DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700206 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
207 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
208 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
209 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400210}
211
212jobject DexFile::GetDexObject(JNIEnv* env) const {
213 MutexLock mu(dex_object_lock_);
214 if (dex_object_ != NULL) {
215 return dex_object_;
216 }
217
Ian Rogers30fab402012-01-23 15:43:46 -0800218 void* address = const_cast<void*>(reinterpret_cast<const void*>(begin_));
jeffhaof6174e82012-01-31 16:14:17 -0800219 jobject byte_buffer = env->NewDirectByteBuffer(address, size_);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400220 if (byte_buffer == NULL) {
221 return NULL;
222 }
223
224 jclass c = env->FindClass("com/android/dex/Dex");
225 if (c == NULL) {
226 return NULL;
227 }
228
229 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
230 if (mid == NULL) {
231 return NULL;
232 }
233
234 jvalue args[1];
235 args[0].l = byte_buffer;
236 jobject local = env->CallStaticObjectMethodA(c, mid, args);
237 if (local == NULL) {
238 return NULL;
239 }
240
241 dex_object_ = env->NewGlobalRef(local);
242 return dex_object_;
243}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700244
Brian Carlstromf615a612011-07-23 12:50:34 -0700245bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700246 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800247 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700248 return false;
249 }
250 InitIndex();
251 return true;
252}
253
Brian Carlstromf615a612011-07-23 12:50:34 -0700254void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800255 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700256 header_ = reinterpret_cast<const Header*>(b);
257 const Header* h = header_;
258 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
259 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
260 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
261 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
262 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
263 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
jeffhaof6174e82012-01-31 16:14:17 -0800264 DCHECK_EQ(size_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700265}
266
jeffhao10037c82012-01-23 15:06:23 -0800267bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800268 CHECK(header_->magic_ != NULL) << GetLocation();
269 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800270 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800271 << " " << header_->magic_[0]
272 << " " << header_->magic_[1]
273 << " " << header_->magic_[2]
274 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700275 return false;
276 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800277 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800278 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800279 << " " << header_->magic_[4]
280 << " " << header_->magic_[5]
281 << " " << header_->magic_[6]
282 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700283 return false;
284 }
285 return true;
286}
287
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800288bool DexFile::IsMagicValid(const byte* magic) {
289 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
290}
291
292bool DexFile::IsVersionValid(const byte* magic) {
293 const byte* version = &magic[sizeof(kDexMagic)];
294 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
295}
296
Ian Rogersd81871c2011-10-03 13:57:23 -0700297uint32_t DexFile::GetVersion() const {
298 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
299 return atoi(version);
300}
301
Ian Rogers0571d352011-11-03 19:51:38 -0700302int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800303 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700304 return DecodeUnsignedLeb128(&ptr);
305}
306
307// Returns a pointer to the UTF-8 string data referred to by the given string_id.
308const char* DexFile::GetStringDataAndLength(const StringId& string_id, int32_t* length) const {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800309 CHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800310 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700311 *length = DecodeUnsignedLeb128(&ptr);
312 return reinterpret_cast<const char*>(ptr);
313}
314
Brian Carlstromf615a612011-07-23 12:50:34 -0700315void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800316 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700317 for (size_t i = 0; i < NumClassDefs(); ++i) {
318 const ClassDef& class_def = GetClassDef(i);
319 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700320 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700321 }
322}
323
Brian Carlstrome24fa612011-09-29 00:53:55 -0700324bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700325 Index::const_iterator it = index_.find(descriptor);
326 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700327 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700328 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700329 idx = it->second;
330 return true;
331}
332
333const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
334 uint32_t idx;
335 if (FindClassDefIndex(descriptor, idx)) {
336 return &GetClassDef(idx);
337 }
338 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700339}
340
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800341const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
342 const DexFile::StringId& name,
343 const DexFile::TypeId& type) const {
344 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
345 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
346 const uint32_t name_idx = GetIndexForStringId(name);
347 const uint16_t type_idx = GetIndexForTypeId(type);
348 uint32_t lo = 0;
349 uint32_t hi = NumFieldIds() - 1;
350 while (hi >= lo) {
351 uint32_t mid = (hi + lo) / 2;
352 const DexFile::FieldId& field = GetFieldId(mid);
353 if (class_idx > field.class_idx_) {
354 lo = mid + 1;
355 } else if (class_idx < field.class_idx_) {
356 hi = mid - 1;
357 } else {
358 if (name_idx > field.name_idx_) {
359 lo = mid + 1;
360 } else if (name_idx < field.name_idx_) {
361 hi = mid - 1;
362 } else {
363 if (type_idx > field.type_idx_) {
364 lo = mid + 1;
365 } else if (type_idx < field.type_idx_) {
366 hi = mid - 1;
367 } else {
368 return &field;
369 }
370 }
371 }
372 }
373 return NULL;
374}
375
376const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700377 const DexFile::StringId& name,
378 const DexFile::ProtoId& signature) const {
379 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800380 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700381 const uint32_t name_idx = GetIndexForStringId(name);
382 const uint16_t proto_idx = GetIndexForProtoId(signature);
383 uint32_t lo = 0;
384 uint32_t hi = NumMethodIds() - 1;
385 while (hi >= lo) {
386 uint32_t mid = (hi + lo) / 2;
387 const DexFile::MethodId& method = GetMethodId(mid);
388 if (class_idx > method.class_idx_) {
389 lo = mid + 1;
390 } else if (class_idx < method.class_idx_) {
391 hi = mid - 1;
392 } else {
393 if (name_idx > method.name_idx_) {
394 lo = mid + 1;
395 } else if (name_idx < method.name_idx_) {
396 hi = mid - 1;
397 } else {
398 if (proto_idx > method.proto_idx_) {
399 lo = mid + 1;
400 } else if (proto_idx < method.proto_idx_) {
401 hi = mid - 1;
402 } else {
403 return &method;
404 }
405 }
406 }
407 }
408 return NULL;
409}
410
411const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
412 uint32_t lo = 0;
413 uint32_t hi = NumStringIds() - 1;
414 while (hi >= lo) {
415 uint32_t mid = (hi + lo) / 2;
416 int32_t length;
417 const DexFile::StringId& str_id = GetStringId(mid);
418 const char* str = GetStringDataAndLength(str_id, &length);
419 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
420 if (compare > 0) {
421 lo = mid + 1;
422 } else if (compare < 0) {
423 hi = mid - 1;
424 } else {
425 return &str_id;
426 }
427 }
428 return NULL;
429}
430
431const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
432 uint32_t lo = 0;
433 uint32_t hi = NumTypeIds() - 1;
434 while (hi >= lo) {
435 uint32_t mid = (hi + lo) / 2;
436 const TypeId& type_id = GetTypeId(mid);
437 if (string_idx > type_id.descriptor_idx_) {
438 lo = mid + 1;
439 } else if (string_idx < type_id.descriptor_idx_) {
440 hi = mid - 1;
441 } else {
442 return &type_id;
443 }
444 }
445 return NULL;
446}
447
448const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800449 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700450 uint32_t lo = 0;
451 uint32_t hi = NumProtoIds() - 1;
452 while (hi >= lo) {
453 uint32_t mid = (hi + lo) / 2;
454 const DexFile::ProtoId& proto = GetProtoId(mid);
455 int compare = return_type_idx - proto.return_type_idx_;
456 if (compare == 0) {
457 DexFileParameterIterator it(*this, proto);
458 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800459 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
460 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700461 it.Next();
462 i++;
463 }
464 if (compare == 0) {
465 if (it.HasNext()) {
466 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800467 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700468 compare = 1;
469 }
470 }
471 }
472 if (compare > 0) {
473 lo = mid + 1;
474 } else if (compare < 0) {
475 hi = mid - 1;
476 } else {
477 return &proto;
478 }
479 }
480 return NULL;
481}
482
483// Given a signature place the type ids into the given vector
484bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
485 const std::string& signature) const {
486 if (signature[0] != '(') {
487 return false;
488 }
489 size_t offset = 1;
490 size_t end = signature.size();
491 bool process_return = false;
492 while (offset < end) {
493 char c = signature[offset];
494 offset++;
495 if (c == ')') {
496 process_return = true;
497 continue;
498 }
499 std::string descriptor;
500 descriptor += c;
501 while (c == '[') { // process array prefix
502 if (offset >= end) { // expect some descriptor following [
503 return false;
504 }
505 c = signature[offset];
506 offset++;
507 descriptor += c;
508 }
509 if (c == 'L') { // process type descriptors
510 do {
511 if (offset >= end) { // unexpected early termination of descriptor
512 return false;
513 }
514 c = signature[offset];
515 offset++;
516 descriptor += c;
517 } while (c != ';');
518 }
519 const DexFile::StringId* string_id = FindStringId(descriptor);
520 if (string_id == NULL) {
521 return false;
522 }
523 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
524 if (type_id == NULL) {
525 return false;
526 }
527 uint16_t type_idx = GetIndexForTypeId(*type_id);
528 if (!process_return) {
529 param_type_idxs->push_back(type_idx);
530 } else {
531 *return_type_idx = type_idx;
532 return offset == end; // return true if the signature had reached a sensible end
533 }
534 }
535 return false; // failed to correctly parse return type
536}
537
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700538// Materializes the method descriptor for a method prototype. Method
539// descriptors are not stored directly in the dex file. Instead, one
540// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700541std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700542 const ProtoId& proto_id = GetProtoId(proto_idx);
543 std::string descriptor;
544 descriptor.push_back('(');
545 const TypeList* type_list = GetProtoParameters(proto_id);
546 size_t parameter_length = 0;
547 if (type_list != NULL) {
548 // A non-zero number of arguments. Append the type names.
549 for (size_t i = 0; i < type_list->Size(); ++i) {
550 const TypeItem& type_item = type_list->GetTypeItem(i);
551 uint32_t type_idx = type_item.type_idx_;
552 int32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700553 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700554 parameter_length += type_length;
555 descriptor.append(name);
556 }
557 }
558 descriptor.push_back(')');
559 uint32_t return_type_idx = proto_id.return_type_idx_;
560 int32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700561 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700562 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700563 if (unicode_length != NULL) {
564 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
565 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700566 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700567}
568
Carl Shapiro1fb86202011-06-27 17:43:13 -0700569
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800570int32_t DexFile::GetLineNumFromPC(const Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700571 // For native method, lineno should be -2 to indicate it is native. Note that
572 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700573 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700574 return -2;
575 }
576
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700577 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800578 DCHECK(code_item != NULL) << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700579
580 // A method with no line number info should return -1
581 LineNumFromPcContext context(rel_pc, -1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800582 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
583 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700584 return context.line_num_;
585}
586
Ian Rogers0571d352011-11-03 19:51:38 -0700587int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800588 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700589 // Note: Signed type is important for max and min.
590 int32_t min = 0;
591 int32_t max = tries_size - 1;
592
593 while (max >= min) {
594 int32_t mid = (min + max) / 2;
595 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
596 uint32_t start = pTry->start_addr_;
597 if (address < start) {
598 max = mid - 1;
599 } else {
600 uint32_t end = start + pTry->insn_count_;
601 if (address >= end) {
602 min = mid + 1;
603 } else { // We have a winner!
604 return (int32_t) pTry->handler_off_;
605 }
606 }
607 }
608 // No match.
609 return -1;
610}
611
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800612void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700613 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
614 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700615 uint32_t line = DecodeUnsignedLeb128(&stream);
616 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
617 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
618 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700619 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700620
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800621 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700622 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800623 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700624 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800625 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800626 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700627 local_in_reg[arg_reg].start_address_ = 0;
628 local_in_reg[arg_reg].is_live_ = true;
629 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700630 arg_reg++;
631 }
632
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800633 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700634 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700635 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700636 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800637 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700638 return;
639 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800640 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700641 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800642 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700643 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700644 local_in_reg[arg_reg].name_ = name;
645 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800646 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700647 local_in_reg[arg_reg].start_address_ = address;
648 local_in_reg[arg_reg].is_live_ = true;
649 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700650 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700651 case 'D':
652 case 'J':
653 arg_reg += 2;
654 break;
655 default:
656 arg_reg += 1;
657 break;
658 }
659 }
660
Ian Rogers0571d352011-11-03 19:51:38 -0700661 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800662 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700663 return;
664 }
665
666 for (;;) {
667 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700668 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700669 uint16_t name_idx;
670 uint16_t descriptor_idx;
671 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700672
Shih-wei Liao195487c2011-08-20 13:29:04 -0700673 switch (opcode) {
674 case DBG_END_SEQUENCE:
675 return;
676
677 case DBG_ADVANCE_PC:
678 address += DecodeUnsignedLeb128(&stream);
679 break;
680
681 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700682 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700683 break;
684
685 case DBG_START_LOCAL:
686 case DBG_START_LOCAL_EXTENDED:
687 reg = DecodeUnsignedLeb128(&stream);
688 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700689 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800690 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700691 return;
692 }
693
jeffhaof8728872011-10-28 19:11:13 -0700694 name_idx = DecodeUnsignedLeb128P1(&stream);
695 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
696 if (opcode == DBG_START_LOCAL_EXTENDED) {
697 signature_idx = DecodeUnsignedLeb128P1(&stream);
698 }
699
Shih-wei Liao195487c2011-08-20 13:29:04 -0700700 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700701 if (need_locals) {
702 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700703
Ian Rogers0571d352011-11-03 19:51:38 -0700704 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
705 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700706 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700707 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700708 }
709 local_in_reg[reg].start_address_ = address;
710 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700711 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700712 break;
713
714 case DBG_END_LOCAL:
715 reg = DecodeUnsignedLeb128(&stream);
716 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700717 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800718 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700719 return;
720 }
721
Elliott Hughes30646832011-10-13 16:59:46 -0700722 if (need_locals) {
723 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
724 local_in_reg[reg].is_live_ = false;
725 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700726 break;
727
728 case DBG_RESTART_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 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800738 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700739 return;
740 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700741
Elliott Hughes30646832011-10-13 16:59:46 -0700742 // If the register is live, the "restart" is superfluous,
743 // and we don't want to mess with the existing start address.
744 if (!local_in_reg[reg].is_live_) {
745 local_in_reg[reg].start_address_ = address;
746 local_in_reg[reg].is_live_ = true;
747 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700748 }
749 break;
750
751 case DBG_SET_PROLOGUE_END:
752 case DBG_SET_EPILOGUE_BEGIN:
753 case DBG_SET_FILE:
754 break;
755
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700756 default: {
757 int adjopcode = opcode - DBG_FIRST_SPECIAL;
758
Shih-wei Liao195487c2011-08-20 13:29:04 -0700759 address += adjopcode / DBG_LINE_RANGE;
760 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
761
762 if (posCb != NULL) {
763 if (posCb(cnxt, address, line)) {
764 // early exit
765 return;
766 }
767 }
768 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700769 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700770 }
771 }
772}
773
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800774void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700775 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
776 void* cnxt) const {
777 const byte* stream = GetDebugInfoStream(code_item);
778 LocalInfo local_in_reg[code_item->registers_size_];
779
780 if (stream != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800781 DecodeDebugInfo0(code_item, is_static, method_idx, posCb, local_cb, cnxt, stream, local_in_reg);
Ian Rogers0571d352011-11-03 19:51:38 -0700782 }
783 for (int reg = 0; reg < code_item->registers_size_; reg++) {
784 InvokeLocalCbIfLive(cnxt, reg, code_item->insns_size_in_code_units_, local_in_reg, local_cb);
785 }
786}
787
788bool DexFile::LineNumForPcCb(void* cnxt, uint32_t address, uint32_t line_num) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800789 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(cnxt);
Ian Rogers0571d352011-11-03 19:51:38 -0700790
791 // We know that this callback will be called in
792 // ascending address order, so keep going until we find
793 // a match or we've just gone past it.
794 if (address > context->address_) {
795 // The line number from the previous positions callback
796 // wil be the final result.
797 return true;
798 } else {
799 context->line_num_ = line_num;
800 return address == context->address_;
801 }
802}
803
804// Decodes the header section from the class data bytes.
805void ClassDataItemIterator::ReadClassDataHeader() {
806 CHECK(ptr_pos_ != NULL);
807 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
808 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
809 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
810 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
811}
812
813void ClassDataItemIterator::ReadClassDataField() {
814 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
815 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
816}
817
818void ClassDataItemIterator::ReadClassDataMethod() {
819 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
820 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
821 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
822}
823
824// Read a signed integer. "zwidth" is the zero-based byte count.
825static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
826 int32_t val = 0;
827 for (int i = zwidth; i >= 0; --i) {
828 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
829 }
830 val >>= (3 - zwidth) * 8;
831 return val;
832}
833
834// Read an unsigned integer. "zwidth" is the zero-based byte count,
835// "fill_on_right" indicates which side we want to zero-fill from.
836static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
837 uint32_t val = 0;
838 if (!fill_on_right) {
839 for (int i = zwidth; i >= 0; --i) {
840 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
841 }
842 val >>= (3 - zwidth) * 8;
843 } else {
844 for (int i = zwidth; i >= 0; --i) {
845 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
846 }
847 }
848 return val;
849}
850
851// Read a signed long. "zwidth" is the zero-based byte count.
852static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
853 int64_t val = 0;
854 for (int i = zwidth; i >= 0; --i) {
855 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
856 }
857 val >>= (7 - zwidth) * 8;
858 return val;
859}
860
861// Read an unsigned long. "zwidth" is the zero-based byte count,
862// "fill_on_right" indicates which side we want to zero-fill from.
863static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
864 uint64_t val = 0;
865 if (!fill_on_right) {
866 for (int i = zwidth; i >= 0; --i) {
867 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
868 }
869 val >>= (7 - zwidth) * 8;
870 } else {
871 for (int i = zwidth; i >= 0; --i) {
872 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
873 }
874 }
875 return val;
876}
877
878EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
879 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
880 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
881 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
882 if (ptr_ == NULL) {
883 array_size_ = 0;
884 } else {
885 array_size_ = DecodeUnsignedLeb128(&ptr_);
886 }
887 if (array_size_ > 0) {
888 Next();
889 }
890}
891
892void EncodedStaticFieldValueIterator::Next() {
893 pos_++;
894 if (pos_ >= array_size_) {
895 return;
896 }
897 byte value_type = *ptr_++;
898 byte value_arg = value_type >> kEncodedValueArgShift;
899 size_t width = value_arg + 1; // assume and correct later
900 type_ = value_type & kEncodedValueTypeMask;
901 switch (type_) {
902 case kBoolean:
903 jval_.i = (value_arg != 0) ? 1 : 0;
904 width = 0;
905 break;
906 case kByte:
907 jval_.i = ReadSignedInt(ptr_, value_arg);
908 CHECK(IsInt(8, jval_.i));
909 break;
910 case kShort:
911 jval_.i = ReadSignedInt(ptr_, value_arg);
912 CHECK(IsInt(16, jval_.i));
913 break;
914 case kChar:
915 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
916 CHECK(IsUint(16, jval_.i));
917 break;
918 case kInt:
919 jval_.i = ReadSignedInt(ptr_, value_arg);
920 break;
921 case kLong:
922 jval_.j = ReadSignedLong(ptr_, value_arg);
923 break;
924 case kFloat:
925 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
926 break;
927 case kDouble:
928 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
929 break;
930 case kString:
931 case kType:
932 case kMethod:
933 case kEnum:
934 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
935 break;
936 case kField:
937 case kArray:
938 case kAnnotation:
939 UNIMPLEMENTED(FATAL) << ": type " << type_;
940 break;
941 case kNull:
942 jval_.l = NULL;
943 width = 0;
944 break;
945 default:
946 LOG(FATAL) << "Unreached";
947 }
948 ptr_ += width;
949}
950
951void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
952 switch (type_) {
953 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
954 case kByte: field->SetByte(NULL, jval_.b); break;
955 case kShort: field->SetShort(NULL, jval_.s); break;
956 case kChar: field->SetChar(NULL, jval_.c); break;
957 case kInt: field->SetInt(NULL, jval_.i); break;
958 case kLong: field->SetLong(NULL, jval_.j); break;
959 case kFloat: field->SetFloat(NULL, jval_.f); break;
960 case kDouble: field->SetDouble(NULL, jval_.d); break;
961 case kNull: field->SetObject(NULL, NULL); break;
962 case kString: {
963 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
964 field->SetObject(NULL, resolved);
965 break;
966 }
967 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
968 }
969}
970
971CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
972 handler_.address_ = -1;
973 int32_t offset = -1;
974
975 // Short-circuit the overwhelmingly common cases.
976 switch (code_item.tries_size_) {
977 case 0:
978 break;
979 case 1: {
980 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
981 uint32_t start = tries->start_addr_;
982 if (address >= start) {
983 uint32_t end = start + tries->insn_count_;
984 if (address < end) {
985 offset = tries->handler_off_;
986 }
987 }
988 break;
989 }
990 default:
991 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
992 }
993 if (offset >= 0) {
994 const byte* handler_data = DexFile::GetCatchHandlerData(code_item, offset);
995 Init(handler_data);
996 } else {
997 // Not found, initialize as empty
998 current_data_ = NULL;
999 remaining_count_ = -1;
1000 catch_all_ = false;
1001 DCHECK(!HasNext());
1002 }
1003}
1004
1005void CatchHandlerIterator::Init(const byte* handler_data) {
1006 current_data_ = handler_data;
1007 remaining_count_ = DecodeSignedLeb128(&current_data_);
1008
1009 // If remaining_count_ is non-positive, then it is the negative of
1010 // the number of catch types, and the catches are followed by a
1011 // catch-all handler.
1012 if (remaining_count_ <= 0) {
1013 catch_all_ = true;
1014 remaining_count_ = -remaining_count_;
1015 } else {
1016 catch_all_ = false;
1017 }
1018 Next();
1019}
1020
1021void CatchHandlerIterator::Next() {
1022 if (remaining_count_ > 0) {
1023 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1024 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1025 remaining_count_--;
1026 return;
1027 }
1028
1029 if (catch_all_) {
1030 handler_.type_idx_ = DexFile::kDexNoIndex16;
1031 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1032 catch_all_ = false;
1033 return;
1034 }
1035
1036 // no more handler
1037 remaining_count_ = -1;
1038}
1039
Carl Shapiro1fb86202011-06-27 17:43:13 -07001040} // namespace art