blob: aace8eba43c14e3b9863c005fecd561f7d075ad7 [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>
Andreas Gampe0dfc3152017-04-24 07:58:06 -070025#include <sys/mman.h> // For the PROT_* and MAP_* constants.
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070026#include <sys/stat.h>
Alex Light40528472017-03-28 09:07:36 -070027#include <zlib.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028
Ian Rogers700a4022014-05-19 16:49:03 -070029#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070030#include <sstream>
Andreas Gampea5b09a62016-11-17 15:21:22 -080031#include <type_traits>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070032
Andreas Gampe46ee31b2016-12-14 10:11:49 -080033#include "android-base/stringprintf.h"
34
Andreas Gampe542451c2016-07-26 09:02:02 -070035#include "base/enums.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000036#include "base/file_magic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080037#include "base/logging.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080038#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070039#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070040#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080041#include "dex_file_verifier.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010042#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070043#include "leb128.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070044#include "os.h"
Ian Rogersa6724902013-09-23 09:23:37 -070045#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070046#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070047#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070048
49namespace art {
50
Andreas Gampe46ee31b2016-12-14 10:11:49 -080051using android::base::StringPrintf;
52
Andreas Gampe8a0128a2016-11-28 07:38:35 -080053static_assert(sizeof(dex::StringIndex) == sizeof(uint32_t), "StringIndex size is wrong");
54static_assert(std::is_trivially_copyable<dex::StringIndex>::value, "StringIndex not trivial");
Andreas Gampea5b09a62016-11-17 15:21:22 -080055static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
56static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
57
David Sehr733ddb22016-09-19 15:02:18 -070058static constexpr OatDexFile* kNoOatDexFile = nullptr;
59
60const char* DexFile::kClassesDex = "classes.dex";
61
Ian Rogers13735952014-10-08 12:43:28 -070062const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070063const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
64 {'0', '3', '5', '\0'},
65 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
66 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010067 {'0', '3', '7', '\0'},
68 // Dex version 038: Android "O" and beyond.
69 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070070};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070071
Alex Light40528472017-03-28 09:07:36 -070072uint32_t DexFile::CalculateChecksum() const {
73 const uint32_t non_sum = OFFSETOF_MEMBER(DexFile::Header, signature_);
74 const uint8_t* non_sum_ptr = Begin() + non_sum;
75 return adler32(adler32(0L, Z_NULL, 0), non_sum_ptr, Size() - non_sum);
76}
77
Vladimir Marko3a21e382016-09-02 12:38:38 +010078struct DexFile::AnnotationValue {
79 JValue value_;
80 uint8_t type_;
81};
82
Richard Uhler69bcf2c2017-01-24 10:25:21 +000083bool DexFile::GetMultiDexChecksums(const char* filename,
84 std::vector<uint32_t>* checksums,
85 std::string* error_msg) {
86 CHECK(checksums != nullptr);
87 uint32_t magic;
88
89 File fd = OpenAndReadMagic(filename, &magic, error_msg);
Andreas Gampe43e10b02016-07-15 17:17:34 -070090 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070091 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070092 return false;
93 }
94 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070095 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070096 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070097 if (zip_archive.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +000098 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", filename,
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080099 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800100 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700101 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000102
103 uint32_t i = 0;
104 std::string zip_entry_name = GetMultiDexClassesDexName(i++);
105 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name.c_str(), error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700106 if (zip_entry.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000107 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", filename,
108 zip_entry_name.c_str(), error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800109 return false;
110 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000111
112 do {
113 checksums->push_back(zip_entry->GetCrc32());
114 zip_entry_name = DexFile::GetMultiDexClassesDexName(i++);
115 zip_entry.reset(zip_archive->Find(zip_entry_name.c_str(), error_msg));
116 } while (zip_entry.get() != nullptr);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700118 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700119 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700120 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700121 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800123 return false;
124 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000125 checksums->push_back(dex_file->GetHeader().checksum_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800126 return true;
127 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700128 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800129 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700130}
131
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800132int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700133 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800134 return 0;
135 } else {
136 return mem_map_->GetProtect();
137 }
138}
139
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200140bool DexFile::IsReadOnly() const {
141 return GetPermissions() == PROT_READ;
142}
143
Brian Carlstrome0948e12013-08-29 09:36:15 -0700144bool DexFile::EnableWrite() 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 | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200150 }
151}
152
Brian Carlstrome0948e12013-08-29 09:36:15 -0700153bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200154 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700155 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200156 return false;
157 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700158 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200159 }
160}
161
David Sehr733ddb22016-09-19 15:02:18 -0700162
163std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
164 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800165 const std::string& location,
166 uint32_t location_checksum,
167 const OatDexFile* oat_dex_file,
168 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700169 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800170 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800171 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700172 return OpenCommon(base,
173 size,
174 location,
175 location_checksum,
176 oat_dex_file,
177 verify,
178 verify_checksum,
179 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100180}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800181
Orion Hodsona4c2a052016-08-17 10:51:42 +0100182std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
183 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700184 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100185 bool verify,
186 bool verify_checksum,
187 std::string* error_msg) {
188 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700189 CHECK(map.get() != nullptr);
Jeff Hao41b2f532017-03-02 16:36:31 -0800190
191 if (map->Size() < sizeof(DexFile::Header)) {
192 *error_msg = StringPrintf(
193 "DexFile: failed to open dex file '%s' that is too short to have a header",
194 location.c_str());
195 return nullptr;
196 }
197
David Sehr733ddb22016-09-19 15:02:18 -0700198 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
199 map->Size(),
200 location,
201 location_checksum,
202 kNoOatDexFile,
203 verify,
204 verify_checksum,
205 error_msg);
206 if (dex_file != nullptr) {
Andreas Gampe8d01c372017-05-30 13:21:28 -0700207 dex_file->mem_map_ = std::move(map);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100208 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800209 return dex_file;
210}
211
David Sehr733ddb22016-09-19 15:02:18 -0700212bool DexFile::Open(const char* filename,
213 const std::string& location,
214 bool verify_checksum,
215 std::string* error_msg,
216 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
217 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
218 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
219 uint32_t magic;
220 File fd = OpenAndReadMagic(filename, &magic, error_msg);
221 if (fd.Fd() == -1) {
222 DCHECK(!error_msg->empty());
223 return false;
224 }
225 if (IsZipMagic(magic)) {
226 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
227 }
228 if (IsDexMagic(magic)) {
229 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
230 location,
231 /* verify */ true,
232 verify_checksum,
233 error_msg));
234 if (dex_file.get() != nullptr) {
235 dex_files->push_back(std::move(dex_file));
236 return true;
237 } else {
238 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000239 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700240 }
David Sehr733ddb22016-09-19 15:02:18 -0700241 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
242 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700243}
244
David Sehr733ddb22016-09-19 15:02:18 -0700245std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
246 const std::string& location,
247 bool verify_checksum,
248 std::string* error_msg) {
249 ScopedTrace trace("Open dex file " + std::string(location));
250 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
251}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700252
Aart Bik37d6a3b2016-06-21 18:30:10 -0700253bool DexFile::OpenZip(int fd,
254 const std::string& location,
255 bool verify_checksum,
256 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800257 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800258 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700259 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700260 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700261 if (zip_archive.get() == nullptr) {
262 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700263 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264 }
David Sehr733ddb22016-09-19 15:02:18 -0700265 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
266 location,
267 verify_checksum,
268 error_msg,
269 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800270}
271
David Sehr733ddb22016-09-19 15:02:18 -0700272std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
273 const std::string& location,
274 bool verify,
275 bool verify_checksum,
276 std::string* error_msg) {
277 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
278 CHECK(!location.empty());
279 std::unique_ptr<MemMap> map;
280 {
281 File delayed_close(fd, /* check_usage */ false);
282 struct stat sbuf;
283 memset(&sbuf, 0, sizeof(sbuf));
284 if (fstat(fd, &sbuf) == -1) {
285 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
286 strerror(errno));
287 return nullptr;
288 }
289 if (S_ISDIR(sbuf.st_mode)) {
290 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
291 return nullptr;
292 }
293 size_t length = sbuf.st_size;
294 map.reset(MemMap::MapFile(length,
295 PROT_READ,
296 MAP_PRIVATE,
297 fd,
298 0,
299 /*low_4gb*/false,
300 location.c_str(),
301 error_msg));
302 if (map == nullptr) {
303 DCHECK(!error_msg->empty());
304 return nullptr;
305 }
306 }
307
308 if (map->Size() < sizeof(DexFile::Header)) {
309 *error_msg = StringPrintf(
310 "DexFile: failed to open dex file '%s' that is too short to have a header",
311 location.c_str());
312 return nullptr;
313 }
314
315 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
316
317 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
318 map->Size(),
319 location,
320 dex_header->checksum_,
321 kNoOatDexFile,
322 verify,
323 verify_checksum,
324 error_msg);
325 if (dex_file != nullptr) {
Andreas Gampe8d01c372017-05-30 13:21:28 -0700326 dex_file->mem_map_ = std::move(map);
David Sehr733ddb22016-09-19 15:02:18 -0700327 }
328
329 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800330}
331
David Sehr733ddb22016-09-19 15:02:18 -0700332std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
333 const char* entry_name,
334 const std::string& location,
335 bool verify_checksum,
336 std::string* error_msg,
337 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800338 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800339 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700341 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700342 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700343 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700344 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800345 if (zip_entry->GetUncompressedLength() == 0) {
346 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
347 *error_code = ZipOpenErrorCode::kDexFileError;
348 return nullptr;
349 }
Igor Murashkin271a0f82017-02-14 21:14:17 +0000350
351 std::unique_ptr<MemMap> map;
352 if (zip_entry->IsUncompressed()) {
353 if (!zip_entry->IsAlignedTo(alignof(Header))) {
354 // Do not mmap unaligned ZIP entries because
355 // doing so would fail dex verification which requires 4 byte alignment.
356 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
357 << "please zipalign to " << alignof(Header) << " bytes. "
358 << "Falling back to extracting file.";
359 } else {
360 // Map uncompressed files within zip as file-backed to avoid a dirty copy.
361 map.reset(zip_entry->MapDirectlyFromFile(location.c_str(), /*out*/error_msg));
362 if (map == nullptr) {
363 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
364 << "is your ZIP file corrupted? Falling back to extraction.";
365 // Try again with Extraction which still has a chance of recovery.
366 }
367 }
368 }
369
370 if (map == nullptr) {
371 // Default path for compressed ZIP entries,
372 // and fallback for stored ZIP entries.
373 map.reset(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
374 }
375
David Sehr9fddd362016-09-22 14:05:37 -0700376 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700377 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700378 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700379 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700381 }
David Sehr733ddb22016-09-19 15:02:18 -0700382 VerifyResult verify_result;
383 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
384 map->Size(),
385 location,
386 zip_entry->GetCrc32(),
387 kNoOatDexFile,
388 /* verify */ true,
389 verify_checksum,
390 error_msg,
391 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700392 if (dex_file == nullptr) {
393 if (verify_result == VerifyResult::kVerifyNotAttempted) {
394 *error_code = ZipOpenErrorCode::kDexFileError;
395 } else {
396 *error_code = ZipOpenErrorCode::kVerifyError;
397 }
398 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800399 }
Andreas Gampe8d01c372017-05-30 13:21:28 -0700400 dex_file->mem_map_ = std::move(map);
Brian Carlstrome0948e12013-08-29 09:36:15 -0700401 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700402 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700403 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700404 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700405 }
406 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700407 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700408 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700409 return nullptr;
410 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700411 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800412 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700413}
414
Andreas Gampe90e34042015-04-27 20:01:52 -0700415// Technically we do not have a limitation with respect to the number of dex files that can be in a
416// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
417// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
418// seems an excessive number.
419static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
420
David Sehr733ddb22016-09-19 15:02:18 -0700421bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
422 const std::string& location,
423 bool verify_checksum,
424 std::string* error_msg,
425 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800426 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700427 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700428 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700429 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
430 kClassesDex,
431 location,
432 verify_checksum,
433 error_msg,
434 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700435 if (dex_file.get() == nullptr) {
436 return false;
437 } else {
438 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800439 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700440
441 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700442
443 // We could try to avoid std::string allocations by working on a char array directly. As we
444 // do not expect a lot of iterations, this seems too involved and brittle.
445
Andreas Gampe90e34042015-04-27 20:01:52 -0700446 for (size_t i = 1; ; ++i) {
447 std::string name = GetMultiDexClassesDexName(i);
448 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700449 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
450 name.c_str(),
451 fake_location,
452 verify_checksum,
453 error_msg,
454 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700455 if (next_dex_file.get() == nullptr) {
456 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
David Sehrc9229222017-02-14 10:57:47 -0800457 LOG(WARNING) << "Zip open failed: " << *error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700458 }
459 break;
460 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800461 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700462 }
463
Andreas Gampe90e34042015-04-27 20:01:52 -0700464 if (i == kWarnOnManyDexFilesThreshold) {
465 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
466 << " dex files. Please consider coalescing and shrinking the number to "
467 " avoid runtime overhead.";
468 }
469
470 if (i == std::numeric_limits<size_t>::max()) {
471 LOG(ERROR) << "Overflow in number of dex files!";
472 break;
473 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700474 }
475
476 return true;
477 }
478}
479
David Sehr733ddb22016-09-19 15:02:18 -0700480std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
481 size_t size,
482 const std::string& location,
483 uint32_t location_checksum,
484 const OatDexFile* oat_dex_file,
485 bool verify,
486 bool verify_checksum,
487 std::string* error_msg,
488 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700489 if (verify_result != nullptr) {
490 *verify_result = VerifyResult::kVerifyNotAttempted;
491 }
David Sehr733ddb22016-09-19 15:02:18 -0700492 std::unique_ptr<DexFile> dex_file(new DexFile(base,
493 size,
494 location,
495 location_checksum,
496 oat_dex_file));
497 if (dex_file == nullptr) {
498 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
499 error_msg->c_str());
500 return nullptr;
501 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800503 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700504 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700505 }
David Sehr733ddb22016-09-19 15:02:18 -0700506 if (verify && !DexFileVerifier::Verify(dex_file.get(),
507 dex_file->Begin(),
508 dex_file->Size(),
509 location.c_str(),
510 verify_checksum,
511 error_msg)) {
512 if (verify_result != nullptr) {
513 *verify_result = VerifyResult::kVerifyFailed;
514 }
515 return nullptr;
516 }
517 if (verify_result != nullptr) {
518 *verify_result = VerifyResult::kVerifySucceeded;
519 }
520 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700521}
522
David Sehr733ddb22016-09-19 15:02:18 -0700523DexFile::DexFile(const uint8_t* base,
524 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800525 const std::string& location,
526 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700527 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800528 : begin_(base),
529 size_(size),
530 location_(location),
531 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800532 header_(reinterpret_cast<const Header*>(base)),
533 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
534 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
535 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
536 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
537 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700538 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000539 method_handles_(nullptr),
540 num_method_handles_(0),
541 call_site_ids_(nullptr),
542 num_call_site_ids_(0),
Richard Uhler07b3c232015-03-31 15:57:54 -0700543 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700544 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800545 CHECK_GT(size_, 0U) << GetLocation();
Igor Murashkin271a0f82017-02-14 21:14:17 +0000546 // Check base (=header) alignment.
547 // Must be 4-byte aligned to avoid undefined behavior when accessing
548 // any of the sections via a pointer.
549 CHECK_ALIGNED(begin_, alignof(Header));
550
Orion Hodson12f4ff42017-01-13 16:43:12 +0000551 InitializeSectionsFromMapList();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800552}
553
Jesse Wilson6bf19152011-09-29 13:12:33 -0400554DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700555 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
556 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
557 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
558 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400559}
560
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700561bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700562 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700563 return false;
564 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700565 return true;
566}
567
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700568bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800569 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700570 std::ostringstream oss;
571 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800572 << " " << header_->magic_[0]
573 << " " << header_->magic_[1]
574 << " " << header_->magic_[2]
575 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700576 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700577 return false;
578 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800579 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700580 std::ostringstream oss;
581 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800582 << " " << header_->magic_[4]
583 << " " << header_->magic_[5]
584 << " " << header_->magic_[6]
585 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700586 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700587 return false;
588 }
589 return true;
590}
591
Orion Hodson12f4ff42017-01-13 16:43:12 +0000592void DexFile::InitializeSectionsFromMapList() {
593 const MapList* map_list = reinterpret_cast<const MapList*>(begin_ + header_->map_off_);
Jeff Haoa4cd6772017-04-13 14:36:29 -0700594 if (header_->map_off_ == 0 || header_->map_off_ > size_) {
595 // Bad offset. The dex file verifier runs after this method and will reject the file.
596 return;
597 }
Orion Hodson12f4ff42017-01-13 16:43:12 +0000598 const size_t count = map_list->size_;
599
600 size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
601 if (header_->map_off_ >= map_limit || map_limit > size_) {
602 // Overflow or out out of bounds. The dex file verifier runs after
603 // this method and will reject the file as it is malformed.
604 return;
605 }
606
607 for (size_t i = 0; i < count; ++i) {
608 const MapItem& map_item = map_list->list_[i];
609 if (map_item.type_ == kDexTypeMethodHandleItem) {
610 method_handles_ = reinterpret_cast<const MethodHandleItem*>(begin_ + map_item.offset_);
611 num_method_handles_ = map_item.size_;
612 } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
613 call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(begin_ + map_item.offset_);
614 num_call_site_ids_ = map_item.size_;
615 }
616 }
617}
618
Ian Rogers13735952014-10-08 12:43:28 -0700619bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800620 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
621}
622
Ian Rogers13735952014-10-08 12:43:28 -0700623bool DexFile::IsVersionValid(const uint8_t* magic) {
624 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700625 for (uint32_t i = 0; i < kNumDexVersions; i++) {
626 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
627 return true;
628 }
629 }
630 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800631}
632
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700633uint32_t DexFile::Header::GetVersion() const {
634 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700635 return atoi(version);
636}
637
Andreas Gampea5b09a62016-11-17 15:21:22 -0800638const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700639 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100640 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700641 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700642 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700643 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700644 for (size_t i = 0; i < num_class_defs; ++i) {
645 const ClassDef& class_def = GetClassDef(i);
646 if (class_def.class_idx_ == type_idx) {
647 return &class_def;
648 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700649 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700650 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700651}
652
Alex Light9c20a142016-08-23 15:05:12 -0700653uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
654 uint32_t method_idx) const {
655 const uint8_t* class_data = GetClassData(class_def);
656 CHECK(class_data != nullptr);
657 ClassDataItemIterator it(*this, class_data);
658 // Skip fields
659 while (it.HasNextStaticField()) {
660 it.Next();
661 }
662 while (it.HasNextInstanceField()) {
663 it.Next();
664 }
665 while (it.HasNextDirectMethod()) {
666 if (it.GetMemberIndex() == method_idx) {
667 return it.GetMethodCodeItemOffset();
668 }
669 it.Next();
670 }
671 while (it.HasNextVirtualMethod()) {
672 if (it.GetMemberIndex() == method_idx) {
673 return it.GetMethodCodeItemOffset();
674 }
675 it.Next();
676 }
677 LOG(FATAL) << "Unable to find method " << method_idx;
678 UNREACHABLE();
679}
680
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800681const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100682 const DexFile::StringId& name,
683 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800684 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800685 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800686 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800687 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700688 int32_t lo = 0;
689 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800690 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700691 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800692 const DexFile::FieldId& field = GetFieldId(mid);
693 if (class_idx > field.class_idx_) {
694 lo = mid + 1;
695 } else if (class_idx < field.class_idx_) {
696 hi = mid - 1;
697 } else {
698 if (name_idx > field.name_idx_) {
699 lo = mid + 1;
700 } else if (name_idx < field.name_idx_) {
701 hi = mid - 1;
702 } else {
703 if (type_idx > field.type_idx_) {
704 lo = mid + 1;
705 } else if (type_idx < field.type_idx_) {
706 hi = mid - 1;
707 } else {
708 return &field;
709 }
710 }
711 }
712 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700713 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800714}
715
716const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700717 const DexFile::StringId& name,
718 const DexFile::ProtoId& signature) const {
719 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800720 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800721 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700722 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700723 int32_t lo = 0;
724 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700725 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700726 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700727 const DexFile::MethodId& method = GetMethodId(mid);
728 if (class_idx > method.class_idx_) {
729 lo = mid + 1;
730 } else if (class_idx < method.class_idx_) {
731 hi = mid - 1;
732 } else {
733 if (name_idx > method.name_idx_) {
734 lo = mid + 1;
735 } else if (name_idx < method.name_idx_) {
736 hi = mid - 1;
737 } else {
738 if (proto_idx > method.proto_idx_) {
739 lo = mid + 1;
740 } else if (proto_idx < method.proto_idx_) {
741 hi = mid - 1;
742 } else {
743 return &method;
744 }
745 }
746 }
747 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700748 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700749}
750
Ian Rogers637c65b2013-05-31 11:46:00 -0700751const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700752 int32_t lo = 0;
753 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700754 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700755 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800756 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700757 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700758 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
759 if (compare > 0) {
760 lo = mid + 1;
761 } else if (compare < 0) {
762 hi = mid - 1;
763 } else {
764 return &str_id;
765 }
766 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700767 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700768}
769
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300770const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
771 int32_t lo = 0;
772 int32_t hi = NumTypeIds() - 1;
773 while (hi >= lo) {
774 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800775 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300776 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
777 const char* str = GetStringData(str_id);
778 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
779 if (compare > 0) {
780 lo = mid + 1;
781 } else if (compare < 0) {
782 hi = mid - 1;
783 } else {
784 return &type_id;
785 }
786 }
787 return nullptr;
788}
789
Vladimir Markoa48aef42014-12-03 17:53:53 +0000790const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700791 int32_t lo = 0;
792 int32_t hi = NumStringIds() - 1;
793 while (hi >= lo) {
794 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800795 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700796 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000797 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700798 if (compare > 0) {
799 lo = mid + 1;
800 } else if (compare < 0) {
801 hi = mid - 1;
802 } else {
803 return &str_id;
804 }
805 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700806 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700807}
808
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800809const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700810 int32_t lo = 0;
811 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700812 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700813 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800814 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700815 if (string_idx > type_id.descriptor_idx_) {
816 lo = mid + 1;
817 } else if (string_idx < type_id.descriptor_idx_) {
818 hi = mid - 1;
819 } else {
820 return &type_id;
821 }
822 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700823 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700824}
825
Andreas Gampea5b09a62016-11-17 15:21:22 -0800826const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
827 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000828 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700829 int32_t lo = 0;
830 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700831 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700832 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700833 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800834 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700835 if (compare == 0) {
836 DexFileParameterIterator it(*this, proto);
837 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000838 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800839 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700840 it.Next();
841 i++;
842 }
843 if (compare == 0) {
844 if (it.HasNext()) {
845 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000846 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700847 compare = 1;
848 }
849 }
850 }
851 if (compare > 0) {
852 lo = mid + 1;
853 } else if (compare < 0) {
854 hi = mid - 1;
855 } else {
856 return &proto;
857 }
858 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700859 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700860}
861
862// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800863bool DexFile::CreateTypeList(const StringPiece& signature,
864 dex::TypeIndex* return_type_idx,
865 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700866 if (signature[0] != '(') {
867 return false;
868 }
869 size_t offset = 1;
870 size_t end = signature.size();
871 bool process_return = false;
872 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000873 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700874 char c = signature[offset];
875 offset++;
876 if (c == ')') {
877 process_return = true;
878 continue;
879 }
Ian Rogers0571d352011-11-03 19:51:38 -0700880 while (c == '[') { // process array prefix
881 if (offset >= end) { // expect some descriptor following [
882 return false;
883 }
884 c = signature[offset];
885 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700886 }
887 if (c == 'L') { // process type descriptors
888 do {
889 if (offset >= end) { // unexpected early termination of descriptor
890 return false;
891 }
892 c = signature[offset];
893 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700894 } while (c != ';');
895 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000896 // TODO: avoid creating a std::string just to get a 0-terminated char array
897 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700898 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700899 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700900 return false;
901 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800902 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700903 if (!process_return) {
904 param_type_idxs->push_back(type_idx);
905 } else {
906 *return_type_idx = type_idx;
907 return offset == end; // return true if the signature had reached a sensible end
908 }
909 }
910 return false; // failed to correctly parse return type
911}
912
Ian Rogersd91d6d62013-09-25 20:26:14 -0700913const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800914 dex::TypeIndex return_type_idx;
915 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700916 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
917 if (!success) {
918 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700919 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700920 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700921 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700922 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700923 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700924 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700925}
926
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700927int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700928 // Note: Signed type is important for max and min.
929 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700930 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700931
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700932 while (min <= max) {
933 int32_t mid = min + ((max - min) / 2);
934
935 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
936 uint32_t start = ti->start_addr_;
937 uint32_t end = start + ti->insn_count_;
938
Ian Rogers0571d352011-11-03 19:51:38 -0700939 if (address < start) {
940 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700941 } else if (address >= end) {
942 min = mid + 1;
943 } else { // We have a winner!
944 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700945 }
946 }
947 // No match.
948 return -1;
949}
950
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700951int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
952 int32_t try_item = FindTryItem(code_item, address);
953 if (try_item == -1) {
954 return -1;
955 } else {
956 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
957 }
958}
959
David Srbeckyb06e28e2015-12-10 13:15:00 +0000960bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
961 DexDebugNewLocalCb local_cb, void* context) const {
962 DCHECK(local_cb != nullptr);
963 if (code_item == nullptr) {
964 return false;
965 }
966 const uint8_t* stream = GetDebugInfoStream(code_item);
967 if (stream == nullptr) {
968 return false;
969 }
970 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700971
David Srbeckyb06e28e2015-12-10 13:15:00 +0000972 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800973 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000974 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
975 local_in_reg[arg_reg].name_ = "this";
976 local_in_reg[arg_reg].descriptor_ = descriptor;
977 local_in_reg[arg_reg].signature_ = nullptr;
978 local_in_reg[arg_reg].start_address_ = 0;
979 local_in_reg[arg_reg].reg_ = arg_reg;
980 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981 arg_reg++;
982 }
983
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800984 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000985 DecodeUnsignedLeb128(&stream); // Line.
986 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
987 uint32_t i;
988 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700989 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700990 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800991 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000992 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700993 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000994 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700995 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800996 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000997 local_in_reg[arg_reg].descriptor_ = descriptor;
998 local_in_reg[arg_reg].signature_ = nullptr;
999 local_in_reg[arg_reg].start_address_ = 0;
1000 local_in_reg[arg_reg].reg_ = arg_reg;
1001 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001002 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -07001003 case 'D':
1004 case 'J':
1005 arg_reg += 2;
1006 break;
1007 default:
1008 arg_reg += 1;
1009 break;
1010 }
1011 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001012 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001013 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -07001014 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001015 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001016 }
1017
David Srbeckyb06e28e2015-12-10 13:15:00 +00001018 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001019 for (;;) {
1020 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001021 switch (opcode) {
1022 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001023 // Emit all variables which are still alive at the end of the method.
1024 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
1025 if (local_in_reg[reg].is_live_) {
1026 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
1027 local_cb(context, local_in_reg[reg]);
1028 }
1029 }
1030 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001031 case DBG_ADVANCE_PC:
1032 address += DecodeUnsignedLeb128(&stream);
1033 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001034 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001035 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001036 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001037 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001038 case DBG_START_LOCAL_EXTENDED: {
1039 uint16_t reg = DecodeUnsignedLeb128(&stream);
1040 if (reg >= code_item->registers_size_) {
1041 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -08001042 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +00001043 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001044 }
1045
David Srbeckyb06e28e2015-12-10 13:15:00 +00001046 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Jeff Haoc1225362017-05-01 17:29:35 -07001047 uint16_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001048 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -07001049 if (opcode == DBG_START_LOCAL_EXTENDED) {
1050 signature_idx = DecodeUnsignedLeb128P1(&stream);
1051 }
1052
Shih-wei Liao195487c2011-08-20 13:29:04 -07001053 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +00001054 if (local_in_reg[reg].is_live_) {
1055 local_in_reg[reg].end_address_ = address;
1056 local_cb(context, local_in_reg[reg]);
1057 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001058
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001059 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -08001060 local_in_reg[reg].descriptor_ =
1061 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001062 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001063 local_in_reg[reg].start_address_ = address;
1064 local_in_reg[reg].reg_ = reg;
1065 local_in_reg[reg].is_live_ = true;
1066 break;
1067 }
1068 case DBG_END_LOCAL: {
1069 uint16_t reg = DecodeUnsignedLeb128(&stream);
1070 if (reg >= code_item->registers_size_) {
1071 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1072 << code_item->registers_size_ << ") in " << GetLocation();
1073 return false;
1074 }
Aart Bik2058b1d2017-05-17 13:32:26 -07001075 // If the register is live, close it properly. Otherwise, closing an already
1076 // closed register is sloppy, but harmless if no further action is taken.
1077 if (local_in_reg[reg].is_live_) {
1078 local_in_reg[reg].end_address_ = address;
1079 local_cb(context, local_in_reg[reg]);
1080 local_in_reg[reg].is_live_ = false;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001081 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001082 break;
1083 }
1084 case DBG_RESTART_LOCAL: {
1085 uint16_t reg = DecodeUnsignedLeb128(&stream);
1086 if (reg >= code_item->registers_size_) {
1087 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1088 << code_item->registers_size_ << ") in " << GetLocation();
1089 return false;
1090 }
1091 // If the register is live, the "restart" is superfluous,
1092 // and we don't want to mess with the existing start address.
1093 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001094 local_in_reg[reg].start_address_ = address;
1095 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001096 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001097 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001098 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001099 case DBG_SET_PROLOGUE_END:
1100 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001101 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001102 case DBG_SET_FILE:
1103 DecodeUnsignedLeb128P1(&stream); // name.
1104 break;
1105 default:
1106 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1107 break;
1108 }
1109 }
1110}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001111
David Srbeckyb06e28e2015-12-10 13:15:00 +00001112bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1113 void* context) const {
1114 DCHECK(position_cb != nullptr);
1115 if (code_item == nullptr) {
1116 return false;
1117 }
1118 const uint8_t* stream = GetDebugInfoStream(code_item);
1119 if (stream == nullptr) {
1120 return false;
1121 }
1122
1123 PositionInfo entry = PositionInfo();
1124 entry.line_ = DecodeUnsignedLeb128(&stream);
1125 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1126 for (uint32_t i = 0; i < parameters_size; ++i) {
1127 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1128 }
1129
1130 for (;;) {
1131 uint8_t opcode = *stream++;
1132 switch (opcode) {
1133 case DBG_END_SEQUENCE:
1134 return true; // end of stream.
1135 case DBG_ADVANCE_PC:
1136 entry.address_ += DecodeUnsignedLeb128(&stream);
1137 break;
1138 case DBG_ADVANCE_LINE:
1139 entry.line_ += DecodeSignedLeb128(&stream);
1140 break;
1141 case DBG_START_LOCAL:
1142 DecodeUnsignedLeb128(&stream); // reg.
1143 DecodeUnsignedLeb128P1(&stream); // name.
1144 DecodeUnsignedLeb128P1(&stream); // descriptor.
1145 break;
1146 case DBG_START_LOCAL_EXTENDED:
1147 DecodeUnsignedLeb128(&stream); // reg.
1148 DecodeUnsignedLeb128P1(&stream); // name.
1149 DecodeUnsignedLeb128P1(&stream); // descriptor.
1150 DecodeUnsignedLeb128P1(&stream); // signature.
1151 break;
1152 case DBG_END_LOCAL:
1153 case DBG_RESTART_LOCAL:
1154 DecodeUnsignedLeb128(&stream); // reg.
1155 break;
1156 case DBG_SET_PROLOGUE_END:
1157 entry.prologue_end_ = true;
1158 break;
1159 case DBG_SET_EPILOGUE_BEGIN:
1160 entry.epilogue_begin_ = true;
1161 break;
1162 case DBG_SET_FILE: {
1163 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001164 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001165 break;
1166 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001167 default: {
1168 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001169 entry.address_ += adjopcode / DBG_LINE_RANGE;
1170 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1171 if (position_cb(context, entry)) {
1172 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001173 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001174 entry.prologue_end_ = false;
1175 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001176 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001177 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001178 }
1179 }
1180}
1181
David Srbeckyb06e28e2015-12-10 13:15:00 +00001182bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001183 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001184
1185 // We know that this callback will be called in
1186 // ascending address order, so keep going until we find
1187 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001188 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001189 // The line number from the previous positions callback
1190 // wil be the final result.
1191 return true;
1192 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001193 context->line_num_ = entry.line_;
1194 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001195 }
1196}
1197
Andreas Gampe833a4852014-05-21 18:46:59 -07001198bool DexFile::IsMultiDexLocation(const char* location) {
1199 return strrchr(location, kMultiDexSeparator) != nullptr;
1200}
1201
Andreas Gampe90e34042015-04-27 20:01:52 -07001202std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1203 if (index == 0) {
1204 return "classes.dex";
1205 } else {
1206 return StringPrintf("classes%zu.dex", index + 1);
1207 }
1208}
1209
1210std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1211 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001212 return dex_location;
1213 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001214 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001215 }
1216}
1217
1218std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1219 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001220 std::string base_location = GetBaseLocation(dex_location);
1221 const char* suffix = dex_location + base_location.size();
1222 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1223 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1224 if (path != nullptr && path.get() != base_location) {
1225 return std::string(path.get()) + suffix;
1226 } else if (suffix[0] == 0) {
1227 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001228 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001229 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001230 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001231}
1232
Jeff Hao13e748b2015-08-25 20:44:19 +00001233// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001234int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001235 int32_t val = 0;
1236 for (int i = zwidth; i >= 0; --i) {
1237 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1238 }
1239 val >>= (3 - zwidth) * 8;
1240 return val;
1241}
1242
1243// Read an unsigned integer. "zwidth" is the zero-based byte count,
1244// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001245uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001246 uint32_t val = 0;
1247 for (int i = zwidth; i >= 0; --i) {
1248 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1249 }
1250 if (!fill_on_right) {
1251 val >>= (3 - zwidth) * 8;
1252 }
1253 return val;
1254}
1255
1256// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001257int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001258 int64_t val = 0;
1259 for (int i = zwidth; i >= 0; --i) {
1260 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1261 }
1262 val >>= (7 - zwidth) * 8;
1263 return val;
1264}
1265
1266// Read an unsigned long. "zwidth" is the zero-based byte count,
1267// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001268uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001269 uint64_t val = 0;
1270 for (int i = zwidth; i >= 0; --i) {
1271 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1272 }
1273 if (!fill_on_right) {
1274 val >>= (7 - zwidth) * 8;
1275 }
1276 return val;
1277}
1278
David Sehr709b0702016-10-13 09:12:37 -07001279std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1280 if (method_idx >= NumMethodIds()) {
1281 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1282 }
1283 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1284 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1285 result += '.';
1286 result += GetMethodName(method_id);
1287 if (with_signature) {
1288 const Signature signature = GetMethodSignature(method_id);
1289 std::string sig_as_string(signature.ToString());
1290 if (signature == Signature::NoSignature()) {
1291 return result + sig_as_string;
1292 }
1293 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1294 PrettyArguments(sig_as_string.c_str());
1295 }
1296 return result;
1297}
1298
1299std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1300 if (field_idx >= NumFieldIds()) {
1301 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1302 }
1303 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1304 std::string result;
1305 if (with_type) {
1306 result += GetFieldTypeDescriptor(field_id);
1307 result += ' ';
1308 }
1309 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1310 result += '.';
1311 result += GetFieldName(field_id);
1312 return result;
1313}
1314
Andreas Gampea5b09a62016-11-17 15:21:22 -08001315std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1316 if (type_idx.index_ >= NumTypeIds()) {
1317 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001318 }
1319 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1320 return PrettyDescriptor(GetTypeDescriptor(type_id));
1321}
1322
Jeff Hao3d080862016-05-26 18:39:17 -07001323// Checks that visibility is as expected. Includes special behavior for M and
1324// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001325std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1326 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1327 dex_file.GetLocation().c_str(),
1328 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1329 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1330 return os;
1331}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001332
Ian Rogersd91d6d62013-09-25 20:26:14 -07001333std::string Signature::ToString() const {
1334 if (dex_file_ == nullptr) {
1335 CHECK(proto_id_ == nullptr);
1336 return "<no signature>";
1337 }
1338 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1339 std::string result;
1340 if (params == nullptr) {
1341 result += "()";
1342 } else {
1343 result += "(";
1344 for (uint32_t i = 0; i < params->Size(); ++i) {
1345 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1346 }
1347 result += ")";
1348 }
1349 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1350 return result;
1351}
1352
Orion Hodson6c4921b2016-09-21 15:41:06 +01001353uint32_t Signature::GetNumberOfParameters() const {
1354 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1355 return (params != nullptr) ? params->Size() : 0;
1356}
1357
1358bool Signature::IsVoid() const {
1359 const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
1360 return strcmp(return_type, "V") == 0;
1361}
1362
Vladimir Markod9cffea2013-11-25 15:08:02 +00001363bool Signature::operator==(const StringPiece& rhs) const {
1364 if (dex_file_ == nullptr) {
1365 return false;
1366 }
1367 StringPiece tail(rhs);
1368 if (!tail.starts_with("(")) {
1369 return false; // Invalid signature
1370 }
1371 tail.remove_prefix(1); // "(";
1372 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1373 if (params != nullptr) {
1374 for (uint32_t i = 0; i < params->Size(); ++i) {
1375 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1376 if (!tail.starts_with(param)) {
1377 return false;
1378 }
1379 tail.remove_prefix(param.length());
1380 }
1381 }
1382 if (!tail.starts_with(")")) {
1383 return false;
1384 }
1385 tail.remove_prefix(1); // ")";
1386 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1387}
1388
Ian Rogersd91d6d62013-09-25 20:26:14 -07001389std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1390 return os << sig.ToString();
1391}
1392
Ian Rogers0571d352011-11-03 19:51:38 -07001393// Decodes the header section from the class data bytes.
1394void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001395 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001396 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1397 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1398 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1399 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1400}
1401
1402void ClassDataItemIterator::ReadClassDataField() {
1403 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1404 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001405 // The user of the iterator is responsible for checking if there
1406 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001407}
1408
1409void ClassDataItemIterator::ReadClassDataMethod() {
1410 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1411 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1412 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001413 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001414 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001415 }
Ian Rogers0571d352011-11-03 19:51:38 -07001416}
1417
Orion Hodson12f4ff42017-01-13 16:43:12 +00001418EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
1419 const uint8_t* array_data)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001420 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001421 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001422 pos_(-1),
Orion Hodson12f4ff42017-01-13 16:43:12 +00001423 ptr_(array_data),
David Sehr9323e6e2016-09-13 08:58:35 -07001424 type_(kByte) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001425 array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001426 if (array_size_ > 0) {
1427 Next();
1428 }
1429}
1430
Orion Hodson12f4ff42017-01-13 16:43:12 +00001431void EncodedArrayValueIterator::Next() {
Ian Rogers0571d352011-11-03 19:51:38 -07001432 pos_++;
1433 if (pos_ >= array_size_) {
1434 return;
1435 }
Ian Rogers13735952014-10-08 12:43:28 -07001436 uint8_t value_type = *ptr_++;
1437 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001438 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001439 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001440 switch (type_) {
1441 case kBoolean:
1442 jval_.i = (value_arg != 0) ? 1 : 0;
1443 width = 0;
1444 break;
1445 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001446 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001447 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001448 break;
1449 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001450 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001451 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001452 break;
1453 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001454 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001455 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001456 break;
1457 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001458 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001459 break;
1460 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001461 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001462 break;
1463 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001464 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001465 break;
1466 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001467 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001468 break;
1469 case kString:
1470 case kType:
Orion Hodson12f4ff42017-01-13 16:43:12 +00001471 case kMethodType:
1472 case kMethodHandle:
David Sehr9323e6e2016-09-13 08:58:35 -07001473 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001474 break;
1475 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001476 case kMethod:
1477 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001478 case kArray:
1479 case kAnnotation:
1480 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001481 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001482 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001483 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001484 width = 0;
1485 break;
1486 default:
1487 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001488 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001489 }
1490 ptr_ += width;
1491}
1492
Ian Rogers0571d352011-11-03 19:51:38 -07001493CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1494 handler_.address_ = -1;
1495 int32_t offset = -1;
1496
1497 // Short-circuit the overwhelmingly common cases.
1498 switch (code_item.tries_size_) {
1499 case 0:
1500 break;
1501 case 1: {
1502 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1503 uint32_t start = tries->start_addr_;
1504 if (address >= start) {
1505 uint32_t end = start + tries->insn_count_;
1506 if (address < end) {
1507 offset = tries->handler_off_;
1508 }
1509 }
1510 break;
1511 }
1512 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001513 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001514 }
Logan Chien736df022012-04-27 16:25:57 +08001515 Init(code_item, offset);
1516}
1517
1518CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1519 const DexFile::TryItem& try_item) {
1520 handler_.address_ = -1;
1521 Init(code_item, try_item.handler_off_);
1522}
1523
1524void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1525 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001526 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001527 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001528 } else {
1529 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001530 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001531 remaining_count_ = -1;
1532 catch_all_ = false;
1533 DCHECK(!HasNext());
1534 }
1535}
1536
Ian Rogers13735952014-10-08 12:43:28 -07001537void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001538 current_data_ = handler_data;
1539 remaining_count_ = DecodeSignedLeb128(&current_data_);
1540
1541 // If remaining_count_ is non-positive, then it is the negative of
1542 // the number of catch types, and the catches are followed by a
1543 // catch-all handler.
1544 if (remaining_count_ <= 0) {
1545 catch_all_ = true;
1546 remaining_count_ = -remaining_count_;
1547 } else {
1548 catch_all_ = false;
1549 }
1550 Next();
1551}
1552
1553void CatchHandlerIterator::Next() {
1554 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001555 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001556 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1557 remaining_count_--;
1558 return;
1559 }
1560
1561 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001562 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001563 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1564 catch_all_ = false;
1565 return;
1566 }
1567
1568 // no more handler
1569 remaining_count_ = -1;
1570}
1571
Andreas Gampea5b09a62016-11-17 15:21:22 -08001572namespace dex {
1573
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001574std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1575 os << "StringIndex[" << index.index_ << "]";
1576 return os;
1577}
1578
Andreas Gampea5b09a62016-11-17 15:21:22 -08001579std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1580 os << "TypeIndex[" << index.index_ << "]";
1581 return os;
1582}
1583
1584} // namespace dex
1585
Carl Shapiro1fb86202011-06-27 17:43:13 -07001586} // namespace art