blob: 3f6175f663fed8c4563a6b1bd5e9aaf811b32048 [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 Gampe833a4852014-05-21 18:46:59 -0700103 *error_msg = StringPrintf("Failed to open zip archive '%s'", file_part);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800104 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700105 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700106 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800107 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700108 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
109 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return false;
111 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700112 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700114 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700115 if (IsDexMagic(magic)) {
Ian Rogers700a4022014-05-19 16:49:03 -0700116 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), filename, false, error_msg));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 if (dex_file.get() == NULL) {
118 return false;
119 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700120 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return true;
122 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700123 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800124 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700125}
126
Andreas Gampe833a4852014-05-21 18:46:59 -0700127bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800128 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
129 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is NULL";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700130 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000131 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
132 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700133 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700137 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700138 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700140 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
141 error_msg));
142 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800143 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 return true;
145 } else {
146 return false;
147 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700148 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700149 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400150 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151}
152
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800153int DexFile::GetPermissions() const {
154 if (mem_map_.get() == NULL) {
155 return 0;
156 } else {
157 return mem_map_->GetProtect();
158 }
159}
160
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200161bool DexFile::IsReadOnly() const {
162 return GetPermissions() == PROT_READ;
163}
164
Brian Carlstrome0948e12013-08-29 09:36:15 -0700165bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200166 CHECK(IsReadOnly());
167 if (mem_map_.get() == NULL) {
168 return false;
169 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700170 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200171 }
172}
173
Brian Carlstrome0948e12013-08-29 09:36:15 -0700174bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200175 CHECK(!IsReadOnly());
176 if (mem_map_.get() == NULL) {
177 return false;
178 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700179 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200180 }
181}
182
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800183std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
184 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700185 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700186 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000187 {
188 ScopedFd delayed_close(fd);
189 struct stat sbuf;
190 memset(&sbuf, 0, sizeof(sbuf));
191 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800192 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000193 return nullptr;
194 }
195 if (S_ISDIR(sbuf.st_mode)) {
196 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
197 return nullptr;
198 }
199 size_t length = sbuf.st_size;
200 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
201 if (map.get() == nullptr) {
202 DCHECK(!error_msg->empty());
203 return nullptr;
204 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700205 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800206
207 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700208 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800209 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700210 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800211 }
212
213 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
214
Andreas Gampe928f72b2014-09-09 19:53:48 -0700215 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
216 error_msg));
217 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700218 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
219 error_msg->c_str());
220 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800221 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800222
Andreas Gampe928f72b2014-09-09 19:53:48 -0700223 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
224 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700225 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800226 }
227
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800228 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700229}
230
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700231const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700232
Andreas Gampe833a4852014-05-21 18:46:59 -0700233bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800234 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
235 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is NULL";
Ian Rogers700a4022014-05-19 16:49:03 -0700236 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700237 if (zip_archive.get() == nullptr) {
238 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700239 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700240 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700241 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800242}
243
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800244std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
245 uint32_t location_checksum,
246 MemMap* mem_map,
247 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800248 return OpenMemory(mem_map->Begin(),
249 mem_map->Size(),
250 location,
251 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700252 mem_map,
253 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800254}
255
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800256std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
257 const std::string& location, std::string* error_msg,
258 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800259 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700260 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Elliott Hughes90a33692011-08-30 13:27:07 -0700261 if (zip_entry.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700262 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700263 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700265 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Brian Carlstrom89521892011-12-07 22:05:07 -0800266 if (map.get() == NULL) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700267 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700268 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700269 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700271 }
Ian Rogers700a4022014-05-19 16:49:03 -0700272 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700273 error_msg));
274 if (dex_file.get() == nullptr) {
275 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
276 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700277 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700278 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800279 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700280 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700281 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700282 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700284 }
285 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700286 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
287 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700288 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700289 return nullptr;
290 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700291 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800292 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700293}
294
Andreas Gampe833a4852014-05-21 18:46:59 -0700295bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800296 std::string* error_msg,
297 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
298 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is NULL";
Andreas Gampe833a4852014-05-21 18:46:59 -0700299 ZipOpenErrorCode error_code;
300 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
301 &error_code));
302 if (dex_file.get() == nullptr) {
303 return false;
304 } else {
305 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800306 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700307
308 // Now try some more.
309 size_t i = 2;
310
311 // We could try to avoid std::string allocations by working on a char array directly. As we
312 // do not expect a lot of iterations, this seems too involved and brittle.
313
314 while (i < 100) {
315 std::string name = StringPrintf("classes%zu.dex", i);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100316 std::string fake_location = location + kMultiDexSeparator + name;
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
318 error_msg, &error_code));
319 if (next_dex_file.get() == nullptr) {
320 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
321 LOG(WARNING) << error_msg;
322 }
323 break;
324 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700326 }
327
328 i++;
329 }
330
331 return true;
332 }
333}
334
335
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800336std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
337 size_t size,
338 const std::string& location,
339 uint32_t location_checksum,
340 MemMap* mem_map, std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700341 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Ian Rogers700a4022014-05-19 16:49:03 -0700342 std::unique_ptr<DexFile> dex_file(new DexFile(base, size, location, location_checksum, mem_map));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700343 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800344 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700345 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800346 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700347}
348
Ian Rogers13735952014-10-08 12:43:28 -0700349DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800350 const std::string& location,
351 uint32_t location_checksum,
352 MemMap* mem_map)
353 : begin_(base),
354 size_(size),
355 location_(location),
356 location_checksum_(location_checksum),
357 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800358 header_(reinterpret_cast<const Header*>(base)),
359 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
360 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
361 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
362 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
363 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700364 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
365 find_class_def_misses_(0),
Ian Rogersecaebd32014-09-12 23:10:21 -0700366 class_def_index_(nullptr) {
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800367 CHECK(begin_ != NULL) << GetLocation();
368 CHECK_GT(size_, 0U) << GetLocation();
369}
370
Jesse Wilson6bf19152011-09-29 13:12:33 -0400371DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700372 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
373 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
374 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
375 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700376 // Remove the index if one were created.
377 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400378}
379
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700381 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700382 return false;
383 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700384 return true;
385}
386
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700387bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800388 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700389 std::ostringstream oss;
390 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800391 << " " << header_->magic_[0]
392 << " " << header_->magic_[1]
393 << " " << header_->magic_[2]
394 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700396 return false;
397 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800398 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700399 std::ostringstream oss;
400 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800401 << " " << header_->magic_[4]
402 << " " << header_->magic_[5]
403 << " " << header_->magic_[6]
404 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700405 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700406 return false;
407 }
408 return true;
409}
410
Ian Rogers13735952014-10-08 12:43:28 -0700411bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800412 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
413}
414
Ian Rogers13735952014-10-08 12:43:28 -0700415bool DexFile::IsVersionValid(const uint8_t* magic) {
416 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800417 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
418}
419
Ian Rogersd81871c2011-10-03 13:57:23 -0700420uint32_t DexFile::GetVersion() const {
421 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
422 return atoi(version);
423}
424
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800425const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
426 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700427 // If we have an index lookup the descriptor via that as its constant time to search.
428 Index* index = class_def_index_.LoadSequentiallyConsistent();
429 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800430 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700431 return (it == index->end()) ? nullptr : it->second;
432 }
433 // Fast path for rate no class defs case.
434 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700435 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700436 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700437 }
Ian Rogers68b56852014-08-29 20:19:11 -0700438 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700439 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700440 if (string_id != nullptr) {
441 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
442 if (type_id != nullptr) {
443 uint16_t type_idx = GetIndexForTypeId(*type_id);
444 for (size_t i = 0; i < num_class_defs; ++i) {
445 const ClassDef& class_def = GetClassDef(i);
446 if (class_def.class_idx_ == type_idx) {
447 return &class_def;
448 }
449 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700450 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700451 }
Ian Rogers68b56852014-08-29 20:19:11 -0700452 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
453 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
454 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
455 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700456 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700457 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
458 if (old_misses == kMaxFailedDexClassDefLookups) {
459 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
460 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
461 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800462 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700463 for (uint32_t i = 0; i < num_class_defs; ++i) {
464 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800465 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800466 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700467 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700468 // Sanity check the index still doesn't exist, only 1 thread should build it.
469 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
470 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700471 }
472 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700473}
474
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700475const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
476 size_t num_class_defs = NumClassDefs();
477 for (size_t i = 0; i < num_class_defs; ++i) {
478 const ClassDef& class_def = GetClassDef(i);
479 if (class_def.class_idx_ == type_idx) {
480 return &class_def;
481 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700482 }
483 return NULL;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700484}
485
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800486const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
487 const DexFile::StringId& name,
488 const DexFile::TypeId& type) const {
489 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
490 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
491 const uint32_t name_idx = GetIndexForStringId(name);
492 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700493 int32_t lo = 0;
494 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800495 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700496 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800497 const DexFile::FieldId& field = GetFieldId(mid);
498 if (class_idx > field.class_idx_) {
499 lo = mid + 1;
500 } else if (class_idx < field.class_idx_) {
501 hi = mid - 1;
502 } else {
503 if (name_idx > field.name_idx_) {
504 lo = mid + 1;
505 } else if (name_idx < field.name_idx_) {
506 hi = mid - 1;
507 } else {
508 if (type_idx > field.type_idx_) {
509 lo = mid + 1;
510 } else if (type_idx < field.type_idx_) {
511 hi = mid - 1;
512 } else {
513 return &field;
514 }
515 }
516 }
517 }
518 return NULL;
519}
520
521const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700522 const DexFile::StringId& name,
523 const DexFile::ProtoId& signature) const {
524 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800525 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700526 const uint32_t name_idx = GetIndexForStringId(name);
527 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700528 int32_t lo = 0;
529 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700530 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700531 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700532 const DexFile::MethodId& method = GetMethodId(mid);
533 if (class_idx > method.class_idx_) {
534 lo = mid + 1;
535 } else if (class_idx < method.class_idx_) {
536 hi = mid - 1;
537 } else {
538 if (name_idx > method.name_idx_) {
539 lo = mid + 1;
540 } else if (name_idx < method.name_idx_) {
541 hi = mid - 1;
542 } else {
543 if (proto_idx > method.proto_idx_) {
544 lo = mid + 1;
545 } else if (proto_idx < method.proto_idx_) {
546 hi = mid - 1;
547 } else {
548 return &method;
549 }
550 }
551 }
552 }
553 return NULL;
554}
555
Ian Rogers637c65b2013-05-31 11:46:00 -0700556const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700557 int32_t lo = 0;
558 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700559 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700560 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700561 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700562 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700563 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
564 if (compare > 0) {
565 lo = mid + 1;
566 } else if (compare < 0) {
567 hi = mid - 1;
568 } else {
569 return &str_id;
570 }
571 }
572 return NULL;
573}
574
575const DexFile::StringId* DexFile::FindStringId(const uint16_t* string) const {
576 int32_t lo = 0;
577 int32_t hi = NumStringIds() - 1;
578 while (hi >= lo) {
579 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700580 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700581 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700582 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string);
Ian Rogers0571d352011-11-03 19:51:38 -0700583 if (compare > 0) {
584 lo = mid + 1;
585 } else if (compare < 0) {
586 hi = mid - 1;
587 } else {
588 return &str_id;
589 }
590 }
591 return NULL;
592}
593
594const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700595 int32_t lo = 0;
596 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700597 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700598 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700599 const TypeId& type_id = GetTypeId(mid);
600 if (string_idx > type_id.descriptor_idx_) {
601 lo = mid + 1;
602 } else if (string_idx < type_id.descriptor_idx_) {
603 hi = mid - 1;
604 } else {
605 return &type_id;
606 }
607 }
608 return NULL;
609}
610
611const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000612 const uint16_t* signature_type_idxs,
613 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700614 int32_t lo = 0;
615 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700616 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700617 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700618 const DexFile::ProtoId& proto = GetProtoId(mid);
619 int compare = return_type_idx - proto.return_type_idx_;
620 if (compare == 0) {
621 DexFileParameterIterator it(*this, proto);
622 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000623 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800624 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700625 it.Next();
626 i++;
627 }
628 if (compare == 0) {
629 if (it.HasNext()) {
630 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000631 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700632 compare = 1;
633 }
634 }
635 }
636 if (compare > 0) {
637 lo = mid + 1;
638 } else if (compare < 0) {
639 hi = mid - 1;
640 } else {
641 return &proto;
642 }
643 }
644 return NULL;
645}
646
647// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700648bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
649 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700650 if (signature[0] != '(') {
651 return false;
652 }
653 size_t offset = 1;
654 size_t end = signature.size();
655 bool process_return = false;
656 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000657 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700658 char c = signature[offset];
659 offset++;
660 if (c == ')') {
661 process_return = true;
662 continue;
663 }
Ian Rogers0571d352011-11-03 19:51:38 -0700664 while (c == '[') { // process array prefix
665 if (offset >= end) { // expect some descriptor following [
666 return false;
667 }
668 c = signature[offset];
669 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700670 }
671 if (c == 'L') { // process type descriptors
672 do {
673 if (offset >= end) { // unexpected early termination of descriptor
674 return false;
675 }
676 c = signature[offset];
677 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700678 } while (c != ';');
679 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000680 // TODO: avoid creating a std::string just to get a 0-terminated char array
681 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700682 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700683 if (string_id == NULL) {
684 return false;
685 }
686 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
687 if (type_id == NULL) {
688 return false;
689 }
690 uint16_t type_idx = GetIndexForTypeId(*type_id);
691 if (!process_return) {
692 param_type_idxs->push_back(type_idx);
693 } else {
694 *return_type_idx = type_idx;
695 return offset == end; // return true if the signature had reached a sensible end
696 }
697 }
698 return false; // failed to correctly parse return type
699}
700
Ian Rogersd91d6d62013-09-25 20:26:14 -0700701const Signature DexFile::CreateSignature(const StringPiece& signature) const {
702 uint16_t return_type_idx;
703 std::vector<uint16_t> param_type_indices;
704 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
705 if (!success) {
706 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700707 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700708 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
709 if (proto_id == NULL) {
710 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700711 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700712 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700713}
714
Ian Rogersef7d42f2014-01-06 12:55:46 -0800715int32_t DexFile::GetLineNumFromPC(mirror::ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700716 // For native method, lineno should be -2 to indicate it is native. Note that
717 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700718 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700719 return -2;
720 }
721
TDYa127c8dc1012012-04-19 07:03:33 -0700722 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Elliott Hughescaf76542012-06-28 16:08:22 -0700723 DCHECK(code_item != NULL) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700724
725 // A method with no line number info should return -1
726 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700727 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800728 NULL, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700729 return context.line_num_;
730}
731
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700732int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700733 // Note: Signed type is important for max and min.
734 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700735 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700736
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700737 while (min <= max) {
738 int32_t mid = min + ((max - min) / 2);
739
740 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
741 uint32_t start = ti->start_addr_;
742 uint32_t end = start + ti->insn_count_;
743
Ian Rogers0571d352011-11-03 19:51:38 -0700744 if (address < start) {
745 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700746 } else if (address >= end) {
747 min = mid + 1;
748 } else { // We have a winner!
749 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700750 }
751 }
752 // No match.
753 return -1;
754}
755
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700756int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
757 int32_t try_item = FindTryItem(code_item, address);
758 if (try_item == -1) {
759 return -1;
760 } else {
761 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
762 }
763}
764
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800765void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800766 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Ian Rogers13735952014-10-08 12:43:28 -0700767 void* context, const uint8_t* stream, LocalInfo* local_in_reg) const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700768 uint32_t line = DecodeUnsignedLeb128(&stream);
769 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
770 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
771 uint32_t address = 0;
Elliott Hughes30646832011-10-13 16:59:46 -0700772 bool need_locals = (local_cb != NULL);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700773
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800774 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700775 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800776 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700777 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800778 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800779 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700780 local_in_reg[arg_reg].start_address_ = 0;
781 local_in_reg[arg_reg].is_live_ = true;
782 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700783 arg_reg++;
784 }
785
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800786 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700787 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700788 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700789 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800790 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700791 return;
792 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800793 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700794 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800795 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700796 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700797 local_in_reg[arg_reg].name_ = name;
798 local_in_reg[arg_reg].descriptor_ = descriptor;
Elliott Hughes392b1242011-11-30 13:55:50 -0800799 local_in_reg[arg_reg].signature_ = NULL;
Elliott Hughes30646832011-10-13 16:59:46 -0700800 local_in_reg[arg_reg].start_address_ = address;
801 local_in_reg[arg_reg].is_live_ = true;
802 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700803 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700804 case 'D':
805 case 'J':
806 arg_reg += 2;
807 break;
808 default:
809 arg_reg += 1;
810 break;
811 }
812 }
813
Ian Rogers0571d352011-11-03 19:51:38 -0700814 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800815 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
816 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700817 return;
818 }
819
820 for (;;) {
821 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700822 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800823 uint32_t name_idx;
824 uint32_t descriptor_idx;
825 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700826
Shih-wei Liao195487c2011-08-20 13:29:04 -0700827 switch (opcode) {
828 case DBG_END_SEQUENCE:
829 return;
830
831 case DBG_ADVANCE_PC:
832 address += DecodeUnsignedLeb128(&stream);
833 break;
834
835 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700836 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700837 break;
838
839 case DBG_START_LOCAL:
840 case DBG_START_LOCAL_EXTENDED:
841 reg = DecodeUnsignedLeb128(&stream);
842 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700843 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800844 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700845 return;
846 }
847
jeffhaof8728872011-10-28 19:11:13 -0700848 name_idx = DecodeUnsignedLeb128P1(&stream);
849 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
850 if (opcode == DBG_START_LOCAL_EXTENDED) {
851 signature_idx = DecodeUnsignedLeb128P1(&stream);
852 }
853
Shih-wei Liao195487c2011-08-20 13:29:04 -0700854 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700855 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800856 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700857
Ian Rogers0571d352011-11-03 19:51:38 -0700858 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
859 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700860 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700861 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700862 }
863 local_in_reg[reg].start_address_ = address;
864 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700865 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700866 break;
867
868 case DBG_END_LOCAL:
869 reg = DecodeUnsignedLeb128(&stream);
870 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700871 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800872 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700873 return;
874 }
875
Elliott Hughes30646832011-10-13 16:59:46 -0700876 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800877 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700878 local_in_reg[reg].is_live_ = false;
879 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 break;
881
882 case DBG_RESTART_LOCAL:
883 reg = DecodeUnsignedLeb128(&stream);
884 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700885 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800886 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 return;
888 }
889
Elliott Hughes30646832011-10-13 16:59:46 -0700890 if (need_locals) {
891 if (local_in_reg[reg].name_ == NULL || local_in_reg[reg].descriptor_ == NULL) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800892 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700893 return;
894 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700895
Elliott Hughes30646832011-10-13 16:59:46 -0700896 // If the register is live, the "restart" is superfluous,
897 // and we don't want to mess with the existing start address.
898 if (!local_in_reg[reg].is_live_) {
899 local_in_reg[reg].start_address_ = address;
900 local_in_reg[reg].is_live_ = true;
901 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700902 }
903 break;
904
905 case DBG_SET_PROLOGUE_END:
906 case DBG_SET_EPILOGUE_BEGIN:
907 case DBG_SET_FILE:
908 break;
909
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700910 default: {
911 int adjopcode = opcode - DBG_FIRST_SPECIAL;
912
Shih-wei Liao195487c2011-08-20 13:29:04 -0700913 address += adjopcode / DBG_LINE_RANGE;
914 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
915
Elliott Hughes2435a572012-02-17 16:07:41 -0800916 if (position_cb != NULL) {
917 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700918 // early exit
919 return;
920 }
921 }
922 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700923 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 }
925 }
926}
927
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800928void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800929 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
930 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100931 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700932 const uint8_t* stream = GetDebugInfoStream(code_item);
Ian Rogers700a4022014-05-19 16:49:03 -0700933 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != NULL ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700934 new LocalInfo[code_item->registers_size_] :
935 NULL);
Ian Rogers0571d352011-11-03 19:51:38 -0700936 if (stream != NULL) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700937 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream, &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700938 }
939 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Elliott Hughesee0fa762012-03-26 17:12:41 -0700940 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0], local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700941 }
942}
943
Elliott Hughes2435a572012-02-17 16:07:41 -0800944bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
945 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700946
947 // We know that this callback will be called in
948 // ascending address order, so keep going until we find
949 // a match or we've just gone past it.
950 if (address > context->address_) {
951 // The line number from the previous positions callback
952 // wil be the final result.
953 return true;
954 } else {
955 context->line_num_ = line_num;
956 return address == context->address_;
957 }
958}
959
Andreas Gampe833a4852014-05-21 18:46:59 -0700960bool DexFile::IsMultiDexLocation(const char* location) {
961 return strrchr(location, kMultiDexSeparator) != nullptr;
962}
963
Calin Juravle4e1d5792014-07-15 23:56:47 +0100964std::string DexFile::GetMultiDexClassesDexName(size_t number, const char* dex_location) {
965 if (number == 0) {
966 return dex_location;
967 } else {
968 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, number + 1);
969 }
970}
971
972std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
973 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100974 std::string base_location = GetBaseLocation(dex_location);
975 const char* suffix = dex_location + base_location.size();
976 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
977 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
978 if (path != nullptr && path.get() != base_location) {
979 return std::string(path.get()) + suffix;
980 } else if (suffix[0] == 0) {
981 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +0100982 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100983 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +0100984 }
Calin Juravle4e1d5792014-07-15 23:56:47 +0100985}
986
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800987std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
988 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
989 dex_file.GetLocation().c_str(),
990 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
991 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
992 return os;
993}
Calin Juravle4e1d5792014-07-15 23:56:47 +0100994
Ian Rogersd91d6d62013-09-25 20:26:14 -0700995std::string Signature::ToString() const {
996 if (dex_file_ == nullptr) {
997 CHECK(proto_id_ == nullptr);
998 return "<no signature>";
999 }
1000 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1001 std::string result;
1002 if (params == nullptr) {
1003 result += "()";
1004 } else {
1005 result += "(";
1006 for (uint32_t i = 0; i < params->Size(); ++i) {
1007 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1008 }
1009 result += ")";
1010 }
1011 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1012 return result;
1013}
1014
Vladimir Markod9cffea2013-11-25 15:08:02 +00001015bool Signature::operator==(const StringPiece& rhs) const {
1016 if (dex_file_ == nullptr) {
1017 return false;
1018 }
1019 StringPiece tail(rhs);
1020 if (!tail.starts_with("(")) {
1021 return false; // Invalid signature
1022 }
1023 tail.remove_prefix(1); // "(";
1024 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1025 if (params != nullptr) {
1026 for (uint32_t i = 0; i < params->Size(); ++i) {
1027 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1028 if (!tail.starts_with(param)) {
1029 return false;
1030 }
1031 tail.remove_prefix(param.length());
1032 }
1033 }
1034 if (!tail.starts_with(")")) {
1035 return false;
1036 }
1037 tail.remove_prefix(1); // ")";
1038 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1039}
1040
Ian Rogersd91d6d62013-09-25 20:26:14 -07001041std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1042 return os << sig.ToString();
1043}
1044
Ian Rogers0571d352011-11-03 19:51:38 -07001045// Decodes the header section from the class data bytes.
1046void ClassDataItemIterator::ReadClassDataHeader() {
1047 CHECK(ptr_pos_ != NULL);
1048 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1049 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1050 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1051 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1052}
1053
1054void ClassDataItemIterator::ReadClassDataField() {
1055 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1056 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001057 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001058 LOG(WARNING) << "Duplicate field in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001059 }
Ian Rogers0571d352011-11-03 19:51:38 -07001060}
1061
1062void ClassDataItemIterator::ReadClassDataMethod() {
1063 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1064 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1065 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001066 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001067 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001068 }
Ian Rogers0571d352011-11-03 19:51:38 -07001069}
1070
1071// Read a signed integer. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001072static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001073 int32_t val = 0;
1074 for (int i = zwidth; i >= 0; --i) {
1075 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1076 }
1077 val >>= (3 - zwidth) * 8;
1078 return val;
1079}
1080
1081// Read an unsigned integer. "zwidth" is the zero-based byte count,
1082// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001083static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001084 uint32_t val = 0;
1085 if (!fill_on_right) {
1086 for (int i = zwidth; i >= 0; --i) {
1087 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1088 }
1089 val >>= (3 - zwidth) * 8;
1090 } else {
1091 for (int i = zwidth; i >= 0; --i) {
1092 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1093 }
1094 }
1095 return val;
1096}
1097
1098// Read a signed long. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001099static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001100 int64_t val = 0;
1101 for (int i = zwidth; i >= 0; --i) {
1102 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1103 }
1104 val >>= (7 - zwidth) * 8;
1105 return val;
1106}
1107
1108// Read an unsigned long. "zwidth" is the zero-based byte count,
1109// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001110static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001111 uint64_t val = 0;
1112 if (!fill_on_right) {
1113 for (int i = zwidth; i >= 0; --i) {
1114 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1115 }
1116 val >>= (7 - zwidth) * 8;
1117 } else {
1118 for (int i = zwidth; i >= 0; --i) {
1119 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1120 }
1121 }
1122 return val;
1123}
1124
1125EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001126 Handle<mirror::DexCache>* dex_cache,
1127 Handle<mirror::ClassLoader>* class_loader,
Ian Rogersca190662012-06-26 15:45:57 -07001128 ClassLinker* linker,
1129 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001130 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1131 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001132 DCHECK(dex_cache != nullptr);
1133 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001134 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
1135 if (ptr_ == NULL) {
1136 array_size_ = 0;
1137 } else {
1138 array_size_ = DecodeUnsignedLeb128(&ptr_);
1139 }
1140 if (array_size_ > 0) {
1141 Next();
1142 }
1143}
1144
1145void EncodedStaticFieldValueIterator::Next() {
1146 pos_++;
1147 if (pos_ >= array_size_) {
1148 return;
1149 }
Ian Rogers13735952014-10-08 12:43:28 -07001150 uint8_t value_type = *ptr_++;
1151 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001152 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001153 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001154 switch (type_) {
1155 case kBoolean:
1156 jval_.i = (value_arg != 0) ? 1 : 0;
1157 width = 0;
1158 break;
1159 case kByte:
1160 jval_.i = ReadSignedInt(ptr_, value_arg);
1161 CHECK(IsInt(8, jval_.i));
1162 break;
1163 case kShort:
1164 jval_.i = ReadSignedInt(ptr_, value_arg);
1165 CHECK(IsInt(16, jval_.i));
1166 break;
1167 case kChar:
1168 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1169 CHECK(IsUint(16, jval_.i));
1170 break;
1171 case kInt:
1172 jval_.i = ReadSignedInt(ptr_, value_arg);
1173 break;
1174 case kLong:
1175 jval_.j = ReadSignedLong(ptr_, value_arg);
1176 break;
1177 case kFloat:
1178 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1179 break;
1180 case kDouble:
1181 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1182 break;
1183 case kString:
1184 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001185 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1186 break;
1187 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001188 case kMethod:
1189 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001190 case kArray:
1191 case kAnnotation:
1192 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001193 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001194 case kNull:
1195 jval_.l = NULL;
1196 width = 0;
1197 break;
1198 default:
1199 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001200 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001201 }
1202 ptr_ += width;
1203}
1204
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001205template<bool kTransactionActive>
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07001206void EncodedStaticFieldValueIterator::ReadValueToField(Handle<mirror::ArtField> field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001207 switch (type_) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001208 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z); break;
1209 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1210 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1211 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1212 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1213 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1214 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1215 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
1216 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), NULL); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001217 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001218 CHECK(!kMovingFields);
1219 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001220 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001221 break;
1222 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001223 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001224 CHECK(!kMovingFields);
1225 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1226 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001227 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001228 break;
1229 }
Ian Rogers0571d352011-11-03 19:51:38 -07001230 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1231 }
1232}
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07001233template void EncodedStaticFieldValueIterator::ReadValueToField<true>(Handle<mirror::ArtField> field) const;
1234template void EncodedStaticFieldValueIterator::ReadValueToField<false>(Handle<mirror::ArtField> field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001235
1236CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1237 handler_.address_ = -1;
1238 int32_t offset = -1;
1239
1240 // Short-circuit the overwhelmingly common cases.
1241 switch (code_item.tries_size_) {
1242 case 0:
1243 break;
1244 case 1: {
1245 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1246 uint32_t start = tries->start_addr_;
1247 if (address >= start) {
1248 uint32_t end = start + tries->insn_count_;
1249 if (address < end) {
1250 offset = tries->handler_off_;
1251 }
1252 }
1253 break;
1254 }
1255 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001256 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001257 }
Logan Chien736df022012-04-27 16:25:57 +08001258 Init(code_item, offset);
1259}
1260
1261CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1262 const DexFile::TryItem& try_item) {
1263 handler_.address_ = -1;
1264 Init(code_item, try_item.handler_off_);
1265}
1266
1267void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1268 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001269 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001270 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001271 } else {
1272 // Not found, initialize as empty
1273 current_data_ = NULL;
1274 remaining_count_ = -1;
1275 catch_all_ = false;
1276 DCHECK(!HasNext());
1277 }
1278}
1279
Ian Rogers13735952014-10-08 12:43:28 -07001280void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001281 current_data_ = handler_data;
1282 remaining_count_ = DecodeSignedLeb128(&current_data_);
1283
1284 // If remaining_count_ is non-positive, then it is the negative of
1285 // the number of catch types, and the catches are followed by a
1286 // catch-all handler.
1287 if (remaining_count_ <= 0) {
1288 catch_all_ = true;
1289 remaining_count_ = -remaining_count_;
1290 } else {
1291 catch_all_ = false;
1292 }
1293 Next();
1294}
1295
1296void CatchHandlerIterator::Next() {
1297 if (remaining_count_ > 0) {
1298 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1299 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1300 remaining_count_--;
1301 return;
1302 }
1303
1304 if (catch_all_) {
1305 handler_.type_idx_ = DexFile::kDexNoIndex16;
1306 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1307 catch_all_ = false;
1308 return;
1309 }
1310
1311 // no more handler
1312 remaining_count_ = -1;
1313}
1314
Carl Shapiro1fb86202011-06-27 17:43:13 -07001315} // namespace art