blob: d368e416f9deff4a552f6bd5665aa9d68fa4f640 [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>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070027
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080029#include "base/stringprintf.h"
Ian Rogers0571d352011-11-03 19:51:38 -070030#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070031#include "dex_file-inl.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 Carlstromea46f952013-07-30 01:26:50 -070035#include "mirror/art_field-inl.h"
36#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070038#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070039#include "safe_map.h"
Vladimir Markofd995762013-11-06 16:36:36 +000040#include "ScopedFd.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070041#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070042#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070043#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070044#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070045#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070046#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070047
48namespace art {
49
Brian Carlstromf615a612011-07-23 12:50:34 -070050const byte DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
51const byte DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070052
Ian Rogers8b2c0b92013-09-19 02:56:49 -070053DexFile::ClassPathEntry DexFile::FindInClassPath(const char* descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070054 const ClassPath& class_path) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070055 for (size_t i = 0; i != class_path.size(); ++i) {
56 const DexFile* dex_file = class_path[i];
57 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
58 if (dex_class_def != NULL) {
59 return ClassPathEntry(dex_file, dex_class_def);
60 }
61 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070062 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Brian Carlstrom7e93b502011-08-04 14:16:22 -070063 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
64 reinterpret_cast<const DexFile::ClassDef*>(NULL));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070065}
66
Ian Rogers8d31bbd2013-10-13 10:44:14 -070067static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 CHECK(magic != NULL);
Vladimir Markofd995762013-11-06 16:36:36 +000069 ScopedFd fd(open(filename, O_RDONLY, 0));
70 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070071 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070072 return -1;
73 }
Vladimir Markofd995762013-11-06 16:36:36 +000074 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070075 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070076 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070077 return -1;
78 }
Vladimir Markofd995762013-11-06 16:36:36 +000079 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070080 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
81 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070082 return -1;
83 }
Vladimir Markofd995762013-11-06 16:36:36 +000084 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085}
86
Ian Rogers8d31bbd2013-10-13 10:44:14 -070087bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070088 CHECK(checksum != NULL);
89 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070090
91 // Strip ":...", which is the location
92 const char* zip_entry_name = kClassesDex;
93 const char* file_part = filename;
94 std::unique_ptr<const char> file_part_ptr;
95
96
97 if (IsMultiDexLocation(filename)) {
98 std::pair<const char*, const char*> pair = SplitMultiDexLocation(filename);
99 file_part_ptr.reset(pair.first);
100 file_part = pair.first;
101 zip_entry_name = pair.second;
102 }
103
104 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000105 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700106 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 return false;
108 }
109 if (IsZipMagic(magic)) {
Ian Rogers700a4022014-05-19 16:49:03 -0700110 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 if (zip_archive.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700112 *error_msg = StringPrintf("Failed to open zip archive '%s'", file_part);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700114 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700115 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700117 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
118 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return false;
120 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700121 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800122 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700123 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700124 if (IsDexMagic(magic)) {
Ian Rogers700a4022014-05-19 16:49:03 -0700125 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), filename, false, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800126 if (dex_file.get() == NULL) {
127 return false;
128 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800130 return true;
131 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800133 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700134}
135
Andreas Gampe833a4852014-05-21 18:46:59 -0700136bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
137 std::vector<const DexFile*>* dex_files) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700138 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000139 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
140 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700141 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700142 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700143 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700144 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700145 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700146 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700147 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700148 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
149 error_msg));
150 if (dex_file.get() != nullptr) {
151 dex_files->push_back(dex_file.release());
152 return true;
153 } else {
154 return false;
155 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700156 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700157 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
158 return nullptr;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700159}
160
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800161int DexFile::GetPermissions() const {
162 if (mem_map_.get() == NULL) {
163 return 0;
164 } else {
165 return mem_map_->GetProtect();
166 }
167}
168
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200169bool DexFile::IsReadOnly() const {
170 return GetPermissions() == PROT_READ;
171}
172
Brian Carlstrome0948e12013-08-29 09:36:15 -0700173bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200174 CHECK(IsReadOnly());
175 if (mem_map_.get() == NULL) {
176 return false;
177 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700178 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200179 }
180}
181
Brian Carlstrome0948e12013-08-29 09:36:15 -0700182bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183 CHECK(!IsReadOnly());
184 if (mem_map_.get() == NULL) {
185 return false;
186 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700187 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200188 }
189}
190
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700191const DexFile* DexFile::OpenFile(int fd, const char* location, bool verify,
192 std::string* error_msg) {
193 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700194 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000195 {
196 ScopedFd delayed_close(fd);
197 struct stat sbuf;
198 memset(&sbuf, 0, sizeof(sbuf));
199 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800200 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000201 return nullptr;
202 }
203 if (S_ISDIR(sbuf.st_mode)) {
204 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
205 return nullptr;
206 }
207 size_t length = sbuf.st_size;
208 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
209 if (map.get() == nullptr) {
210 DCHECK(!error_msg->empty());
211 return nullptr;
212 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700213 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800214
215 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700216 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800217 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700218 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800219 }
220
221 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
222
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700223 const DexFile* dex_file = OpenMemory(location, dex_header->checksum_, map.release(), error_msg);
224 if (dex_file == nullptr) {
225 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
226 error_msg->c_str());
227 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800228 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800229
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230 if (verify && !DexFileVerifier::Verify(dex_file, dex_file->Begin(), dex_file->Size(), location,
231 error_msg)) {
232 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800233 }
234
jeffhaof6174e82012-01-31 16:14:17 -0800235 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700236}
237
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700238const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700239
Andreas Gampe833a4852014-05-21 18:46:59 -0700240bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
241 std::vector<const DexFile*>* dex_files) {
Ian Rogers700a4022014-05-19 16:49:03 -0700242 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700243 if (zip_archive.get() == nullptr) {
244 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700245 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700246 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700247 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800248}
249
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800250const DexFile* DexFile::OpenMemory(const std::string& location,
251 uint32_t location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700252 MemMap* mem_map,
253 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800254 return OpenMemory(mem_map->Begin(),
255 mem_map->Size(),
256 location,
257 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700258 mem_map,
259 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800260}
261
Andreas Gampe833a4852014-05-21 18:46:59 -0700262const DexFile* DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
263 const std::string& location, std::string* error_msg,
264 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800265 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700266 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Elliott Hughes90a33692011-08-30 13:27:07 -0700267 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700268 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700269 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700270 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700271 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Brian Carlstrom89521892011-12-07 22:05:07 -0800272 if (map.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700274 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700275 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700276 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700277 }
Ian Rogers700a4022014-05-19 16:49:03 -0700278 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700279 error_msg));
280 if (dex_file.get() == nullptr) {
281 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
282 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700283 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700284 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800285 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700286 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700287 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700288 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700289 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700290 }
291 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700292 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
293 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700294 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700295 return nullptr;
296 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 *error_code = ZipOpenErrorCode::kNoError;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700298 return dex_file.release();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700299}
300
Andreas Gampe833a4852014-05-21 18:46:59 -0700301bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
302 std::string* error_msg, std::vector<const DexFile*>* dex_files) {
303 ZipOpenErrorCode error_code;
304 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
305 &error_code));
306 if (dex_file.get() == nullptr) {
307 return false;
308 } else {
309 // Had at least classes.dex.
310 dex_files->push_back(dex_file.release());
311
312 // Now try some more.
313 size_t i = 2;
314
315 // We could try to avoid std::string allocations by working on a char array directly. As we
316 // do not expect a lot of iterations, this seems too involved and brittle.
317
318 while (i < 100) {
319 std::string name = StringPrintf("classes%zu.dex", i);
320 std::string fake_location = location + ":" + name;
321 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
322 error_msg, &error_code));
323 if (next_dex_file.get() == nullptr) {
324 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
325 LOG(WARNING) << error_msg;
326 }
327 break;
328 } else {
329 dex_files->push_back(next_dex_file.release());
330 }
331
332 i++;
333 }
334
335 return true;
336 }
337}
338
339
Brian Carlstrom89521892011-12-07 22:05:07 -0800340const DexFile* DexFile::OpenMemory(const byte* base,
jeffhaof6174e82012-01-31 16:14:17 -0800341 size_t size,
Brian Carlstrom89521892011-12-07 22:05:07 -0800342 const std::string& location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800343 uint32_t location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700344 MemMap* mem_map, std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700345 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Ian Rogers700a4022014-05-19 16:49:03 -0700346 std::unique_ptr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347 if (!dex_file->Init(error_msg)) {
348 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700349 } else {
Brian Carlstromf615a612011-07-23 12:50:34 -0700350 return dex_file.release();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700351 }
352}
353
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800354DexFile::DexFile(const byte* base, size_t size,
355 const std::string& location,
356 uint32_t location_checksum,
357 MemMap* mem_map)
358 : begin_(base),
359 size_(size),
360 location_(location),
361 location_checksum_(location_checksum),
362 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800363 header_(reinterpret_cast<const Header*>(base)),
364 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
365 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
366 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
367 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
368 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
369 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)) {
370 CHECK(begin_ != NULL) << GetLocation();
371 CHECK_GT(size_, 0U) << GetLocation();
372}
373
Jesse Wilson6bf19152011-09-29 13:12:33 -0400374DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700375 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
376 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
377 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
378 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400379}
380
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700381bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700382 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700383 return false;
384 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700385 return true;
386}
387
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800389 CHECK(header_->magic_ != NULL) << GetLocation();
390 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700391 std::ostringstream oss;
392 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800393 << " " << header_->magic_[0]
394 << " " << header_->magic_[1]
395 << " " << header_->magic_[2]
396 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700397 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700398 return false;
399 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800400 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700401 std::ostringstream oss;
402 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800403 << " " << header_->magic_[4]
404 << " " << header_->magic_[5]
405 << " " << header_->magic_[6]
406 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700407 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700408 return false;
409 }
410 return true;
411}
412
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800413bool DexFile::IsMagicValid(const byte* magic) {
414 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
415}
416
417bool DexFile::IsVersionValid(const byte* magic) {
418 const byte* version = &magic[sizeof(kDexMagic)];
419 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
420}
421
Ian Rogersd81871c2011-10-03 13:57:23 -0700422uint32_t DexFile::GetVersion() const {
423 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
424 return atoi(version);
425}
426
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700427const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor) const {
428 size_t num_class_defs = NumClassDefs();
429 if (num_class_defs == 0) {
430 return NULL;
431 }
432 const StringId* string_id = FindStringId(descriptor);
433 if (string_id == NULL) {
434 return NULL;
435 }
436 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
437 if (type_id == NULL) {
438 return NULL;
439 }
440 uint16_t type_idx = GetIndexForTypeId(*type_id);
441 for (size_t i = 0; i < num_class_defs; ++i) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700442 const ClassDef& class_def = GetClassDef(i);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700443 if (class_def.class_idx_ == type_idx) {
444 return &class_def;
445 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700446 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700447 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700448}
449
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700450const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
451 size_t num_class_defs = NumClassDefs();
452 for (size_t i = 0; i < num_class_defs; ++i) {
453 const ClassDef& class_def = GetClassDef(i);
454 if (class_def.class_idx_ == type_idx) {
455 return &class_def;
456 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700457 }
458 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700459}
460
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800461const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
462 const DexFile::StringId& name,
463 const DexFile::TypeId& type) const {
464 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
465 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
466 const uint32_t name_idx = GetIndexForStringId(name);
467 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700468 int32_t lo = 0;
469 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800470 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700471 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800472 const DexFile::FieldId& field = GetFieldId(mid);
473 if (class_idx > field.class_idx_) {
474 lo = mid + 1;
475 } else if (class_idx < field.class_idx_) {
476 hi = mid - 1;
477 } else {
478 if (name_idx > field.name_idx_) {
479 lo = mid + 1;
480 } else if (name_idx < field.name_idx_) {
481 hi = mid - 1;
482 } else {
483 if (type_idx > field.type_idx_) {
484 lo = mid + 1;
485 } else if (type_idx < field.type_idx_) {
486 hi = mid - 1;
487 } else {
488 return &field;
489 }
490 }
491 }
492 }
493 return NULL;
494}
495
496const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700497 const DexFile::StringId& name,
498 const DexFile::ProtoId& signature) const {
499 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800500 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700501 const uint32_t name_idx = GetIndexForStringId(name);
502 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700503 int32_t lo = 0;
504 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700505 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700506 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700507 const DexFile::MethodId& method = GetMethodId(mid);
508 if (class_idx > method.class_idx_) {
509 lo = mid + 1;
510 } else if (class_idx < method.class_idx_) {
511 hi = mid - 1;
512 } else {
513 if (name_idx > method.name_idx_) {
514 lo = mid + 1;
515 } else if (name_idx < method.name_idx_) {
516 hi = mid - 1;
517 } else {
518 if (proto_idx > method.proto_idx_) {
519 lo = mid + 1;
520 } else if (proto_idx < method.proto_idx_) {
521 hi = mid - 1;
522 } else {
523 return &method;
524 }
525 }
526 }
527 }
528 return NULL;
529}
530
Ian Rogers637c65b2013-05-31 11:46:00 -0700531const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700532 int32_t lo = 0;
533 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700534 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700535 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700536 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700537 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700538 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
539 if (compare > 0) {
540 lo = mid + 1;
541 } else if (compare < 0) {
542 hi = mid - 1;
543 } else {
544 return &str_id;
545 }
546 }
547 return NULL;
548}
549
550const DexFile::StringId* DexFile::FindStringId(const uint16_t* string) const {
551 int32_t lo = 0;
552 int32_t hi = NumStringIds() - 1;
553 while (hi >= lo) {
554 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700555 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700556 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700557 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string);
Ian Rogers0571d352011-11-03 19:51:38 -0700558 if (compare > 0) {
559 lo = mid + 1;
560 } else if (compare < 0) {
561 hi = mid - 1;
562 } else {
563 return &str_id;
564 }
565 }
566 return NULL;
567}
568
569const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700570 int32_t lo = 0;
571 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700572 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700573 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700574 const TypeId& type_id = GetTypeId(mid);
575 if (string_idx > type_id.descriptor_idx_) {
576 lo = mid + 1;
577 } else if (string_idx < type_id.descriptor_idx_) {
578 hi = mid - 1;
579 } else {
580 return &type_id;
581 }
582 }
583 return NULL;
584}
585
586const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000587 const uint16_t* signature_type_idxs,
588 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700589 int32_t lo = 0;
590 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700591 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700593 const DexFile::ProtoId& proto = GetProtoId(mid);
594 int compare = return_type_idx - proto.return_type_idx_;
595 if (compare == 0) {
596 DexFileParameterIterator it(*this, proto);
597 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000598 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800599 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700600 it.Next();
601 i++;
602 }
603 if (compare == 0) {
604 if (it.HasNext()) {
605 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000606 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700607 compare = 1;
608 }
609 }
610 }
611 if (compare > 0) {
612 lo = mid + 1;
613 } else if (compare < 0) {
614 hi = mid - 1;
615 } else {
616 return &proto;
617 }
618 }
619 return NULL;
620}
621
622// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700623bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
624 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700625 if (signature[0] != '(') {
626 return false;
627 }
628 size_t offset = 1;
629 size_t end = signature.size();
630 bool process_return = false;
631 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000632 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700633 char c = signature[offset];
634 offset++;
635 if (c == ')') {
636 process_return = true;
637 continue;
638 }
Ian Rogers0571d352011-11-03 19:51:38 -0700639 while (c == '[') { // process array prefix
640 if (offset >= end) { // expect some descriptor following [
641 return false;
642 }
643 c = signature[offset];
644 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700645 }
646 if (c == 'L') { // process type descriptors
647 do {
648 if (offset >= end) { // unexpected early termination of descriptor
649 return false;
650 }
651 c = signature[offset];
652 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700653 } while (c != ';');
654 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000655 // TODO: avoid creating a std::string just to get a 0-terminated char array
656 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700657 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700658 if (string_id == NULL) {
659 return false;
660 }
661 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
662 if (type_id == NULL) {
663 return false;
664 }
665 uint16_t type_idx = GetIndexForTypeId(*type_id);
666 if (!process_return) {
667 param_type_idxs->push_back(type_idx);
668 } else {
669 *return_type_idx = type_idx;
670 return offset == end; // return true if the signature had reached a sensible end
671 }
672 }
673 return false; // failed to correctly parse return type
674}
675
Ian Rogersd91d6d62013-09-25 20:26:14 -0700676const Signature DexFile::CreateSignature(const StringPiece& signature) const {
677 uint16_t return_type_idx;
678 std::vector<uint16_t> param_type_indices;
679 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
680 if (!success) {
681 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700682 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700683 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
684 if (proto_id == NULL) {
685 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700686 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700687 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700688}
689
Ian Rogersef7d42f2014-01-06 12:55:46 -0800690int32_t DexFile::GetLineNumFromPC(mirror::ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700691 // For native method, lineno should be -2 to indicate it is native. Note that
692 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700693 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700694 return -2;
695 }
696
TDYa127c8dc1012012-04-19 07:03:33 -0700697 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Elliott Hughescaf76542012-06-28 16:08:22 -0700698 DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700699
700 // A method with no line number info should return -1
701 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700702 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800703 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700704 return context.line_num_;
705}
706
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700707int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700708 // Note: Signed type is important for max and min.
709 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700710 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700711
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700712 while (min <= max) {
713 int32_t mid = min + ((max - min) / 2);
714
715 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
716 uint32_t start = ti->start_addr_;
717 uint32_t end = start + ti->insn_count_;
718
Ian Rogers0571d352011-11-03 19:51:38 -0700719 if (address < start) {
720 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700721 } else if (address >= end) {
722 min = mid + 1;
723 } else { // We have a winner!
724 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700725 }
726 }
727 // No match.
728 return -1;
729}
730
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700731int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
732 int32_t try_item = FindTryItem(code_item, address);
733 if (try_item == -1) {
734 return -1;
735 } else {
736 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
737 }
738}
739
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800740void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800741 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
742 void* context, const byte* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700743 uint32_t line = DecodeUnsignedLeb128(&stream);
744 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
745 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
746 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700747 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700748
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800749 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700750 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800751 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700752 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800753 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800754 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700755 local_in_reg[arg_reg].start_address_ = 0;
756 local_in_reg[arg_reg].is_live_ = true;
757 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700758 arg_reg++;
759 }
760
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800761 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700762 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700763 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700764 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800765 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700766 return;
767 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800768 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700769 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800770 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700771 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700772 local_in_reg[arg_reg].name_ = name;
773 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800774 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700775 local_in_reg[arg_reg].start_address_ = address;
776 local_in_reg[arg_reg].is_live_ = true;
777 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700778 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700779 case 'D':
780 case 'J':
781 arg_reg += 2;
782 break;
783 default:
784 arg_reg += 1;
785 break;
786 }
787 }
788
Ian Rogers0571d352011-11-03 19:51:38 -0700789 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800790 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
791 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700792 return;
793 }
794
795 for (;;) {
796 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700797 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800798 uint32_t name_idx;
799 uint32_t descriptor_idx;
800 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700801
Shih-wei Liao195487c2011-08-20 13:29:04 -0700802 switch (opcode) {
803 case DBG_END_SEQUENCE:
804 return;
805
806 case DBG_ADVANCE_PC:
807 address += DecodeUnsignedLeb128(&stream);
808 break;
809
810 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700811 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700812 break;
813
814 case DBG_START_LOCAL:
815 case DBG_START_LOCAL_EXTENDED:
816 reg = DecodeUnsignedLeb128(&stream);
817 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700818 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800819 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700820 return;
821 }
822
jeffhaof8728872011-10-28 19:11:13 -0700823 name_idx = DecodeUnsignedLeb128P1(&stream);
824 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
825 if (opcode == DBG_START_LOCAL_EXTENDED) {
826 signature_idx = DecodeUnsignedLeb128P1(&stream);
827 }
828
Shih-wei Liao195487c2011-08-20 13:29:04 -0700829 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700830 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800831 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700832
Ian Rogers0571d352011-11-03 19:51:38 -0700833 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
834 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700835 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700836 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700837 }
838 local_in_reg[reg].start_address_ = address;
839 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700840 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 break;
842
843 case DBG_END_LOCAL:
844 reg = DecodeUnsignedLeb128(&stream);
845 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700846 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800847 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700848 return;
849 }
850
Elliott Hughes30646832011-10-13 16:59:46 -0700851 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800852 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700853 local_in_reg[reg].is_live_ = false;
854 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700855 break;
856
857 case DBG_RESTART_LOCAL:
858 reg = DecodeUnsignedLeb128(&stream);
859 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700860 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800861 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700862 return;
863 }
864
Elliott Hughes30646832011-10-13 16:59:46 -0700865 if (need_locals) {
866 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800867 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700868 return;
869 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700870
Elliott Hughes30646832011-10-13 16:59:46 -0700871 // If the register is live, the "restart" is superfluous,
872 // and we don't want to mess with the existing start address.
873 if (!local_in_reg[reg].is_live_) {
874 local_in_reg[reg].start_address_ = address;
875 local_in_reg[reg].is_live_ = true;
876 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700877 }
878 break;
879
880 case DBG_SET_PROLOGUE_END:
881 case DBG_SET_EPILOGUE_BEGIN:
882 case DBG_SET_FILE:
883 break;
884
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700885 default: {
886 int adjopcode = opcode - DBG_FIRST_SPECIAL;
887
Shih-wei Liao195487c2011-08-20 13:29:04 -0700888 address += adjopcode / DBG_LINE_RANGE;
889 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
890
Elliott Hughes2435a572012-02-17 16:07:41 -0800891 if (position_cb != NULL) {
892 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700893 // early exit
894 return;
895 }
896 }
897 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700898 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700899 }
900 }
901}
902
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800903void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800904 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
905 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100906 DCHECK(code_item != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -0700907 const byte* stream = GetDebugInfoStream(code_item);
Ian Rogers700a4022014-05-19 16:49:03 -0700908 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != NULL ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700909 new LocalInfo[code_item->registers_size_] :
910 NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700911 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700912 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700913 }
914 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700915 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700916 }
917}
918
Elliott Hughes2435a572012-02-17 16:07:41 -0800919bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
920 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700921
922 // We know that this callback will be called in
923 // ascending address order, so keep going until we find
924 // a match or we've just gone past it.
925 if (address > context->address_) {
926 // The line number from the previous positions callback
927 // wil be the final result.
928 return true;
929 } else {
930 context->line_num_ = line_num;
931 return address == context->address_;
932 }
933}
934
Andreas Gampe833a4852014-05-21 18:46:59 -0700935bool DexFile::IsMultiDexLocation(const char* location) {
936 return strrchr(location, kMultiDexSeparator) != nullptr;
937}
938
939std::pair<const char*, const char*> DexFile::SplitMultiDexLocation(
940 const char* location) {
941 const char* colon_ptr = strrchr(location, kMultiDexSeparator);
942
943 // Check it's synthetic.
944 CHECK_NE(colon_ptr, static_cast<const char*>(nullptr));
945
946 size_t colon_index = colon_ptr - location;
947 char* tmp = new char[colon_index + 1];
948 strncpy(tmp, location, colon_index);
949 tmp[colon_index] = 0;
950
951 return std::make_pair(tmp, colon_ptr + 1);
952}
953
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800954std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
955 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
956 dex_file.GetLocation().c_str(),
957 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
958 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
959 return os;
960}
Ian Rogersd91d6d62013-09-25 20:26:14 -0700961std::string Signature::ToString() const {
962 if (dex_file_ == nullptr) {
963 CHECK(proto_id_ == nullptr);
964 return "<no signature>";
965 }
966 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
967 std::string result;
968 if (params == nullptr) {
969 result += "()";
970 } else {
971 result += "(";
972 for (uint32_t i = 0; i < params->Size(); ++i) {
973 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
974 }
975 result += ")";
976 }
977 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
978 return result;
979}
980
Vladimir Markod9cffea2013-11-25 15:08:02 +0000981bool Signature::operator==(const StringPiece& rhs) const {
982 if (dex_file_ == nullptr) {
983 return false;
984 }
985 StringPiece tail(rhs);
986 if (!tail.starts_with("(")) {
987 return false; // Invalid signature
988 }
989 tail.remove_prefix(1); // "(";
990 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
991 if (params != nullptr) {
992 for (uint32_t i = 0; i < params->Size(); ++i) {
993 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
994 if (!tail.starts_with(param)) {
995 return false;
996 }
997 tail.remove_prefix(param.length());
998 }
999 }
1000 if (!tail.starts_with(")")) {
1001 return false;
1002 }
1003 tail.remove_prefix(1); // ")";
1004 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1005}
1006
Ian Rogersd91d6d62013-09-25 20:26:14 -07001007std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1008 return os << sig.ToString();
1009}
1010
Ian Rogers0571d352011-11-03 19:51:38 -07001011// Decodes the header section from the class data bytes.
1012void ClassDataItemIterator::ReadClassDataHeader() {
1013 CHECK(ptr_pos_ != NULL);
1014 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1015 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1016 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1017 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1018}
1019
1020void ClassDataItemIterator::ReadClassDataField() {
1021 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1022 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001023 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001024 LOG(WARNING) << "Duplicate field in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001025 }
Ian Rogers0571d352011-11-03 19:51:38 -07001026}
1027
1028void ClassDataItemIterator::ReadClassDataMethod() {
1029 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1030 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1031 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001032 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001033 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001034 }
Ian Rogers0571d352011-11-03 19:51:38 -07001035}
1036
1037// Read a signed integer. "zwidth" is the zero-based byte count.
1038static int32_t ReadSignedInt(const byte* ptr, int zwidth) {
1039 int32_t val = 0;
1040 for (int i = zwidth; i >= 0; --i) {
1041 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1042 }
1043 val >>= (3 - zwidth) * 8;
1044 return val;
1045}
1046
1047// Read an unsigned integer. "zwidth" is the zero-based byte count,
1048// "fill_on_right" indicates which side we want to zero-fill from.
1049static uint32_t ReadUnsignedInt(const byte* ptr, int zwidth, bool fill_on_right) {
1050 uint32_t val = 0;
1051 if (!fill_on_right) {
1052 for (int i = zwidth; i >= 0; --i) {
1053 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1054 }
1055 val >>= (3 - zwidth) * 8;
1056 } else {
1057 for (int i = zwidth; i >= 0; --i) {
1058 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1059 }
1060 }
1061 return val;
1062}
1063
1064// Read a signed long. "zwidth" is the zero-based byte count.
1065static int64_t ReadSignedLong(const byte* ptr, int zwidth) {
1066 int64_t val = 0;
1067 for (int i = zwidth; i >= 0; --i) {
1068 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1069 }
1070 val >>= (7 - zwidth) * 8;
1071 return val;
1072}
1073
1074// Read an unsigned long. "zwidth" is the zero-based byte count,
1075// "fill_on_right" indicates which side we want to zero-fill from.
1076static uint64_t ReadUnsignedLong(const byte* ptr, int zwidth, bool fill_on_right) {
1077 uint64_t val = 0;
1078 if (!fill_on_right) {
1079 for (int i = zwidth; i >= 0; --i) {
1080 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1081 }
1082 val >>= (7 - zwidth) * 8;
1083 } else {
1084 for (int i = zwidth; i >= 0; --i) {
1085 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1086 }
1087 }
1088 return val;
1089}
1090
1091EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001092 Handle<mirror::DexCache>* dex_cache,
1093 Handle<mirror::ClassLoader>* class_loader,
Ian Rogersca190662012-06-26 15:45:57 -07001094 ClassLinker* linker,
1095 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001096 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1097 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001098 DCHECK(dex_cache != nullptr);
1099 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001100 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
1101 if (ptr_ == NULL) {
1102 array_size_ = 0;
1103 } else {
1104 array_size_ = DecodeUnsignedLeb128(&ptr_);
1105 }
1106 if (array_size_ > 0) {
1107 Next();
1108 }
1109}
1110
1111void EncodedStaticFieldValueIterator::Next() {
1112 pos_++;
1113 if (pos_ >= array_size_) {
1114 return;
1115 }
1116 byte value_type = *ptr_++;
1117 byte value_arg = value_type >> kEncodedValueArgShift;
1118 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001119 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001120 switch (type_) {
1121 case kBoolean:
1122 jval_.i = (value_arg != 0) ? 1 : 0;
1123 width = 0;
1124 break;
1125 case kByte:
1126 jval_.i = ReadSignedInt(ptr_, value_arg);
1127 CHECK(IsInt(8, jval_.i));
1128 break;
1129 case kShort:
1130 jval_.i = ReadSignedInt(ptr_, value_arg);
1131 CHECK(IsInt(16, jval_.i));
1132 break;
1133 case kChar:
1134 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1135 CHECK(IsUint(16, jval_.i));
1136 break;
1137 case kInt:
1138 jval_.i = ReadSignedInt(ptr_, value_arg);
1139 break;
1140 case kLong:
1141 jval_.j = ReadSignedLong(ptr_, value_arg);
1142 break;
1143 case kFloat:
1144 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1145 break;
1146 case kDouble:
1147 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1148 break;
1149 case kString:
1150 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001151 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1152 break;
1153 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001154 case kMethod:
1155 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001156 case kArray:
1157 case kAnnotation:
1158 UNIMPLEMENTED(FATAL) << ": type " << type_;
1159 break;
1160 case kNull:
1161 jval_.l = NULL;
1162 width = 0;
1163 break;
1164 default:
1165 LOG(FATAL) << "Unreached";
1166 }
1167 ptr_ += width;
1168}
1169
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001170template<bool kTransactionActive>
Brian Carlstromea46f952013-07-30 01:26:50 -07001171void EncodedStaticFieldValueIterator::ReadValueToField(mirror::ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001172 switch (type_) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001173 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z); break;
1174 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1175 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1176 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1177 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1178 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1179 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1180 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
1181 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), NULL); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001182 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 CHECK(!kMovingFields);
1184 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001185 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001186 break;
1187 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001188 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001189 CHECK(!kMovingFields);
1190 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1191 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001192 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001193 break;
1194 }
Ian Rogers0571d352011-11-03 19:51:38 -07001195 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1196 }
1197}
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001198template void EncodedStaticFieldValueIterator::ReadValueToField<true>(mirror::ArtField* field) const;
1199template void EncodedStaticFieldValueIterator::ReadValueToField<false>(mirror::ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001200
1201CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1202 handler_.address_ = -1;
1203 int32_t offset = -1;
1204
1205 // Short-circuit the overwhelmingly common cases.
1206 switch (code_item.tries_size_) {
1207 case 0:
1208 break;
1209 case 1: {
1210 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1211 uint32_t start = tries->start_addr_;
1212 if (address >= start) {
1213 uint32_t end = start + tries->insn_count_;
1214 if (address < end) {
1215 offset = tries->handler_off_;
1216 }
1217 }
1218 break;
1219 }
1220 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001221 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001222 }
Logan Chien736df022012-04-27 16:25:57 +08001223 Init(code_item, offset);
1224}
1225
1226CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1227 const DexFile::TryItem& try_item) {
1228 handler_.address_ = -1;
1229 Init(code_item, try_item.handler_off_);
1230}
1231
1232void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1233 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001234 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001235 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001236 } else {
1237 // Not found, initialize as empty
1238 current_data_ = NULL;
1239 remaining_count_ = -1;
1240 catch_all_ = false;
1241 DCHECK(!HasNext());
1242 }
1243}
1244
1245void CatchHandlerIterator::Init(const byte* handler_data) {
1246 current_data_ = handler_data;
1247 remaining_count_ = DecodeSignedLeb128(&current_data_);
1248
1249 // If remaining_count_ is non-positive, then it is the negative of
1250 // the number of catch types, and the catches are followed by a
1251 // catch-all handler.
1252 if (remaining_count_ <= 0) {
1253 catch_all_ = true;
1254 remaining_count_ = -remaining_count_;
1255 } else {
1256 catch_all_ = false;
1257 }
1258 Next();
1259}
1260
1261void CatchHandlerIterator::Next() {
1262 if (remaining_count_ > 0) {
1263 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1264 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1265 remaining_count_--;
1266 return;
1267 }
1268
1269 if (catch_all_) {
1270 handler_.type_idx_ = DexFile::kDexNoIndex16;
1271 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1272 catch_all_ = false;
1273 return;
1274 }
1275
1276 // no more handler
1277 remaining_count_ = -1;
1278}
1279
Carl Shapiro1fb86202011-06-27 17:43:13 -07001280} // namespace art