blob: 52590a59709068e6ac8c18e3ea0980705b286113 [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"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080034#include "base/stringprintf.h"
Ian Rogers0571d352011-11-03 19:51:38 -070035#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080037#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "leb128.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070041#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070042#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070044#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070045#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070046#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070047#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070048#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070049
Andreas Gampe277ccbd2014-11-03 21:36:10 -080050#pragma GCC diagnostic push
51#pragma GCC diagnostic ignored "-Wshadow"
52#include "ScopedFd.h"
53#pragma GCC diagnostic pop
54
Carl Shapiro1fb86202011-06-27 17:43:13 -070055namespace art {
56
Ian Rogers13735952014-10-08 12:43:28 -070057const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
58const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070059
Ian Rogers8d31bbd2013-10-13 10:44:14 -070060static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070061 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000062 ScopedFd fd(open(filename, O_RDONLY, 0));
63 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070064 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070065 return -1;
66 }
Vladimir Markofd995762013-11-06 16:36:36 +000067 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070070 return -1;
71 }
Vladimir Markofd995762013-11-06 16:36:36 +000072 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070073 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
74 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070075 return -1;
76 }
Vladimir Markofd995762013-11-06 16:36:36 +000077 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070078}
79
Ian Rogers8d31bbd2013-10-13 10:44:14 -070080bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070081 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070082 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070083
84 // Strip ":...", which is the location
85 const char* zip_entry_name = kClassesDex;
86 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010087 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070088
Vladimir Markoaa4497d2014-09-05 14:01:17 +010089 if (DexFile::IsMultiDexLocation(filename)) {
90 file_part_storage = GetBaseLocation(filename);
91 file_part = file_part_storage.c_str();
92 zip_entry_name = filename + file_part_storage.size() + 1;
93 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070094 }
95
96 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000097 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070098 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070099 return false;
100 }
101 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 std::unique_ptr<ZipArchive> zip_archive(
103 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
104 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800105 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
106 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800107 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700108 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700109 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700110 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700111 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
112 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return false;
114 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700115 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700117 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700118 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 std::unique_ptr<const DexFile> dex_file(
120 DexFile::OpenFile(fd.release(), filename, false, error_msg));
121 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800122 return false;
123 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700124 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800125 return true;
126 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700127 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800128 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700129}
130
Andreas Gampe833a4852014-05-21 18:46:59 -0700131bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800132 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700133 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700134 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000135 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
136 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700137 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700138 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700139 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700140 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700142 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700143 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
145 error_msg));
146 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800147 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700148 return true;
149 } else {
150 return false;
151 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700152 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700153 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400154 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700155}
156
Andreas Gampe0cba0042015-04-29 20:47:16 -0700157static bool ContainsClassesDex(int fd, const char* filename) {
158 std::string error_msg;
159 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
160 if (zip_archive.get() == nullptr) {
161 return false;
162 }
163 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
164 return (zip_entry.get() != nullptr);
165}
166
167bool DexFile::MaybeDex(const char* filename) {
168 uint32_t magic;
169 std::string error_msg;
170 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
171 if (fd.get() == -1) {
172 return false;
173 }
174 if (IsZipMagic(magic)) {
175 return ContainsClassesDex(fd.release(), filename);
176 } else if (IsDexMagic(magic)) {
177 return true;
178 }
179 return false;
180}
181
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800182int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700183 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800184 return 0;
185 } else {
186 return mem_map_->GetProtect();
187 }
188}
189
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200190bool DexFile::IsReadOnly() const {
191 return GetPermissions() == PROT_READ;
192}
193
Brian Carlstrome0948e12013-08-29 09:36:15 -0700194bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700196 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200197 return false;
198 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700199 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 }
201}
202
Brian Carlstrome0948e12013-08-29 09:36:15 -0700203bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200204 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700205 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200206 return false;
207 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700208 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200209 }
210}
211
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800212std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
213 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700214 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700215 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000216 {
217 ScopedFd delayed_close(fd);
218 struct stat sbuf;
219 memset(&sbuf, 0, sizeof(sbuf));
220 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800221 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000222 return nullptr;
223 }
224 if (S_ISDIR(sbuf.st_mode)) {
225 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
226 return nullptr;
227 }
228 size_t length = sbuf.st_size;
229 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
230 if (map.get() == nullptr) {
231 DCHECK(!error_msg->empty());
232 return nullptr;
233 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700234 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800235
236 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700237 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800238 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700239 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800240 }
241
242 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
243
Andreas Gampe928f72b2014-09-09 19:53:48 -0700244 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
245 error_msg));
246 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700247 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
248 error_msg->c_str());
249 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800250 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800251
Andreas Gampe928f72b2014-09-09 19:53:48 -0700252 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
253 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700254 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800255 }
256
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800257 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700258}
259
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700260const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700261
Andreas Gampe833a4852014-05-21 18:46:59 -0700262bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800263 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700264 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700265 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700266 if (zip_archive.get() == nullptr) {
267 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700268 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700269 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700270 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800271}
272
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800273std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
274 uint32_t location_checksum,
275 MemMap* mem_map,
276 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277 return OpenMemory(mem_map->Begin(),
278 mem_map->Size(),
279 location,
280 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700281 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800282 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800284}
285
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800286std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
287 const std::string& location, std::string* error_msg,
288 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800289 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700290 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700291 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700292 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700294 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700296 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700298 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700299 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700300 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700301 }
Ian Rogers700a4022014-05-19 16:49:03 -0700302 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 error_msg));
304 if (dex_file.get() == nullptr) {
305 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
306 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700307 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800309 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700310 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700311 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700312 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700313 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700314 }
315 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700316 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
317 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700318 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700319 return nullptr;
320 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700321 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800322 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700323}
324
Andreas Gampe90e34042015-04-27 20:01:52 -0700325// Technically we do not have a limitation with respect to the number of dex files that can be in a
326// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
327// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
328// seems an excessive number.
329static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
330
Andreas Gampe833a4852014-05-21 18:46:59 -0700331bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800332 std::string* error_msg,
333 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700334 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 ZipOpenErrorCode error_code;
336 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
337 &error_code));
338 if (dex_file.get() == nullptr) {
339 return false;
340 } else {
341 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800342 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700343
344 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700345
346 // We could try to avoid std::string allocations by working on a char array directly. As we
347 // do not expect a lot of iterations, this seems too involved and brittle.
348
Andreas Gampe90e34042015-04-27 20:01:52 -0700349 for (size_t i = 1; ; ++i) {
350 std::string name = GetMultiDexClassesDexName(i);
351 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700352 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
353 error_msg, &error_code));
354 if (next_dex_file.get() == nullptr) {
355 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
356 LOG(WARNING) << error_msg;
357 }
358 break;
359 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800360 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700361 }
362
Andreas Gampe90e34042015-04-27 20:01:52 -0700363 if (i == kWarnOnManyDexFilesThreshold) {
364 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
365 << " dex files. Please consider coalescing and shrinking the number to "
366 " avoid runtime overhead.";
367 }
368
369 if (i == std::numeric_limits<size_t>::max()) {
370 LOG(ERROR) << "Overflow in number of dex files!";
371 break;
372 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700373 }
374
375 return true;
376 }
377}
378
379
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800380std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
381 size_t size,
382 const std::string& location,
383 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800384 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700385 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800386 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700387 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800388 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700389 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700390 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800391 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700392 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800393 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700394}
395
Ian Rogers13735952014-10-08 12:43:28 -0700396DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800397 const std::string& location,
398 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800399 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700400 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800401 : begin_(base),
402 size_(size),
403 location_(location),
404 location_checksum_(location_checksum),
405 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800406 header_(reinterpret_cast<const Header*>(base)),
407 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
408 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
409 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
410 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
411 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700412 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
413 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800414 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700415 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700416 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800417 CHECK_GT(size_, 0U) << GetLocation();
418}
419
Jesse Wilson6bf19152011-09-29 13:12:33 -0400420DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700421 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
422 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
423 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
424 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700425 // Remove the index if one were created.
426 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400427}
428
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700430 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700431 return false;
432 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700433 return true;
434}
435
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700436bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800437 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700438 std::ostringstream oss;
439 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800440 << " " << header_->magic_[0]
441 << " " << header_->magic_[1]
442 << " " << header_->magic_[2]
443 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700444 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700445 return false;
446 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800447 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700448 std::ostringstream oss;
449 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800450 << " " << header_->magic_[4]
451 << " " << header_->magic_[5]
452 << " " << header_->magic_[6]
453 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700454 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700455 return false;
456 }
457 return true;
458}
459
Ian Rogers13735952014-10-08 12:43:28 -0700460bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800461 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
462}
463
Ian Rogers13735952014-10-08 12:43:28 -0700464bool DexFile::IsVersionValid(const uint8_t* magic) {
465 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800466 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
467}
468
Ian Rogersd81871c2011-10-03 13:57:23 -0700469uint32_t DexFile::GetVersion() const {
470 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
471 return atoi(version);
472}
473
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800474const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
475 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700476 // If we have an index lookup the descriptor via that as its constant time to search.
477 Index* index = class_def_index_.LoadSequentiallyConsistent();
478 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800479 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700480 return (it == index->end()) ? nullptr : it->second;
481 }
482 // Fast path for rate no class defs case.
483 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700484 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700485 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700486 }
Ian Rogers68b56852014-08-29 20:19:11 -0700487 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700488 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700489 if (string_id != nullptr) {
490 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
491 if (type_id != nullptr) {
492 uint16_t type_idx = GetIndexForTypeId(*type_id);
493 for (size_t i = 0; i < num_class_defs; ++i) {
494 const ClassDef& class_def = GetClassDef(i);
495 if (class_def.class_idx_ == type_idx) {
496 return &class_def;
497 }
498 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700499 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700500 }
Ian Rogers68b56852014-08-29 20:19:11 -0700501 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
502 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
503 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
504 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700505 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700506 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
507 if (old_misses == kMaxFailedDexClassDefLookups) {
508 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
509 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
510 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800511 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700512 for (uint32_t i = 0; i < num_class_defs; ++i) {
513 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800514 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800515 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700516 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700517 // Sanity check the index still doesn't exist, only 1 thread should build it.
518 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
519 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700520 }
521 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700522}
523
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700524const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
525 size_t num_class_defs = NumClassDefs();
526 for (size_t i = 0; i < num_class_defs; ++i) {
527 const ClassDef& class_def = GetClassDef(i);
528 if (class_def.class_idx_ == type_idx) {
529 return &class_def;
530 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700531 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700532 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700533}
534
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800535const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
536 const DexFile::StringId& name,
537 const DexFile::TypeId& type) const {
538 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
539 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
540 const uint32_t name_idx = GetIndexForStringId(name);
541 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700542 int32_t lo = 0;
543 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800544 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700545 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800546 const DexFile::FieldId& field = GetFieldId(mid);
547 if (class_idx > field.class_idx_) {
548 lo = mid + 1;
549 } else if (class_idx < field.class_idx_) {
550 hi = mid - 1;
551 } else {
552 if (name_idx > field.name_idx_) {
553 lo = mid + 1;
554 } else if (name_idx < field.name_idx_) {
555 hi = mid - 1;
556 } else {
557 if (type_idx > field.type_idx_) {
558 lo = mid + 1;
559 } else if (type_idx < field.type_idx_) {
560 hi = mid - 1;
561 } else {
562 return &field;
563 }
564 }
565 }
566 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700567 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800568}
569
570const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700571 const DexFile::StringId& name,
572 const DexFile::ProtoId& signature) const {
573 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800574 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700575 const uint32_t name_idx = GetIndexForStringId(name);
576 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700577 int32_t lo = 0;
578 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700579 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700581 const DexFile::MethodId& method = GetMethodId(mid);
582 if (class_idx > method.class_idx_) {
583 lo = mid + 1;
584 } else if (class_idx < method.class_idx_) {
585 hi = mid - 1;
586 } else {
587 if (name_idx > method.name_idx_) {
588 lo = mid + 1;
589 } else if (name_idx < method.name_idx_) {
590 hi = mid - 1;
591 } else {
592 if (proto_idx > method.proto_idx_) {
593 lo = mid + 1;
594 } else if (proto_idx < method.proto_idx_) {
595 hi = mid - 1;
596 } else {
597 return &method;
598 }
599 }
600 }
601 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700602 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700603}
604
Ian Rogers637c65b2013-05-31 11:46:00 -0700605const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700606 int32_t lo = 0;
607 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700608 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700609 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700610 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700611 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700612 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
613 if (compare > 0) {
614 lo = mid + 1;
615 } else if (compare < 0) {
616 hi = mid - 1;
617 } else {
618 return &str_id;
619 }
620 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700621 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700622}
623
Vladimir Markoa48aef42014-12-03 17:53:53 +0000624const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700625 int32_t lo = 0;
626 int32_t hi = NumStringIds() - 1;
627 while (hi >= lo) {
628 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700629 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700630 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000631 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700632 if (compare > 0) {
633 lo = mid + 1;
634 } else if (compare < 0) {
635 hi = mid - 1;
636 } else {
637 return &str_id;
638 }
639 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700640 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700641}
642
643const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700644 int32_t lo = 0;
645 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700646 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700647 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700648 const TypeId& type_id = GetTypeId(mid);
649 if (string_idx > type_id.descriptor_idx_) {
650 lo = mid + 1;
651 } else if (string_idx < type_id.descriptor_idx_) {
652 hi = mid - 1;
653 } else {
654 return &type_id;
655 }
656 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700657 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700658}
659
660const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000661 const uint16_t* signature_type_idxs,
662 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700663 int32_t lo = 0;
664 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700665 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700666 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700667 const DexFile::ProtoId& proto = GetProtoId(mid);
668 int compare = return_type_idx - proto.return_type_idx_;
669 if (compare == 0) {
670 DexFileParameterIterator it(*this, proto);
671 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000672 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800673 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700674 it.Next();
675 i++;
676 }
677 if (compare == 0) {
678 if (it.HasNext()) {
679 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000680 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700681 compare = 1;
682 }
683 }
684 }
685 if (compare > 0) {
686 lo = mid + 1;
687 } else if (compare < 0) {
688 hi = mid - 1;
689 } else {
690 return &proto;
691 }
692 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700693 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700694}
695
696// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700697bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
698 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700699 if (signature[0] != '(') {
700 return false;
701 }
702 size_t offset = 1;
703 size_t end = signature.size();
704 bool process_return = false;
705 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000706 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700707 char c = signature[offset];
708 offset++;
709 if (c == ')') {
710 process_return = true;
711 continue;
712 }
Ian Rogers0571d352011-11-03 19:51:38 -0700713 while (c == '[') { // process array prefix
714 if (offset >= end) { // expect some descriptor following [
715 return false;
716 }
717 c = signature[offset];
718 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700719 }
720 if (c == 'L') { // process type descriptors
721 do {
722 if (offset >= end) { // unexpected early termination of descriptor
723 return false;
724 }
725 c = signature[offset];
726 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700727 } while (c != ';');
728 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000729 // TODO: avoid creating a std::string just to get a 0-terminated char array
730 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700731 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700732 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700733 return false;
734 }
735 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700736 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700737 return false;
738 }
739 uint16_t type_idx = GetIndexForTypeId(*type_id);
740 if (!process_return) {
741 param_type_idxs->push_back(type_idx);
742 } else {
743 *return_type_idx = type_idx;
744 return offset == end; // return true if the signature had reached a sensible end
745 }
746 }
747 return false; // failed to correctly parse return type
748}
749
Ian Rogersd91d6d62013-09-25 20:26:14 -0700750const Signature DexFile::CreateSignature(const StringPiece& signature) const {
751 uint16_t return_type_idx;
752 std::vector<uint16_t> param_type_indices;
753 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
754 if (!success) {
755 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700756 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700757 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700759 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700760 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700761 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700762}
763
Mathieu Chartiere401d142015-04-22 13:56:20 -0700764int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700765 // For native method, lineno should be -2 to indicate it is native. Note that
766 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700767 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700768 return -2;
769 }
770
TDYa127c8dc1012012-04-19 07:03:33 -0700771 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700772 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700773
774 // A method with no line number info should return -1
775 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700776 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700777 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700778 return context.line_num_;
779}
780
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700781int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700782 // Note: Signed type is important for max and min.
783 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700784 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700785
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700786 while (min <= max) {
787 int32_t mid = min + ((max - min) / 2);
788
789 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
790 uint32_t start = ti->start_addr_;
791 uint32_t end = start + ti->insn_count_;
792
Ian Rogers0571d352011-11-03 19:51:38 -0700793 if (address < start) {
794 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700795 } else if (address >= end) {
796 min = mid + 1;
797 } else { // We have a winner!
798 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700799 }
800 }
801 // No match.
802 return -1;
803}
804
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700805int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
806 int32_t try_item = FindTryItem(code_item, address);
807 if (try_item == -1) {
808 return -1;
809 } else {
810 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
811 }
812}
813
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800814void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800815 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700816 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
817 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700818 uint32_t line = DecodeUnsignedLeb128(&stream);
819 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
820 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
821 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700822 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700823
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800824 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700825 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800826 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700827 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800828 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700829 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700830 local_in_reg[arg_reg].start_address_ = 0;
831 local_in_reg[arg_reg].is_live_ = true;
832 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700833 arg_reg++;
834 }
835
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800836 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700837 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700838 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700839 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800840 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 return;
842 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800843 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700844 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800845 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700846 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700847 local_in_reg[arg_reg].name_ = name;
848 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700849 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700850 local_in_reg[arg_reg].start_address_ = address;
851 local_in_reg[arg_reg].is_live_ = true;
852 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700853 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700854 case 'D':
855 case 'J':
856 arg_reg += 2;
857 break;
858 default:
859 arg_reg += 1;
860 break;
861 }
862 }
863
Ian Rogers0571d352011-11-03 19:51:38 -0700864 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800865 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
866 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700867 return;
868 }
869
870 for (;;) {
871 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700872 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800873 uint32_t name_idx;
874 uint32_t descriptor_idx;
875 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700876
Shih-wei Liao195487c2011-08-20 13:29:04 -0700877 switch (opcode) {
878 case DBG_END_SEQUENCE:
879 return;
880
881 case DBG_ADVANCE_PC:
882 address += DecodeUnsignedLeb128(&stream);
883 break;
884
885 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700886 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 break;
888
889 case DBG_START_LOCAL:
890 case DBG_START_LOCAL_EXTENDED:
891 reg = DecodeUnsignedLeb128(&stream);
892 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700893 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800894 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700895 return;
896 }
897
jeffhaof8728872011-10-28 19:11:13 -0700898 name_idx = DecodeUnsignedLeb128P1(&stream);
899 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
900 if (opcode == DBG_START_LOCAL_EXTENDED) {
901 signature_idx = DecodeUnsignedLeb128P1(&stream);
902 }
903
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700905 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800906 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907
Ian Rogers0571d352011-11-03 19:51:38 -0700908 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
909 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700910 local_in_reg[reg].signature_ =
911 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
912 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700913 local_in_reg[reg].start_address_ = address;
914 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700915 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700916 break;
917
918 case DBG_END_LOCAL:
919 reg = DecodeUnsignedLeb128(&stream);
920 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700921 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800922 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700923 return;
924 }
925
Elliott Hughes30646832011-10-13 16:59:46 -0700926 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800927 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700928 local_in_reg[reg].is_live_ = false;
929 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700930 break;
931
932 case DBG_RESTART_LOCAL:
933 reg = DecodeUnsignedLeb128(&stream);
934 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700935 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800936 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700937 return;
938 }
939
Elliott Hughes30646832011-10-13 16:59:46 -0700940 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700941 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800942 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700943 return;
944 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945
Elliott Hughes30646832011-10-13 16:59:46 -0700946 // If the register is live, the "restart" is superfluous,
947 // and we don't want to mess with the existing start address.
948 if (!local_in_reg[reg].is_live_) {
949 local_in_reg[reg].start_address_ = address;
950 local_in_reg[reg].is_live_ = true;
951 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700952 }
953 break;
954
955 case DBG_SET_PROLOGUE_END:
956 case DBG_SET_EPILOGUE_BEGIN:
957 case DBG_SET_FILE:
958 break;
959
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700960 default: {
961 int adjopcode = opcode - DBG_FIRST_SPECIAL;
962
Shih-wei Liao195487c2011-08-20 13:29:04 -0700963 address += adjopcode / DBG_LINE_RANGE;
964 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
965
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700966 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800967 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700968 // early exit
969 return;
970 }
971 }
972 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700973 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700974 }
975 }
976}
977
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800978void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800979 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
980 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100981 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700982 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700983 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700984 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700985 nullptr);
986 if (stream != nullptr) {
987 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
988 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700989 }
990 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700991 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
992 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700993 }
994}
995
Elliott Hughes2435a572012-02-17 16:07:41 -0800996bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
997 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700998
999 // We know that this callback will be called in
1000 // ascending address order, so keep going until we find
1001 // a match or we've just gone past it.
1002 if (address > context->address_) {
1003 // The line number from the previous positions callback
1004 // wil be the final result.
1005 return true;
1006 } else {
1007 context->line_num_ = line_num;
1008 return address == context->address_;
1009 }
1010}
1011
Andreas Gampe833a4852014-05-21 18:46:59 -07001012bool DexFile::IsMultiDexLocation(const char* location) {
1013 return strrchr(location, kMultiDexSeparator) != nullptr;
1014}
1015
Andreas Gampe90e34042015-04-27 20:01:52 -07001016std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1017 if (index == 0) {
1018 return "classes.dex";
1019 } else {
1020 return StringPrintf("classes%zu.dex", index + 1);
1021 }
1022}
1023
1024std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1025 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001026 return dex_location;
1027 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001028 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001029 }
1030}
1031
1032std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1033 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001034 std::string base_location = GetBaseLocation(dex_location);
1035 const char* suffix = dex_location + base_location.size();
1036 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1037 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1038 if (path != nullptr && path.get() != base_location) {
1039 return std::string(path.get()) + suffix;
1040 } else if (suffix[0] == 0) {
1041 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001042 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001043 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001044 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001045}
1046
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001047std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1048 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1049 dex_file.GetLocation().c_str(),
1050 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1051 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1052 return os;
1053}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001054
Ian Rogersd91d6d62013-09-25 20:26:14 -07001055std::string Signature::ToString() const {
1056 if (dex_file_ == nullptr) {
1057 CHECK(proto_id_ == nullptr);
1058 return "<no signature>";
1059 }
1060 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1061 std::string result;
1062 if (params == nullptr) {
1063 result += "()";
1064 } else {
1065 result += "(";
1066 for (uint32_t i = 0; i < params->Size(); ++i) {
1067 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1068 }
1069 result += ")";
1070 }
1071 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1072 return result;
1073}
1074
Vladimir Markod9cffea2013-11-25 15:08:02 +00001075bool Signature::operator==(const StringPiece& rhs) const {
1076 if (dex_file_ == nullptr) {
1077 return false;
1078 }
1079 StringPiece tail(rhs);
1080 if (!tail.starts_with("(")) {
1081 return false; // Invalid signature
1082 }
1083 tail.remove_prefix(1); // "(";
1084 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1085 if (params != nullptr) {
1086 for (uint32_t i = 0; i < params->Size(); ++i) {
1087 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1088 if (!tail.starts_with(param)) {
1089 return false;
1090 }
1091 tail.remove_prefix(param.length());
1092 }
1093 }
1094 if (!tail.starts_with(")")) {
1095 return false;
1096 }
1097 tail.remove_prefix(1); // ")";
1098 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1099}
1100
Ian Rogersd91d6d62013-09-25 20:26:14 -07001101std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1102 return os << sig.ToString();
1103}
1104
Ian Rogers0571d352011-11-03 19:51:38 -07001105// Decodes the header section from the class data bytes.
1106void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001107 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001108 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1109 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1110 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1111 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1112}
1113
1114void ClassDataItemIterator::ReadClassDataField() {
1115 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1116 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001117 // The user of the iterator is responsible for checking if there
1118 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001119}
1120
1121void ClassDataItemIterator::ReadClassDataMethod() {
1122 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1123 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1124 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001125 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001126 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001127 }
Ian Rogers0571d352011-11-03 19:51:38 -07001128}
1129
1130// Read a signed integer. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001131static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001132 int32_t val = 0;
1133 for (int i = zwidth; i >= 0; --i) {
1134 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1135 }
1136 val >>= (3 - zwidth) * 8;
1137 return val;
1138}
1139
1140// Read an unsigned integer. "zwidth" is the zero-based byte count,
1141// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001142static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001143 uint32_t val = 0;
1144 if (!fill_on_right) {
1145 for (int i = zwidth; i >= 0; --i) {
1146 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1147 }
1148 val >>= (3 - zwidth) * 8;
1149 } else {
1150 for (int i = zwidth; i >= 0; --i) {
1151 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1152 }
1153 }
1154 return val;
1155}
1156
1157// Read a signed long. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001158static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001159 int64_t val = 0;
1160 for (int i = zwidth; i >= 0; --i) {
1161 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1162 }
1163 val >>= (7 - zwidth) * 8;
1164 return val;
1165}
1166
1167// Read an unsigned long. "zwidth" is the zero-based byte count,
1168// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001169static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001170 uint64_t val = 0;
1171 if (!fill_on_right) {
1172 for (int i = zwidth; i >= 0; --i) {
1173 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1174 }
1175 val >>= (7 - zwidth) * 8;
1176 } else {
1177 for (int i = zwidth; i >= 0; --i) {
1178 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1179 }
1180 }
1181 return val;
1182}
1183
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001184EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
1185 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
1186 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
1187 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001188 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1189 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001190 DCHECK(dex_cache != nullptr);
1191 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001192 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001193 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001194 array_size_ = 0;
1195 } else {
1196 array_size_ = DecodeUnsignedLeb128(&ptr_);
1197 }
1198 if (array_size_ > 0) {
1199 Next();
1200 }
1201}
1202
1203void EncodedStaticFieldValueIterator::Next() {
1204 pos_++;
1205 if (pos_ >= array_size_) {
1206 return;
1207 }
Ian Rogers13735952014-10-08 12:43:28 -07001208 uint8_t value_type = *ptr_++;
1209 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001210 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001211 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001212 switch (type_) {
1213 case kBoolean:
1214 jval_.i = (value_arg != 0) ? 1 : 0;
1215 width = 0;
1216 break;
1217 case kByte:
1218 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001219 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001220 break;
1221 case kShort:
1222 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001223 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001224 break;
1225 case kChar:
1226 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001227 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001228 break;
1229 case kInt:
1230 jval_.i = ReadSignedInt(ptr_, value_arg);
1231 break;
1232 case kLong:
1233 jval_.j = ReadSignedLong(ptr_, value_arg);
1234 break;
1235 case kFloat:
1236 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1237 break;
1238 case kDouble:
1239 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1240 break;
1241 case kString:
1242 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001243 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1244 break;
1245 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001246 case kMethod:
1247 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001248 case kArray:
1249 case kAnnotation:
1250 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001251 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001252 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001253 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001254 width = 0;
1255 break;
1256 default:
1257 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001258 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001259 }
1260 ptr_ += width;
1261}
1262
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001263template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07001264void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001265 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001266 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
1267 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001268 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1269 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1270 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1271 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1272 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1273 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1274 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001275 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001276 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001277 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001278 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001279 break;
1280 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001281 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001282 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1283 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001284 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001285 break;
1286 }
Ian Rogers0571d352011-11-03 19:51:38 -07001287 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1288 }
1289}
Mathieu Chartierc7853442015-03-27 14:35:38 -07001290template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
1291template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001292
1293CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1294 handler_.address_ = -1;
1295 int32_t offset = -1;
1296
1297 // Short-circuit the overwhelmingly common cases.
1298 switch (code_item.tries_size_) {
1299 case 0:
1300 break;
1301 case 1: {
1302 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1303 uint32_t start = tries->start_addr_;
1304 if (address >= start) {
1305 uint32_t end = start + tries->insn_count_;
1306 if (address < end) {
1307 offset = tries->handler_off_;
1308 }
1309 }
1310 break;
1311 }
1312 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001313 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001314 }
Logan Chien736df022012-04-27 16:25:57 +08001315 Init(code_item, offset);
1316}
1317
1318CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1319 const DexFile::TryItem& try_item) {
1320 handler_.address_ = -1;
1321 Init(code_item, try_item.handler_off_);
1322}
1323
1324void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1325 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001326 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001327 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001328 } else {
1329 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001330 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001331 remaining_count_ = -1;
1332 catch_all_ = false;
1333 DCHECK(!HasNext());
1334 }
1335}
1336
Ian Rogers13735952014-10-08 12:43:28 -07001337void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001338 current_data_ = handler_data;
1339 remaining_count_ = DecodeSignedLeb128(&current_data_);
1340
1341 // If remaining_count_ is non-positive, then it is the negative of
1342 // the number of catch types, and the catches are followed by a
1343 // catch-all handler.
1344 if (remaining_count_ <= 0) {
1345 catch_all_ = true;
1346 remaining_count_ = -remaining_count_;
1347 } else {
1348 catch_all_ = false;
1349 }
1350 Next();
1351}
1352
1353void CatchHandlerIterator::Next() {
1354 if (remaining_count_ > 0) {
1355 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1356 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1357 remaining_count_--;
1358 return;
1359 }
1360
1361 if (catch_all_) {
1362 handler_.type_idx_ = DexFile::kDexNoIndex16;
1363 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1364 catch_all_ = false;
1365 return;
1366 }
1367
1368 // no more handler
1369 remaining_count_ = -1;
1370}
1371
Carl Shapiro1fb86202011-06-27 17:43:13 -07001372} // namespace art