blob: 8685d8e73c1de9d69653502b9f5e317c24fc5052 [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 Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Elliott Hughes07ed66b2012-12-12 18:34:25 -080030#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080031#include "base/stringprintf.h"
Ian Rogers0571d352011-11-03 19:51:38 -070032#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080034#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070036#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070037#include "mirror/art_field-inl.h"
38#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070040#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070041#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070043#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070044#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070045#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070046#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070047#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070048
Andreas Gampe277ccbd2014-11-03 21:36:10 -080049#pragma GCC diagnostic push
50#pragma GCC diagnostic ignored "-Wshadow"
51#include "ScopedFd.h"
52#pragma GCC diagnostic pop
53
Carl Shapiro1fb86202011-06-27 17:43:13 -070054namespace art {
55
Ian Rogers13735952014-10-08 12:43:28 -070056const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
57const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070058
Ian Rogers8d31bbd2013-10-13 10:44:14 -070059static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070060 CHECK(magic != NULL);
Vladimir Markofd995762013-11-06 16:36:36 +000061 ScopedFd fd(open(filename, O_RDONLY, 0));
62 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070063 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070064 return -1;
65 }
Vladimir Markofd995762013-11-06 16:36:36 +000066 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070067 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070068 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070069 return -1;
70 }
Vladimir Markofd995762013-11-06 16:36:36 +000071 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
73 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 return -1;
75 }
Vladimir Markofd995762013-11-06 16:36:36 +000076 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070077}
78
Ian Rogers8d31bbd2013-10-13 10:44:14 -070079bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070080 CHECK(checksum != NULL);
81 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070082
83 // Strip ":...", which is the location
84 const char* zip_entry_name = kClassesDex;
85 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010086 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070087
Vladimir Markoaa4497d2014-09-05 14:01:17 +010088 if (DexFile::IsMultiDexLocation(filename)) {
89 file_part_storage = GetBaseLocation(filename);
90 file_part = file_part_storage.c_str();
91 zip_entry_name = filename + file_part_storage.size() + 1;
92 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070093 }
94
95 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000096 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070097 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070098 return false;
99 }
100 if (IsZipMagic(magic)) {
Ian Rogers700a4022014-05-19 16:49:03 -0700101 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 if (zip_archive.get() == NULL) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800103 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
104 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700106 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700107 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700109 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
110 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return false;
112 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700113 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700115 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700116 if (IsDexMagic(magic)) {
Ian Rogers700a4022014-05-19 16:49:03 -0700117 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), filename, false, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 if (dex_file.get() == NULL) {
119 return false;
120 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700121 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800122 return true;
123 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700124 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800125 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700126}
127
Andreas Gampe833a4852014-05-21 18:46:59 -0700128bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800129 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
130 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is NULL";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700131 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000132 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
133 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700134 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700135 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700136 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700137 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700138 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700139 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700140 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
142 error_msg));
143 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800144 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700145 return true;
146 } else {
147 return false;
148 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700149 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400151 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700152}
153
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800154int DexFile::GetPermissions() const {
155 if (mem_map_.get() == NULL) {
156 return 0;
157 } else {
158 return mem_map_->GetProtect();
159 }
160}
161
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200162bool DexFile::IsReadOnly() const {
163 return GetPermissions() == PROT_READ;
164}
165
Brian Carlstrome0948e12013-08-29 09:36:15 -0700166bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200167 CHECK(IsReadOnly());
168 if (mem_map_.get() == NULL) {
169 return false;
170 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700171 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200172 }
173}
174
Brian Carlstrome0948e12013-08-29 09:36:15 -0700175bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200176 CHECK(!IsReadOnly());
177 if (mem_map_.get() == NULL) {
178 return false;
179 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700180 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200181 }
182}
183
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800184std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
185 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700186 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700187 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000188 {
189 ScopedFd delayed_close(fd);
190 struct stat sbuf;
191 memset(&sbuf, 0, sizeof(sbuf));
192 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800193 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000194 return nullptr;
195 }
196 if (S_ISDIR(sbuf.st_mode)) {
197 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
198 return nullptr;
199 }
200 size_t length = sbuf.st_size;
201 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
202 if (map.get() == nullptr) {
203 DCHECK(!error_msg->empty());
204 return nullptr;
205 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700206 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800207
208 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700209 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800210 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700211 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800212 }
213
214 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
215
Andreas Gampe928f72b2014-09-09 19:53:48 -0700216 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
217 error_msg));
218 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700219 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
220 error_msg->c_str());
221 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800222 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800223
Andreas Gampe928f72b2014-09-09 19:53:48 -0700224 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
225 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700226 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800227 }
228
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800229 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700230}
231
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700232const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700233
Andreas Gampe833a4852014-05-21 18:46:59 -0700234bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800235 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
236 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is NULL";
Ian Rogers700a4022014-05-19 16:49:03 -0700237 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700238 if (zip_archive.get() == nullptr) {
239 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700240 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700241 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700242 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800243}
244
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800245std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
246 uint32_t location_checksum,
247 MemMap* mem_map,
248 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800249 return OpenMemory(mem_map->Begin(),
250 mem_map->Size(),
251 location,
252 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700253 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800254 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700255 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800256}
257
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800258std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
259 const std::string& location, std::string* error_msg,
260 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800261 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700262 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Elliott Hughes90a33692011-08-30 13:27:07 -0700263 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700264 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700266 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700267 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Brian Carlstrom89521892011-12-07 22:05:07 -0800268 if (map.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700269 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700271 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700273 }
Ian Rogers700a4022014-05-19 16:49:03 -0700274 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700275 error_msg));
276 if (dex_file.get() == nullptr) {
277 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
278 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700279 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800281 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700282 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700284 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700285 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700286 }
287 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700288 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
289 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700290 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700291 return nullptr;
292 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700293 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800294 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700295}
296
Andreas Gampe833a4852014-05-21 18:46:59 -0700297bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800298 std::string* error_msg,
299 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
300 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is NULL";
Andreas Gampe833a4852014-05-21 18:46:59 -0700301 ZipOpenErrorCode error_code;
302 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
303 &error_code));
304 if (dex_file.get() == nullptr) {
305 return false;
306 } else {
307 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800308 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700309
310 // Now try some more.
311 size_t i = 2;
312
313 // We could try to avoid std::string allocations by working on a char array directly. As we
314 // do not expect a lot of iterations, this seems too involved and brittle.
315
316 while (i < 100) {
317 std::string name = StringPrintf("classes%zu.dex", i);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100318 std::string fake_location = location + kMultiDexSeparator + name;
Andreas Gampe833a4852014-05-21 18:46:59 -0700319 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
320 error_msg, &error_code));
321 if (next_dex_file.get() == nullptr) {
322 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
323 LOG(WARNING) << error_msg;
324 }
325 break;
326 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800327 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700328 }
329
330 i++;
331 }
332
333 return true;
334 }
335}
336
337
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800338std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
339 size_t size,
340 const std::string& location,
341 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800342 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700343 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800344 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700345 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800346 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700347 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700348 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800349 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700350 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800351 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700352}
353
Ian Rogers13735952014-10-08 12:43:28 -0700354DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800355 const std::string& location,
356 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800357 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700358 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800359 : begin_(base),
360 size_(size),
361 location_(location),
362 location_checksum_(location_checksum),
363 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800364 header_(reinterpret_cast<const Header*>(base)),
365 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
366 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
367 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
368 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
369 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700370 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
371 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800372 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700373 oat_dex_file_(oat_dex_file) {
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800374 CHECK(begin_ != NULL) << GetLocation();
375 CHECK_GT(size_, 0U) << GetLocation();
376}
377
Jesse Wilson6bf19152011-09-29 13:12:33 -0400378DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700379 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
380 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
381 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
382 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700383 // Remove the index if one were created.
384 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400385}
386
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700387bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700389 return false;
390 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700391 return true;
392}
393
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800395 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700396 std::ostringstream oss;
397 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800398 << " " << header_->magic_[0]
399 << " " << header_->magic_[1]
400 << " " << header_->magic_[2]
401 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700402 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700403 return false;
404 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800405 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700406 std::ostringstream oss;
407 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800408 << " " << header_->magic_[4]
409 << " " << header_->magic_[5]
410 << " " << header_->magic_[6]
411 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700412 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700413 return false;
414 }
415 return true;
416}
417
Ian Rogers13735952014-10-08 12:43:28 -0700418bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800419 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
420}
421
Ian Rogers13735952014-10-08 12:43:28 -0700422bool DexFile::IsVersionValid(const uint8_t* magic) {
423 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800424 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
425}
426
Ian Rogersd81871c2011-10-03 13:57:23 -0700427uint32_t DexFile::GetVersion() const {
428 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
429 return atoi(version);
430}
431
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800432const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
433 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700434 // If we have an index lookup the descriptor via that as its constant time to search.
435 Index* index = class_def_index_.LoadSequentiallyConsistent();
436 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800437 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700438 return (it == index->end()) ? nullptr : it->second;
439 }
440 // Fast path for rate no class defs case.
441 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700442 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700443 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700444 }
Ian Rogers68b56852014-08-29 20:19:11 -0700445 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700446 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700447 if (string_id != nullptr) {
448 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
449 if (type_id != nullptr) {
450 uint16_t type_idx = GetIndexForTypeId(*type_id);
451 for (size_t i = 0; i < num_class_defs; ++i) {
452 const ClassDef& class_def = GetClassDef(i);
453 if (class_def.class_idx_ == type_idx) {
454 return &class_def;
455 }
456 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700457 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700458 }
Ian Rogers68b56852014-08-29 20:19:11 -0700459 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
460 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
461 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
462 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700463 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700464 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
465 if (old_misses == kMaxFailedDexClassDefLookups) {
466 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
467 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
468 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800469 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700470 for (uint32_t i = 0; i < num_class_defs; ++i) {
471 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800472 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800473 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700474 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700475 // Sanity check the index still doesn't exist, only 1 thread should build it.
476 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
477 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700478 }
479 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700480}
481
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700482const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
483 size_t num_class_defs = NumClassDefs();
484 for (size_t i = 0; i < num_class_defs; ++i) {
485 const ClassDef& class_def = GetClassDef(i);
486 if (class_def.class_idx_ == type_idx) {
487 return &class_def;
488 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700489 }
490 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700491}
492
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800493const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
494 const DexFile::StringId& name,
495 const DexFile::TypeId& type) const {
496 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
497 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
498 const uint32_t name_idx = GetIndexForStringId(name);
499 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700500 int32_t lo = 0;
501 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800502 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700503 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800504 const DexFile::FieldId& field = GetFieldId(mid);
505 if (class_idx > field.class_idx_) {
506 lo = mid + 1;
507 } else if (class_idx < field.class_idx_) {
508 hi = mid - 1;
509 } else {
510 if (name_idx > field.name_idx_) {
511 lo = mid + 1;
512 } else if (name_idx < field.name_idx_) {
513 hi = mid - 1;
514 } else {
515 if (type_idx > field.type_idx_) {
516 lo = mid + 1;
517 } else if (type_idx < field.type_idx_) {
518 hi = mid - 1;
519 } else {
520 return &field;
521 }
522 }
523 }
524 }
525 return NULL;
526}
527
528const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700529 const DexFile::StringId& name,
530 const DexFile::ProtoId& signature) const {
531 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800532 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700533 const uint32_t name_idx = GetIndexForStringId(name);
534 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700535 int32_t lo = 0;
536 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700537 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700538 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700539 const DexFile::MethodId& method = GetMethodId(mid);
540 if (class_idx > method.class_idx_) {
541 lo = mid + 1;
542 } else if (class_idx < method.class_idx_) {
543 hi = mid - 1;
544 } else {
545 if (name_idx > method.name_idx_) {
546 lo = mid + 1;
547 } else if (name_idx < method.name_idx_) {
548 hi = mid - 1;
549 } else {
550 if (proto_idx > method.proto_idx_) {
551 lo = mid + 1;
552 } else if (proto_idx < method.proto_idx_) {
553 hi = mid - 1;
554 } else {
555 return &method;
556 }
557 }
558 }
559 }
560 return NULL;
561}
562
Ian Rogers637c65b2013-05-31 11:46:00 -0700563const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700564 int32_t lo = 0;
565 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700566 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700567 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700568 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700569 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700570 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
571 if (compare > 0) {
572 lo = mid + 1;
573 } else if (compare < 0) {
574 hi = mid - 1;
575 } else {
576 return &str_id;
577 }
578 }
579 return NULL;
580}
581
Vladimir Markoa48aef42014-12-03 17:53:53 +0000582const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700583 int32_t lo = 0;
584 int32_t hi = NumStringIds() - 1;
585 while (hi >= lo) {
586 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700587 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700588 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000589 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700590 if (compare > 0) {
591 lo = mid + 1;
592 } else if (compare < 0) {
593 hi = mid - 1;
594 } else {
595 return &str_id;
596 }
597 }
598 return NULL;
599}
600
601const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700602 int32_t lo = 0;
603 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700604 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700605 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700606 const TypeId& type_id = GetTypeId(mid);
607 if (string_idx > type_id.descriptor_idx_) {
608 lo = mid + 1;
609 } else if (string_idx < type_id.descriptor_idx_) {
610 hi = mid - 1;
611 } else {
612 return &type_id;
613 }
614 }
615 return NULL;
616}
617
618const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000619 const uint16_t* signature_type_idxs,
620 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700621 int32_t lo = 0;
622 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700623 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700624 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700625 const DexFile::ProtoId& proto = GetProtoId(mid);
626 int compare = return_type_idx - proto.return_type_idx_;
627 if (compare == 0) {
628 DexFileParameterIterator it(*this, proto);
629 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000630 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800631 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700632 it.Next();
633 i++;
634 }
635 if (compare == 0) {
636 if (it.HasNext()) {
637 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000638 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700639 compare = 1;
640 }
641 }
642 }
643 if (compare > 0) {
644 lo = mid + 1;
645 } else if (compare < 0) {
646 hi = mid - 1;
647 } else {
648 return &proto;
649 }
650 }
651 return NULL;
652}
653
654// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700655bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
656 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700657 if (signature[0] != '(') {
658 return false;
659 }
660 size_t offset = 1;
661 size_t end = signature.size();
662 bool process_return = false;
663 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000664 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700665 char c = signature[offset];
666 offset++;
667 if (c == ')') {
668 process_return = true;
669 continue;
670 }
Ian Rogers0571d352011-11-03 19:51:38 -0700671 while (c == '[') { // process array prefix
672 if (offset >= end) { // expect some descriptor following [
673 return false;
674 }
675 c = signature[offset];
676 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700677 }
678 if (c == 'L') { // process type descriptors
679 do {
680 if (offset >= end) { // unexpected early termination of descriptor
681 return false;
682 }
683 c = signature[offset];
684 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700685 } while (c != ';');
686 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000687 // TODO: avoid creating a std::string just to get a 0-terminated char array
688 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700689 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700690 if (string_id == NULL) {
691 return false;
692 }
693 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
694 if (type_id == NULL) {
695 return false;
696 }
697 uint16_t type_idx = GetIndexForTypeId(*type_id);
698 if (!process_return) {
699 param_type_idxs->push_back(type_idx);
700 } else {
701 *return_type_idx = type_idx;
702 return offset == end; // return true if the signature had reached a sensible end
703 }
704 }
705 return false; // failed to correctly parse return type
706}
707
Ian Rogersd91d6d62013-09-25 20:26:14 -0700708const Signature DexFile::CreateSignature(const StringPiece& signature) const {
709 uint16_t return_type_idx;
710 std::vector<uint16_t> param_type_indices;
711 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
712 if (!success) {
713 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700714 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700715 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
716 if (proto_id == NULL) {
717 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700718 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700719 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700720}
721
Ian Rogersef7d42f2014-01-06 12:55:46 -0800722int32_t DexFile::GetLineNumFromPC(mirror::ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700723 // For native method, lineno should be -2 to indicate it is native. Note that
724 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700725 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700726 return -2;
727 }
728
TDYa127c8dc1012012-04-19 07:03:33 -0700729 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Elliott Hughescaf76542012-06-28 16:08:22 -0700730 DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700731
732 // A method with no line number info should return -1
733 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700734 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800735 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700736 return context.line_num_;
737}
738
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700739int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700740 // Note: Signed type is important for max and min.
741 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700742 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700743
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700744 while (min <= max) {
745 int32_t mid = min + ((max - min) / 2);
746
747 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
748 uint32_t start = ti->start_addr_;
749 uint32_t end = start + ti->insn_count_;
750
Ian Rogers0571d352011-11-03 19:51:38 -0700751 if (address < start) {
752 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700753 } else if (address >= end) {
754 min = mid + 1;
755 } else { // We have a winner!
756 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700757 }
758 }
759 // No match.
760 return -1;
761}
762
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700763int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
764 int32_t try_item = FindTryItem(code_item, address);
765 if (try_item == -1) {
766 return -1;
767 } else {
768 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
769 }
770}
771
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800772void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800773 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Ian Rogers13735952014-10-08 12:43:28 -0700774 void* context, const uint8_t* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700775 uint32_t line = DecodeUnsignedLeb128(&stream);
776 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
777 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
778 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700779 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700780
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800781 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700782 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800783 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700784 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800785 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800786 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700787 local_in_reg[arg_reg].start_address_ = 0;
788 local_in_reg[arg_reg].is_live_ = true;
789 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700790 arg_reg++;
791 }
792
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800793 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700794 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700795 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700796 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800797 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700798 return;
799 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800800 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700801 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800802 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700803 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700804 local_in_reg[arg_reg].name_ = name;
805 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800806 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700807 local_in_reg[arg_reg].start_address_ = address;
808 local_in_reg[arg_reg].is_live_ = true;
809 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700810 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700811 case 'D':
812 case 'J':
813 arg_reg += 2;
814 break;
815 default:
816 arg_reg += 1;
817 break;
818 }
819 }
820
Ian Rogers0571d352011-11-03 19:51:38 -0700821 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800822 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
823 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700824 return;
825 }
826
827 for (;;) {
828 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700829 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800830 uint32_t name_idx;
831 uint32_t descriptor_idx;
832 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700833
Shih-wei Liao195487c2011-08-20 13:29:04 -0700834 switch (opcode) {
835 case DBG_END_SEQUENCE:
836 return;
837
838 case DBG_ADVANCE_PC:
839 address += DecodeUnsignedLeb128(&stream);
840 break;
841
842 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700843 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700844 break;
845
846 case DBG_START_LOCAL:
847 case DBG_START_LOCAL_EXTENDED:
848 reg = DecodeUnsignedLeb128(&stream);
849 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700850 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800851 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700852 return;
853 }
854
jeffhaof8728872011-10-28 19:11:13 -0700855 name_idx = DecodeUnsignedLeb128P1(&stream);
856 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
857 if (opcode == DBG_START_LOCAL_EXTENDED) {
858 signature_idx = DecodeUnsignedLeb128P1(&stream);
859 }
860
Shih-wei Liao195487c2011-08-20 13:29:04 -0700861 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700862 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800863 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700864
Ian Rogers0571d352011-11-03 19:51:38 -0700865 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
866 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700867 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700868 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700869 }
870 local_in_reg[reg].start_address_ = address;
871 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700872 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700873 break;
874
875 case DBG_END_LOCAL:
876 reg = DecodeUnsignedLeb128(&stream);
877 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700878 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800879 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 return;
881 }
882
Elliott Hughes30646832011-10-13 16:59:46 -0700883 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800884 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700885 local_in_reg[reg].is_live_ = false;
886 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 break;
888
889 case DBG_RESTART_LOCAL:
890 reg = DecodeUnsignedLeb128(&stream);
891 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700892 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800893 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700894 return;
895 }
896
Elliott Hughes30646832011-10-13 16:59:46 -0700897 if (need_locals) {
898 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800899 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700900 return;
901 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700902
Elliott Hughes30646832011-10-13 16:59:46 -0700903 // If the register is live, the "restart" is superfluous,
904 // and we don't want to mess with the existing start address.
905 if (!local_in_reg[reg].is_live_) {
906 local_in_reg[reg].start_address_ = address;
907 local_in_reg[reg].is_live_ = true;
908 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700909 }
910 break;
911
912 case DBG_SET_PROLOGUE_END:
913 case DBG_SET_EPILOGUE_BEGIN:
914 case DBG_SET_FILE:
915 break;
916
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700917 default: {
918 int adjopcode = opcode - DBG_FIRST_SPECIAL;
919
Shih-wei Liao195487c2011-08-20 13:29:04 -0700920 address += adjopcode / DBG_LINE_RANGE;
921 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
922
Elliott Hughes2435a572012-02-17 16:07:41 -0800923 if (position_cb != NULL) {
924 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 // early exit
926 return;
927 }
928 }
929 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700930 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700931 }
932 }
933}
934
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800935void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800936 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
937 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100938 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700939 const uint8_t* stream = GetDebugInfoStream(code_item);
Ian Rogers700a4022014-05-19 16:49:03 -0700940 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != NULL ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700941 new LocalInfo[code_item->registers_size_] :
942 NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700943 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700944 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700945 }
946 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700947 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700948 }
949}
950
Elliott Hughes2435a572012-02-17 16:07:41 -0800951bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
952 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700953
954 // We know that this callback will be called in
955 // ascending address order, so keep going until we find
956 // a match or we've just gone past it.
957 if (address > context->address_) {
958 // The line number from the previous positions callback
959 // wil be the final result.
960 return true;
961 } else {
962 context->line_num_ = line_num;
963 return address == context->address_;
964 }
965}
966
Andreas Gampe833a4852014-05-21 18:46:59 -0700967bool DexFile::IsMultiDexLocation(const char* location) {
968 return strrchr(location, kMultiDexSeparator) != nullptr;
969}
970
Calin Juravle4e1d5792014-07-15 23:56:47 +0100971std::string DexFile::GetMultiDexClassesDexName(size_t number, const char* dex_location) {
972 if (number == 0) {
973 return dex_location;
974 } else {
975 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, number + 1);
976 }
977}
978
979std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
980 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100981 std::string base_location = GetBaseLocation(dex_location);
982 const char* suffix = dex_location + base_location.size();
983 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
984 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
985 if (path != nullptr && path.get() != base_location) {
986 return std::string(path.get()) + suffix;
987 } else if (suffix[0] == 0) {
988 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +0100989 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100990 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +0100991 }
Calin Juravle4e1d5792014-07-15 23:56:47 +0100992}
993
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800994std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
995 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
996 dex_file.GetLocation().c_str(),
997 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
998 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
999 return os;
1000}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001001
Ian Rogersd91d6d62013-09-25 20:26:14 -07001002std::string Signature::ToString() const {
1003 if (dex_file_ == nullptr) {
1004 CHECK(proto_id_ == nullptr);
1005 return "<no signature>";
1006 }
1007 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1008 std::string result;
1009 if (params == nullptr) {
1010 result += "()";
1011 } else {
1012 result += "(";
1013 for (uint32_t i = 0; i < params->Size(); ++i) {
1014 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1015 }
1016 result += ")";
1017 }
1018 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1019 return result;
1020}
1021
Vladimir Markod9cffea2013-11-25 15:08:02 +00001022bool Signature::operator==(const StringPiece& rhs) const {
1023 if (dex_file_ == nullptr) {
1024 return false;
1025 }
1026 StringPiece tail(rhs);
1027 if (!tail.starts_with("(")) {
1028 return false; // Invalid signature
1029 }
1030 tail.remove_prefix(1); // "(";
1031 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1032 if (params != nullptr) {
1033 for (uint32_t i = 0; i < params->Size(); ++i) {
1034 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1035 if (!tail.starts_with(param)) {
1036 return false;
1037 }
1038 tail.remove_prefix(param.length());
1039 }
1040 }
1041 if (!tail.starts_with(")")) {
1042 return false;
1043 }
1044 tail.remove_prefix(1); // ")";
1045 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1046}
1047
Ian Rogersd91d6d62013-09-25 20:26:14 -07001048std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1049 return os << sig.ToString();
1050}
1051
Ian Rogers0571d352011-11-03 19:51:38 -07001052// Decodes the header section from the class data bytes.
1053void ClassDataItemIterator::ReadClassDataHeader() {
1054 CHECK(ptr_pos_ != NULL);
1055 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1056 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1057 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1058 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1059}
1060
1061void ClassDataItemIterator::ReadClassDataField() {
1062 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1063 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001064 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001065 LOG(WARNING) << "Duplicate field in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001066 }
Ian Rogers0571d352011-11-03 19:51:38 -07001067}
1068
1069void ClassDataItemIterator::ReadClassDataMethod() {
1070 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1071 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1072 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001073 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001074 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001075 }
Ian Rogers0571d352011-11-03 19:51:38 -07001076}
1077
1078// Read a signed integer. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001079static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001080 int32_t val = 0;
1081 for (int i = zwidth; i >= 0; --i) {
1082 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1083 }
1084 val >>= (3 - zwidth) * 8;
1085 return val;
1086}
1087
1088// Read an unsigned integer. "zwidth" is the zero-based byte count,
1089// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001090static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001091 uint32_t val = 0;
1092 if (!fill_on_right) {
1093 for (int i = zwidth; i >= 0; --i) {
1094 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1095 }
1096 val >>= (3 - zwidth) * 8;
1097 } else {
1098 for (int i = zwidth; i >= 0; --i) {
1099 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1100 }
1101 }
1102 return val;
1103}
1104
1105// Read a signed long. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001106static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001107 int64_t val = 0;
1108 for (int i = zwidth; i >= 0; --i) {
1109 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1110 }
1111 val >>= (7 - zwidth) * 8;
1112 return val;
1113}
1114
1115// Read an unsigned long. "zwidth" is the zero-based byte count,
1116// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001117static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001118 uint64_t val = 0;
1119 if (!fill_on_right) {
1120 for (int i = zwidth; i >= 0; --i) {
1121 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1122 }
1123 val >>= (7 - zwidth) * 8;
1124 } else {
1125 for (int i = zwidth; i >= 0; --i) {
1126 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1127 }
1128 }
1129 return val;
1130}
1131
1132EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001133 Handle<mirror::DexCache>* dex_cache,
1134 Handle<mirror::ClassLoader>* class_loader,
Ian Rogersca190662012-06-26 15:45:57 -07001135 ClassLinker* linker,
1136 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001137 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1138 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001139 DCHECK(dex_cache != nullptr);
1140 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001141 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
1142 if (ptr_ == NULL) {
1143 array_size_ = 0;
1144 } else {
1145 array_size_ = DecodeUnsignedLeb128(&ptr_);
1146 }
1147 if (array_size_ > 0) {
1148 Next();
1149 }
1150}
1151
1152void EncodedStaticFieldValueIterator::Next() {
1153 pos_++;
1154 if (pos_ >= array_size_) {
1155 return;
1156 }
Ian Rogers13735952014-10-08 12:43:28 -07001157 uint8_t value_type = *ptr_++;
1158 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001159 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001160 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001161 switch (type_) {
1162 case kBoolean:
1163 jval_.i = (value_arg != 0) ? 1 : 0;
1164 width = 0;
1165 break;
1166 case kByte:
1167 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001168 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001169 break;
1170 case kShort:
1171 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001172 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001173 break;
1174 case kChar:
1175 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001176 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001177 break;
1178 case kInt:
1179 jval_.i = ReadSignedInt(ptr_, value_arg);
1180 break;
1181 case kLong:
1182 jval_.j = ReadSignedLong(ptr_, value_arg);
1183 break;
1184 case kFloat:
1185 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1186 break;
1187 case kDouble:
1188 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1189 break;
1190 case kString:
1191 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001192 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1193 break;
1194 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001195 case kMethod:
1196 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001197 case kArray:
1198 case kAnnotation:
1199 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001200 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001201 case kNull:
1202 jval_.l = NULL;
1203 width = 0;
1204 break;
1205 default:
1206 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001207 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001208 }
1209 ptr_ += width;
1210}
1211
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001212template<bool kTransactionActive>
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07001213void EncodedStaticFieldValueIterator::ReadValueToField(Handle<mirror::ArtField> field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001214 switch (type_) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001215 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z); break;
1216 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1217 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1218 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1219 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1220 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1221 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1222 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
1223 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), NULL); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001224 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001225 CHECK(!kMovingFields);
1226 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001227 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001228 break;
1229 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001230 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001231 CHECK(!kMovingFields);
1232 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1233 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001234 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001235 break;
1236 }
Ian Rogers0571d352011-11-03 19:51:38 -07001237 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1238 }
1239}
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07001240template void EncodedStaticFieldValueIterator::ReadValueToField<true>(Handle<mirror::ArtField> field) const;
1241template void EncodedStaticFieldValueIterator::ReadValueToField<false>(Handle<mirror::ArtField> field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001242
1243CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1244 handler_.address_ = -1;
1245 int32_t offset = -1;
1246
1247 // Short-circuit the overwhelmingly common cases.
1248 switch (code_item.tries_size_) {
1249 case 0:
1250 break;
1251 case 1: {
1252 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1253 uint32_t start = tries->start_addr_;
1254 if (address >= start) {
1255 uint32_t end = start + tries->insn_count_;
1256 if (address < end) {
1257 offset = tries->handler_off_;
1258 }
1259 }
1260 break;
1261 }
1262 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001263 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001264 }
Logan Chien736df022012-04-27 16:25:57 +08001265 Init(code_item, offset);
1266}
1267
1268CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1269 const DexFile::TryItem& try_item) {
1270 handler_.address_ = -1;
1271 Init(code_item, try_item.handler_off_);
1272}
1273
1274void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1275 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001276 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001277 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001278 } else {
1279 // Not found, initialize as empty
1280 current_data_ = NULL;
1281 remaining_count_ = -1;
1282 catch_all_ = false;
1283 DCHECK(!HasNext());
1284 }
1285}
1286
Ian Rogers13735952014-10-08 12:43:28 -07001287void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001288 current_data_ = handler_data;
1289 remaining_count_ = DecodeSignedLeb128(&current_data_);
1290
1291 // If remaining_count_ is non-positive, then it is the negative of
1292 // the number of catch types, and the catches are followed by a
1293 // catch-all handler.
1294 if (remaining_count_ <= 0) {
1295 catch_all_ = true;
1296 remaining_count_ = -remaining_count_;
1297 } else {
1298 catch_all_ = false;
1299 }
1300 Next();
1301}
1302
1303void CatchHandlerIterator::Next() {
1304 if (remaining_count_ > 0) {
1305 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1306 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1307 remaining_count_--;
1308 return;
1309 }
1310
1311 if (catch_all_) {
1312 handler_.type_idx_ = DexFile::kDexNoIndex16;
1313 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1314 catch_all_ = false;
1315 return;
1316 }
1317
1318 // no more handler
1319 remaining_count_ = -1;
1320}
1321
Carl Shapiro1fb86202011-06-27 17:43:13 -07001322} // namespace art