blob: ccc4c168e5a8f2a2d283c443a62996cf7ccf415e [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Andreas Gampe542451c2016-07-26 09:02:02 -070030#include "base/enums.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000031#include "base/file_magic.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010034#include "base/stl_util.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"
Jeff Hao13e748b2015-08-25 20:44:19 +000037#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070038#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080039#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070040#include "globals.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010041#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070042#include "leb128.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070043#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070044#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070045#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030046#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070047#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070048#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070049#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070050#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070051
52namespace art {
53
Ian Rogers13735952014-10-08 12:43:28 -070054const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070055const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
56 {'0', '3', '5', '\0'},
57 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
58 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010059 {'0', '3', '7', '\0'},
60 // Dex version 038: Android "O" and beyond.
61 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070062};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070063
Vladimir Marko3a21e382016-09-02 12:38:38 +010064struct DexFile::AnnotationValue {
65 JValue value_;
66 uint8_t type_;
67};
68
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070070 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070071 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070072
73 // Strip ":...", which is the location
74 const char* zip_entry_name = kClassesDex;
75 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010076 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070077
Vladimir Markoaa4497d2014-09-05 14:01:17 +010078 if (DexFile::IsMultiDexLocation(filename)) {
79 file_part_storage = GetBaseLocation(filename);
80 file_part = file_part_storage.c_str();
81 zip_entry_name = filename + file_part_storage.size() + 1;
82 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070083 }
84
Andreas Gampe43e10b02016-07-15 17:17:34 -070085 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
86 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070087 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070088 return false;
89 }
90 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070091 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070092 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070093 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080094 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
95 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080096 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070097 }
Andreas Gampe833a4852014-05-21 18:46:59 -070098 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070099 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700100 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
101 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 return false;
103 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700106 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700108 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700109 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700110 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return false;
112 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700113 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return true;
115 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700116 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700118}
119
Aart Bik37d6a3b2016-06-21 18:30:10 -0700120bool DexFile::Open(const char* filename,
121 const char* location,
122 bool verify_checksum,
123 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800124 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800125 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700128 File fd = OpenAndReadMagic(filename, &magic, error_msg);
129 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700131 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700132 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700134 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700137 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700138 location,
139 /* verify */ true,
140 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 error_msg));
142 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800143 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 return true;
145 } else {
146 return false;
147 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700148 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700149 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400150 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151}
152
Andreas Gampe0cba0042015-04-29 20:47:16 -0700153static bool ContainsClassesDex(int fd, const char* filename) {
154 std::string error_msg;
155 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
156 if (zip_archive.get() == nullptr) {
157 return false;
158 }
159 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
160 return (zip_entry.get() != nullptr);
161}
162
163bool DexFile::MaybeDex(const char* filename) {
164 uint32_t magic;
165 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700166 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
167 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700168 return false;
169 }
170 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700171 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700172 } else if (IsDexMagic(magic)) {
173 return true;
174 }
175 return false;
176}
177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800178int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700179 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800180 return 0;
181 } else {
182 return mem_map_->GetProtect();
183 }
184}
185
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200186bool DexFile::IsReadOnly() const {
187 return GetPermissions() == PROT_READ;
188}
189
Brian Carlstrome0948e12013-08-29 09:36:15 -0700190bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200191 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700192 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193 return false;
194 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700195 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200196 }
197}
198
Brian Carlstrome0948e12013-08-29 09:36:15 -0700199bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 return false;
203 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700204 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 }
206}
207
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800208std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
209 const std::string& location,
210 uint32_t location_checksum,
211 const OatDexFile* oat_dex_file,
212 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700213 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800214 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800215 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800216 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
217 size,
218 location,
219 location_checksum,
220 nullptr,
221 oat_dex_file,
222 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100223 if (dex_file == nullptr) {
224 return nullptr;
225 }
226
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800227 if (verify && !DexFileVerifier::Verify(dex_file.get(),
228 dex_file->Begin(),
229 dex_file->Size(),
230 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700231 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800232 error_msg)) {
233 return nullptr;
234 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100235 return dex_file;
236}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800237
Orion Hodsona4c2a052016-08-17 10:51:42 +0100238std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
239 uint32_t location_checksum,
240 std::unique_ptr<MemMap> mem_map,
241 bool verify,
242 bool verify_checksum,
243 std::string* error_msg) {
244 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
245 std::unique_ptr<const DexFile> dex_file = OpenMemory(location,
246 location_checksum,
247 std::move(mem_map),
248 error_msg);
249 if (dex_file == nullptr) {
250 return nullptr;
251 }
252
253 if (verify && !DexFileVerifier::Verify(dex_file.get(),
254 dex_file->Begin(),
255 dex_file->Size(),
256 location.c_str(),
257 verify_checksum,
258 error_msg)) {
259 return nullptr;
260 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800261 return dex_file;
262}
263
Aart Bik37d6a3b2016-06-21 18:30:10 -0700264std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
265 const char* location,
266 bool verify,
267 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800268 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800269 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700271 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000272 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700273 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000274 struct stat sbuf;
275 memset(&sbuf, 0, sizeof(sbuf));
276 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800277 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000278 return nullptr;
279 }
280 if (S_ISDIR(sbuf.st_mode)) {
281 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
282 return nullptr;
283 }
284 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800285 map.reset(MemMap::MapFile(length,
286 PROT_READ,
287 MAP_PRIVATE,
288 fd,
289 0,
290 /*low_4gb*/false,
291 location,
292 error_msg));
Orion Hodsona4c2a052016-08-17 10:51:42 +0100293 if (map == nullptr) {
Vladimir Markofd995762013-11-06 16:36:36 +0000294 DCHECK(!error_msg->empty());
295 return nullptr;
296 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700297 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800298
299 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700300 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800301 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700302 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800303 }
304
305 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
306
Orion Hodsona4c2a052016-08-17 10:51:42 +0100307 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
308 dex_header->checksum_,
309 std::move(map),
Andreas Gampe928f72b2014-09-09 19:53:48 -0700310 error_msg));
311 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700312 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
313 error_msg->c_str());
314 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800315 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800316
Andreas Gampe928f72b2014-09-09 19:53:48 -0700317 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700318 location,
319 verify_checksum,
320 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700321 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800322 }
323
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800324 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700325}
326
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700327const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700328
Aart Bik37d6a3b2016-06-21 18:30:10 -0700329bool DexFile::OpenZip(int fd,
330 const std::string& location,
331 bool verify_checksum,
332 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800333 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800334 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700335 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700336 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700337 if (zip_archive.get() == nullptr) {
338 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700339 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700340 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700341 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800342}
343
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800344std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
345 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100346 std::unique_ptr<MemMap> mem_map,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800347 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800348 return OpenMemory(mem_map->Begin(),
349 mem_map->Size(),
350 location,
351 location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100352 std::move(mem_map),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800353 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800355}
356
Aart Bik37d6a3b2016-06-21 18:30:10 -0700357std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
358 const char* entry_name,
359 const std::string& location,
360 bool verify_checksum,
361 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800362 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800363 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800364 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700365 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700366 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700367 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700369 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800370 if (zip_entry->GetUncompressedLength() == 0) {
371 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
372 *error_code = ZipOpenErrorCode::kDexFileError;
373 return nullptr;
374 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700375 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700376 if (map.get() == 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 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100382 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
383 zip_entry->GetCrc32(),
384 std::move(map),
385 error_msg));
386 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700387 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
388 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700389 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700390 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800391 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700392 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700393 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700394 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700396 }
397 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700398 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700399 location.c_str(),
400 verify_checksum,
401 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700402 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700403 return nullptr;
404 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700405 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800406 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700407}
408
Andreas Gampe90e34042015-04-27 20:01:52 -0700409// Technically we do not have a limitation with respect to the number of dex files that can be in a
410// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
411// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
412// seems an excessive number.
413static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
414
Aart Bik37d6a3b2016-06-21 18:30:10 -0700415bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
416 const std::string& location,
417 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800418 std::string* error_msg,
419 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800420 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700421 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700422 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700423 std::unique_ptr<const DexFile> dex_file(
424 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700425 if (dex_file.get() == nullptr) {
426 return false;
427 } else {
428 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800429 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700430
431 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700432
433 // We could try to avoid std::string allocations by working on a char array directly. As we
434 // do not expect a lot of iterations, this seems too involved and brittle.
435
Andreas Gampe90e34042015-04-27 20:01:52 -0700436 for (size_t i = 1; ; ++i) {
437 std::string name = GetMultiDexClassesDexName(i);
438 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700439 std::unique_ptr<const DexFile> next_dex_file(
440 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700441 if (next_dex_file.get() == nullptr) {
442 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
443 LOG(WARNING) << error_msg;
444 }
445 break;
446 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800447 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700448 }
449
Andreas Gampe90e34042015-04-27 20:01:52 -0700450 if (i == kWarnOnManyDexFilesThreshold) {
451 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
452 << " dex files. Please consider coalescing and shrinking the number to "
453 " avoid runtime overhead.";
454 }
455
456 if (i == std::numeric_limits<size_t>::max()) {
457 LOG(ERROR) << "Overflow in number of dex files!";
458 break;
459 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700460 }
461
462 return true;
463 }
464}
465
466
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800467std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
468 size_t size,
469 const std::string& location,
470 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100471 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700472 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800473 std::string* error_msg) {
ganxiaolincd16d0a2016-07-18 11:21:44 +0800474 DCHECK(base != nullptr);
David Sehrd81c0f82016-08-03 09:05:20 -0700475 DCHECK_NE(size, 0U);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700476 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800477 std::unique_ptr<DexFile> dex_file(
Orion Hodsona4c2a052016-08-17 10:51:42 +0100478 new DexFile(base, size, location, location_checksum, std::move(mem_map), oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700479 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800480 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700481 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800482 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700483}
484
Ian Rogers13735952014-10-08 12:43:28 -0700485DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800486 const std::string& location,
487 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100488 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700489 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800490 : begin_(base),
491 size_(size),
492 location_(location),
493 location_checksum_(location_checksum),
Orion Hodsona4c2a052016-08-17 10:51:42 +0100494 mem_map_(std::move(mem_map)),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800495 header_(reinterpret_cast<const Header*>(base)),
496 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
497 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
498 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
499 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
500 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700501 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700502 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700503 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800504 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300505 const uint8_t* lookup_data = (oat_dex_file != nullptr)
506 ? oat_dex_file->GetLookupTableData()
507 : nullptr;
508 if (lookup_data != nullptr) {
509 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
510 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
511 } else {
512 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
513 }
514 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800515}
516
Jesse Wilson6bf19152011-09-29 13:12:33 -0400517DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700518 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
519 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
520 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
521 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400522}
523
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700524bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700525 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700526 return false;
527 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700528 return true;
529}
530
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700531bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800532 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700533 std::ostringstream oss;
534 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800535 << " " << header_->magic_[0]
536 << " " << header_->magic_[1]
537 << " " << header_->magic_[2]
538 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700539 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700540 return false;
541 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800542 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700543 std::ostringstream oss;
544 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800545 << " " << header_->magic_[4]
546 << " " << header_->magic_[5]
547 << " " << header_->magic_[6]
548 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700549 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700550 return false;
551 }
552 return true;
553}
554
Ian Rogers13735952014-10-08 12:43:28 -0700555bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800556 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
557}
558
Ian Rogers13735952014-10-08 12:43:28 -0700559bool DexFile::IsVersionValid(const uint8_t* magic) {
560 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700561 for (uint32_t i = 0; i < kNumDexVersions; i++) {
562 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
563 return true;
564 }
565 }
566 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800567}
568
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700569uint32_t DexFile::Header::GetVersion() const {
570 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700571 return atoi(version);
572}
573
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800574const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
575 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300576 if (LIKELY(lookup_table_ != nullptr)) {
577 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
578 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700579 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300580
Roland Levillainab880f42016-05-12 16:24:36 +0100581 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300582 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700583 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700584 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700585 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300586 const TypeId* type_id = FindTypeId(descriptor);
587 if (type_id != nullptr) {
588 uint16_t type_idx = GetIndexForTypeId(*type_id);
589 for (size_t i = 0; i < num_class_defs; ++i) {
590 const ClassDef& class_def = GetClassDef(i);
591 if (class_def.class_idx_ == type_idx) {
592 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700593 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700594 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700595 }
Ian Rogers68b56852014-08-29 20:19:11 -0700596 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700597}
598
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700599const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
600 size_t num_class_defs = NumClassDefs();
601 for (size_t i = 0; i < num_class_defs; ++i) {
602 const ClassDef& class_def = GetClassDef(i);
603 if (class_def.class_idx_ == type_idx) {
604 return &class_def;
605 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700606 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700608}
609
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800610const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100611 const DexFile::StringId& name,
612 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800613 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
614 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
615 const uint32_t name_idx = GetIndexForStringId(name);
616 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700617 int32_t lo = 0;
618 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800619 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700620 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800621 const DexFile::FieldId& field = GetFieldId(mid);
622 if (class_idx > field.class_idx_) {
623 lo = mid + 1;
624 } else if (class_idx < field.class_idx_) {
625 hi = mid - 1;
626 } else {
627 if (name_idx > field.name_idx_) {
628 lo = mid + 1;
629 } else if (name_idx < field.name_idx_) {
630 hi = mid - 1;
631 } else {
632 if (type_idx > field.type_idx_) {
633 lo = mid + 1;
634 } else if (type_idx < field.type_idx_) {
635 hi = mid - 1;
636 } else {
637 return &field;
638 }
639 }
640 }
641 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700642 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800643}
644
645const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700646 const DexFile::StringId& name,
647 const DexFile::ProtoId& signature) const {
648 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800649 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700650 const uint32_t name_idx = GetIndexForStringId(name);
651 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700652 int32_t lo = 0;
653 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700654 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700655 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700656 const DexFile::MethodId& method = GetMethodId(mid);
657 if (class_idx > method.class_idx_) {
658 lo = mid + 1;
659 } else if (class_idx < method.class_idx_) {
660 hi = mid - 1;
661 } else {
662 if (name_idx > method.name_idx_) {
663 lo = mid + 1;
664 } else if (name_idx < method.name_idx_) {
665 hi = mid - 1;
666 } else {
667 if (proto_idx > method.proto_idx_) {
668 lo = mid + 1;
669 } else if (proto_idx < method.proto_idx_) {
670 hi = mid - 1;
671 } else {
672 return &method;
673 }
674 }
675 }
676 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700677 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700678}
679
Ian Rogers637c65b2013-05-31 11:46:00 -0700680const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700681 int32_t lo = 0;
682 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700683 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700684 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700685 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700686 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700687 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
688 if (compare > 0) {
689 lo = mid + 1;
690 } else if (compare < 0) {
691 hi = mid - 1;
692 } else {
693 return &str_id;
694 }
695 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700696 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700697}
698
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300699const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
700 int32_t lo = 0;
701 int32_t hi = NumTypeIds() - 1;
702 while (hi >= lo) {
703 int32_t mid = (hi + lo) / 2;
704 const TypeId& type_id = GetTypeId(mid);
705 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
706 const char* str = GetStringData(str_id);
707 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
708 if (compare > 0) {
709 lo = mid + 1;
710 } else if (compare < 0) {
711 hi = mid - 1;
712 } else {
713 return &type_id;
714 }
715 }
716 return nullptr;
717}
718
Vladimir Markoa48aef42014-12-03 17:53:53 +0000719const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700720 int32_t lo = 0;
721 int32_t hi = NumStringIds() - 1;
722 while (hi >= lo) {
723 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700724 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700725 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000726 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700727 if (compare > 0) {
728 lo = mid + 1;
729 } else if (compare < 0) {
730 hi = mid - 1;
731 } else {
732 return &str_id;
733 }
734 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700735 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700736}
737
738const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700739 int32_t lo = 0;
740 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700741 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700742 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700743 const TypeId& type_id = GetTypeId(mid);
744 if (string_idx > type_id.descriptor_idx_) {
745 lo = mid + 1;
746 } else if (string_idx < type_id.descriptor_idx_) {
747 hi = mid - 1;
748 } else {
749 return &type_id;
750 }
751 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700752 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700753}
754
755const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000756 const uint16_t* signature_type_idxs,
757 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700758 int32_t lo = 0;
759 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700760 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700761 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700762 const DexFile::ProtoId& proto = GetProtoId(mid);
763 int compare = return_type_idx - proto.return_type_idx_;
764 if (compare == 0) {
765 DexFileParameterIterator it(*this, proto);
766 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000767 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800768 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700769 it.Next();
770 i++;
771 }
772 if (compare == 0) {
773 if (it.HasNext()) {
774 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000775 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700776 compare = 1;
777 }
778 }
779 }
780 if (compare > 0) {
781 lo = mid + 1;
782 } else if (compare < 0) {
783 hi = mid - 1;
784 } else {
785 return &proto;
786 }
787 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700788 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700789}
790
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000791void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
792 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300793}
794
Ian Rogers0571d352011-11-03 19:51:38 -0700795// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700796bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
797 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700798 if (signature[0] != '(') {
799 return false;
800 }
801 size_t offset = 1;
802 size_t end = signature.size();
803 bool process_return = false;
804 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000805 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700806 char c = signature[offset];
807 offset++;
808 if (c == ')') {
809 process_return = true;
810 continue;
811 }
Ian Rogers0571d352011-11-03 19:51:38 -0700812 while (c == '[') { // process array prefix
813 if (offset >= end) { // expect some descriptor following [
814 return false;
815 }
816 c = signature[offset];
817 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700818 }
819 if (c == 'L') { // process type descriptors
820 do {
821 if (offset >= end) { // unexpected early termination of descriptor
822 return false;
823 }
824 c = signature[offset];
825 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700826 } while (c != ';');
827 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000828 // TODO: avoid creating a std::string just to get a 0-terminated char array
829 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700830 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700831 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700832 return false;
833 }
834 uint16_t type_idx = GetIndexForTypeId(*type_id);
835 if (!process_return) {
836 param_type_idxs->push_back(type_idx);
837 } else {
838 *return_type_idx = type_idx;
839 return offset == end; // return true if the signature had reached a sensible end
840 }
841 }
842 return false; // failed to correctly parse return type
843}
844
Ian Rogersd91d6d62013-09-25 20:26:14 -0700845const Signature DexFile::CreateSignature(const StringPiece& signature) const {
846 uint16_t return_type_idx;
847 std::vector<uint16_t> param_type_indices;
848 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
849 if (!success) {
850 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700851 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700852 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700853 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700854 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700855 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700856 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700857}
858
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700859int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700860 // Note: Signed type is important for max and min.
861 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700862 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700863
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700864 while (min <= max) {
865 int32_t mid = min + ((max - min) / 2);
866
867 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
868 uint32_t start = ti->start_addr_;
869 uint32_t end = start + ti->insn_count_;
870
Ian Rogers0571d352011-11-03 19:51:38 -0700871 if (address < start) {
872 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700873 } else if (address >= end) {
874 min = mid + 1;
875 } else { // We have a winner!
876 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700877 }
878 }
879 // No match.
880 return -1;
881}
882
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700883int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
884 int32_t try_item = FindTryItem(code_item, address);
885 if (try_item == -1) {
886 return -1;
887 } else {
888 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
889 }
890}
891
David Srbeckyb06e28e2015-12-10 13:15:00 +0000892bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
893 DexDebugNewLocalCb local_cb, void* context) const {
894 DCHECK(local_cb != nullptr);
895 if (code_item == nullptr) {
896 return false;
897 }
898 const uint8_t* stream = GetDebugInfoStream(code_item);
899 if (stream == nullptr) {
900 return false;
901 }
902 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700903
David Srbeckyb06e28e2015-12-10 13:15:00 +0000904 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800905 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
907 local_in_reg[arg_reg].name_ = "this";
908 local_in_reg[arg_reg].descriptor_ = descriptor;
909 local_in_reg[arg_reg].signature_ = nullptr;
910 local_in_reg[arg_reg].start_address_ = 0;
911 local_in_reg[arg_reg].reg_ = arg_reg;
912 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700913 arg_reg++;
914 }
915
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800916 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000917 DecodeUnsignedLeb128(&stream); // Line.
918 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
919 uint32_t i;
920 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700921 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700922 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800923 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000924 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700927 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000928 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
929 local_in_reg[arg_reg].descriptor_ = descriptor;
930 local_in_reg[arg_reg].signature_ = nullptr;
931 local_in_reg[arg_reg].start_address_ = 0;
932 local_in_reg[arg_reg].reg_ = arg_reg;
933 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700934 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700935 case 'D':
936 case 'J':
937 arg_reg += 2;
938 break;
939 default:
940 arg_reg += 1;
941 break;
942 }
943 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000944 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800945 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
946 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000947 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948 }
949
David Srbeckyb06e28e2015-12-10 13:15:00 +0000950 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 for (;;) {
952 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700953 switch (opcode) {
954 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000955 // Emit all variables which are still alive at the end of the method.
956 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
957 if (local_in_reg[reg].is_live_) {
958 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
959 local_cb(context, local_in_reg[reg]);
960 }
961 }
962 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700963 case DBG_ADVANCE_PC:
964 address += DecodeUnsignedLeb128(&stream);
965 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000967 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700968 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000970 case DBG_START_LOCAL_EXTENDED: {
971 uint16_t reg = DecodeUnsignedLeb128(&stream);
972 if (reg >= code_item->registers_size_) {
973 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800974 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000975 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700976 }
977
David Srbeckyb06e28e2015-12-10 13:15:00 +0000978 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
979 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
980 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700981 if (opcode == DBG_START_LOCAL_EXTENDED) {
982 signature_idx = DecodeUnsignedLeb128P1(&stream);
983 }
984
Shih-wei Liao195487c2011-08-20 13:29:04 -0700985 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000986 if (local_in_reg[reg].is_live_) {
987 local_in_reg[reg].end_address_ = address;
988 local_cb(context, local_in_reg[reg]);
989 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700990
David Srbeckyb06e28e2015-12-10 13:15:00 +0000991 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
992 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
993 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
994 local_in_reg[reg].start_address_ = address;
995 local_in_reg[reg].reg_ = reg;
996 local_in_reg[reg].is_live_ = true;
997 break;
998 }
999 case DBG_END_LOCAL: {
1000 uint16_t reg = DecodeUnsignedLeb128(&stream);
1001 if (reg >= code_item->registers_size_) {
1002 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1003 << code_item->registers_size_ << ") in " << GetLocation();
1004 return false;
1005 }
1006 if (!local_in_reg[reg].is_live_) {
1007 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
1008 return false;
1009 }
1010 local_in_reg[reg].end_address_ = address;
1011 local_cb(context, local_in_reg[reg]);
1012 local_in_reg[reg].is_live_ = false;
1013 break;
1014 }
1015 case DBG_RESTART_LOCAL: {
1016 uint16_t reg = DecodeUnsignedLeb128(&stream);
1017 if (reg >= code_item->registers_size_) {
1018 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1019 << code_item->registers_size_ << ") in " << GetLocation();
1020 return false;
1021 }
1022 // If the register is live, the "restart" is superfluous,
1023 // and we don't want to mess with the existing start address.
1024 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001025 local_in_reg[reg].start_address_ = address;
1026 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001027 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001028 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001029 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001030 case DBG_SET_PROLOGUE_END:
1031 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001032 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001033 case DBG_SET_FILE:
1034 DecodeUnsignedLeb128P1(&stream); // name.
1035 break;
1036 default:
1037 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1038 break;
1039 }
1040 }
1041}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001042
David Srbeckyb06e28e2015-12-10 13:15:00 +00001043bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1044 void* context) const {
1045 DCHECK(position_cb != nullptr);
1046 if (code_item == nullptr) {
1047 return false;
1048 }
1049 const uint8_t* stream = GetDebugInfoStream(code_item);
1050 if (stream == nullptr) {
1051 return false;
1052 }
1053
1054 PositionInfo entry = PositionInfo();
1055 entry.line_ = DecodeUnsignedLeb128(&stream);
1056 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1057 for (uint32_t i = 0; i < parameters_size; ++i) {
1058 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1059 }
1060
1061 for (;;) {
1062 uint8_t opcode = *stream++;
1063 switch (opcode) {
1064 case DBG_END_SEQUENCE:
1065 return true; // end of stream.
1066 case DBG_ADVANCE_PC:
1067 entry.address_ += DecodeUnsignedLeb128(&stream);
1068 break;
1069 case DBG_ADVANCE_LINE:
1070 entry.line_ += DecodeSignedLeb128(&stream);
1071 break;
1072 case DBG_START_LOCAL:
1073 DecodeUnsignedLeb128(&stream); // reg.
1074 DecodeUnsignedLeb128P1(&stream); // name.
1075 DecodeUnsignedLeb128P1(&stream); // descriptor.
1076 break;
1077 case DBG_START_LOCAL_EXTENDED:
1078 DecodeUnsignedLeb128(&stream); // reg.
1079 DecodeUnsignedLeb128P1(&stream); // name.
1080 DecodeUnsignedLeb128P1(&stream); // descriptor.
1081 DecodeUnsignedLeb128P1(&stream); // signature.
1082 break;
1083 case DBG_END_LOCAL:
1084 case DBG_RESTART_LOCAL:
1085 DecodeUnsignedLeb128(&stream); // reg.
1086 break;
1087 case DBG_SET_PROLOGUE_END:
1088 entry.prologue_end_ = true;
1089 break;
1090 case DBG_SET_EPILOGUE_BEGIN:
1091 entry.epilogue_begin_ = true;
1092 break;
1093 case DBG_SET_FILE: {
1094 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1095 entry.source_file_ = StringDataByIdx(name_idx);
1096 break;
1097 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001098 default: {
1099 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001100 entry.address_ += adjopcode / DBG_LINE_RANGE;
1101 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1102 if (position_cb(context, entry)) {
1103 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001104 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001105 entry.prologue_end_ = false;
1106 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001107 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001108 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001109 }
1110 }
1111}
1112
David Srbeckyb06e28e2015-12-10 13:15:00 +00001113bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001114 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001115
1116 // We know that this callback will be called in
1117 // ascending address order, so keep going until we find
1118 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001119 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001120 // The line number from the previous positions callback
1121 // wil be the final result.
1122 return true;
1123 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001124 context->line_num_ = entry.line_;
1125 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001126 }
1127}
1128
Andreas Gampe833a4852014-05-21 18:46:59 -07001129bool DexFile::IsMultiDexLocation(const char* location) {
1130 return strrchr(location, kMultiDexSeparator) != nullptr;
1131}
1132
Andreas Gampe90e34042015-04-27 20:01:52 -07001133std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1134 if (index == 0) {
1135 return "classes.dex";
1136 } else {
1137 return StringPrintf("classes%zu.dex", index + 1);
1138 }
1139}
1140
1141std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1142 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001143 return dex_location;
1144 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001145 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001146 }
1147}
1148
1149std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1150 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001151 std::string base_location = GetBaseLocation(dex_location);
1152 const char* suffix = dex_location + base_location.size();
1153 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1154 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1155 if (path != nullptr && path.get() != base_location) {
1156 return std::string(path.get()) + suffix;
1157 } else if (suffix[0] == 0) {
1158 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001159 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001160 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001161 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001162}
1163
Jeff Hao13e748b2015-08-25 20:44:19 +00001164// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001165int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001166 int32_t val = 0;
1167 for (int i = zwidth; i >= 0; --i) {
1168 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1169 }
1170 val >>= (3 - zwidth) * 8;
1171 return val;
1172}
1173
1174// Read an unsigned integer. "zwidth" is the zero-based byte count,
1175// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001176uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001177 uint32_t val = 0;
1178 for (int i = zwidth; i >= 0; --i) {
1179 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1180 }
1181 if (!fill_on_right) {
1182 val >>= (3 - zwidth) * 8;
1183 }
1184 return val;
1185}
1186
1187// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001188int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001189 int64_t val = 0;
1190 for (int i = zwidth; i >= 0; --i) {
1191 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1192 }
1193 val >>= (7 - zwidth) * 8;
1194 return val;
1195}
1196
1197// Read an unsigned long. "zwidth" is the zero-based byte count,
1198// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001199uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001200 uint64_t val = 0;
1201 for (int i = zwidth; i >= 0; --i) {
1202 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1203 }
1204 if (!fill_on_right) {
1205 val >>= (7 - zwidth) * 8;
1206 }
1207 return val;
1208}
1209
Jeff Hao3d080862016-05-26 18:39:17 -07001210// Checks that visibility is as expected. Includes special behavior for M and
1211// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001212std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1213 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1214 dex_file.GetLocation().c_str(),
1215 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1216 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1217 return os;
1218}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001219
Ian Rogersd91d6d62013-09-25 20:26:14 -07001220std::string Signature::ToString() const {
1221 if (dex_file_ == nullptr) {
1222 CHECK(proto_id_ == nullptr);
1223 return "<no signature>";
1224 }
1225 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1226 std::string result;
1227 if (params == nullptr) {
1228 result += "()";
1229 } else {
1230 result += "(";
1231 for (uint32_t i = 0; i < params->Size(); ++i) {
1232 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1233 }
1234 result += ")";
1235 }
1236 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1237 return result;
1238}
1239
Vladimir Markod9cffea2013-11-25 15:08:02 +00001240bool Signature::operator==(const StringPiece& rhs) const {
1241 if (dex_file_ == nullptr) {
1242 return false;
1243 }
1244 StringPiece tail(rhs);
1245 if (!tail.starts_with("(")) {
1246 return false; // Invalid signature
1247 }
1248 tail.remove_prefix(1); // "(";
1249 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1250 if (params != nullptr) {
1251 for (uint32_t i = 0; i < params->Size(); ++i) {
1252 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1253 if (!tail.starts_with(param)) {
1254 return false;
1255 }
1256 tail.remove_prefix(param.length());
1257 }
1258 }
1259 if (!tail.starts_with(")")) {
1260 return false;
1261 }
1262 tail.remove_prefix(1); // ")";
1263 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1264}
1265
Ian Rogersd91d6d62013-09-25 20:26:14 -07001266std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1267 return os << sig.ToString();
1268}
1269
Ian Rogers0571d352011-11-03 19:51:38 -07001270// Decodes the header section from the class data bytes.
1271void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001272 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001273 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1274 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1275 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1276 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1277}
1278
1279void ClassDataItemIterator::ReadClassDataField() {
1280 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1281 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001282 // The user of the iterator is responsible for checking if there
1283 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001284}
1285
1286void ClassDataItemIterator::ReadClassDataMethod() {
1287 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1288 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1289 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001290 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001291 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001292 }
Ian Rogers0571d352011-11-03 19:51:38 -07001293}
1294
David Sehr9323e6e2016-09-13 08:58:35 -07001295EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1296 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001297 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001298 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001299 pos_(-1),
1300 type_(kByte) {
1301 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001302 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001303 array_size_ = 0;
1304 } else {
1305 array_size_ = DecodeUnsignedLeb128(&ptr_);
1306 }
1307 if (array_size_ > 0) {
1308 Next();
1309 }
1310}
1311
1312void EncodedStaticFieldValueIterator::Next() {
1313 pos_++;
1314 if (pos_ >= array_size_) {
1315 return;
1316 }
Ian Rogers13735952014-10-08 12:43:28 -07001317 uint8_t value_type = *ptr_++;
1318 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001319 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001320 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001321 switch (type_) {
1322 case kBoolean:
1323 jval_.i = (value_arg != 0) ? 1 : 0;
1324 width = 0;
1325 break;
1326 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001327 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001328 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001329 break;
1330 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001331 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001332 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001333 break;
1334 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001335 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001336 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001337 break;
1338 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001339 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001340 break;
1341 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001342 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001343 break;
1344 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001345 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001346 break;
1347 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001348 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001349 break;
1350 case kString:
1351 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001352 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001353 break;
1354 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001355 case kMethod:
1356 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001357 case kArray:
1358 case kAnnotation:
1359 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001360 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001361 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001362 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001363 width = 0;
1364 break;
1365 default:
1366 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001367 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001368 }
1369 ptr_ += width;
1370}
1371
Ian Rogers0571d352011-11-03 19:51:38 -07001372CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1373 handler_.address_ = -1;
1374 int32_t offset = -1;
1375
1376 // Short-circuit the overwhelmingly common cases.
1377 switch (code_item.tries_size_) {
1378 case 0:
1379 break;
1380 case 1: {
1381 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1382 uint32_t start = tries->start_addr_;
1383 if (address >= start) {
1384 uint32_t end = start + tries->insn_count_;
1385 if (address < end) {
1386 offset = tries->handler_off_;
1387 }
1388 }
1389 break;
1390 }
1391 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001392 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001393 }
Logan Chien736df022012-04-27 16:25:57 +08001394 Init(code_item, offset);
1395}
1396
1397CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1398 const DexFile::TryItem& try_item) {
1399 handler_.address_ = -1;
1400 Init(code_item, try_item.handler_off_);
1401}
1402
1403void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1404 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001405 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001406 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001407 } else {
1408 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001409 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001410 remaining_count_ = -1;
1411 catch_all_ = false;
1412 DCHECK(!HasNext());
1413 }
1414}
1415
Ian Rogers13735952014-10-08 12:43:28 -07001416void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001417 current_data_ = handler_data;
1418 remaining_count_ = DecodeSignedLeb128(&current_data_);
1419
1420 // If remaining_count_ is non-positive, then it is the negative of
1421 // the number of catch types, and the catches are followed by a
1422 // catch-all handler.
1423 if (remaining_count_ <= 0) {
1424 catch_all_ = true;
1425 remaining_count_ = -remaining_count_;
1426 } else {
1427 catch_all_ = false;
1428 }
1429 Next();
1430}
1431
1432void CatchHandlerIterator::Next() {
1433 if (remaining_count_ > 0) {
1434 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1435 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1436 remaining_count_--;
1437 return;
1438 }
1439
1440 if (catch_all_) {
1441 handler_.type_idx_ = DexFile::kDexNoIndex16;
1442 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1443 catch_all_ = false;
1444 return;
1445 }
1446
1447 // no more handler
1448 remaining_count_ = -1;
1449}
1450
Carl Shapiro1fb86202011-06-27 17:43:13 -07001451} // namespace art