blob: 97171344765d15e9b9329d5ddc692fa85e6c71dd [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070026
Ian Rogers0571d352011-11-03 19:51:38 -070027#include "class_linker.h"
jeffhao10037c82012-01-23 15:06:23 -080028#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070030#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070031#include "logging.h"
32#include "object.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070033#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070034#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070035#include "stringprintf.h"
36#include "thread.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070037#include "UniquePtr.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "utf.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070039#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070040#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070041#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070042
43namespace art {
44
Brian Carlstromf615a612011-07-23 12:50:34 -070045const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
46const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070047
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070048DexFile::ClassPathEntry DexFile::FindInClassPath(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070049 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070050 for (size_t i = 0; i != class_path.size(); ++i) {
51 const DexFile* dex_file = class_path[i];
52 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
53 if (dex_class_def != NULL) {
54 return ClassPathEntry(dex_file, dex_class_def);
55 }
56 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070057 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070058 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
59 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070060}
61
Brian Carlstrom5b332c82012-02-01 15:02:31 -080062bool DexFile::GetChecksum(const std::string& filename, uint32_t& checksum) {
63 if (IsValidZipFilename(filename)) {
64 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
65 if (zip_archive.get() == NULL) {
66 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070067 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080068 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(kClassesDex));
69 if (zip_entry.get() == NULL) {
70 return false;
71 }
72 checksum = zip_entry->GetCrc32();
73 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -070074 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -080075 if (IsValidDexFilename(filename)) {
Brian Carlstrom1db858a2012-03-11 22:44:45 -070076 UniquePtr<const DexFile> dex_file(DexFile::OpenFile(filename, filename, false));
Brian Carlstrom5b332c82012-02-01 15:02:31 -080077 if (dex_file.get() == NULL) {
78 return false;
79 }
80 checksum = dex_file->GetHeader().checksum_;
81 return true;
82 }
83 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070084}
85
Brian Carlstrom16192862011-09-12 17:50:06 -070086const DexFile* DexFile::Open(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -080087 const std::string& location) {
jeffhao262bf462011-10-20 18:36:32 -070088 if (IsValidZipFilename(filename)) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080089 return DexFile::OpenZip(filename, location);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070090 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -070091 if (!IsValidDexFilename(filename)) {
92 LOG(WARNING) << "Attempting to open dex file with unknown extension '" << filename << "'";
93 }
Brian Carlstroma004aa92012-02-08 18:05:09 -080094 return DexFile::OpenFile(filename, location, true);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070095}
96
jeffhaob4df5142011-09-19 20:25:32 -070097void DexFile::ChangePermissions(int prot) const {
Shih-wei Liaoa060ed92012-06-07 09:25:28 -070098 CHECK(mem_map_->Protect(prot)) << GetLocation();
jeffhaob4df5142011-09-19 20:25:32 -070099}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700100
Brian Carlstrom16192862011-09-12 17:50:06 -0700101const DexFile* DexFile::OpenFile(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800102 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800103 bool verify) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800104 CHECK(!location.empty()) << filename;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700105 int fd = open(filename.c_str(), O_RDONLY); // TODO: scoped_fd
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700106 if (fd == -1) {
107 PLOG(ERROR) << "open(\"" << filename << "\", O_RDONLY) failed";
108 return NULL;
109 }
110 struct stat sbuf;
111 memset(&sbuf, 0, sizeof(sbuf));
112 if (fstat(fd, &sbuf) == -1) {
113 PLOG(ERROR) << "fstat \"" << filename << "\" failed";
114 close(fd);
115 return NULL;
116 }
Ian Rogers7cfb93e2012-01-17 19:46:36 -0800117 if (S_ISDIR(sbuf.st_mode)) {
118 LOG(ERROR) << "attempt to mmap directory \"" << filename << "\"";
119 return NULL;
120 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700121 size_t length = sbuf.st_size;
Brian Carlstrom89521892011-12-07 22:05:07 -0800122 UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0));
Brian Carlstrom33f741e2011-10-03 11:24:05 -0700123 if (map.get() == NULL) {
124 LOG(ERROR) << "mmap \"" << filename << "\" failed";
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700125 close(fd);
126 return NULL;
127 }
128 close(fd);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800129
130 if (map->Size() < sizeof(DexFile::Header)) {
131 LOG(ERROR) << "Failed to open dex file '" << filename << "' that is too short to have a header";
132 return NULL;
133 }
134
135 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
136
137 const DexFile* dex_file = OpenMemory(location, dex_header->checksum_, map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800138 if (dex_file == NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800139 LOG(ERROR) << "Failed to open dex file '" << filename << "' from memory";
jeffhao54c1ceb2012-02-01 11:45:32 -0800140 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800141 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800142
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700143 if (verify && !DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800144 LOG(ERROR) << "Failed to verify dex file '" << filename << "'";
jeffhao54c1ceb2012-02-01 11:45:32 -0800145 return NULL;
146 }
147
jeffhaof6174e82012-01-31 16:14:17 -0800148 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700149}
150
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700151const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700152
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700153// Open classes.dex from within a .zip, .jar, .apk, ...
Brian Carlstrom16192862011-09-12 17:50:06 -0700154const DexFile* DexFile::OpenZip(const std::string& filename,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800155 const std::string& location) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700156 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(filename));
157 if (zip_archive.get() == NULL) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700158 LOG(ERROR) << "Failed to open " << filename << " when looking for classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700159 return NULL;
160 }
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800161 return DexFile::Open(*zip_archive.get(), location);
162}
163
164const DexFile* DexFile::Open(const ZipArchive& zip_archive, const std::string& location) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800165 CHECK(!location.empty());
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800166 UniquePtr<ZipEntry> zip_entry(zip_archive.Find(kClassesDex));
Elliott Hughes90a33692011-08-30 13:27:07 -0700167 if (zip_entry.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800168 LOG(ERROR) << "Failed to find classes.dex within " << location;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700169 return NULL;
170 }
171
Brian Carlstrom89521892011-12-07 22:05:07 -0800172 uint32_t length = zip_entry->GetUncompressedLength();
Elliott Hughes850162c2012-01-12 18:46:43 -0800173 std::string name("classes.dex extracted in memory from ");
174 name += location;
175 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(), NULL, length, PROT_READ | PROT_WRITE));
Brian Carlstrom89521892011-12-07 22:05:07 -0800176 if (map.get() == NULL) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800177 LOG(ERROR) << "mmap classes.dex for \"" << location << "\" failed";
Brian Carlstrom89521892011-12-07 22:05:07 -0800178 return NULL;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700179 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800180
181 // Extract classes.dex
182 bool success = zip_entry->ExtractToMemory(*map.get());
183 if (!success) {
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800184 LOG(ERROR) << "Failed to extract classes.dex from '" << location << "' to memory";
Brian Carlstrom89521892011-12-07 22:05:07 -0800185 return NULL;
186 }
187
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800188 const DexFile* dex_file = OpenMemory(location, zip_entry->GetCrc32(), map.release());
jeffhao54c1ceb2012-02-01 11:45:32 -0800189 if (dex_file == NULL) {
190 LOG(ERROR) << "Failed to open dex file '" << location << "' from memory";
191 return NULL;
jeffhaof6174e82012-01-31 16:14:17 -0800192 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800193
194 if (!DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size())) {
195 LOG(ERROR) << "Failed to verify dex file '" << location << "'";
196 return NULL;
197 }
198
jeffhaof6174e82012-01-31 16:14:17 -0800199 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700200}
201
Brian Carlstrom89521892011-12-07 22:05:07 -0800202const DexFile* DexFile::OpenMemory(const byte* base,
jeffhaof6174e82012-01-31 16:14:17 -0800203 size_t size,
Brian Carlstrom89521892011-12-07 22:05:07 -0800204 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800205 uint32_t location_checksum,
Brian Carlstrom89521892011-12-07 22:05:07 -0800206 MemMap* mem_map) {
207 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800208 UniquePtr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map));
Brian Carlstromf615a612011-07-23 12:50:34 -0700209 if (!dex_file->Init()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700210 return NULL;
211 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700212 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700213 }
214}
215
Jesse Wilson6bf19152011-09-29 13:12:33 -0400216DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700217 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
218 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
219 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
220 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400221}
222
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700223class ScopedJniMonitorLock {
224 public:
225 ScopedJniMonitorLock(JNIEnv* env, jobject locked) : env_(env), locked_(locked){
226 env->MonitorEnter(locked_);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400227 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228 ~ScopedJniMonitorLock() {
229 env_->MonitorExit(locked_);
230 }
231 private:
232 JNIEnv* const env_;
233 const jobject locked_;
234};
Jesse Wilson6bf19152011-09-29 13:12:33 -0400235
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700236jobject DexFile::GetDexObject(JNIEnv* env) const {
237 {
238 ScopedJniMonitorLock lock(env, WellKnownClasses::com_android_dex_Dex);
239 if (dex_object_ != NULL) {
240 return dex_object_;
241 }
242 }
Ian Rogers30fab402012-01-23 15:43:46 -0800243 void* address = const_cast<void*>(reinterpret_cast<const void*>(begin_));
jeffhaof6174e82012-01-31 16:14:17 -0800244 jobject byte_buffer = env->NewDirectByteBuffer(address, size_);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400245 if (byte_buffer == NULL) {
246 return NULL;
247 }
248
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700249 ScopedJniMonitorLock lock(env, WellKnownClasses::com_android_dex_Dex);
250 // Re-test to see if someone beat us to the creation when we had the lock released.
251 if (dex_object_ != NULL) {
252 return dex_object_;
253 }
Jesse Wilson6bf19152011-09-29 13:12:33 -0400254 jvalue args[1];
255 args[0].l = byte_buffer;
Elliott Hugheseac76672012-05-24 21:56:51 -0700256 jobject local = env->CallStaticObjectMethodA(WellKnownClasses::com_android_dex_Dex,
257 WellKnownClasses::com_android_dex_Dex_create,
258 args);
Jesse Wilson6bf19152011-09-29 13:12:33 -0400259 if (local == NULL) {
260 return NULL;
261 }
262
263 dex_object_ = env->NewGlobalRef(local);
264 return dex_object_;
265}
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700266
Brian Carlstromf615a612011-07-23 12:50:34 -0700267bool DexFile::Init() {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700268 InitMembers();
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800269 if (!CheckMagicAndVersion()) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700270 return false;
271 }
272 InitIndex();
273 return true;
274}
275
Brian Carlstromf615a612011-07-23 12:50:34 -0700276void DexFile::InitMembers() {
Ian Rogers30fab402012-01-23 15:43:46 -0800277 const byte* b = begin_;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700278 header_ = reinterpret_cast<const Header*>(b);
279 const Header* h = header_;
280 string_ids_ = reinterpret_cast<const StringId*>(b + h->string_ids_off_);
281 type_ids_ = reinterpret_cast<const TypeId*>(b + h->type_ids_off_);
282 field_ids_ = reinterpret_cast<const FieldId*>(b + h->field_ids_off_);
283 method_ids_ = reinterpret_cast<const MethodId*>(b + h->method_ids_off_);
284 proto_ids_ = reinterpret_cast<const ProtoId*>(b + h->proto_ids_off_);
285 class_defs_ = reinterpret_cast<const ClassDef*>(b + h->class_defs_off_);
jeffhaof6174e82012-01-31 16:14:17 -0800286 DCHECK_EQ(size_, header_->file_size_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700287}
288
jeffhao10037c82012-01-23 15:06:23 -0800289bool DexFile::CheckMagicAndVersion() const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800290 CHECK(header_->magic_ != NULL) << GetLocation();
291 if (!IsMagicValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800292 LOG(ERROR) << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800293 << " " << header_->magic_[0]
294 << " " << header_->magic_[1]
295 << " " << header_->magic_[2]
296 << " " << header_->magic_[3];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700297 return false;
298 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800299 if (!IsVersionValid(header_->magic_)) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800300 LOG(ERROR) << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800301 << " " << header_->magic_[4]
302 << " " << header_->magic_[5]
303 << " " << header_->magic_[6]
304 << " " << header_->magic_[7];
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700305 return false;
306 }
307 return true;
308}
309
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800310bool DexFile::IsMagicValid(const byte* magic) {
311 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
312}
313
314bool DexFile::IsVersionValid(const byte* magic) {
315 const byte* version = &magic[sizeof(kDexMagic)];
316 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
317}
318
Ian Rogersd81871c2011-10-03 13:57:23 -0700319uint32_t DexFile::GetVersion() const {
320 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
321 return atoi(version);
322}
323
Ian Rogers0571d352011-11-03 19:51:38 -0700324int32_t DexFile::GetStringLength(const StringId& string_id) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800325 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700326 return DecodeUnsignedLeb128(&ptr);
327}
328
329// Returns a pointer to the UTF-8 string data referred to by the given string_id.
Elliott Hughes45651fd2012-02-21 15:48:20 -0800330const char* DexFile::GetStringDataAndLength(const StringId& string_id, uint32_t* length) const {
Ian Rogers7b0c5b42012-02-16 15:29:07 -0800331 DCHECK(length != NULL) << GetLocation();
Ian Rogers30fab402012-01-23 15:43:46 -0800332 const byte* ptr = begin_ + string_id.string_data_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700333 *length = DecodeUnsignedLeb128(&ptr);
334 return reinterpret_cast<const char*>(ptr);
335}
336
Brian Carlstromf615a612011-07-23 12:50:34 -0700337void DexFile::InitIndex() {
Brian Carlstrom61e513c2011-12-09 15:30:06 -0800338 CHECK_EQ(index_.size(), 0U) << GetLocation();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700339 for (size_t i = 0; i < NumClassDefs(); ++i) {
340 const ClassDef& class_def = GetClassDef(i);
341 const char* descriptor = GetClassDescriptor(class_def);
Elliott Hughesa0e18062012-04-13 15:59:59 -0700342 index_.Put(descriptor, i);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700343 }
344}
345
Brian Carlstrome24fa612011-09-29 00:53:55 -0700346bool DexFile::FindClassDefIndex(const StringPiece& descriptor, uint32_t& idx) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700347 Index::const_iterator it = index_.find(descriptor);
348 if (it == index_.end()) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700349 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700350 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700351 idx = it->second;
352 return true;
353}
354
355const DexFile::ClassDef* DexFile::FindClassDef(const StringPiece& descriptor) const {
356 uint32_t idx;
357 if (FindClassDefIndex(descriptor, idx)) {
358 return &GetClassDef(idx);
359 }
360 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700361}
362
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800363const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
364 const DexFile::StringId& name,
365 const DexFile::TypeId& type) const {
366 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
367 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
368 const uint32_t name_idx = GetIndexForStringId(name);
369 const uint16_t type_idx = GetIndexForTypeId(type);
370 uint32_t lo = 0;
371 uint32_t hi = NumFieldIds() - 1;
372 while (hi >= lo) {
373 uint32_t mid = (hi + lo) / 2;
374 const DexFile::FieldId& field = GetFieldId(mid);
375 if (class_idx > field.class_idx_) {
376 lo = mid + 1;
377 } else if (class_idx < field.class_idx_) {
378 hi = mid - 1;
379 } else {
380 if (name_idx > field.name_idx_) {
381 lo = mid + 1;
382 } else if (name_idx < field.name_idx_) {
383 hi = mid - 1;
384 } else {
385 if (type_idx > field.type_idx_) {
386 lo = mid + 1;
387 } else if (type_idx < field.type_idx_) {
388 hi = mid - 1;
389 } else {
390 return &field;
391 }
392 }
393 }
394 }
395 return NULL;
396}
397
398const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700399 const DexFile::StringId& name,
400 const DexFile::ProtoId& signature) const {
401 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800402 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700403 const uint32_t name_idx = GetIndexForStringId(name);
404 const uint16_t proto_idx = GetIndexForProtoId(signature);
405 uint32_t lo = 0;
406 uint32_t hi = NumMethodIds() - 1;
407 while (hi >= lo) {
408 uint32_t mid = (hi + lo) / 2;
409 const DexFile::MethodId& method = GetMethodId(mid);
410 if (class_idx > method.class_idx_) {
411 lo = mid + 1;
412 } else if (class_idx < method.class_idx_) {
413 hi = mid - 1;
414 } else {
415 if (name_idx > method.name_idx_) {
416 lo = mid + 1;
417 } else if (name_idx < method.name_idx_) {
418 hi = mid - 1;
419 } else {
420 if (proto_idx > method.proto_idx_) {
421 lo = mid + 1;
422 } else if (proto_idx < method.proto_idx_) {
423 hi = mid - 1;
424 } else {
425 return &method;
426 }
427 }
428 }
429 }
430 return NULL;
431}
432
433const DexFile::StringId* DexFile::FindStringId(const std::string& string) const {
434 uint32_t lo = 0;
435 uint32_t hi = NumStringIds() - 1;
436 while (hi >= lo) {
437 uint32_t mid = (hi + lo) / 2;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800438 uint32_t length;
Ian Rogers0571d352011-11-03 19:51:38 -0700439 const DexFile::StringId& str_id = GetStringId(mid);
440 const char* str = GetStringDataAndLength(str_id, &length);
441 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string.c_str(), str);
442 if (compare > 0) {
443 lo = mid + 1;
444 } else if (compare < 0) {
445 hi = mid - 1;
446 } else {
447 return &str_id;
448 }
449 }
450 return NULL;
451}
452
453const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
454 uint32_t lo = 0;
455 uint32_t hi = NumTypeIds() - 1;
456 while (hi >= lo) {
457 uint32_t mid = (hi + lo) / 2;
458 const TypeId& type_id = GetTypeId(mid);
459 if (string_idx > type_id.descriptor_idx_) {
460 lo = mid + 1;
461 } else if (string_idx < type_id.descriptor_idx_) {
462 hi = mid - 1;
463 } else {
464 return &type_id;
465 }
466 }
467 return NULL;
468}
469
470const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800471 const std::vector<uint16_t>& signature_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700472 uint32_t lo = 0;
473 uint32_t hi = NumProtoIds() - 1;
474 while (hi >= lo) {
475 uint32_t mid = (hi + lo) / 2;
476 const DexFile::ProtoId& proto = GetProtoId(mid);
477 int compare = return_type_idx - proto.return_type_idx_;
478 if (compare == 0) {
479 DexFileParameterIterator it(*this, proto);
480 size_t i = 0;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800481 while (it.HasNext() && i < signature_type_idxs.size() && compare == 0) {
482 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700483 it.Next();
484 i++;
485 }
486 if (compare == 0) {
487 if (it.HasNext()) {
488 compare = -1;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800489 } else if (i < signature_type_idxs.size()) {
Ian Rogers0571d352011-11-03 19:51:38 -0700490 compare = 1;
491 }
492 }
493 }
494 if (compare > 0) {
495 lo = mid + 1;
496 } else if (compare < 0) {
497 hi = mid - 1;
498 } else {
499 return &proto;
500 }
501 }
502 return NULL;
503}
504
505// Given a signature place the type ids into the given vector
506bool DexFile::CreateTypeList(uint16_t* return_type_idx, std::vector<uint16_t>* param_type_idxs,
507 const std::string& signature) const {
508 if (signature[0] != '(') {
509 return false;
510 }
511 size_t offset = 1;
512 size_t end = signature.size();
513 bool process_return = false;
514 while (offset < end) {
515 char c = signature[offset];
516 offset++;
517 if (c == ')') {
518 process_return = true;
519 continue;
520 }
521 std::string descriptor;
522 descriptor += c;
523 while (c == '[') { // process array prefix
524 if (offset >= end) { // expect some descriptor following [
525 return false;
526 }
527 c = signature[offset];
528 offset++;
529 descriptor += c;
530 }
531 if (c == 'L') { // process type descriptors
532 do {
533 if (offset >= end) { // unexpected early termination of descriptor
534 return false;
535 }
536 c = signature[offset];
537 offset++;
538 descriptor += c;
539 } while (c != ';');
540 }
541 const DexFile::StringId* string_id = FindStringId(descriptor);
542 if (string_id == NULL) {
543 return false;
544 }
545 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
546 if (type_id == NULL) {
547 return false;
548 }
549 uint16_t type_idx = GetIndexForTypeId(*type_id);
550 if (!process_return) {
551 param_type_idxs->push_back(type_idx);
552 } else {
553 *return_type_idx = type_idx;
554 return offset == end; // return true if the signature had reached a sensible end
555 }
556 }
557 return false; // failed to correctly parse return type
558}
559
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700560// Materializes the method descriptor for a method prototype. Method
561// descriptors are not stored directly in the dex file. Instead, one
562// must assemble the descriptor from references in the prototype.
Ian Rogers0571d352011-11-03 19:51:38 -0700563std::string DexFile::CreateMethodSignature(uint32_t proto_idx, int32_t* unicode_length) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700564 const ProtoId& proto_id = GetProtoId(proto_idx);
565 std::string descriptor;
566 descriptor.push_back('(');
567 const TypeList* type_list = GetProtoParameters(proto_id);
568 size_t parameter_length = 0;
569 if (type_list != NULL) {
570 // A non-zero number of arguments. Append the type names.
571 for (size_t i = 0; i < type_list->Size(); ++i) {
572 const TypeItem& type_item = type_list->GetTypeItem(i);
573 uint32_t type_idx = type_item.type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800574 uint32_t type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700575 const char* name = StringByTypeIdx(type_idx, &type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700576 parameter_length += type_length;
577 descriptor.append(name);
578 }
579 }
580 descriptor.push_back(')');
581 uint32_t return_type_idx = proto_id.return_type_idx_;
Elliott Hughes45651fd2012-02-21 15:48:20 -0800582 uint32_t return_type_length;
Ian Rogers0571d352011-11-03 19:51:38 -0700583 const char* name = StringByTypeIdx(return_type_idx, &return_type_length);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700584 descriptor.append(name);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700585 if (unicode_length != NULL) {
586 *unicode_length = parameter_length + return_type_length + 2; // 2 for ( and )
587 }
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700588 return descriptor;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700589}
590
Mathieu Chartier66f19252012-09-18 08:57:04 -0700591int32_t DexFile::GetLineNumFromPC(const AbstractMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700592 // For native method, lineno should be -2 to indicate it is native. Note that
593 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700594 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700595 return -2;
596 }
597
TDYa127c8dc1012012-04-19 07:03:33 -0700598 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Elliott Hughescaf76542012-06-28 16:08:22 -0700599 DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700600
601 // A method with no line number info should return -1
602 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700603 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800604 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700605 return context.line_num_;
606}
607
Ian Rogers0571d352011-11-03 19:51:38 -0700608int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, int32_t tries_size,
Elliott Hughesba8eee12012-01-24 20:25:24 -0800609 uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700610 // Note: Signed type is important for max and min.
611 int32_t min = 0;
612 int32_t max = tries_size - 1;
613
614 while (max >= min) {
615 int32_t mid = (min + max) / 2;
Elliott Hughes24edeb52012-06-18 15:29:46 -0700616 const TryItem* try_item = DexFile::GetTryItems(code_item, mid);
617 uint32_t start = try_item->start_addr_;
Ian Rogers0571d352011-11-03 19:51:38 -0700618 if (address < start) {
619 max = mid - 1;
620 } else {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700621 uint32_t end = start + try_item->insn_count_;
Ian Rogers0571d352011-11-03 19:51:38 -0700622 if (address >= end) {
623 min = mid + 1;
624 } else { // We have a winner!
Elliott Hughes24edeb52012-06-18 15:29:46 -0700625 return (int32_t) try_item->handler_off_;
Ian Rogers0571d352011-11-03 19:51:38 -0700626 }
627 }
628 }
629 // No match.
630 return -1;
631}
632
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800633void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800634 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
635 void* context, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700636 uint32_t line = DecodeUnsignedLeb128(&stream);
637 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
638 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
639 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700640 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700641
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800642 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700643 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800644 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700645 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800646 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800647 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700648 local_in_reg[arg_reg].start_address_ = 0;
649 local_in_reg[arg_reg].is_live_ = true;
650 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700651 arg_reg++;
652 }
653
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800654 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700655 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700656 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700657 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800658 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700659 return;
660 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800661 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700662 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800663 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700664 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700665 local_in_reg[arg_reg].name_ = name;
666 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800667 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700668 local_in_reg[arg_reg].start_address_ = address;
669 local_in_reg[arg_reg].is_live_ = true;
670 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700671 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700672 case 'D':
673 case 'J':
674 arg_reg += 2;
675 break;
676 default:
677 arg_reg += 1;
678 break;
679 }
680 }
681
Ian Rogers0571d352011-11-03 19:51:38 -0700682 if (it.HasNext()) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800683 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700684 return;
685 }
686
687 for (;;) {
688 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700689 uint16_t reg;
jeffhaof8728872011-10-28 19:11:13 -0700690 uint16_t name_idx;
691 uint16_t descriptor_idx;
692 uint16_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700693
Shih-wei Liao195487c2011-08-20 13:29:04 -0700694 switch (opcode) {
695 case DBG_END_SEQUENCE:
696 return;
697
698 case DBG_ADVANCE_PC:
699 address += DecodeUnsignedLeb128(&stream);
700 break;
701
702 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700703 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700704 break;
705
706 case DBG_START_LOCAL:
707 case DBG_START_LOCAL_EXTENDED:
708 reg = DecodeUnsignedLeb128(&stream);
709 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700710 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800711 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700712 return;
713 }
714
jeffhaof8728872011-10-28 19:11:13 -0700715 name_idx = DecodeUnsignedLeb128P1(&stream);
716 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
717 if (opcode == DBG_START_LOCAL_EXTENDED) {
718 signature_idx = DecodeUnsignedLeb128P1(&stream);
719 }
720
Shih-wei Liao195487c2011-08-20 13:29:04 -0700721 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700722 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800723 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700724
Ian Rogers0571d352011-11-03 19:51:38 -0700725 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
726 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700727 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700728 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700729 }
730 local_in_reg[reg].start_address_ = address;
731 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700732 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700733 break;
734
735 case DBG_END_LOCAL:
736 reg = DecodeUnsignedLeb128(&stream);
737 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700738 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800739 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700740 return;
741 }
742
Elliott Hughes30646832011-10-13 16:59:46 -0700743 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800744 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700745 local_in_reg[reg].is_live_ = false;
746 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700747 break;
748
749 case DBG_RESTART_LOCAL:
750 reg = DecodeUnsignedLeb128(&stream);
751 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700752 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800753 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700754 return;
755 }
756
Elliott Hughes30646832011-10-13 16:59:46 -0700757 if (need_locals) {
758 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800759 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700760 return;
761 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700762
Elliott Hughes30646832011-10-13 16:59:46 -0700763 // If the register is live, the "restart" is superfluous,
764 // and we don't want to mess with the existing start address.
765 if (!local_in_reg[reg].is_live_) {
766 local_in_reg[reg].start_address_ = address;
767 local_in_reg[reg].is_live_ = true;
768 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700769 }
770 break;
771
772 case DBG_SET_PROLOGUE_END:
773 case DBG_SET_EPILOGUE_BEGIN:
774 case DBG_SET_FILE:
775 break;
776
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700777 default: {
778 int adjopcode = opcode - DBG_FIRST_SPECIAL;
779
Shih-wei Liao195487c2011-08-20 13:29:04 -0700780 address += adjopcode / DBG_LINE_RANGE;
781 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
782
Elliott Hughes2435a572012-02-17 16:07:41 -0800783 if (position_cb != NULL) {
784 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700785 // early exit
786 return;
787 }
788 }
789 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700790 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700791 }
792 }
793}
794
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800795void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800796 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
797 void* context) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700798 const byte* stream = GetDebugInfoStream(code_item);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700799 UniquePtr<LocalInfo[]> local_in_reg(local_cb != NULL ? new LocalInfo[code_item->registers_size_] : NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700800 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700801 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700802 }
803 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700804 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700805 }
806}
807
Elliott Hughes2435a572012-02-17 16:07:41 -0800808bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
809 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700810
811 // We know that this callback will be called in
812 // ascending address order, so keep going until we find
813 // a match or we've just gone past it.
814 if (address > context->address_) {
815 // The line number from the previous positions callback
816 // wil be the final result.
817 return true;
818 } else {
819 context->line_num_ = line_num;
820 return address == context->address_;
821 }
822}
823
824// Decodes the header section from the class data bytes.
825void ClassDataItemIterator::ReadClassDataHeader() {
826 CHECK(ptr_pos_ != NULL);
827 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
828 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
829 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
830 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
831}
832
833void ClassDataItemIterator::ReadClassDataField() {
834 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
835 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700836 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700837 LOG(WARNING) << "Duplicate field " << PrettyField(GetMemberIndex(), dex_file_)
838 << " in " << dex_file_.GetLocation();
839 }
Ian Rogers0571d352011-11-03 19:51:38 -0700840}
841
842void ClassDataItemIterator::ReadClassDataMethod() {
843 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
844 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
845 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700846 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700847 LOG(WARNING) << "Duplicate method " << PrettyMethod(GetMemberIndex(), dex_file_)
848 << " in " << dex_file_.GetLocation();
849 }
Ian Rogers0571d352011-11-03 19:51:38 -0700850}
851
852// Read a signed integer. "zwidth" is the zero-based byte count.
853static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
854 int32_t val = 0;
855 for (int i = zwidth; i >= 0; --i) {
856 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
857 }
858 val >>= (3 - zwidth) * 8;
859 return val;
860}
861
862// Read an unsigned integer. "zwidth" is the zero-based byte count,
863// "fill_on_right" indicates which side we want to zero-fill from.
864static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
865 uint32_t val = 0;
866 if (!fill_on_right) {
867 for (int i = zwidth; i >= 0; --i) {
868 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
869 }
870 val >>= (3 - zwidth) * 8;
871 } else {
872 for (int i = zwidth; i >= 0; --i) {
873 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
874 }
875 }
876 return val;
877}
878
879// Read a signed long. "zwidth" is the zero-based byte count.
880static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
881 int64_t val = 0;
882 for (int i = zwidth; i >= 0; --i) {
883 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
884 }
885 val >>= (7 - zwidth) * 8;
886 return val;
887}
888
889// Read an unsigned long. "zwidth" is the zero-based byte count,
890// "fill_on_right" indicates which side we want to zero-fill from.
891static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
892 uint64_t val = 0;
893 if (!fill_on_right) {
894 for (int i = zwidth; i >= 0; --i) {
895 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
896 }
897 val >>= (7 - zwidth) * 8;
898 } else {
899 for (int i = zwidth; i >= 0; --i) {
900 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
901 }
902 }
903 return val;
904}
905
906EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
Ian Rogersca190662012-06-26 15:45:57 -0700907 DexCache* dex_cache,
908 ClassLinker* linker,
909 const DexFile::ClassDef& class_def)
910 : dex_file_(dex_file), dex_cache_(dex_cache), linker_(linker), array_size_(), pos_(-1),
911 type_(0) {
Ian Rogers0571d352011-11-03 19:51:38 -0700912 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
913 if (ptr_ == NULL) {
914 array_size_ = 0;
915 } else {
916 array_size_ = DecodeUnsignedLeb128(&ptr_);
917 }
918 if (array_size_ > 0) {
919 Next();
920 }
921}
922
923void EncodedStaticFieldValueIterator::Next() {
924 pos_++;
925 if (pos_ >= array_size_) {
926 return;
927 }
928 byte value_type = *ptr_++;
929 byte value_arg = value_type >> kEncodedValueArgShift;
930 size_t width = value_arg + 1; // assume and correct later
931 type_ = value_type & kEncodedValueTypeMask;
932 switch (type_) {
933 case kBoolean:
934 jval_.i = (value_arg != 0) ? 1 : 0;
935 width = 0;
936 break;
937 case kByte:
938 jval_.i = ReadSignedInt(ptr_, value_arg);
939 CHECK(IsInt(8, jval_.i));
940 break;
941 case kShort:
942 jval_.i = ReadSignedInt(ptr_, value_arg);
943 CHECK(IsInt(16, jval_.i));
944 break;
945 case kChar:
946 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
947 CHECK(IsUint(16, jval_.i));
948 break;
949 case kInt:
950 jval_.i = ReadSignedInt(ptr_, value_arg);
951 break;
952 case kLong:
953 jval_.j = ReadSignedLong(ptr_, value_arg);
954 break;
955 case kFloat:
956 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
957 break;
958 case kDouble:
959 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
960 break;
961 case kString:
962 case kType:
963 case kMethod:
964 case kEnum:
965 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
966 break;
967 case kField:
968 case kArray:
969 case kAnnotation:
970 UNIMPLEMENTED(FATAL) << ": type " << type_;
971 break;
972 case kNull:
973 jval_.l = NULL;
974 width = 0;
975 break;
976 default:
977 LOG(FATAL) << "Unreached";
978 }
979 ptr_ += width;
980}
981
982void EncodedStaticFieldValueIterator::ReadValueToField(Field* field) const {
983 switch (type_) {
984 case kBoolean: field->SetBoolean(NULL, jval_.z); break;
985 case kByte: field->SetByte(NULL, jval_.b); break;
986 case kShort: field->SetShort(NULL, jval_.s); break;
987 case kChar: field->SetChar(NULL, jval_.c); break;
988 case kInt: field->SetInt(NULL, jval_.i); break;
989 case kLong: field->SetLong(NULL, jval_.j); break;
990 case kFloat: field->SetFloat(NULL, jval_.f); break;
991 case kDouble: field->SetDouble(NULL, jval_.d); break;
992 case kNull: field->SetObject(NULL, NULL); break;
993 case kString: {
994 String* resolved = linker_->ResolveString(dex_file_, jval_.i, dex_cache_);
995 field->SetObject(NULL, resolved);
996 break;
997 }
998 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
999 }
1000}
1001
1002CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1003 handler_.address_ = -1;
1004 int32_t offset = -1;
1005
1006 // Short-circuit the overwhelmingly common cases.
1007 switch (code_item.tries_size_) {
1008 case 0:
1009 break;
1010 case 1: {
1011 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1012 uint32_t start = tries->start_addr_;
1013 if (address >= start) {
1014 uint32_t end = start + tries->insn_count_;
1015 if (address < end) {
1016 offset = tries->handler_off_;
1017 }
1018 }
1019 break;
1020 }
1021 default:
1022 offset = DexFile::FindCatchHandlerOffset(code_item, code_item.tries_size_, address);
1023 }
Logan Chien736df022012-04-27 16:25:57 +08001024 Init(code_item, offset);
1025}
1026
1027CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1028 const DexFile::TryItem& try_item) {
1029 handler_.address_ = -1;
1030 Init(code_item, try_item.handler_off_);
1031}
1032
1033void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1034 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001035 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001036 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001037 } else {
1038 // Not found, initialize as empty
1039 current_data_ = NULL;
1040 remaining_count_ = -1;
1041 catch_all_ = false;
1042 DCHECK(!HasNext());
1043 }
1044}
1045
1046void CatchHandlerIterator::Init(const byte* handler_data) {
1047 current_data_ = handler_data;
1048 remaining_count_ = DecodeSignedLeb128(&current_data_);
1049
1050 // If remaining_count_ is non-positive, then it is the negative of
1051 // the number of catch types, and the catches are followed by a
1052 // catch-all handler.
1053 if (remaining_count_ <= 0) {
1054 catch_all_ = true;
1055 remaining_count_ = -remaining_count_;
1056 } else {
1057 catch_all_ = false;
1058 }
1059 Next();
1060}
1061
1062void CatchHandlerIterator::Next() {
1063 if (remaining_count_ > 0) {
1064 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1065 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1066 remaining_count_--;
1067 return;
1068 }
1069
1070 if (catch_all_) {
1071 handler_.type_idx_ = DexFile::kDexNoIndex16;
1072 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1073 catch_all_ = false;
1074 return;
1075 }
1076
1077 // no more handler
1078 remaining_count_ = -1;
1079}
1080
Carl Shapiro1fb86202011-06-27 17:43:13 -07001081} // namespace art