blob: d30fac4cde79627526ee070e95627261264daed0 [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
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080032#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080033#include "base/stringprintf.h"
Ian Rogers0571d352011-11-03 19:51:38 -070034#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080036#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "leb128.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) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070060 CHECK(magic != nullptr);
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) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070080 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070081 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)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700101 std::unique_ptr<ZipArchive> zip_archive(
102 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
103 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800104 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
105 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800106 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700107 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700108 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700110 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
111 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
113 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700114 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700116 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700117 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 std::unique_ptr<const DexFile> dex_file(
119 DexFile::OpenFile(fd.release(), filename, false, error_msg));
120 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return false;
122 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700123 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800124 return true;
125 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700126 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800127 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700128}
129
Andreas Gampe833a4852014-05-21 18:46:59 -0700130bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800131 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700132 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000134 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
135 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700136 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700137 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700138 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700140 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700141 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700142 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
144 error_msg));
145 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800146 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700147 return true;
148 } else {
149 return false;
150 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700151 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700152 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400153 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700154}
155
Andreas Gampe0cba0042015-04-29 20:47:16 -0700156static bool ContainsClassesDex(int fd, const char* filename) {
157 std::string error_msg;
158 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
159 if (zip_archive.get() == nullptr) {
160 return false;
161 }
162 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
163 return (zip_entry.get() != nullptr);
164}
165
166bool DexFile::MaybeDex(const char* filename) {
167 uint32_t magic;
168 std::string error_msg;
169 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
170 if (fd.get() == -1) {
171 return false;
172 }
173 if (IsZipMagic(magic)) {
174 return ContainsClassesDex(fd.release(), filename);
175 } else if (IsDexMagic(magic)) {
176 return true;
177 }
178 return false;
179}
180
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800181int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800183 return 0;
184 } else {
185 return mem_map_->GetProtect();
186 }
187}
188
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200189bool DexFile::IsReadOnly() const {
190 return GetPermissions() == PROT_READ;
191}
192
Brian Carlstrome0948e12013-08-29 09:36:15 -0700193bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700195 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200196 return false;
197 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700198 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 }
200}
201
Brian Carlstrome0948e12013-08-29 09:36:15 -0700202bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200203 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700204 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 return false;
206 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700207 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200208 }
209}
210
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800211std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
212 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700213 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700214 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000215 {
216 ScopedFd delayed_close(fd);
217 struct stat sbuf;
218 memset(&sbuf, 0, sizeof(sbuf));
219 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800220 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000221 return nullptr;
222 }
223 if (S_ISDIR(sbuf.st_mode)) {
224 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
225 return nullptr;
226 }
227 size_t length = sbuf.st_size;
228 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
229 if (map.get() == nullptr) {
230 DCHECK(!error_msg->empty());
231 return nullptr;
232 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700233 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800234
235 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700236 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800237 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700238 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800239 }
240
241 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
242
Andreas Gampe928f72b2014-09-09 19:53:48 -0700243 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
244 error_msg));
245 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700246 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
247 error_msg->c_str());
248 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800249 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800250
Andreas Gampe928f72b2014-09-09 19:53:48 -0700251 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
252 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700253 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800254 }
255
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800256 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700257}
258
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700259const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700260
Andreas Gampe833a4852014-05-21 18:46:59 -0700261bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800262 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700263 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700264 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 if (zip_archive.get() == nullptr) {
266 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700267 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700268 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700269 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800270}
271
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800272std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
273 uint32_t location_checksum,
274 MemMap* mem_map,
275 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800276 return OpenMemory(mem_map->Begin(),
277 mem_map->Size(),
278 location,
279 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800281 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700282 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800283}
284
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800285std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
286 const std::string& location, std::string* error_msg,
287 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800288 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700289 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700290 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700291 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700292 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700293 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700294 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700295 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700296 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700297 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700298 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700299 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700300 }
Ian Rogers700a4022014-05-19 16:49:03 -0700301 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700302 error_msg));
303 if (dex_file.get() == nullptr) {
304 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
305 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700306 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700307 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800308 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700309 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700311 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700312 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700313 }
314 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700315 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
316 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700318 return nullptr;
319 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700320 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800321 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700322}
323
Andreas Gampe90e34042015-04-27 20:01:52 -0700324// Technically we do not have a limitation with respect to the number of dex files that can be in a
325// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
326// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
327// seems an excessive number.
328static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
329
Andreas Gampe833a4852014-05-21 18:46:59 -0700330bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800331 std::string* error_msg,
332 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700333 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700334 ZipOpenErrorCode error_code;
335 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
336 &error_code));
337 if (dex_file.get() == nullptr) {
338 return false;
339 } else {
340 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800341 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700342
343 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700344
345 // We could try to avoid std::string allocations by working on a char array directly. As we
346 // do not expect a lot of iterations, this seems too involved and brittle.
347
Andreas Gampe90e34042015-04-27 20:01:52 -0700348 for (size_t i = 1; ; ++i) {
349 std::string name = GetMultiDexClassesDexName(i);
350 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700351 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
352 error_msg, &error_code));
353 if (next_dex_file.get() == nullptr) {
354 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
355 LOG(WARNING) << error_msg;
356 }
357 break;
358 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800359 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700360 }
361
Andreas Gampe90e34042015-04-27 20:01:52 -0700362 if (i == kWarnOnManyDexFilesThreshold) {
363 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
364 << " dex files. Please consider coalescing and shrinking the number to "
365 " avoid runtime overhead.";
366 }
367
368 if (i == std::numeric_limits<size_t>::max()) {
369 LOG(ERROR) << "Overflow in number of dex files!";
370 break;
371 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700372 }
373
374 return true;
375 }
376}
377
378
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800379std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
380 size_t size,
381 const std::string& location,
382 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800383 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700384 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800385 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700386 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800387 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700388 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700389 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800390 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700391 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800392 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700393}
394
Ian Rogers13735952014-10-08 12:43:28 -0700395DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800396 const std::string& location,
397 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800398 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700399 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800400 : begin_(base),
401 size_(size),
402 location_(location),
403 location_checksum_(location_checksum),
404 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800405 header_(reinterpret_cast<const Header*>(base)),
406 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
407 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
408 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
409 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
410 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700411 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
412 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800413 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700414 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700415 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800416 CHECK_GT(size_, 0U) << GetLocation();
417}
418
Jesse Wilson6bf19152011-09-29 13:12:33 -0400419DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700420 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
421 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
422 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
423 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700424 // Remove the index if one were created.
425 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400426}
427
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700428bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700430 return false;
431 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700432 return true;
433}
434
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700435bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800436 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700437 std::ostringstream oss;
438 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800439 << " " << header_->magic_[0]
440 << " " << header_->magic_[1]
441 << " " << header_->magic_[2]
442 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700443 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700444 return false;
445 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800446 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 std::ostringstream oss;
448 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800449 << " " << header_->magic_[4]
450 << " " << header_->magic_[5]
451 << " " << header_->magic_[6]
452 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700453 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700454 return false;
455 }
456 return true;
457}
458
Ian Rogers13735952014-10-08 12:43:28 -0700459bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800460 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
461}
462
Ian Rogers13735952014-10-08 12:43:28 -0700463bool DexFile::IsVersionValid(const uint8_t* magic) {
464 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800465 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
466}
467
Ian Rogersd81871c2011-10-03 13:57:23 -0700468uint32_t DexFile::GetVersion() const {
469 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
470 return atoi(version);
471}
472
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800473const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
474 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700475 // If we have an index lookup the descriptor via that as its constant time to search.
476 Index* index = class_def_index_.LoadSequentiallyConsistent();
477 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800478 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700479 return (it == index->end()) ? nullptr : it->second;
480 }
481 // Fast path for rate no class defs case.
482 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700483 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700484 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700485 }
Ian Rogers68b56852014-08-29 20:19:11 -0700486 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700487 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700488 if (string_id != nullptr) {
489 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
490 if (type_id != nullptr) {
491 uint16_t type_idx = GetIndexForTypeId(*type_id);
492 for (size_t i = 0; i < num_class_defs; ++i) {
493 const ClassDef& class_def = GetClassDef(i);
494 if (class_def.class_idx_ == type_idx) {
495 return &class_def;
496 }
497 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700498 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700499 }
Ian Rogers68b56852014-08-29 20:19:11 -0700500 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
501 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
502 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
503 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700504 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700505 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
506 if (old_misses == kMaxFailedDexClassDefLookups) {
507 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
508 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
509 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800510 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700511 for (uint32_t i = 0; i < num_class_defs; ++i) {
512 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800513 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800514 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700515 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700516 // Sanity check the index still doesn't exist, only 1 thread should build it.
517 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
518 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700519 }
520 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700521}
522
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700523const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
524 size_t num_class_defs = NumClassDefs();
525 for (size_t i = 0; i < num_class_defs; ++i) {
526 const ClassDef& class_def = GetClassDef(i);
527 if (class_def.class_idx_ == type_idx) {
528 return &class_def;
529 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700530 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700531 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700532}
533
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800534const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
535 const DexFile::StringId& name,
536 const DexFile::TypeId& type) const {
537 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
538 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
539 const uint32_t name_idx = GetIndexForStringId(name);
540 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700541 int32_t lo = 0;
542 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800543 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700544 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800545 const DexFile::FieldId& field = GetFieldId(mid);
546 if (class_idx > field.class_idx_) {
547 lo = mid + 1;
548 } else if (class_idx < field.class_idx_) {
549 hi = mid - 1;
550 } else {
551 if (name_idx > field.name_idx_) {
552 lo = mid + 1;
553 } else if (name_idx < field.name_idx_) {
554 hi = mid - 1;
555 } else {
556 if (type_idx > field.type_idx_) {
557 lo = mid + 1;
558 } else if (type_idx < field.type_idx_) {
559 hi = mid - 1;
560 } else {
561 return &field;
562 }
563 }
564 }
565 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700566 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800567}
568
569const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700570 const DexFile::StringId& name,
571 const DexFile::ProtoId& signature) const {
572 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800573 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700574 const uint32_t name_idx = GetIndexForStringId(name);
575 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700576 int32_t lo = 0;
577 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700578 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700579 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700580 const DexFile::MethodId& method = GetMethodId(mid);
581 if (class_idx > method.class_idx_) {
582 lo = mid + 1;
583 } else if (class_idx < method.class_idx_) {
584 hi = mid - 1;
585 } else {
586 if (name_idx > method.name_idx_) {
587 lo = mid + 1;
588 } else if (name_idx < method.name_idx_) {
589 hi = mid - 1;
590 } else {
591 if (proto_idx > method.proto_idx_) {
592 lo = mid + 1;
593 } else if (proto_idx < method.proto_idx_) {
594 hi = mid - 1;
595 } else {
596 return &method;
597 }
598 }
599 }
600 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700601 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700602}
603
Ian Rogers637c65b2013-05-31 11:46:00 -0700604const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700605 int32_t lo = 0;
606 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700607 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700608 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700609 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700610 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700611 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
612 if (compare > 0) {
613 lo = mid + 1;
614 } else if (compare < 0) {
615 hi = mid - 1;
616 } else {
617 return &str_id;
618 }
619 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700620 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700621}
622
Vladimir Markoa48aef42014-12-03 17:53:53 +0000623const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700624 int32_t lo = 0;
625 int32_t hi = NumStringIds() - 1;
626 while (hi >= lo) {
627 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700628 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700629 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000630 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700631 if (compare > 0) {
632 lo = mid + 1;
633 } else if (compare < 0) {
634 hi = mid - 1;
635 } else {
636 return &str_id;
637 }
638 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700639 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700640}
641
642const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700643 int32_t lo = 0;
644 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700645 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700646 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700647 const TypeId& type_id = GetTypeId(mid);
648 if (string_idx > type_id.descriptor_idx_) {
649 lo = mid + 1;
650 } else if (string_idx < type_id.descriptor_idx_) {
651 hi = mid - 1;
652 } else {
653 return &type_id;
654 }
655 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700656 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700657}
658
659const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000660 const uint16_t* signature_type_idxs,
661 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700662 int32_t lo = 0;
663 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700664 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700665 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700666 const DexFile::ProtoId& proto = GetProtoId(mid);
667 int compare = return_type_idx - proto.return_type_idx_;
668 if (compare == 0) {
669 DexFileParameterIterator it(*this, proto);
670 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000671 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800672 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700673 it.Next();
674 i++;
675 }
676 if (compare == 0) {
677 if (it.HasNext()) {
678 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000679 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700680 compare = 1;
681 }
682 }
683 }
684 if (compare > 0) {
685 lo = mid + 1;
686 } else if (compare < 0) {
687 hi = mid - 1;
688 } else {
689 return &proto;
690 }
691 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700692 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700693}
694
695// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700696bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
697 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700698 if (signature[0] != '(') {
699 return false;
700 }
701 size_t offset = 1;
702 size_t end = signature.size();
703 bool process_return = false;
704 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000705 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700706 char c = signature[offset];
707 offset++;
708 if (c == ')') {
709 process_return = true;
710 continue;
711 }
Ian Rogers0571d352011-11-03 19:51:38 -0700712 while (c == '[') { // process array prefix
713 if (offset >= end) { // expect some descriptor following [
714 return false;
715 }
716 c = signature[offset];
717 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700718 }
719 if (c == 'L') { // process type descriptors
720 do {
721 if (offset >= end) { // unexpected early termination of descriptor
722 return false;
723 }
724 c = signature[offset];
725 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700726 } while (c != ';');
727 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000728 // TODO: avoid creating a std::string just to get a 0-terminated char array
729 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700730 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700731 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700732 return false;
733 }
734 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700735 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700736 return false;
737 }
738 uint16_t type_idx = GetIndexForTypeId(*type_id);
739 if (!process_return) {
740 param_type_idxs->push_back(type_idx);
741 } else {
742 *return_type_idx = type_idx;
743 return offset == end; // return true if the signature had reached a sensible end
744 }
745 }
746 return false; // failed to correctly parse return type
747}
748
Ian Rogersd91d6d62013-09-25 20:26:14 -0700749const Signature DexFile::CreateSignature(const StringPiece& signature) const {
750 uint16_t return_type_idx;
751 std::vector<uint16_t> param_type_indices;
752 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
753 if (!success) {
754 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700755 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700756 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700757 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700758 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700759 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700760 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700761}
762
Mathieu Chartiere401d142015-04-22 13:56:20 -0700763int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700764 // For native method, lineno should be -2 to indicate it is native. Note that
765 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700766 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700767 return -2;
768 }
769
TDYa127c8dc1012012-04-19 07:03:33 -0700770 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700772
773 // A method with no line number info should return -1
774 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700775 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700776 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700777 return context.line_num_;
778}
779
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700780int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700781 // Note: Signed type is important for max and min.
782 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700783 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700784
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700785 while (min <= max) {
786 int32_t mid = min + ((max - min) / 2);
787
788 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
789 uint32_t start = ti->start_addr_;
790 uint32_t end = start + ti->insn_count_;
791
Ian Rogers0571d352011-11-03 19:51:38 -0700792 if (address < start) {
793 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700794 } else if (address >= end) {
795 min = mid + 1;
796 } else { // We have a winner!
797 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700798 }
799 }
800 // No match.
801 return -1;
802}
803
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700804int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
805 int32_t try_item = FindTryItem(code_item, address);
806 if (try_item == -1) {
807 return -1;
808 } else {
809 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
810 }
811}
812
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800813void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800814 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
816 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700817 uint32_t line = DecodeUnsignedLeb128(&stream);
818 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
819 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
820 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700821 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700822
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800823 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700824 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800825 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700826 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700828 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700829 local_in_reg[arg_reg].start_address_ = 0;
830 local_in_reg[arg_reg].is_live_ = true;
831 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700832 arg_reg++;
833 }
834
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800835 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700836 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700837 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700838 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800839 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700840 return;
841 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800842 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700843 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800844 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700845 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700846 local_in_reg[arg_reg].name_ = name;
847 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700848 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700849 local_in_reg[arg_reg].start_address_ = address;
850 local_in_reg[arg_reg].is_live_ = true;
851 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700852 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700853 case 'D':
854 case 'J':
855 arg_reg += 2;
856 break;
857 default:
858 arg_reg += 1;
859 break;
860 }
861 }
862
Ian Rogers0571d352011-11-03 19:51:38 -0700863 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800864 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
865 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700866 return;
867 }
868
869 for (;;) {
870 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700871 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800872 uint32_t name_idx;
873 uint32_t descriptor_idx;
874 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700875
Shih-wei Liao195487c2011-08-20 13:29:04 -0700876 switch (opcode) {
877 case DBG_END_SEQUENCE:
878 return;
879
880 case DBG_ADVANCE_PC:
881 address += DecodeUnsignedLeb128(&stream);
882 break;
883
884 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700885 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700886 break;
887
888 case DBG_START_LOCAL:
889 case DBG_START_LOCAL_EXTENDED:
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
jeffhaof8728872011-10-28 19:11:13 -0700897 name_idx = DecodeUnsignedLeb128P1(&stream);
898 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
899 if (opcode == DBG_START_LOCAL_EXTENDED) {
900 signature_idx = DecodeUnsignedLeb128P1(&stream);
901 }
902
Shih-wei Liao195487c2011-08-20 13:29:04 -0700903 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700904 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800905 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700906
Ian Rogers0571d352011-11-03 19:51:38 -0700907 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
908 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700909 local_in_reg[reg].signature_ =
910 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
911 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700912 local_in_reg[reg].start_address_ = address;
913 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700915 break;
916
917 case DBG_END_LOCAL:
918 reg = DecodeUnsignedLeb128(&stream);
919 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700920 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800921 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 return;
923 }
924
Elliott Hughes30646832011-10-13 16:59:46 -0700925 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800926 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700927 local_in_reg[reg].is_live_ = false;
928 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 break;
930
931 case DBG_RESTART_LOCAL:
932 reg = DecodeUnsignedLeb128(&stream);
933 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700934 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800935 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700936 return;
937 }
938
Elliott Hughes30646832011-10-13 16:59:46 -0700939 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700940 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800941 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700942 return;
943 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944
Elliott Hughes30646832011-10-13 16:59:46 -0700945 // If the register is live, the "restart" is superfluous,
946 // and we don't want to mess with the existing start address.
947 if (!local_in_reg[reg].is_live_) {
948 local_in_reg[reg].start_address_ = address;
949 local_in_reg[reg].is_live_ = true;
950 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 }
952 break;
953
954 case DBG_SET_PROLOGUE_END:
955 case DBG_SET_EPILOGUE_BEGIN:
956 case DBG_SET_FILE:
957 break;
958
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700959 default: {
960 int adjopcode = opcode - DBG_FIRST_SPECIAL;
961
Shih-wei Liao195487c2011-08-20 13:29:04 -0700962 address += adjopcode / DBG_LINE_RANGE;
963 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
964
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700965 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800966 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700967 // early exit
968 return;
969 }
970 }
971 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700972 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700973 }
974 }
975}
976
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800977void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800978 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
979 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100980 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700981 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700982 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700983 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700984 nullptr);
985 if (stream != nullptr) {
986 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
987 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700988 }
989 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700990 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
991 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700992 }
993}
994
Elliott Hughes2435a572012-02-17 16:07:41 -0800995bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
996 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700997
998 // We know that this callback will be called in
999 // ascending address order, so keep going until we find
1000 // a match or we've just gone past it.
1001 if (address > context->address_) {
1002 // The line number from the previous positions callback
1003 // wil be the final result.
1004 return true;
1005 } else {
1006 context->line_num_ = line_num;
1007 return address == context->address_;
1008 }
1009}
1010
Andreas Gampe833a4852014-05-21 18:46:59 -07001011bool DexFile::IsMultiDexLocation(const char* location) {
1012 return strrchr(location, kMultiDexSeparator) != nullptr;
1013}
1014
Andreas Gampe90e34042015-04-27 20:01:52 -07001015std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1016 if (index == 0) {
1017 return "classes.dex";
1018 } else {
1019 return StringPrintf("classes%zu.dex", index + 1);
1020 }
1021}
1022
1023std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1024 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001025 return dex_location;
1026 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001027 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001028 }
1029}
1030
1031std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1032 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001033 std::string base_location = GetBaseLocation(dex_location);
1034 const char* suffix = dex_location + base_location.size();
1035 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1036 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1037 if (path != nullptr && path.get() != base_location) {
1038 return std::string(path.get()) + suffix;
1039 } else if (suffix[0] == 0) {
1040 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001041 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001042 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001043 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001044}
1045
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001046std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1047 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1048 dex_file.GetLocation().c_str(),
1049 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1050 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1051 return os;
1052}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001053
Ian Rogersd91d6d62013-09-25 20:26:14 -07001054std::string Signature::ToString() const {
1055 if (dex_file_ == nullptr) {
1056 CHECK(proto_id_ == nullptr);
1057 return "<no signature>";
1058 }
1059 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1060 std::string result;
1061 if (params == nullptr) {
1062 result += "()";
1063 } else {
1064 result += "(";
1065 for (uint32_t i = 0; i < params->Size(); ++i) {
1066 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1067 }
1068 result += ")";
1069 }
1070 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1071 return result;
1072}
1073
Vladimir Markod9cffea2013-11-25 15:08:02 +00001074bool Signature::operator==(const StringPiece& rhs) const {
1075 if (dex_file_ == nullptr) {
1076 return false;
1077 }
1078 StringPiece tail(rhs);
1079 if (!tail.starts_with("(")) {
1080 return false; // Invalid signature
1081 }
1082 tail.remove_prefix(1); // "(";
1083 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1084 if (params != nullptr) {
1085 for (uint32_t i = 0; i < params->Size(); ++i) {
1086 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1087 if (!tail.starts_with(param)) {
1088 return false;
1089 }
1090 tail.remove_prefix(param.length());
1091 }
1092 }
1093 if (!tail.starts_with(")")) {
1094 return false;
1095 }
1096 tail.remove_prefix(1); // ")";
1097 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1098}
1099
Ian Rogersd91d6d62013-09-25 20:26:14 -07001100std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1101 return os << sig.ToString();
1102}
1103
Ian Rogers0571d352011-11-03 19:51:38 -07001104// Decodes the header section from the class data bytes.
1105void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001106 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001107 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1108 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1109 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1110 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1111}
1112
1113void ClassDataItemIterator::ReadClassDataField() {
1114 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1115 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001116 // The user of the iterator is responsible for checking if there
1117 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001118}
1119
1120void ClassDataItemIterator::ReadClassDataMethod() {
1121 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1122 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1123 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001124 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001125 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001126 }
Ian Rogers0571d352011-11-03 19:51:38 -07001127}
1128
1129// Read a signed integer. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001130static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001131 int32_t val = 0;
1132 for (int i = zwidth; i >= 0; --i) {
1133 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1134 }
1135 val >>= (3 - zwidth) * 8;
1136 return val;
1137}
1138
1139// Read an unsigned integer. "zwidth" is the zero-based byte count,
1140// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001141static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001142 uint32_t val = 0;
1143 if (!fill_on_right) {
1144 for (int i = zwidth; i >= 0; --i) {
1145 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1146 }
1147 val >>= (3 - zwidth) * 8;
1148 } else {
1149 for (int i = zwidth; i >= 0; --i) {
1150 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1151 }
1152 }
1153 return val;
1154}
1155
1156// Read a signed long. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001157static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001158 int64_t val = 0;
1159 for (int i = zwidth; i >= 0; --i) {
1160 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1161 }
1162 val >>= (7 - zwidth) * 8;
1163 return val;
1164}
1165
1166// Read an unsigned long. "zwidth" is the zero-based byte count,
1167// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001168static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001169 uint64_t val = 0;
1170 if (!fill_on_right) {
1171 for (int i = zwidth; i >= 0; --i) {
1172 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1173 }
1174 val >>= (7 - zwidth) * 8;
1175 } else {
1176 for (int i = zwidth; i >= 0; --i) {
1177 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1178 }
1179 }
1180 return val;
1181}
1182
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001183EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
1184 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
1185 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
1186 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001187 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1188 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001189 DCHECK(dex_cache != nullptr);
1190 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001191 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001192 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001193 array_size_ = 0;
1194 } else {
1195 array_size_ = DecodeUnsignedLeb128(&ptr_);
1196 }
1197 if (array_size_ > 0) {
1198 Next();
1199 }
1200}
1201
1202void EncodedStaticFieldValueIterator::Next() {
1203 pos_++;
1204 if (pos_ >= array_size_) {
1205 return;
1206 }
Ian Rogers13735952014-10-08 12:43:28 -07001207 uint8_t value_type = *ptr_++;
1208 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001209 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001210 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001211 switch (type_) {
1212 case kBoolean:
1213 jval_.i = (value_arg != 0) ? 1 : 0;
1214 width = 0;
1215 break;
1216 case kByte:
1217 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001218 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001219 break;
1220 case kShort:
1221 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001222 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001223 break;
1224 case kChar:
1225 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001226 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001227 break;
1228 case kInt:
1229 jval_.i = ReadSignedInt(ptr_, value_arg);
1230 break;
1231 case kLong:
1232 jval_.j = ReadSignedLong(ptr_, value_arg);
1233 break;
1234 case kFloat:
1235 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1236 break;
1237 case kDouble:
1238 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1239 break;
1240 case kString:
1241 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001242 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1243 break;
1244 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001245 case kMethod:
1246 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001247 case kArray:
1248 case kAnnotation:
1249 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001250 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001251 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001252 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001253 width = 0;
1254 break;
1255 default:
1256 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001257 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001258 }
1259 ptr_ += width;
1260}
1261
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001262template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07001263void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001264 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001265 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
1266 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001267 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1268 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1269 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1270 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1271 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1272 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1273 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001274 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001275 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001276 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001277 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001278 break;
1279 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001280 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001281 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1282 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001283 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001284 break;
1285 }
Ian Rogers0571d352011-11-03 19:51:38 -07001286 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1287 }
1288}
Mathieu Chartierc7853442015-03-27 14:35:38 -07001289template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
1290template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001291
1292CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1293 handler_.address_ = -1;
1294 int32_t offset = -1;
1295
1296 // Short-circuit the overwhelmingly common cases.
1297 switch (code_item.tries_size_) {
1298 case 0:
1299 break;
1300 case 1: {
1301 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1302 uint32_t start = tries->start_addr_;
1303 if (address >= start) {
1304 uint32_t end = start + tries->insn_count_;
1305 if (address < end) {
1306 offset = tries->handler_off_;
1307 }
1308 }
1309 break;
1310 }
1311 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001312 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001313 }
Logan Chien736df022012-04-27 16:25:57 +08001314 Init(code_item, offset);
1315}
1316
1317CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1318 const DexFile::TryItem& try_item) {
1319 handler_.address_ = -1;
1320 Init(code_item, try_item.handler_off_);
1321}
1322
1323void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1324 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001325 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001326 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001327 } else {
1328 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001329 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001330 remaining_count_ = -1;
1331 catch_all_ = false;
1332 DCHECK(!HasNext());
1333 }
1334}
1335
Ian Rogers13735952014-10-08 12:43:28 -07001336void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001337 current_data_ = handler_data;
1338 remaining_count_ = DecodeSignedLeb128(&current_data_);
1339
1340 // If remaining_count_ is non-positive, then it is the negative of
1341 // the number of catch types, and the catches are followed by a
1342 // catch-all handler.
1343 if (remaining_count_ <= 0) {
1344 catch_all_ = true;
1345 remaining_count_ = -remaining_count_;
1346 } else {
1347 catch_all_ = false;
1348 }
1349 Next();
1350}
1351
1352void CatchHandlerIterator::Next() {
1353 if (remaining_count_ > 0) {
1354 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1355 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1356 remaining_count_--;
1357 return;
1358 }
1359
1360 if (catch_all_) {
1361 handler_.type_idx_ = DexFile::kDexNoIndex16;
1362 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1363 catch_all_ = false;
1364 return;
1365 }
1366
1367 // no more handler
1368 remaining_count_ = -1;
1369}
1370
Carl Shapiro1fb86202011-06-27 17:43:13 -07001371} // namespace art