blob: 14413e8b1facbe2fccba84defc707dfa13ce42bf [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);
Brian Carlstrom89521892011-12-07 22:05:07 -0800137 return OpenMemory(location, map.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700138}
139
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700140const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700141
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700142// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700143const DexFile* DexFile::OpenZip(const std::string& filename,
144 const std::string& strip_location_prefix) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800145 std::string location(StripLocationPrefix(filename, strip_location_prefix));
146 if (location.empty()) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700147 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700148 }
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700149
Elliott Hughes90a33692011-08-30 13:27:07 -0700150 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
151 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700152 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700153 return NULL;
154 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800155 return DexFile::Open(*zip_archive.get(), location);
156}
157
158const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) {
159 UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex));
Elliott Hughes90a33692011-08-30 13:27:07 -0700160 if (zip_entry.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800161 LOG(ERROR) << "Failed to find classes.dex within " << location;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700162 return NULL;
163 }
164
Brian Carlstrom89521892011-12-07 22:05:07 -0800165 uint32_t length = zip_entry->GetUncompressedLength();
Elliott Hughes850162c2012-01-12 18:46:43 -0800166 std::string name("classes.dex extracted in memory from ");
167 name += location;
168 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(), NULL, length, PROT_READ | PROT_WRITE));
Brian Carlstrom89521892011-12-07 22:05:07 -0800169 if (map.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800170 LOG(ERROR) << "mmap classes.dex for \"" << location << "\" failed";
Brian Carlstrom89521892011-12-07 22:05:07 -0800171 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700172 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800173
174 // Extract classes.dex
175 bool success = zip_entry->ExtractToMemory(*map.get());
176 if (!success) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800177 LOG(ERROR) << "Failed to extract classes.dex from '" << location << "' to memory";
Brian Carlstrom89521892011-12-07 22:05:07 -0800178 return NULL;
179 }
180
181 return OpenMemory(location, map.release());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700182}
183
Brian Carlstrom89521892011-12-07 22:05:07 -0800184const DexFile* DexFile::OpenMemory(const byte* base,
185 size_t length,
186 const std::string& location,
187 MemMap* mem_map) {
188 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
189 UniquePtr<DexFile> dex_file(new DexFile(base, length, location, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700190 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700191 return NULL;
192 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700193 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700194 }
195}
196
Jesse Wilson6bf19152011-09-29 13:12:33 -0400197DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700198 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
199 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
200 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
201 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400202}
203
204jobject DexFile::GetDexObject(JNIEnv* env) const {
205 MutexLock mu(dex_object_lock_);
206 if (dex_object_ != NULL) {
207 return dex_object_;
208 }
209
Ian Rogers30fab402012-01-23 15:43:46 -0800210 void* address = const_cast<void*>(reinterpret_cast<const void*>(begin_));
Jesse Wilson6bf19152011-09-29 13:12:33 -0400211 jobject byte_buffer = env->NewDirectByteBuffer(address, length_);
212 if (byte_buffer == NULL) {
213 return NULL;
214 }
215
216 jclass c = env->FindClass("com/android/dex/Dex");
217 if (c == NULL) {
218 return NULL;
219 }
220
221 jmethodID mid = env->GetStaticMethodID(c, "create", "(Ljava/nio/ByteBuffer;)Lcom/android/dex/Dex;");
222 if (mid == NULL) {
223 return NULL;
224 }
225
226 jvalue args[1];
227 args[0].l = byte_buffer;
228 jobject local = env->CallStaticObjectMethodA(c, mid, args);
229 if (local == NULL) {
230 return NULL;
231 }
232
233 dex_object_ = env->NewGlobalRef(local);
234 return dex_object_;
235}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700236
Brian Carlstromf615a612011-07-23 12:50:34 -0700237bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700238 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800239 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700240 return false;
241 }
242 InitIndex();
Ian Rogers30fab402012-01-23 15:43:46 -0800243 if (!DexFileVerifier::Verify(this, begin_, length_)) {
jeffhao10037c82012-01-23 15:06:23 -0800244 return false;
245 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700246 return true;
247}
248
Brian Carlstromf615a612011-07-23 12:50:34 -0700249void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800250 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700251 header_ = reinterpret_cast<const Header*>(b);
252 const Header* h = header_;
253 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
254 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
255 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
256 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
257 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
258 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
Brian Carlstrom89521892011-12-07 22:05:07 -0800259 DCHECK_EQ(length_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700260}
261
jeffhao10037c82012-01-23 15:06:23 -0800262bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800263 CHECK(header_->magic_ != NULL) << GetLocation();
264 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800265 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800266 << " " << header_->magic_[0]
267 << " " << header_->magic_[1]
268 << " " << header_->magic_[2]
269 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700270 return false;
271 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800272 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800273 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800274 << " " << header_->magic_[4]
275 << " " << header_->magic_[5]
276 << " " << header_->magic_[6]
277 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700278 return false;
279 }
280 return true;
281}
282
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800283bool DexFile::IsMagicValid(const byte* magic) {
284 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
285}
286
287bool DexFile::IsVersionValid(const byte* magic) {
288 const byte* version = &magic[sizeof(kDexMagic)];
289 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
290}
291
Ian Rogersd81871c2011-10-03 13:57:23 -0700292uint32_t DexFile::GetVersion() const {
293 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
294 return atoi(version);
295}
296
Ian Rogers0571d352011-11-03 19:51:38 -0700297int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800298 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700299 return DecodeUnsignedLeb128(&ptr);
300}
301
302// Returns a pointer to the UTF-8 string data referred to by the given string_id.
303const char* DexFile::GetStringDataAndLength(const StringId& string_id, int32_t* length) const {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800304 CHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800305 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700306 *length = DecodeUnsignedLeb128(&ptr);
307 return reinterpret_cast<const char*>(ptr);
308}
309
Brian Carlstromf615a612011-07-23 12:50:34 -0700310void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800311 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700312 for (size_t i = 0; i < NumClassDefs(); ++i) {
313 const ClassDef& class_def = GetClassDef(i);
314 const char* descriptor = GetClassDescriptor(class_def);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700315 index_[descriptor] = i;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700316 }
317}
318
Brian Carlstrome24fa612011-09-29 00:53:55 -0700319bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700320 Index::const_iterator it = index_.find(descriptor);
321 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700322 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700323 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700324 idx = it->second;
325 return true;
326}
327
328const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
329 uint32_t idx;
330 if (FindClassDefIndex(descriptor, idx)) {
331 return &GetClassDef(idx);
332 }
333 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700334}
335
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800336const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
337 const DexFile::StringId& name,
338 const DexFile::TypeId& type) const {
339 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
340 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
341 const uint32_t name_idx = GetIndexForStringId(name);
342 const uint16_t type_idx = GetIndexForTypeId(type);
343 uint32_t lo = 0;
344 uint32_t hi = NumFieldIds() - 1;
345 while (hi >= lo) {
346 uint32_t mid = (hi + lo) / 2;
347 const DexFile::FieldId& field = GetFieldId(mid);
348 if (class_idx > field.class_idx_) {
349 lo = mid + 1;
350 } else if (class_idx < field.class_idx_) {
351 hi = mid - 1;
352 } else {
353 if (name_idx > field.name_idx_) {
354 lo = mid + 1;
355 } else if (name_idx < field.name_idx_) {
356 hi = mid - 1;
357 } else {
358 if (type_idx > field.type_idx_) {
359 lo = mid + 1;
360 } else if (type_idx < field.type_idx_) {
361 hi = mid - 1;
362 } else {
363 return &field;
364 }
365 }
366 }
367 }
368 return NULL;
369}
370
371const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700372 const DexFile::StringId& name,
373 const DexFile::ProtoId& signature) const {
374 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800375 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700376 const uint32_t name_idx = GetIndexForStringId(name);
377 const uint16_t proto_idx = GetIndexForProtoId(signature);
378 uint32_t lo = 0;
379 uint32_t hi = NumMethodIds() - 1;
380 while (hi >= lo) {
381 uint32_t mid = (hi + lo) / 2;
382 const DexFile::MethodId& method = GetMethodId(mid);
383 if (class_idx > method.class_idx_) {
384 lo = mid + 1;
385 } else if (class_idx < method.class_idx_) {
386 hi = mid - 1;
387 } else {
388 if (name_idx > method.name_idx_) {
389 lo = mid + 1;
390 } else if (name_idx < method.name_idx_) {
391 hi = mid - 1;
392 } else {
393 if (proto_idx > method.proto_idx_) {
394 lo = mid + 1;
395 } else if (proto_idx < method.proto_idx_) {
396 hi = mid - 1;
397 } else {
398 return &method;
399 }
400 }
401 }
402 }
403 return NULL;
404}
405
406const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
407 uint32_t lo = 0;
408 uint32_t hi = NumStringIds() - 1;
409 while (hi >= lo) {
410 uint32_t mid = (hi + lo) / 2;
411 int32_t length;
412 const DexFile::StringId& str_id = GetStringId(mid);
413 const char* str = GetStringDataAndLength(str_id, &length);
414 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
415 if (compare > 0) {
416 lo = mid + 1;
417 } else if (compare < 0) {
418 hi = mid - 1;
419 } else {
420 return &str_id;
421 }
422 }
423 return NULL;
424}
425
426const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
427 uint32_t lo = 0;
428 uint32_t hi = NumTypeIds() - 1;
429 while (hi >= lo) {
430 uint32_t mid = (hi + lo) / 2;
431 const TypeId& type_id = GetTypeId(mid);
432 if (string_idx > type_id.descriptor_idx_) {
433 lo = mid + 1;
434 } else if (string_idx < type_id.descriptor_idx_) {
435 hi = mid - 1;
436 } else {
437 return &type_id;
438 }
439 }
440 return NULL;
441}
442
443const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800444 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700445 uint32_t lo = 0;
446 uint32_t hi = NumProtoIds() - 1;
447 while (hi >= lo) {
448 uint32_t mid = (hi + lo) / 2;
449 const DexFile::ProtoId& proto = GetProtoId(mid);
450 int compare = return_type_idx - proto.return_type_idx_;
451 if (compare == 0) {
452 DexFileParameterIterator it(*this, proto);
453 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800454 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
455 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700456 it.Next();
457 i++;
458 }
459 if (compare == 0) {
460 if (it.HasNext()) {
461 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800462 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700463 compare = 1;
464 }
465 }
466 }
467 if (compare > 0) {
468 lo = mid + 1;
469 } else if (compare < 0) {
470 hi = mid - 1;
471 } else {
472 return &proto;
473 }
474 }
475 return NULL;
476}
477
478// Given a signature place the type ids into the given vector
479bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
480 const std::string& signature) const {
481 if (signature[0] != '(') {
482 return false;
483 }
484 size_t offset = 1;
485 size_t end = signature.size();
486 bool process_return = false;
487 while (offset < end) {
488 char c = signature[offset];
489 offset++;
490 if (c == ')') {
491 process_return = true;
492 continue;
493 }
494 std::string descriptor;
495 descriptor += c;
496 while (c == '[') { // process array prefix
497 if (offset >= end) { // expect some descriptor following [
498 return false;
499 }
500 c = signature[offset];
501 offset++;
502 descriptor += c;
503 }
504 if (c == 'L') { // process type descriptors
505 do {
506 if (offset >= end) { // unexpected early termination of descriptor
507 return false;
508 }
509 c = signature[offset];
510 offset++;
511 descriptor += c;
512 } while (c != ';');
513 }
514 const DexFile::StringId* string_id = FindStringId(descriptor);
515 if (string_id == NULL) {
516 return false;
517 }
518 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
519 if (type_id == NULL) {
520 return false;
521 }
522 uint16_t type_idx = GetIndexForTypeId(*type_id);
523 if (!process_return) {
524 param_type_idxs->push_back(type_idx);
525 } else {
526 *return_type_idx = type_idx;
527 return offset == end; // return true if the signature had reached a sensible end
528 }
529 }
530 return false; // failed to correctly parse return type
531}
532
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700533// Materializes the method descriptor for a method prototype. Method
534// descriptors are not stored directly in the dex file. Instead, one
535// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700536std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700537 const ProtoId& proto_id = GetProtoId(proto_idx);
538 std::string descriptor;
539 descriptor.push_back('(');
540 const TypeList* type_list = GetProtoParameters(proto_id);
541 size_t parameter_length = 0;
542 if (type_list != NULL) {
543 // A non-zero number of arguments. Append the type names.
544 for (size_t i = 0; i < type_list->Size(); ++i) {
545 const TypeItem& type_item = type_list->GetTypeItem(i);
546 uint32_t type_idx = type_item.type_idx_;
547 int32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700548 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700549 parameter_length += type_length;
550 descriptor.append(name);
551 }
552 }
553 descriptor.push_back(')');
554 uint32_t return_type_idx = proto_id.return_type_idx_;
555 int32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700556 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700557 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700558 if (unicode_length != NULL) {
559 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
560 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700561 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700562}
563
Carl Shapiro1fb86202011-06-27 17:43:13 -0700564
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800565int32_t DexFile::GetLineNumFromPC(const Method* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700566 // For native method, lineno should be -2 to indicate it is native. Note that
567 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700569 return -2;
570 }
571
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800573 DCHECK(code_item != NULL) << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700574
575 // A method with no line number info should return -1
576 LineNumFromPcContext context(rel_pc, -1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800577 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
578 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700579 return context.line_num_;
580}
581
Ian Rogers0571d352011-11-03 19:51:38 -0700582int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800583 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700584 // Note: Signed type is important for max and min.
585 int32_t min = 0;
586 int32_t max = tries_size - 1;
587
588 while (max >= min) {
589 int32_t mid = (min + max) / 2;
590 const TryItem* pTry = DexFile::GetTryItems(code_item, mid);
591 uint32_t start = pTry->start_addr_;
592 if (address < start) {
593 max = mid - 1;
594 } else {
595 uint32_t end = start + pTry->insn_count_;
596 if (address >= end) {
597 min = mid + 1;
598 } else { // We have a winner!
599 return (int32_t) pTry->handler_off_;
600 }
601 }
602 }
603 // No match.
604 return -1;
605}
606
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800607void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700608 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
609 void* cnxt, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700610 uint32_t line = DecodeUnsignedLeb128(&stream);
611 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
612 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
613 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700614 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700615
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800616 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700617 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800618 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700619 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800620 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800621 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700622 local_in_reg[arg_reg].start_address_ = 0;
623 local_in_reg[arg_reg].is_live_ = true;
624 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700625 arg_reg++;
626 }
627
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800628 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700629 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700630 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700631 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800632 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700633 return;
634 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800635 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700636 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800637 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700638 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700639 local_in_reg[arg_reg].name_ = name;
640 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800641 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700642 local_in_reg[arg_reg].start_address_ = address;
643 local_in_reg[arg_reg].is_live_ = true;
644 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700645 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700646 case 'D':
647 case 'J':
648 arg_reg += 2;
649 break;
650 default:
651 arg_reg += 1;
652 break;
653 }
654 }
655
Ian Rogers0571d352011-11-03 19:51:38 -0700656 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800657 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700658 return;
659 }
660
661 for (;;) {
662 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700663 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700664 uint16_t name_idx;
665 uint16_t descriptor_idx;
666 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700667
Shih-wei Liao195487c2011-08-20 13:29:04 -0700668 switch (opcode) {
669 case DBG_END_SEQUENCE:
670 return;
671
672 case DBG_ADVANCE_PC:
673 address += DecodeUnsignedLeb128(&stream);
674 break;
675
676 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700677 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700678 break;
679
680 case DBG_START_LOCAL:
681 case DBG_START_LOCAL_EXTENDED:
682 reg = DecodeUnsignedLeb128(&stream);
683 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700684 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800685 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700686 return;
687 }
688
jeffhaof8728872011-10-28 19:11:13 -0700689 name_idx = DecodeUnsignedLeb128P1(&stream);
690 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
691 if (opcode == DBG_START_LOCAL_EXTENDED) {
692 signature_idx = DecodeUnsignedLeb128P1(&stream);
693 }
694
Shih-wei Liao195487c2011-08-20 13:29:04 -0700695 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700696 if (need_locals) {
697 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700698
Ian Rogers0571d352011-11-03 19:51:38 -0700699 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
700 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700701 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700702 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700703 }
704 local_in_reg[reg].start_address_ = address;
705 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700706 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700707 break;
708
709 case DBG_END_LOCAL:
710 reg = DecodeUnsignedLeb128(&stream);
711 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700712 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800713 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700714 return;
715 }
716
Elliott Hughes30646832011-10-13 16:59:46 -0700717 if (need_locals) {
718 InvokeLocalCbIfLive(cnxt, reg, address, local_in_reg, local_cb);
719 local_in_reg[reg].is_live_ = false;
720 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700721 break;
722
723 case DBG_RESTART_LOCAL:
724 reg = DecodeUnsignedLeb128(&stream);
725 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700726 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800727 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700728 return;
729 }
730
Elliott Hughes30646832011-10-13 16:59:46 -0700731 if (need_locals) {
732 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800733 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700734 return;
735 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700736
Elliott Hughes30646832011-10-13 16:59:46 -0700737 // If the register is live, the "restart" is superfluous,
738 // and we don't want to mess with the existing start address.
739 if (!local_in_reg[reg].is_live_) {
740 local_in_reg[reg].start_address_ = address;
741 local_in_reg[reg].is_live_ = true;
742 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700743 }
744 break;
745
746 case DBG_SET_PROLOGUE_END:
747 case DBG_SET_EPILOGUE_BEGIN:
748 case DBG_SET_FILE:
749 break;
750
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700751 default: {
752 int adjopcode = opcode - DBG_FIRST_SPECIAL;
753
Shih-wei Liao195487c2011-08-20 13:29:04 -0700754 address += adjopcode / DBG_LINE_RANGE;
755 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
756
757 if (posCb != NULL) {
758 if (posCb(cnxt, address, line)) {
759 // early exit
760 return;
761 }
762 }
763 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700764 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700765 }
766 }
767}
768
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800769void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Ian Rogers0571d352011-11-03 19:51:38 -0700770 DexDebugNewPositionCb posCb, DexDebugNewLocalCb local_cb,
771 void* cnxt) const {
772 const byte* stream = GetDebugInfoStream(code_item);
773 LocalInfo local_in_reg[code_item->registers_size_];
774
775 if (stream != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800776 DecodeDebugInfo0(code_item, is_static, method_idx, posCb, local_cb, cnxt, stream, local_in_reg);
Ian Rogers0571d352011-11-03 19:51:38 -0700777 }
778 for (int reg = 0; reg < code_item->registers_size_; reg++) {
779 InvokeLocalCbIfLive(cnxt, reg, code_item->insns_size_in_code_units_, local_in_reg, local_cb);
780 }
781}
782
783bool DexFile::LineNumForPcCb(void* cnxt, uint32_t address, uint32_t line_num) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800784 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(cnxt);
Ian Rogers0571d352011-11-03 19:51:38 -0700785
786 // We know that this callback will be called in
787 // ascending address order, so keep going until we find
788 // a match or we've just gone past it.
789 if (address > context->address_) {
790 // The line number from the previous positions callback
791 // wil be the final result.
792 return true;
793 } else {
794 context->line_num_ = line_num;
795 return address == context->address_;
796 }
797}
798
799// Decodes the header section from the class data bytes.
800void ClassDataItemIterator::ReadClassDataHeader() {
801 CHECK(ptr_pos_ != NULL);
802 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
803 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
804 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
805 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
806}
807
808void ClassDataItemIterator::ReadClassDataField() {
809 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
810 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
811}
812
813void ClassDataItemIterator::ReadClassDataMethod() {
814 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
815 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
816 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
817}
818
819// Read a signed integer. "zwidth" is the zero-based byte count.
820static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
821 int32_t val = 0;
822 for (int i = zwidth; i >= 0; --i) {
823 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
824 }
825 val >>= (3 - zwidth) * 8;
826 return val;
827}
828
829// Read an unsigned integer. "zwidth" is the zero-based byte count,
830// "fill_on_right" indicates which side we want to zero-fill from.
831static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
832 uint32_t val = 0;
833 if (!fill_on_right) {
834 for (int i = zwidth; i >= 0; --i) {
835 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
836 }
837 val >>= (3 - zwidth) * 8;
838 } else {
839 for (int i = zwidth; i >= 0; --i) {
840 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
841 }
842 }
843 return val;
844}
845
846// Read a signed long. "zwidth" is the zero-based byte count.
847static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
848 int64_t val = 0;
849 for (int i = zwidth; i >= 0; --i) {
850 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
851 }
852 val >>= (7 - zwidth) * 8;
853 return val;
854}
855
856// Read an unsigned long. "zwidth" is the zero-based byte count,
857// "fill_on_right" indicates which side we want to zero-fill from.
858static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
859 uint64_t val = 0;
860 if (!fill_on_right) {
861 for (int i = zwidth; i >= 0; --i) {
862 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
863 }
864 val >>= (7 - zwidth) * 8;
865 } else {
866 for (int i = zwidth; i >= 0; --i) {
867 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
868 }
869 }
870 return val;
871}
872
873EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
874 DexCache* dex_cache, ClassLinker* linker, const DexFile::ClassDef& class_def) :
875 dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1), type_(0) {
876 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
877 if (ptr_ == NULL) {
878 array_size_ = 0;
879 } else {
880 array_size_ = DecodeUnsignedLeb128(&ptr_);
881 }
882 if (array_size_ > 0) {
883 Next();
884 }
885}
886
887void EncodedStaticFieldValueIterator::Next() {
888 pos_++;
889 if (pos_ >= array_size_) {
890 return;
891 }
892 byte value_type = *ptr_++;
893 byte value_arg = value_type >> kEncodedValueArgShift;
894 size_t width = value_arg + 1; // assume and correct later
895 type_ = value_type & kEncodedValueTypeMask;
896 switch (type_) {
897 case kBoolean:
898 jval_.i = (value_arg != 0) ? 1 : 0;
899 width = 0;
900 break;
901 case kByte:
902 jval_.i = ReadSignedInt(ptr_, value_arg);
903 CHECK(IsInt(8, jval_.i));
904 break;
905 case kShort:
906 jval_.i = ReadSignedInt(ptr_, value_arg);
907 CHECK(IsInt(16, jval_.i));
908 break;
909 case kChar:
910 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
911 CHECK(IsUint(16, jval_.i));
912 break;
913 case kInt:
914 jval_.i = ReadSignedInt(ptr_, value_arg);
915 break;
916 case kLong:
917 jval_.j = ReadSignedLong(ptr_, value_arg);
918 break;
919 case kFloat:
920 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
921 break;
922 case kDouble:
923 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
924 break;
925 case kString:
926 case kType:
927 case kMethod:
928 case kEnum:
929 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
930 break;
931 case kField:
932 case kArray:
933 case kAnnotation:
934 UNIMPLEMENTED(FATAL) << ": type " << type_;
935 break;
936 case kNull:
937 jval_.l = NULL;
938 width = 0;
939 break;
940 default:
941 LOG(FATAL) << "Unreached";
942 }
943 ptr_ += width;
944}
945
946void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
947 switch (type_) {
948 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
949 case kByte: field->SetByte(NULL, jval_.b); break;
950 case kShort: field->SetShort(NULL, jval_.s); break;
951 case kChar: field->SetChar(NULL, jval_.c); break;
952 case kInt: field->SetInt(NULL, jval_.i); break;
953 case kLong: field->SetLong(NULL, jval_.j); break;
954 case kFloat: field->SetFloat(NULL, jval_.f); break;
955 case kDouble: field->SetDouble(NULL, jval_.d); break;
956 case kNull: field->SetObject(NULL, NULL); break;
957 case kString: {
958 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
959 field->SetObject(NULL, resolved);
960 break;
961 }
962 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
963 }
964}
965
966CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
967 handler_.address_ = -1;
968 int32_t offset = -1;
969
970 // Short-circuit the overwhelmingly common cases.
971 switch (code_item.tries_size_) {
972 case 0:
973 break;
974 case 1: {
975 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
976 uint32_t start = tries->start_addr_;
977 if (address >= start) {
978 uint32_t end = start + tries->insn_count_;
979 if (address < end) {
980 offset = tries->handler_off_;
981 }
982 }
983 break;
984 }
985 default:
986 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
987 }
988 if (offset >= 0) {
989 const byte* handler_data = DexFile::GetCatchHandlerData(code_item, offset);
990 Init(handler_data);
991 } else {
992 // Not found, initialize as empty
993 current_data_ = NULL;
994 remaining_count_ = -1;
995 catch_all_ = false;
996 DCHECK(!HasNext());
997 }
998}
999
1000void CatchHandlerIterator::Init(const byte* handler_data) {
1001 current_data_ = handler_data;
1002 remaining_count_ = DecodeSignedLeb128(&current_data_);
1003
1004 // If remaining_count_ is non-positive, then it is the negative of
1005 // the number of catch types, and the catches are followed by a
1006 // catch-all handler.
1007 if (remaining_count_ <= 0) {
1008 catch_all_ = true;
1009 remaining_count_ = -remaining_count_;
1010 } else {
1011 catch_all_ = false;
1012 }
1013 Next();
1014}
1015
1016void CatchHandlerIterator::Next() {
1017 if (remaining_count_ > 0) {
1018 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1019 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1020 remaining_count_--;
1021 return;
1022 }
1023
1024 if (catch_all_) {
1025 handler_.type_idx_ = DexFile::kDexNoIndex16;
1026 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1027 catch_all_ = false;
1028 return;
1029 }
1030
1031 // no more handler
1032 remaining_count_ = -1;
1033}
1034
Carl Shapiro1fb86202011-06-27 17:43:13 -07001035} // namespace art