blob: aa8fb38fca2f3e0f773229cb587ad7d91cdb9461 [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>
Andreas Gampea5b09a62016-11-17 15:21:22 -080029#include <type_traits>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070030
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000032#include "base/file_magic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
David Sehr9aa352e2016-09-15 18:13:52 -070034#include "base/stringprintf.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080035#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070036#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080038#include "dex_file_verifier.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010039#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070040#include "leb128.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070041#include "os.h"
Ian Rogersa6724902013-09-23 09:23:37 -070042#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070043#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070044#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070045
46namespace art {
47
Andreas Gampe8a0128a2016-11-28 07:38:35 -080048static_assert(sizeof(dex::StringIndex) == sizeof(uint32_t), "StringIndex size is wrong");
49static_assert(std::is_trivially_copyable<dex::StringIndex>::value, "StringIndex not trivial");
Andreas Gampea5b09a62016-11-17 15:21:22 -080050static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
51static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
52
David Sehr733ddb22016-09-19 15:02:18 -070053static constexpr OatDexFile* kNoOatDexFile = nullptr;
54
55const char* DexFile::kClassesDex = "classes.dex";
56
Ian Rogers13735952014-10-08 12:43:28 -070057const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070058const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
59 {'0', '3', '5', '\0'},
60 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
61 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010062 {'0', '3', '7', '\0'},
63 // Dex version 038: Android "O" and beyond.
64 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070065};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070066
Vladimir Marko3a21e382016-09-02 12:38:38 +010067struct DexFile::AnnotationValue {
68 JValue value_;
69 uint8_t type_;
70};
71
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070073 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070075
76 // Strip ":...", which is the location
77 const char* zip_entry_name = kClassesDex;
78 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010079 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070080
Vladimir Markoaa4497d2014-09-05 14:01:17 +010081 if (DexFile::IsMultiDexLocation(filename)) {
82 file_part_storage = GetBaseLocation(filename);
83 file_part = file_part_storage.c_str();
84 zip_entry_name = filename + file_part_storage.size() + 1;
85 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070086 }
87
Andreas Gampe43e10b02016-07-15 17:17:34 -070088 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
89 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070090 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070091 return false;
92 }
93 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070095 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080097 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
98 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700100 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700101 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700103 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
104 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return false;
106 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700112 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
115 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700116 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return true;
118 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700119 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800120 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700121}
122
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800123int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800125 return 0;
126 } else {
127 return mem_map_->GetProtect();
128 }
129}
130
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200131bool DexFile::IsReadOnly() const {
132 return GetPermissions() == PROT_READ;
133}
134
Brian Carlstrome0948e12013-08-29 09:36:15 -0700135bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200136 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700137 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200138 return false;
139 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700140 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200141 }
142}
143
Brian Carlstrome0948e12013-08-29 09:36:15 -0700144bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200145 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700146 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200147 return false;
148 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700149 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200150 }
151}
152
David Sehr733ddb22016-09-19 15:02:18 -0700153
154std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
155 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800156 const std::string& location,
157 uint32_t location_checksum,
158 const OatDexFile* oat_dex_file,
159 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700160 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800161 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800162 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700163 return OpenCommon(base,
164 size,
165 location,
166 location_checksum,
167 oat_dex_file,
168 verify,
169 verify_checksum,
170 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100171}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800172
Orion Hodsona4c2a052016-08-17 10:51:42 +0100173std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
174 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700175 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100176 bool verify,
177 bool verify_checksum,
178 std::string* error_msg) {
179 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700180 CHECK(map.get() != nullptr);
181 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
182 map->Size(),
183 location,
184 location_checksum,
185 kNoOatDexFile,
186 verify,
187 verify_checksum,
188 error_msg);
189 if (dex_file != nullptr) {
190 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100191 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800192 return dex_file;
193}
194
David Sehr733ddb22016-09-19 15:02:18 -0700195bool DexFile::Open(const char* filename,
196 const std::string& location,
197 bool verify_checksum,
198 std::string* error_msg,
199 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
200 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
201 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
202 uint32_t magic;
203 File fd = OpenAndReadMagic(filename, &magic, error_msg);
204 if (fd.Fd() == -1) {
205 DCHECK(!error_msg->empty());
206 return false;
207 }
208 if (IsZipMagic(magic)) {
209 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
210 }
211 if (IsDexMagic(magic)) {
212 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
213 location,
214 /* verify */ true,
215 verify_checksum,
216 error_msg));
217 if (dex_file.get() != nullptr) {
218 dex_files->push_back(std::move(dex_file));
219 return true;
220 } else {
221 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000222 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700223 }
David Sehr733ddb22016-09-19 15:02:18 -0700224 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
225 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700226}
227
David Sehr733ddb22016-09-19 15:02:18 -0700228std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
229 const std::string& location,
230 bool verify_checksum,
231 std::string* error_msg) {
232 ScopedTrace trace("Open dex file " + std::string(location));
233 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
234}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700235
Aart Bik37d6a3b2016-06-21 18:30:10 -0700236bool DexFile::OpenZip(int fd,
237 const std::string& location,
238 bool verify_checksum,
239 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800240 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800241 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700242 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700243 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700244 if (zip_archive.get() == nullptr) {
245 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700246 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700247 }
David Sehr733ddb22016-09-19 15:02:18 -0700248 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
249 location,
250 verify_checksum,
251 error_msg,
252 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800253}
254
David Sehr733ddb22016-09-19 15:02:18 -0700255std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
256 const std::string& location,
257 bool verify,
258 bool verify_checksum,
259 std::string* error_msg) {
260 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
261 CHECK(!location.empty());
262 std::unique_ptr<MemMap> map;
263 {
264 File delayed_close(fd, /* check_usage */ false);
265 struct stat sbuf;
266 memset(&sbuf, 0, sizeof(sbuf));
267 if (fstat(fd, &sbuf) == -1) {
268 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
269 strerror(errno));
270 return nullptr;
271 }
272 if (S_ISDIR(sbuf.st_mode)) {
273 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
274 return nullptr;
275 }
276 size_t length = sbuf.st_size;
277 map.reset(MemMap::MapFile(length,
278 PROT_READ,
279 MAP_PRIVATE,
280 fd,
281 0,
282 /*low_4gb*/false,
283 location.c_str(),
284 error_msg));
285 if (map == nullptr) {
286 DCHECK(!error_msg->empty());
287 return nullptr;
288 }
289 }
290
291 if (map->Size() < sizeof(DexFile::Header)) {
292 *error_msg = StringPrintf(
293 "DexFile: failed to open dex file '%s' that is too short to have a header",
294 location.c_str());
295 return nullptr;
296 }
297
298 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
299
300 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
301 map->Size(),
302 location,
303 dex_header->checksum_,
304 kNoOatDexFile,
305 verify,
306 verify_checksum,
307 error_msg);
308 if (dex_file != nullptr) {
309 dex_file->mem_map_.reset(map.release());
310 }
311
312 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800313}
314
David Sehr733ddb22016-09-19 15:02:18 -0700315std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
316 const char* entry_name,
317 const std::string& location,
318 bool verify_checksum,
319 std::string* error_msg,
320 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800321 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800322 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700324 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700325 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700327 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800328 if (zip_entry->GetUncompressedLength() == 0) {
329 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
330 *error_code = ZipOpenErrorCode::kDexFileError;
331 return nullptr;
332 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700333 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700334 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700337 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700338 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700339 }
David Sehr733ddb22016-09-19 15:02:18 -0700340 VerifyResult verify_result;
341 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
342 map->Size(),
343 location,
344 zip_entry->GetCrc32(),
345 kNoOatDexFile,
346 /* verify */ true,
347 verify_checksum,
348 error_msg,
349 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700350 if (dex_file == nullptr) {
351 if (verify_result == VerifyResult::kVerifyNotAttempted) {
352 *error_code = ZipOpenErrorCode::kDexFileError;
353 } else {
354 *error_code = ZipOpenErrorCode::kVerifyError;
355 }
356 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800357 }
David Sehr9fddd362016-09-22 14:05:37 -0700358 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700359 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700361 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700363 }
364 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700365 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700367 return nullptr;
368 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800370 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700371}
372
Andreas Gampe90e34042015-04-27 20:01:52 -0700373// Technically we do not have a limitation with respect to the number of dex files that can be in a
374// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
375// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
376// seems an excessive number.
377static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
378
David Sehr733ddb22016-09-19 15:02:18 -0700379bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
380 const std::string& location,
381 bool verify_checksum,
382 std::string* error_msg,
383 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800384 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700385 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700386 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700387 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
388 kClassesDex,
389 location,
390 verify_checksum,
391 error_msg,
392 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700393 if (dex_file.get() == nullptr) {
394 return false;
395 } else {
396 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800397 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700398
399 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700400
401 // We could try to avoid std::string allocations by working on a char array directly. As we
402 // do not expect a lot of iterations, this seems too involved and brittle.
403
Andreas Gampe90e34042015-04-27 20:01:52 -0700404 for (size_t i = 1; ; ++i) {
405 std::string name = GetMultiDexClassesDexName(i);
406 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700407 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
408 name.c_str(),
409 fake_location,
410 verify_checksum,
411 error_msg,
412 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700413 if (next_dex_file.get() == nullptr) {
414 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
415 LOG(WARNING) << error_msg;
416 }
417 break;
418 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800419 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700420 }
421
Andreas Gampe90e34042015-04-27 20:01:52 -0700422 if (i == kWarnOnManyDexFilesThreshold) {
423 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
424 << " dex files. Please consider coalescing and shrinking the number to "
425 " avoid runtime overhead.";
426 }
427
428 if (i == std::numeric_limits<size_t>::max()) {
429 LOG(ERROR) << "Overflow in number of dex files!";
430 break;
431 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700432 }
433
434 return true;
435 }
436}
437
David Sehr733ddb22016-09-19 15:02:18 -0700438std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
439 size_t size,
440 const std::string& location,
441 uint32_t location_checksum,
442 const OatDexFile* oat_dex_file,
443 bool verify,
444 bool verify_checksum,
445 std::string* error_msg,
446 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700447 if (verify_result != nullptr) {
448 *verify_result = VerifyResult::kVerifyNotAttempted;
449 }
David Sehr733ddb22016-09-19 15:02:18 -0700450 std::unique_ptr<DexFile> dex_file(new DexFile(base,
451 size,
452 location,
453 location_checksum,
454 oat_dex_file));
455 if (dex_file == nullptr) {
456 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
457 error_msg->c_str());
458 return nullptr;
459 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700460 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800461 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700462 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700463 }
David Sehr733ddb22016-09-19 15:02:18 -0700464 if (verify && !DexFileVerifier::Verify(dex_file.get(),
465 dex_file->Begin(),
466 dex_file->Size(),
467 location.c_str(),
468 verify_checksum,
469 error_msg)) {
470 if (verify_result != nullptr) {
471 *verify_result = VerifyResult::kVerifyFailed;
472 }
473 return nullptr;
474 }
475 if (verify_result != nullptr) {
476 *verify_result = VerifyResult::kVerifySucceeded;
477 }
478 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700479}
480
David Sehr733ddb22016-09-19 15:02:18 -0700481DexFile::DexFile(const uint8_t* base,
482 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800483 const std::string& location,
484 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700485 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800486 : begin_(base),
487 size_(size),
488 location_(location),
489 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800490 header_(reinterpret_cast<const Header*>(base)),
491 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
492 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
493 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
494 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
495 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700496 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700497 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700498 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800499 CHECK_GT(size_, 0U) << GetLocation();
500}
501
Jesse Wilson6bf19152011-09-29 13:12:33 -0400502DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700503 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
504 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
505 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
506 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400507}
508
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700510 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700511 return false;
512 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700513 return true;
514}
515
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700516bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800517 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700518 std::ostringstream oss;
519 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800520 << " " << header_->magic_[0]
521 << " " << header_->magic_[1]
522 << " " << header_->magic_[2]
523 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700524 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700525 return false;
526 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800527 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700528 std::ostringstream oss;
529 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800530 << " " << header_->magic_[4]
531 << " " << header_->magic_[5]
532 << " " << header_->magic_[6]
533 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700534 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700535 return false;
536 }
537 return true;
538}
539
Ian Rogers13735952014-10-08 12:43:28 -0700540bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800541 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
542}
543
Ian Rogers13735952014-10-08 12:43:28 -0700544bool DexFile::IsVersionValid(const uint8_t* magic) {
545 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700546 for (uint32_t i = 0; i < kNumDexVersions; i++) {
547 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
548 return true;
549 }
550 }
551 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800552}
553
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700554uint32_t DexFile::Header::GetVersion() const {
555 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700556 return atoi(version);
557}
558
Andreas Gampea5b09a62016-11-17 15:21:22 -0800559const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700560 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100561 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700562 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700563 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700564 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700565 for (size_t i = 0; i < num_class_defs; ++i) {
566 const ClassDef& class_def = GetClassDef(i);
567 if (class_def.class_idx_ == type_idx) {
568 return &class_def;
569 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700570 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700571 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700572}
573
Alex Light9c20a142016-08-23 15:05:12 -0700574uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
575 uint32_t method_idx) const {
576 const uint8_t* class_data = GetClassData(class_def);
577 CHECK(class_data != nullptr);
578 ClassDataItemIterator it(*this, class_data);
579 // Skip fields
580 while (it.HasNextStaticField()) {
581 it.Next();
582 }
583 while (it.HasNextInstanceField()) {
584 it.Next();
585 }
586 while (it.HasNextDirectMethod()) {
587 if (it.GetMemberIndex() == method_idx) {
588 return it.GetMethodCodeItemOffset();
589 }
590 it.Next();
591 }
592 while (it.HasNextVirtualMethod()) {
593 if (it.GetMemberIndex() == method_idx) {
594 return it.GetMethodCodeItemOffset();
595 }
596 it.Next();
597 }
598 LOG(FATAL) << "Unable to find method " << method_idx;
599 UNREACHABLE();
600}
601
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800602const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100603 const DexFile::StringId& name,
604 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800605 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800606 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800607 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800608 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700609 int32_t lo = 0;
610 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800611 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700612 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800613 const DexFile::FieldId& field = GetFieldId(mid);
614 if (class_idx > field.class_idx_) {
615 lo = mid + 1;
616 } else if (class_idx < field.class_idx_) {
617 hi = mid - 1;
618 } else {
619 if (name_idx > field.name_idx_) {
620 lo = mid + 1;
621 } else if (name_idx < field.name_idx_) {
622 hi = mid - 1;
623 } else {
624 if (type_idx > field.type_idx_) {
625 lo = mid + 1;
626 } else if (type_idx < field.type_idx_) {
627 hi = mid - 1;
628 } else {
629 return &field;
630 }
631 }
632 }
633 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700634 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800635}
636
637const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700638 const DexFile::StringId& name,
639 const DexFile::ProtoId& signature) const {
640 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800641 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800642 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700643 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700644 int32_t lo = 0;
645 int32_t hi = NumMethodIds() - 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 DexFile::MethodId& method = GetMethodId(mid);
649 if (class_idx > method.class_idx_) {
650 lo = mid + 1;
651 } else if (class_idx < method.class_idx_) {
652 hi = mid - 1;
653 } else {
654 if (name_idx > method.name_idx_) {
655 lo = mid + 1;
656 } else if (name_idx < method.name_idx_) {
657 hi = mid - 1;
658 } else {
659 if (proto_idx > method.proto_idx_) {
660 lo = mid + 1;
661 } else if (proto_idx < method.proto_idx_) {
662 hi = mid - 1;
663 } else {
664 return &method;
665 }
666 }
667 }
668 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700669 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700670}
671
Ian Rogers637c65b2013-05-31 11:46:00 -0700672const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700673 int32_t lo = 0;
674 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700675 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700676 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800677 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700678 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700679 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
680 if (compare > 0) {
681 lo = mid + 1;
682 } else if (compare < 0) {
683 hi = mid - 1;
684 } else {
685 return &str_id;
686 }
687 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700688 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700689}
690
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300691const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
692 int32_t lo = 0;
693 int32_t hi = NumTypeIds() - 1;
694 while (hi >= lo) {
695 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800696 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300697 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
698 const char* str = GetStringData(str_id);
699 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
700 if (compare > 0) {
701 lo = mid + 1;
702 } else if (compare < 0) {
703 hi = mid - 1;
704 } else {
705 return &type_id;
706 }
707 }
708 return nullptr;
709}
710
Vladimir Markoa48aef42014-12-03 17:53:53 +0000711const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700712 int32_t lo = 0;
713 int32_t hi = NumStringIds() - 1;
714 while (hi >= lo) {
715 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800716 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700717 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000718 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700719 if (compare > 0) {
720 lo = mid + 1;
721 } else if (compare < 0) {
722 hi = mid - 1;
723 } else {
724 return &str_id;
725 }
726 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700727 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700728}
729
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800730const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700731 int32_t lo = 0;
732 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700733 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700734 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800735 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700736 if (string_idx > type_id.descriptor_idx_) {
737 lo = mid + 1;
738 } else if (string_idx < type_id.descriptor_idx_) {
739 hi = mid - 1;
740 } else {
741 return &type_id;
742 }
743 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700744 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700745}
746
Andreas Gampea5b09a62016-11-17 15:21:22 -0800747const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
748 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000749 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700750 int32_t lo = 0;
751 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700752 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700753 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700754 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800755 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700756 if (compare == 0) {
757 DexFileParameterIterator it(*this, proto);
758 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000759 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800760 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700761 it.Next();
762 i++;
763 }
764 if (compare == 0) {
765 if (it.HasNext()) {
766 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000767 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700768 compare = 1;
769 }
770 }
771 }
772 if (compare > 0) {
773 lo = mid + 1;
774 } else if (compare < 0) {
775 hi = mid - 1;
776 } else {
777 return &proto;
778 }
779 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700780 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700781}
782
783// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800784bool DexFile::CreateTypeList(const StringPiece& signature,
785 dex::TypeIndex* return_type_idx,
786 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700787 if (signature[0] != '(') {
788 return false;
789 }
790 size_t offset = 1;
791 size_t end = signature.size();
792 bool process_return = false;
793 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000794 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700795 char c = signature[offset];
796 offset++;
797 if (c == ')') {
798 process_return = true;
799 continue;
800 }
Ian Rogers0571d352011-11-03 19:51:38 -0700801 while (c == '[') { // process array prefix
802 if (offset >= end) { // expect some descriptor following [
803 return false;
804 }
805 c = signature[offset];
806 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700807 }
808 if (c == 'L') { // process type descriptors
809 do {
810 if (offset >= end) { // unexpected early termination of descriptor
811 return false;
812 }
813 c = signature[offset];
814 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700815 } while (c != ';');
816 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000817 // TODO: avoid creating a std::string just to get a 0-terminated char array
818 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700819 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700820 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700821 return false;
822 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800823 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700824 if (!process_return) {
825 param_type_idxs->push_back(type_idx);
826 } else {
827 *return_type_idx = type_idx;
828 return offset == end; // return true if the signature had reached a sensible end
829 }
830 }
831 return false; // failed to correctly parse return type
832}
833
Ian Rogersd91d6d62013-09-25 20:26:14 -0700834const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800835 dex::TypeIndex return_type_idx;
836 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700837 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
838 if (!success) {
839 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700840 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700841 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700842 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700843 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700844 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700845 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700846}
847
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700848int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700849 // Note: Signed type is important for max and min.
850 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700851 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700852
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700853 while (min <= max) {
854 int32_t mid = min + ((max - min) / 2);
855
856 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
857 uint32_t start = ti->start_addr_;
858 uint32_t end = start + ti->insn_count_;
859
Ian Rogers0571d352011-11-03 19:51:38 -0700860 if (address < start) {
861 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700862 } else if (address >= end) {
863 min = mid + 1;
864 } else { // We have a winner!
865 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700866 }
867 }
868 // No match.
869 return -1;
870}
871
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700872int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
873 int32_t try_item = FindTryItem(code_item, address);
874 if (try_item == -1) {
875 return -1;
876 } else {
877 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
878 }
879}
880
David Srbeckyb06e28e2015-12-10 13:15:00 +0000881bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
882 DexDebugNewLocalCb local_cb, void* context) const {
883 DCHECK(local_cb != nullptr);
884 if (code_item == nullptr) {
885 return false;
886 }
887 const uint8_t* stream = GetDebugInfoStream(code_item);
888 if (stream == nullptr) {
889 return false;
890 }
891 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700892
David Srbeckyb06e28e2015-12-10 13:15:00 +0000893 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800894 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000895 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
896 local_in_reg[arg_reg].name_ = "this";
897 local_in_reg[arg_reg].descriptor_ = descriptor;
898 local_in_reg[arg_reg].signature_ = nullptr;
899 local_in_reg[arg_reg].start_address_ = 0;
900 local_in_reg[arg_reg].reg_ = arg_reg;
901 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700902 arg_reg++;
903 }
904
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800905 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 DecodeUnsignedLeb128(&stream); // Line.
907 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
908 uint32_t i;
909 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700911 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800912 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000913 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000915 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700916 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800917 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000918 local_in_reg[arg_reg].descriptor_ = descriptor;
919 local_in_reg[arg_reg].signature_ = nullptr;
920 local_in_reg[arg_reg].start_address_ = 0;
921 local_in_reg[arg_reg].reg_ = arg_reg;
922 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700923 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 case 'D':
925 case 'J':
926 arg_reg += 2;
927 break;
928 default:
929 arg_reg += 1;
930 break;
931 }
932 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000933 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800934 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700935 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000936 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700937 }
938
David Srbeckyb06e28e2015-12-10 13:15:00 +0000939 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700940 for (;;) {
941 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 switch (opcode) {
943 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000944 // Emit all variables which are still alive at the end of the method.
945 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
946 if (local_in_reg[reg].is_live_) {
947 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
948 local_cb(context, local_in_reg[reg]);
949 }
950 }
951 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700952 case DBG_ADVANCE_PC:
953 address += DecodeUnsignedLeb128(&stream);
954 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000956 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700957 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700958 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000959 case DBG_START_LOCAL_EXTENDED: {
960 uint16_t reg = DecodeUnsignedLeb128(&stream);
961 if (reg >= code_item->registers_size_) {
962 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800963 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000964 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700965 }
966
David Srbeckyb06e28e2015-12-10 13:15:00 +0000967 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
968 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
969 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700970 if (opcode == DBG_START_LOCAL_EXTENDED) {
971 signature_idx = DecodeUnsignedLeb128P1(&stream);
972 }
973
Shih-wei Liao195487c2011-08-20 13:29:04 -0700974 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000975 if (local_in_reg[reg].is_live_) {
976 local_in_reg[reg].end_address_ = address;
977 local_cb(context, local_in_reg[reg]);
978 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700979
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800980 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800981 local_in_reg[reg].descriptor_ =
982 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800983 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000984 local_in_reg[reg].start_address_ = address;
985 local_in_reg[reg].reg_ = reg;
986 local_in_reg[reg].is_live_ = true;
987 break;
988 }
989 case DBG_END_LOCAL: {
990 uint16_t reg = DecodeUnsignedLeb128(&stream);
991 if (reg >= code_item->registers_size_) {
992 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
993 << code_item->registers_size_ << ") in " << GetLocation();
994 return false;
995 }
996 if (!local_in_reg[reg].is_live_) {
997 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
998 return false;
999 }
1000 local_in_reg[reg].end_address_ = address;
1001 local_cb(context, local_in_reg[reg]);
1002 local_in_reg[reg].is_live_ = false;
1003 break;
1004 }
1005 case DBG_RESTART_LOCAL: {
1006 uint16_t reg = DecodeUnsignedLeb128(&stream);
1007 if (reg >= code_item->registers_size_) {
1008 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1009 << code_item->registers_size_ << ") in " << GetLocation();
1010 return false;
1011 }
1012 // If the register is live, the "restart" is superfluous,
1013 // and we don't want to mess with the existing start address.
1014 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001015 local_in_reg[reg].start_address_ = address;
1016 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001019 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001020 case DBG_SET_PROLOGUE_END:
1021 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001022 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001023 case DBG_SET_FILE:
1024 DecodeUnsignedLeb128P1(&stream); // name.
1025 break;
1026 default:
1027 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1028 break;
1029 }
1030 }
1031}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001032
David Srbeckyb06e28e2015-12-10 13:15:00 +00001033bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1034 void* context) const {
1035 DCHECK(position_cb != nullptr);
1036 if (code_item == nullptr) {
1037 return false;
1038 }
1039 const uint8_t* stream = GetDebugInfoStream(code_item);
1040 if (stream == nullptr) {
1041 return false;
1042 }
1043
1044 PositionInfo entry = PositionInfo();
1045 entry.line_ = DecodeUnsignedLeb128(&stream);
1046 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1047 for (uint32_t i = 0; i < parameters_size; ++i) {
1048 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1049 }
1050
1051 for (;;) {
1052 uint8_t opcode = *stream++;
1053 switch (opcode) {
1054 case DBG_END_SEQUENCE:
1055 return true; // end of stream.
1056 case DBG_ADVANCE_PC:
1057 entry.address_ += DecodeUnsignedLeb128(&stream);
1058 break;
1059 case DBG_ADVANCE_LINE:
1060 entry.line_ += DecodeSignedLeb128(&stream);
1061 break;
1062 case DBG_START_LOCAL:
1063 DecodeUnsignedLeb128(&stream); // reg.
1064 DecodeUnsignedLeb128P1(&stream); // name.
1065 DecodeUnsignedLeb128P1(&stream); // descriptor.
1066 break;
1067 case DBG_START_LOCAL_EXTENDED:
1068 DecodeUnsignedLeb128(&stream); // reg.
1069 DecodeUnsignedLeb128P1(&stream); // name.
1070 DecodeUnsignedLeb128P1(&stream); // descriptor.
1071 DecodeUnsignedLeb128P1(&stream); // signature.
1072 break;
1073 case DBG_END_LOCAL:
1074 case DBG_RESTART_LOCAL:
1075 DecodeUnsignedLeb128(&stream); // reg.
1076 break;
1077 case DBG_SET_PROLOGUE_END:
1078 entry.prologue_end_ = true;
1079 break;
1080 case DBG_SET_EPILOGUE_BEGIN:
1081 entry.epilogue_begin_ = true;
1082 break;
1083 case DBG_SET_FILE: {
1084 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001085 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001086 break;
1087 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001088 default: {
1089 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001090 entry.address_ += adjopcode / DBG_LINE_RANGE;
1091 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1092 if (position_cb(context, entry)) {
1093 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001094 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001095 entry.prologue_end_ = false;
1096 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001097 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001098 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001099 }
1100 }
1101}
1102
David Srbeckyb06e28e2015-12-10 13:15:00 +00001103bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001104 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001105
1106 // We know that this callback will be called in
1107 // ascending address order, so keep going until we find
1108 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001109 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001110 // The line number from the previous positions callback
1111 // wil be the final result.
1112 return true;
1113 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001114 context->line_num_ = entry.line_;
1115 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001116 }
1117}
1118
Andreas Gampe833a4852014-05-21 18:46:59 -07001119bool DexFile::IsMultiDexLocation(const char* location) {
1120 return strrchr(location, kMultiDexSeparator) != nullptr;
1121}
1122
Andreas Gampe90e34042015-04-27 20:01:52 -07001123std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1124 if (index == 0) {
1125 return "classes.dex";
1126 } else {
1127 return StringPrintf("classes%zu.dex", index + 1);
1128 }
1129}
1130
1131std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1132 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001133 return dex_location;
1134 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001135 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001136 }
1137}
1138
1139std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1140 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001141 std::string base_location = GetBaseLocation(dex_location);
1142 const char* suffix = dex_location + base_location.size();
1143 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1144 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1145 if (path != nullptr && path.get() != base_location) {
1146 return std::string(path.get()) + suffix;
1147 } else if (suffix[0] == 0) {
1148 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001149 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001150 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001151 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001152}
1153
Jeff Hao13e748b2015-08-25 20:44:19 +00001154// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001155int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001156 int32_t val = 0;
1157 for (int i = zwidth; i >= 0; --i) {
1158 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1159 }
1160 val >>= (3 - zwidth) * 8;
1161 return val;
1162}
1163
1164// Read an unsigned integer. "zwidth" is the zero-based byte count,
1165// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001166uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001167 uint32_t val = 0;
1168 for (int i = zwidth; i >= 0; --i) {
1169 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1170 }
1171 if (!fill_on_right) {
1172 val >>= (3 - zwidth) * 8;
1173 }
1174 return val;
1175}
1176
1177// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001178int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001179 int64_t val = 0;
1180 for (int i = zwidth; i >= 0; --i) {
1181 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1182 }
1183 val >>= (7 - zwidth) * 8;
1184 return val;
1185}
1186
1187// Read an unsigned long. "zwidth" is the zero-based byte count,
1188// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001189uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001190 uint64_t val = 0;
1191 for (int i = zwidth; i >= 0; --i) {
1192 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1193 }
1194 if (!fill_on_right) {
1195 val >>= (7 - zwidth) * 8;
1196 }
1197 return val;
1198}
1199
David Sehr709b0702016-10-13 09:12:37 -07001200std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1201 if (method_idx >= NumMethodIds()) {
1202 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1203 }
1204 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1205 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1206 result += '.';
1207 result += GetMethodName(method_id);
1208 if (with_signature) {
1209 const Signature signature = GetMethodSignature(method_id);
1210 std::string sig_as_string(signature.ToString());
1211 if (signature == Signature::NoSignature()) {
1212 return result + sig_as_string;
1213 }
1214 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1215 PrettyArguments(sig_as_string.c_str());
1216 }
1217 return result;
1218}
1219
1220std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1221 if (field_idx >= NumFieldIds()) {
1222 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1223 }
1224 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1225 std::string result;
1226 if (with_type) {
1227 result += GetFieldTypeDescriptor(field_id);
1228 result += ' ';
1229 }
1230 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1231 result += '.';
1232 result += GetFieldName(field_id);
1233 return result;
1234}
1235
Andreas Gampea5b09a62016-11-17 15:21:22 -08001236std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1237 if (type_idx.index_ >= NumTypeIds()) {
1238 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001239 }
1240 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1241 return PrettyDescriptor(GetTypeDescriptor(type_id));
1242}
1243
Jeff Hao3d080862016-05-26 18:39:17 -07001244// Checks that visibility is as expected. Includes special behavior for M and
1245// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001246std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1247 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1248 dex_file.GetLocation().c_str(),
1249 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1250 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1251 return os;
1252}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001253
Ian Rogersd91d6d62013-09-25 20:26:14 -07001254std::string Signature::ToString() const {
1255 if (dex_file_ == nullptr) {
1256 CHECK(proto_id_ == nullptr);
1257 return "<no signature>";
1258 }
1259 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1260 std::string result;
1261 if (params == nullptr) {
1262 result += "()";
1263 } else {
1264 result += "(";
1265 for (uint32_t i = 0; i < params->Size(); ++i) {
1266 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1267 }
1268 result += ")";
1269 }
1270 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1271 return result;
1272}
1273
Vladimir Markod9cffea2013-11-25 15:08:02 +00001274bool Signature::operator==(const StringPiece& rhs) const {
1275 if (dex_file_ == nullptr) {
1276 return false;
1277 }
1278 StringPiece tail(rhs);
1279 if (!tail.starts_with("(")) {
1280 return false; // Invalid signature
1281 }
1282 tail.remove_prefix(1); // "(";
1283 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1284 if (params != nullptr) {
1285 for (uint32_t i = 0; i < params->Size(); ++i) {
1286 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1287 if (!tail.starts_with(param)) {
1288 return false;
1289 }
1290 tail.remove_prefix(param.length());
1291 }
1292 }
1293 if (!tail.starts_with(")")) {
1294 return false;
1295 }
1296 tail.remove_prefix(1); // ")";
1297 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1298}
1299
Ian Rogersd91d6d62013-09-25 20:26:14 -07001300std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1301 return os << sig.ToString();
1302}
1303
Ian Rogers0571d352011-11-03 19:51:38 -07001304// Decodes the header section from the class data bytes.
1305void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001306 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001307 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1308 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1309 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1310 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1311}
1312
1313void ClassDataItemIterator::ReadClassDataField() {
1314 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1315 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001316 // The user of the iterator is responsible for checking if there
1317 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001318}
1319
1320void ClassDataItemIterator::ReadClassDataMethod() {
1321 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1322 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1323 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001324 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001325 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001326 }
Ian Rogers0571d352011-11-03 19:51:38 -07001327}
1328
David Sehr9323e6e2016-09-13 08:58:35 -07001329EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1330 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001331 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001332 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001333 pos_(-1),
1334 type_(kByte) {
1335 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001336 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001337 array_size_ = 0;
1338 } else {
1339 array_size_ = DecodeUnsignedLeb128(&ptr_);
1340 }
1341 if (array_size_ > 0) {
1342 Next();
1343 }
1344}
1345
1346void EncodedStaticFieldValueIterator::Next() {
1347 pos_++;
1348 if (pos_ >= array_size_) {
1349 return;
1350 }
Ian Rogers13735952014-10-08 12:43:28 -07001351 uint8_t value_type = *ptr_++;
1352 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001353 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001354 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001355 switch (type_) {
1356 case kBoolean:
1357 jval_.i = (value_arg != 0) ? 1 : 0;
1358 width = 0;
1359 break;
1360 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001361 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001362 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001363 break;
1364 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001365 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001366 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001367 break;
1368 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001369 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001370 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001371 break;
1372 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001373 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001374 break;
1375 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001376 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001377 break;
1378 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001379 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001380 break;
1381 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001382 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001383 break;
1384 case kString:
1385 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001386 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001387 break;
1388 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001389 case kMethod:
1390 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001391 case kArray:
1392 case kAnnotation:
1393 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001394 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001395 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001396 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001397 width = 0;
1398 break;
1399 default:
1400 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001401 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001402 }
1403 ptr_ += width;
1404}
1405
Ian Rogers0571d352011-11-03 19:51:38 -07001406CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1407 handler_.address_ = -1;
1408 int32_t offset = -1;
1409
1410 // Short-circuit the overwhelmingly common cases.
1411 switch (code_item.tries_size_) {
1412 case 0:
1413 break;
1414 case 1: {
1415 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1416 uint32_t start = tries->start_addr_;
1417 if (address >= start) {
1418 uint32_t end = start + tries->insn_count_;
1419 if (address < end) {
1420 offset = tries->handler_off_;
1421 }
1422 }
1423 break;
1424 }
1425 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001426 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001427 }
Logan Chien736df022012-04-27 16:25:57 +08001428 Init(code_item, offset);
1429}
1430
1431CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1432 const DexFile::TryItem& try_item) {
1433 handler_.address_ = -1;
1434 Init(code_item, try_item.handler_off_);
1435}
1436
1437void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1438 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001439 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001440 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001441 } else {
1442 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001443 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001444 remaining_count_ = -1;
1445 catch_all_ = false;
1446 DCHECK(!HasNext());
1447 }
1448}
1449
Ian Rogers13735952014-10-08 12:43:28 -07001450void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001451 current_data_ = handler_data;
1452 remaining_count_ = DecodeSignedLeb128(&current_data_);
1453
1454 // If remaining_count_ is non-positive, then it is the negative of
1455 // the number of catch types, and the catches are followed by a
1456 // catch-all handler.
1457 if (remaining_count_ <= 0) {
1458 catch_all_ = true;
1459 remaining_count_ = -remaining_count_;
1460 } else {
1461 catch_all_ = false;
1462 }
1463 Next();
1464}
1465
1466void CatchHandlerIterator::Next() {
1467 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001468 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001469 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1470 remaining_count_--;
1471 return;
1472 }
1473
1474 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001475 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001476 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1477 catch_all_ = false;
1478 return;
1479 }
1480
1481 // no more handler
1482 remaining_count_ = -1;
1483}
1484
Andreas Gampea5b09a62016-11-17 15:21:22 -08001485namespace dex {
1486
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001487std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1488 os << "StringIndex[" << index.index_ << "]";
1489 return os;
1490}
1491
Andreas Gampea5b09a62016-11-17 15:21:22 -08001492std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1493 os << "TypeIndex[" << index.index_ << "]";
1494 return os;
1495}
1496
1497} // namespace dex
1498
Carl Shapiro1fb86202011-06-27 17:43:13 -07001499} // namespace art