blob: cc544fd51c29f390c451c377c51c278ba68f2f90 [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 Gampea5b09a62016-11-17 15:21:22 -080048static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
49static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
50
David Sehr733ddb22016-09-19 15:02:18 -070051static constexpr OatDexFile* kNoOatDexFile = nullptr;
52
53const char* DexFile::kClassesDex = "classes.dex";
54
Ian Rogers13735952014-10-08 12:43:28 -070055const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070056const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
57 {'0', '3', '5', '\0'},
58 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
59 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010060 {'0', '3', '7', '\0'},
61 // Dex version 038: Android "O" and beyond.
62 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070063};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070064
Vladimir Marko3a21e382016-09-02 12:38:38 +010065struct DexFile::AnnotationValue {
66 JValue value_;
67 uint8_t type_;
68};
69
Ian Rogers8d31bbd2013-10-13 10:44:14 -070070bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070071 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070072 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070073
74 // Strip ":...", which is the location
75 const char* zip_entry_name = kClassesDex;
76 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010077 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070078
Vladimir Markoaa4497d2014-09-05 14:01:17 +010079 if (DexFile::IsMultiDexLocation(filename)) {
80 file_part_storage = GetBaseLocation(filename);
81 file_part = file_part_storage.c_str();
82 zip_entry_name = filename + file_part_storage.size() + 1;
83 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070084 }
85
Andreas Gampe43e10b02016-07-15 17:17:34 -070086 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
87 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070088 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070089 return false;
90 }
91 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070092 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070093 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080095 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
96 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080097 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070098 }
Andreas Gampe833a4852014-05-21 18:46:59 -070099 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700100 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700101 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
102 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800103 return false;
104 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700105 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800106 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700107 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700108 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700110 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
113 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700114 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return true;
116 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700117 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700119}
120
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800121int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800123 return 0;
124 } else {
125 return mem_map_->GetProtect();
126 }
127}
128
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200129bool DexFile::IsReadOnly() const {
130 return GetPermissions() == PROT_READ;
131}
132
Brian Carlstrome0948e12013-08-29 09:36:15 -0700133bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200134 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700135 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200136 return false;
137 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700138 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200139 }
140}
141
Brian Carlstrome0948e12013-08-29 09:36:15 -0700142bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200143 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700144 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200145 return false;
146 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700147 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200148 }
149}
150
David Sehr733ddb22016-09-19 15:02:18 -0700151
152std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
153 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800154 const std::string& location,
155 uint32_t location_checksum,
156 const OatDexFile* oat_dex_file,
157 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700158 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800159 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800160 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700161 return OpenCommon(base,
162 size,
163 location,
164 location_checksum,
165 oat_dex_file,
166 verify,
167 verify_checksum,
168 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100169}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800170
Orion Hodsona4c2a052016-08-17 10:51:42 +0100171std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
172 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700173 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100174 bool verify,
175 bool verify_checksum,
176 std::string* error_msg) {
177 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700178 CHECK(map.get() != nullptr);
179 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
180 map->Size(),
181 location,
182 location_checksum,
183 kNoOatDexFile,
184 verify,
185 verify_checksum,
186 error_msg);
187 if (dex_file != nullptr) {
188 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100189 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800190 return dex_file;
191}
192
David Sehr733ddb22016-09-19 15:02:18 -0700193bool DexFile::Open(const char* filename,
194 const std::string& location,
195 bool verify_checksum,
196 std::string* error_msg,
197 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
198 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
199 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
200 uint32_t magic;
201 File fd = OpenAndReadMagic(filename, &magic, error_msg);
202 if (fd.Fd() == -1) {
203 DCHECK(!error_msg->empty());
204 return false;
205 }
206 if (IsZipMagic(magic)) {
207 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
208 }
209 if (IsDexMagic(magic)) {
210 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
211 location,
212 /* verify */ true,
213 verify_checksum,
214 error_msg));
215 if (dex_file.get() != nullptr) {
216 dex_files->push_back(std::move(dex_file));
217 return true;
218 } else {
219 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000220 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700221 }
David Sehr733ddb22016-09-19 15:02:18 -0700222 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
223 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700224}
225
David Sehr733ddb22016-09-19 15:02:18 -0700226std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
227 const std::string& location,
228 bool verify_checksum,
229 std::string* error_msg) {
230 ScopedTrace trace("Open dex file " + std::string(location));
231 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
232}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700233
Aart Bik37d6a3b2016-06-21 18:30:10 -0700234bool DexFile::OpenZip(int fd,
235 const std::string& location,
236 bool verify_checksum,
237 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800238 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800239 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700240 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700241 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700242 if (zip_archive.get() == nullptr) {
243 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700244 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700245 }
David Sehr733ddb22016-09-19 15:02:18 -0700246 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
247 location,
248 verify_checksum,
249 error_msg,
250 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800251}
252
David Sehr733ddb22016-09-19 15:02:18 -0700253std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
254 const std::string& location,
255 bool verify,
256 bool verify_checksum,
257 std::string* error_msg) {
258 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
259 CHECK(!location.empty());
260 std::unique_ptr<MemMap> map;
261 {
262 File delayed_close(fd, /* check_usage */ false);
263 struct stat sbuf;
264 memset(&sbuf, 0, sizeof(sbuf));
265 if (fstat(fd, &sbuf) == -1) {
266 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
267 strerror(errno));
268 return nullptr;
269 }
270 if (S_ISDIR(sbuf.st_mode)) {
271 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
272 return nullptr;
273 }
274 size_t length = sbuf.st_size;
275 map.reset(MemMap::MapFile(length,
276 PROT_READ,
277 MAP_PRIVATE,
278 fd,
279 0,
280 /*low_4gb*/false,
281 location.c_str(),
282 error_msg));
283 if (map == nullptr) {
284 DCHECK(!error_msg->empty());
285 return nullptr;
286 }
287 }
288
289 if (map->Size() < sizeof(DexFile::Header)) {
290 *error_msg = StringPrintf(
291 "DexFile: failed to open dex file '%s' that is too short to have a header",
292 location.c_str());
293 return nullptr;
294 }
295
296 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
297
298 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
299 map->Size(),
300 location,
301 dex_header->checksum_,
302 kNoOatDexFile,
303 verify,
304 verify_checksum,
305 error_msg);
306 if (dex_file != nullptr) {
307 dex_file->mem_map_.reset(map.release());
308 }
309
310 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311}
312
David Sehr733ddb22016-09-19 15:02:18 -0700313std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
314 const char* entry_name,
315 const std::string& location,
316 bool verify_checksum,
317 std::string* error_msg,
318 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800319 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800320 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700321 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700322 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700324 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700325 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800326 if (zip_entry->GetUncompressedLength() == 0) {
327 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
328 *error_code = ZipOpenErrorCode::kDexFileError;
329 return nullptr;
330 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700331 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700332 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700333 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700334 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700337 }
David Sehr733ddb22016-09-19 15:02:18 -0700338 VerifyResult verify_result;
339 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
340 map->Size(),
341 location,
342 zip_entry->GetCrc32(),
343 kNoOatDexFile,
344 /* verify */ true,
345 verify_checksum,
346 error_msg,
347 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700348 if (dex_file == nullptr) {
349 if (verify_result == VerifyResult::kVerifyNotAttempted) {
350 *error_code = ZipOpenErrorCode::kDexFileError;
351 } else {
352 *error_code = ZipOpenErrorCode::kVerifyError;
353 }
354 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800355 }
David Sehr9fddd362016-09-22 14:05:37 -0700356 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700357 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700359 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700361 }
362 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700363 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700365 return nullptr;
366 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700367 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800368 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700369}
370
Andreas Gampe90e34042015-04-27 20:01:52 -0700371// Technically we do not have a limitation with respect to the number of dex files that can be in a
372// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
373// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
374// seems an excessive number.
375static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
376
David Sehr733ddb22016-09-19 15:02:18 -0700377bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
378 const std::string& location,
379 bool verify_checksum,
380 std::string* error_msg,
381 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800382 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700383 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700384 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700385 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
386 kClassesDex,
387 location,
388 verify_checksum,
389 error_msg,
390 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700391 if (dex_file.get() == nullptr) {
392 return false;
393 } else {
394 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800395 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700396
397 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700398
399 // We could try to avoid std::string allocations by working on a char array directly. As we
400 // do not expect a lot of iterations, this seems too involved and brittle.
401
Andreas Gampe90e34042015-04-27 20:01:52 -0700402 for (size_t i = 1; ; ++i) {
403 std::string name = GetMultiDexClassesDexName(i);
404 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700405 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
406 name.c_str(),
407 fake_location,
408 verify_checksum,
409 error_msg,
410 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700411 if (next_dex_file.get() == nullptr) {
412 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
413 LOG(WARNING) << error_msg;
414 }
415 break;
416 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800417 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700418 }
419
Andreas Gampe90e34042015-04-27 20:01:52 -0700420 if (i == kWarnOnManyDexFilesThreshold) {
421 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
422 << " dex files. Please consider coalescing and shrinking the number to "
423 " avoid runtime overhead.";
424 }
425
426 if (i == std::numeric_limits<size_t>::max()) {
427 LOG(ERROR) << "Overflow in number of dex files!";
428 break;
429 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700430 }
431
432 return true;
433 }
434}
435
David Sehr733ddb22016-09-19 15:02:18 -0700436std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
437 size_t size,
438 const std::string& location,
439 uint32_t location_checksum,
440 const OatDexFile* oat_dex_file,
441 bool verify,
442 bool verify_checksum,
443 std::string* error_msg,
444 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700445 if (verify_result != nullptr) {
446 *verify_result = VerifyResult::kVerifyNotAttempted;
447 }
David Sehr733ddb22016-09-19 15:02:18 -0700448 std::unique_ptr<DexFile> dex_file(new DexFile(base,
449 size,
450 location,
451 location_checksum,
452 oat_dex_file));
453 if (dex_file == nullptr) {
454 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
455 error_msg->c_str());
456 return nullptr;
457 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700458 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800459 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700460 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700461 }
David Sehr733ddb22016-09-19 15:02:18 -0700462 if (verify && !DexFileVerifier::Verify(dex_file.get(),
463 dex_file->Begin(),
464 dex_file->Size(),
465 location.c_str(),
466 verify_checksum,
467 error_msg)) {
468 if (verify_result != nullptr) {
469 *verify_result = VerifyResult::kVerifyFailed;
470 }
471 return nullptr;
472 }
473 if (verify_result != nullptr) {
474 *verify_result = VerifyResult::kVerifySucceeded;
475 }
476 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700477}
478
David Sehr733ddb22016-09-19 15:02:18 -0700479DexFile::DexFile(const uint8_t* base,
480 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800481 const std::string& location,
482 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700483 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800484 : begin_(base),
485 size_(size),
486 location_(location),
487 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800488 header_(reinterpret_cast<const Header*>(base)),
489 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
490 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
491 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
492 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
493 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700494 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700495 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700496 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800497 CHECK_GT(size_, 0U) << GetLocation();
498}
499
Jesse Wilson6bf19152011-09-29 13:12:33 -0400500DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700501 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
502 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
503 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
504 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400505}
506
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700507bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700509 return false;
510 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700511 return true;
512}
513
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700514bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800515 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700516 std::ostringstream oss;
517 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800518 << " " << header_->magic_[0]
519 << " " << header_->magic_[1]
520 << " " << header_->magic_[2]
521 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700522 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700523 return false;
524 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800525 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700526 std::ostringstream oss;
527 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800528 << " " << header_->magic_[4]
529 << " " << header_->magic_[5]
530 << " " << header_->magic_[6]
531 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700532 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700533 return false;
534 }
535 return true;
536}
537
Ian Rogers13735952014-10-08 12:43:28 -0700538bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800539 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
540}
541
Ian Rogers13735952014-10-08 12:43:28 -0700542bool DexFile::IsVersionValid(const uint8_t* magic) {
543 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700544 for (uint32_t i = 0; i < kNumDexVersions; i++) {
545 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
546 return true;
547 }
548 }
549 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800550}
551
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700552uint32_t DexFile::Header::GetVersion() const {
553 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700554 return atoi(version);
555}
556
Andreas Gampea5b09a62016-11-17 15:21:22 -0800557const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700558 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100559 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700560 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700561 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700562 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700563 for (size_t i = 0; i < num_class_defs; ++i) {
564 const ClassDef& class_def = GetClassDef(i);
565 if (class_def.class_idx_ == type_idx) {
566 return &class_def;
567 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700568 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700569 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700570}
571
Alex Light9c20a142016-08-23 15:05:12 -0700572uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
573 uint32_t method_idx) const {
574 const uint8_t* class_data = GetClassData(class_def);
575 CHECK(class_data != nullptr);
576 ClassDataItemIterator it(*this, class_data);
577 // Skip fields
578 while (it.HasNextStaticField()) {
579 it.Next();
580 }
581 while (it.HasNextInstanceField()) {
582 it.Next();
583 }
584 while (it.HasNextDirectMethod()) {
585 if (it.GetMemberIndex() == method_idx) {
586 return it.GetMethodCodeItemOffset();
587 }
588 it.Next();
589 }
590 while (it.HasNextVirtualMethod()) {
591 if (it.GetMemberIndex() == method_idx) {
592 return it.GetMethodCodeItemOffset();
593 }
594 it.Next();
595 }
596 LOG(FATAL) << "Unable to find method " << method_idx;
597 UNREACHABLE();
598}
599
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800600const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100601 const DexFile::StringId& name,
602 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800603 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800604 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800605 const uint32_t name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800606 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700607 int32_t lo = 0;
608 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800609 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700610 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800611 const DexFile::FieldId& field = GetFieldId(mid);
612 if (class_idx > field.class_idx_) {
613 lo = mid + 1;
614 } else if (class_idx < field.class_idx_) {
615 hi = mid - 1;
616 } else {
617 if (name_idx > field.name_idx_) {
618 lo = mid + 1;
619 } else if (name_idx < field.name_idx_) {
620 hi = mid - 1;
621 } else {
622 if (type_idx > field.type_idx_) {
623 lo = mid + 1;
624 } else if (type_idx < field.type_idx_) {
625 hi = mid - 1;
626 } else {
627 return &field;
628 }
629 }
630 }
631 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700632 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800633}
634
635const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700636 const DexFile::StringId& name,
637 const DexFile::ProtoId& signature) const {
638 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800639 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700640 const uint32_t name_idx = GetIndexForStringId(name);
641 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700642 int32_t lo = 0;
643 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700644 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700645 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700646 const DexFile::MethodId& method = GetMethodId(mid);
647 if (class_idx > method.class_idx_) {
648 lo = mid + 1;
649 } else if (class_idx < method.class_idx_) {
650 hi = mid - 1;
651 } else {
652 if (name_idx > method.name_idx_) {
653 lo = mid + 1;
654 } else if (name_idx < method.name_idx_) {
655 hi = mid - 1;
656 } else {
657 if (proto_idx > method.proto_idx_) {
658 lo = mid + 1;
659 } else if (proto_idx < method.proto_idx_) {
660 hi = mid - 1;
661 } else {
662 return &method;
663 }
664 }
665 }
666 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700667 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700668}
669
Ian Rogers637c65b2013-05-31 11:46:00 -0700670const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700671 int32_t lo = 0;
672 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700673 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700674 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700675 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700676 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700677 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
678 if (compare > 0) {
679 lo = mid + 1;
680 } else if (compare < 0) {
681 hi = mid - 1;
682 } else {
683 return &str_id;
684 }
685 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700686 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700687}
688
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300689const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
690 int32_t lo = 0;
691 int32_t hi = NumTypeIds() - 1;
692 while (hi >= lo) {
693 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800694 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300695 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
696 const char* str = GetStringData(str_id);
697 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
698 if (compare > 0) {
699 lo = mid + 1;
700 } else if (compare < 0) {
701 hi = mid - 1;
702 } else {
703 return &type_id;
704 }
705 }
706 return nullptr;
707}
708
Vladimir Markoa48aef42014-12-03 17:53:53 +0000709const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700710 int32_t lo = 0;
711 int32_t hi = NumStringIds() - 1;
712 while (hi >= lo) {
713 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700714 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700715 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000716 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700717 if (compare > 0) {
718 lo = mid + 1;
719 } else if (compare < 0) {
720 hi = mid - 1;
721 } else {
722 return &str_id;
723 }
724 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700725 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700726}
727
728const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700729 int32_t lo = 0;
730 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700731 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700732 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800733 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700734 if (string_idx > type_id.descriptor_idx_) {
735 lo = mid + 1;
736 } else if (string_idx < type_id.descriptor_idx_) {
737 hi = mid - 1;
738 } else {
739 return &type_id;
740 }
741 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700742 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700743}
744
Andreas Gampea5b09a62016-11-17 15:21:22 -0800745const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
746 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000747 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700748 int32_t lo = 0;
749 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700750 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700751 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700752 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800753 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700754 if (compare == 0) {
755 DexFileParameterIterator it(*this, proto);
756 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000757 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800758 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700759 it.Next();
760 i++;
761 }
762 if (compare == 0) {
763 if (it.HasNext()) {
764 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000765 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700766 compare = 1;
767 }
768 }
769 }
770 if (compare > 0) {
771 lo = mid + 1;
772 } else if (compare < 0) {
773 hi = mid - 1;
774 } else {
775 return &proto;
776 }
777 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700778 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700779}
780
781// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800782bool DexFile::CreateTypeList(const StringPiece& signature,
783 dex::TypeIndex* return_type_idx,
784 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700785 if (signature[0] != '(') {
786 return false;
787 }
788 size_t offset = 1;
789 size_t end = signature.size();
790 bool process_return = false;
791 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000792 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700793 char c = signature[offset];
794 offset++;
795 if (c == ')') {
796 process_return = true;
797 continue;
798 }
Ian Rogers0571d352011-11-03 19:51:38 -0700799 while (c == '[') { // process array prefix
800 if (offset >= end) { // expect some descriptor following [
801 return false;
802 }
803 c = signature[offset];
804 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700805 }
806 if (c == 'L') { // process type descriptors
807 do {
808 if (offset >= end) { // unexpected early termination of descriptor
809 return false;
810 }
811 c = signature[offset];
812 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700813 } while (c != ';');
814 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000815 // TODO: avoid creating a std::string just to get a 0-terminated char array
816 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700817 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700818 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700819 return false;
820 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800821 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700822 if (!process_return) {
823 param_type_idxs->push_back(type_idx);
824 } else {
825 *return_type_idx = type_idx;
826 return offset == end; // return true if the signature had reached a sensible end
827 }
828 }
829 return false; // failed to correctly parse return type
830}
831
Ian Rogersd91d6d62013-09-25 20:26:14 -0700832const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800833 dex::TypeIndex return_type_idx;
834 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700835 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
836 if (!success) {
837 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700838 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700839 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700840 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700841 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700842 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700843 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700844}
845
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700846int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700847 // Note: Signed type is important for max and min.
848 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700849 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700850
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700851 while (min <= max) {
852 int32_t mid = min + ((max - min) / 2);
853
854 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
855 uint32_t start = ti->start_addr_;
856 uint32_t end = start + ti->insn_count_;
857
Ian Rogers0571d352011-11-03 19:51:38 -0700858 if (address < start) {
859 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700860 } else if (address >= end) {
861 min = mid + 1;
862 } else { // We have a winner!
863 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700864 }
865 }
866 // No match.
867 return -1;
868}
869
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700870int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
871 int32_t try_item = FindTryItem(code_item, address);
872 if (try_item == -1) {
873 return -1;
874 } else {
875 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
876 }
877}
878
David Srbeckyb06e28e2015-12-10 13:15:00 +0000879bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
880 DexDebugNewLocalCb local_cb, void* context) const {
881 DCHECK(local_cb != nullptr);
882 if (code_item == nullptr) {
883 return false;
884 }
885 const uint8_t* stream = GetDebugInfoStream(code_item);
886 if (stream == nullptr) {
887 return false;
888 }
889 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890
David Srbeckyb06e28e2015-12-10 13:15:00 +0000891 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800892 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000893 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
894 local_in_reg[arg_reg].name_ = "this";
895 local_in_reg[arg_reg].descriptor_ = descriptor;
896 local_in_reg[arg_reg].signature_ = nullptr;
897 local_in_reg[arg_reg].start_address_ = 0;
898 local_in_reg[arg_reg].reg_ = arg_reg;
899 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700900 arg_reg++;
901 }
902
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800903 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000904 DecodeUnsignedLeb128(&stream); // Line.
905 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
906 uint32_t i;
907 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700908 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700909 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800910 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000911 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700912 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000913 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700914 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000915 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
916 local_in_reg[arg_reg].descriptor_ = descriptor;
917 local_in_reg[arg_reg].signature_ = nullptr;
918 local_in_reg[arg_reg].start_address_ = 0;
919 local_in_reg[arg_reg].reg_ = arg_reg;
920 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700921 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 case 'D':
923 case 'J':
924 arg_reg += 2;
925 break;
926 default:
927 arg_reg += 1;
928 break;
929 }
930 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000931 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800932 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700933 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000934 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700935 }
936
David Srbeckyb06e28e2015-12-10 13:15:00 +0000937 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700938 for (;;) {
939 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700940 switch (opcode) {
941 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000942 // Emit all variables which are still alive at the end of the method.
943 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
944 if (local_in_reg[reg].is_live_) {
945 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
946 local_cb(context, local_in_reg[reg]);
947 }
948 }
949 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700950 case DBG_ADVANCE_PC:
951 address += DecodeUnsignedLeb128(&stream);
952 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700953 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000954 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700956 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000957 case DBG_START_LOCAL_EXTENDED: {
958 uint16_t reg = DecodeUnsignedLeb128(&stream);
959 if (reg >= code_item->registers_size_) {
960 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800961 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000962 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700963 }
964
David Srbeckyb06e28e2015-12-10 13:15:00 +0000965 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
966 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
967 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700968 if (opcode == DBG_START_LOCAL_EXTENDED) {
969 signature_idx = DecodeUnsignedLeb128P1(&stream);
970 }
971
Shih-wei Liao195487c2011-08-20 13:29:04 -0700972 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000973 if (local_in_reg[reg].is_live_) {
974 local_in_reg[reg].end_address_ = address;
975 local_cb(context, local_in_reg[reg]);
976 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700977
David Srbeckyb06e28e2015-12-10 13:15:00 +0000978 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800979 local_in_reg[reg].descriptor_ =
980 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000981 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
982 local_in_reg[reg].start_address_ = address;
983 local_in_reg[reg].reg_ = reg;
984 local_in_reg[reg].is_live_ = true;
985 break;
986 }
987 case DBG_END_LOCAL: {
988 uint16_t reg = DecodeUnsignedLeb128(&stream);
989 if (reg >= code_item->registers_size_) {
990 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
991 << code_item->registers_size_ << ") in " << GetLocation();
992 return false;
993 }
994 if (!local_in_reg[reg].is_live_) {
995 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
996 return false;
997 }
998 local_in_reg[reg].end_address_ = address;
999 local_cb(context, local_in_reg[reg]);
1000 local_in_reg[reg].is_live_ = false;
1001 break;
1002 }
1003 case DBG_RESTART_LOCAL: {
1004 uint16_t reg = DecodeUnsignedLeb128(&stream);
1005 if (reg >= code_item->registers_size_) {
1006 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1007 << code_item->registers_size_ << ") in " << GetLocation();
1008 return false;
1009 }
1010 // If the register is live, the "restart" is superfluous,
1011 // and we don't want to mess with the existing start address.
1012 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001013 local_in_reg[reg].start_address_ = address;
1014 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001015 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001016 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001017 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018 case DBG_SET_PROLOGUE_END:
1019 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001020 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001021 case DBG_SET_FILE:
1022 DecodeUnsignedLeb128P1(&stream); // name.
1023 break;
1024 default:
1025 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1026 break;
1027 }
1028 }
1029}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001030
David Srbeckyb06e28e2015-12-10 13:15:00 +00001031bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1032 void* context) const {
1033 DCHECK(position_cb != nullptr);
1034 if (code_item == nullptr) {
1035 return false;
1036 }
1037 const uint8_t* stream = GetDebugInfoStream(code_item);
1038 if (stream == nullptr) {
1039 return false;
1040 }
1041
1042 PositionInfo entry = PositionInfo();
1043 entry.line_ = DecodeUnsignedLeb128(&stream);
1044 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1045 for (uint32_t i = 0; i < parameters_size; ++i) {
1046 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1047 }
1048
1049 for (;;) {
1050 uint8_t opcode = *stream++;
1051 switch (opcode) {
1052 case DBG_END_SEQUENCE:
1053 return true; // end of stream.
1054 case DBG_ADVANCE_PC:
1055 entry.address_ += DecodeUnsignedLeb128(&stream);
1056 break;
1057 case DBG_ADVANCE_LINE:
1058 entry.line_ += DecodeSignedLeb128(&stream);
1059 break;
1060 case DBG_START_LOCAL:
1061 DecodeUnsignedLeb128(&stream); // reg.
1062 DecodeUnsignedLeb128P1(&stream); // name.
1063 DecodeUnsignedLeb128P1(&stream); // descriptor.
1064 break;
1065 case DBG_START_LOCAL_EXTENDED:
1066 DecodeUnsignedLeb128(&stream); // reg.
1067 DecodeUnsignedLeb128P1(&stream); // name.
1068 DecodeUnsignedLeb128P1(&stream); // descriptor.
1069 DecodeUnsignedLeb128P1(&stream); // signature.
1070 break;
1071 case DBG_END_LOCAL:
1072 case DBG_RESTART_LOCAL:
1073 DecodeUnsignedLeb128(&stream); // reg.
1074 break;
1075 case DBG_SET_PROLOGUE_END:
1076 entry.prologue_end_ = true;
1077 break;
1078 case DBG_SET_EPILOGUE_BEGIN:
1079 entry.epilogue_begin_ = true;
1080 break;
1081 case DBG_SET_FILE: {
1082 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1083 entry.source_file_ = StringDataByIdx(name_idx);
1084 break;
1085 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001086 default: {
1087 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001088 entry.address_ += adjopcode / DBG_LINE_RANGE;
1089 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1090 if (position_cb(context, entry)) {
1091 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001092 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001093 entry.prologue_end_ = false;
1094 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001095 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001096 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001097 }
1098 }
1099}
1100
David Srbeckyb06e28e2015-12-10 13:15:00 +00001101bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001102 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001103
1104 // We know that this callback will be called in
1105 // ascending address order, so keep going until we find
1106 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001107 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001108 // The line number from the previous positions callback
1109 // wil be the final result.
1110 return true;
1111 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001112 context->line_num_ = entry.line_;
1113 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001114 }
1115}
1116
Andreas Gampe833a4852014-05-21 18:46:59 -07001117bool DexFile::IsMultiDexLocation(const char* location) {
1118 return strrchr(location, kMultiDexSeparator) != nullptr;
1119}
1120
Andreas Gampe90e34042015-04-27 20:01:52 -07001121std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1122 if (index == 0) {
1123 return "classes.dex";
1124 } else {
1125 return StringPrintf("classes%zu.dex", index + 1);
1126 }
1127}
1128
1129std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1130 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001131 return dex_location;
1132 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001133 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001134 }
1135}
1136
1137std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1138 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001139 std::string base_location = GetBaseLocation(dex_location);
1140 const char* suffix = dex_location + base_location.size();
1141 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1142 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1143 if (path != nullptr && path.get() != base_location) {
1144 return std::string(path.get()) + suffix;
1145 } else if (suffix[0] == 0) {
1146 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001147 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001148 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001149 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001150}
1151
Jeff Hao13e748b2015-08-25 20:44:19 +00001152// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001153int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001154 int32_t val = 0;
1155 for (int i = zwidth; i >= 0; --i) {
1156 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1157 }
1158 val >>= (3 - zwidth) * 8;
1159 return val;
1160}
1161
1162// Read an unsigned integer. "zwidth" is the zero-based byte count,
1163// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001164uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001165 uint32_t val = 0;
1166 for (int i = zwidth; i >= 0; --i) {
1167 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1168 }
1169 if (!fill_on_right) {
1170 val >>= (3 - zwidth) * 8;
1171 }
1172 return val;
1173}
1174
1175// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001176int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001177 int64_t val = 0;
1178 for (int i = zwidth; i >= 0; --i) {
1179 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1180 }
1181 val >>= (7 - zwidth) * 8;
1182 return val;
1183}
1184
1185// Read an unsigned long. "zwidth" is the zero-based byte count,
1186// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001187uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001188 uint64_t val = 0;
1189 for (int i = zwidth; i >= 0; --i) {
1190 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1191 }
1192 if (!fill_on_right) {
1193 val >>= (7 - zwidth) * 8;
1194 }
1195 return val;
1196}
1197
David Sehr709b0702016-10-13 09:12:37 -07001198std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1199 if (method_idx >= NumMethodIds()) {
1200 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1201 }
1202 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1203 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1204 result += '.';
1205 result += GetMethodName(method_id);
1206 if (with_signature) {
1207 const Signature signature = GetMethodSignature(method_id);
1208 std::string sig_as_string(signature.ToString());
1209 if (signature == Signature::NoSignature()) {
1210 return result + sig_as_string;
1211 }
1212 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1213 PrettyArguments(sig_as_string.c_str());
1214 }
1215 return result;
1216}
1217
1218std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1219 if (field_idx >= NumFieldIds()) {
1220 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1221 }
1222 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1223 std::string result;
1224 if (with_type) {
1225 result += GetFieldTypeDescriptor(field_id);
1226 result += ' ';
1227 }
1228 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1229 result += '.';
1230 result += GetFieldName(field_id);
1231 return result;
1232}
1233
Andreas Gampea5b09a62016-11-17 15:21:22 -08001234std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1235 if (type_idx.index_ >= NumTypeIds()) {
1236 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001237 }
1238 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1239 return PrettyDescriptor(GetTypeDescriptor(type_id));
1240}
1241
Jeff Hao3d080862016-05-26 18:39:17 -07001242// Checks that visibility is as expected. Includes special behavior for M and
1243// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001244std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1245 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1246 dex_file.GetLocation().c_str(),
1247 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1248 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1249 return os;
1250}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001251
Ian Rogersd91d6d62013-09-25 20:26:14 -07001252std::string Signature::ToString() const {
1253 if (dex_file_ == nullptr) {
1254 CHECK(proto_id_ == nullptr);
1255 return "<no signature>";
1256 }
1257 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1258 std::string result;
1259 if (params == nullptr) {
1260 result += "()";
1261 } else {
1262 result += "(";
1263 for (uint32_t i = 0; i < params->Size(); ++i) {
1264 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1265 }
1266 result += ")";
1267 }
1268 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1269 return result;
1270}
1271
Vladimir Markod9cffea2013-11-25 15:08:02 +00001272bool Signature::operator==(const StringPiece& rhs) const {
1273 if (dex_file_ == nullptr) {
1274 return false;
1275 }
1276 StringPiece tail(rhs);
1277 if (!tail.starts_with("(")) {
1278 return false; // Invalid signature
1279 }
1280 tail.remove_prefix(1); // "(";
1281 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1282 if (params != nullptr) {
1283 for (uint32_t i = 0; i < params->Size(); ++i) {
1284 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1285 if (!tail.starts_with(param)) {
1286 return false;
1287 }
1288 tail.remove_prefix(param.length());
1289 }
1290 }
1291 if (!tail.starts_with(")")) {
1292 return false;
1293 }
1294 tail.remove_prefix(1); // ")";
1295 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1296}
1297
Ian Rogersd91d6d62013-09-25 20:26:14 -07001298std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1299 return os << sig.ToString();
1300}
1301
Ian Rogers0571d352011-11-03 19:51:38 -07001302// Decodes the header section from the class data bytes.
1303void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001304 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001305 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1306 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1307 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1308 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1309}
1310
1311void ClassDataItemIterator::ReadClassDataField() {
1312 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1313 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001314 // The user of the iterator is responsible for checking if there
1315 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001316}
1317
1318void ClassDataItemIterator::ReadClassDataMethod() {
1319 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1320 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1321 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001322 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001323 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001324 }
Ian Rogers0571d352011-11-03 19:51:38 -07001325}
1326
David Sehr9323e6e2016-09-13 08:58:35 -07001327EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1328 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001329 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001330 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001331 pos_(-1),
1332 type_(kByte) {
1333 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001334 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001335 array_size_ = 0;
1336 } else {
1337 array_size_ = DecodeUnsignedLeb128(&ptr_);
1338 }
1339 if (array_size_ > 0) {
1340 Next();
1341 }
1342}
1343
1344void EncodedStaticFieldValueIterator::Next() {
1345 pos_++;
1346 if (pos_ >= array_size_) {
1347 return;
1348 }
Ian Rogers13735952014-10-08 12:43:28 -07001349 uint8_t value_type = *ptr_++;
1350 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001351 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001352 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001353 switch (type_) {
1354 case kBoolean:
1355 jval_.i = (value_arg != 0) ? 1 : 0;
1356 width = 0;
1357 break;
1358 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001359 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001360 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001361 break;
1362 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001363 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001364 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001365 break;
1366 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001367 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001368 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001369 break;
1370 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001371 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001372 break;
1373 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001374 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001375 break;
1376 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001377 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001378 break;
1379 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001380 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001381 break;
1382 case kString:
1383 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001384 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001385 break;
1386 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001387 case kMethod:
1388 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001389 case kArray:
1390 case kAnnotation:
1391 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001392 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001393 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001394 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001395 width = 0;
1396 break;
1397 default:
1398 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001399 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001400 }
1401 ptr_ += width;
1402}
1403
Ian Rogers0571d352011-11-03 19:51:38 -07001404CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1405 handler_.address_ = -1;
1406 int32_t offset = -1;
1407
1408 // Short-circuit the overwhelmingly common cases.
1409 switch (code_item.tries_size_) {
1410 case 0:
1411 break;
1412 case 1: {
1413 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1414 uint32_t start = tries->start_addr_;
1415 if (address >= start) {
1416 uint32_t end = start + tries->insn_count_;
1417 if (address < end) {
1418 offset = tries->handler_off_;
1419 }
1420 }
1421 break;
1422 }
1423 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001424 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001425 }
Logan Chien736df022012-04-27 16:25:57 +08001426 Init(code_item, offset);
1427}
1428
1429CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1430 const DexFile::TryItem& try_item) {
1431 handler_.address_ = -1;
1432 Init(code_item, try_item.handler_off_);
1433}
1434
1435void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1436 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001437 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001438 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001439 } else {
1440 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001441 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001442 remaining_count_ = -1;
1443 catch_all_ = false;
1444 DCHECK(!HasNext());
1445 }
1446}
1447
Ian Rogers13735952014-10-08 12:43:28 -07001448void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001449 current_data_ = handler_data;
1450 remaining_count_ = DecodeSignedLeb128(&current_data_);
1451
1452 // If remaining_count_ is non-positive, then it is the negative of
1453 // the number of catch types, and the catches are followed by a
1454 // catch-all handler.
1455 if (remaining_count_ <= 0) {
1456 catch_all_ = true;
1457 remaining_count_ = -remaining_count_;
1458 } else {
1459 catch_all_ = false;
1460 }
1461 Next();
1462}
1463
1464void CatchHandlerIterator::Next() {
1465 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001466 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001467 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1468 remaining_count_--;
1469 return;
1470 }
1471
1472 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001473 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001474 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1475 catch_all_ = false;
1476 return;
1477 }
1478
1479 // no more handler
1480 remaining_count_ = -1;
1481}
1482
Andreas Gampea5b09a62016-11-17 15:21:22 -08001483namespace dex {
1484
1485std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1486 os << "TypeIndex[" << index.index_ << "]";
1487 return os;
1488}
1489
1490} // namespace dex
1491
Carl Shapiro1fb86202011-06-27 17:43:13 -07001492} // namespace art