blob: 03223b0d3c9a473157219351fb272aa7c1beb502 [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"
David Sehr9aa352e2016-09-15 18:13:52 -070035#include "base/stringprintf.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080036#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070037#include "base/unix_file/fd_file.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"
David Sehr9aa352e2016-09-15 18:13:52 -070043#include "oat_file.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070044#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070046#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030047#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070048#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070049#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070050#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070051#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070052
53namespace art {
54
Ian Rogers13735952014-10-08 12:43:28 -070055const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070056const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
57 {'0', '3', '5', '\0'},
58 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
59 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010060 {'0', '3', '7', '\0'},
61 // Dex version 038: Android "O" and beyond.
62 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070063};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070064
Vladimir Marko3a21e382016-09-02 12:38:38 +010065struct DexFile::AnnotationValue {
66 JValue value_;
67 uint8_t type_;
68};
69
Ian Rogers8d31bbd2013-10-13 10:44:14 -070070bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070071 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070072 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070073
74 // Strip ":...", which is the location
75 const char* zip_entry_name = kClassesDex;
76 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010077 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070078
Vladimir Markoaa4497d2014-09-05 14:01:17 +010079 if (DexFile::IsMultiDexLocation(filename)) {
80 file_part_storage = GetBaseLocation(filename);
81 file_part = file_part_storage.c_str();
82 zip_entry_name = filename + file_part_storage.size() + 1;
83 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070084 }
85
Andreas Gampe43e10b02016-07-15 17:17:34 -070086 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
87 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070088 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070089 return false;
90 }
91 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070092 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070093 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080095 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
96 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080097 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070098 }
Andreas Gampe833a4852014-05-21 18:46:59 -070099 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700100 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700101 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
102 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800103 return false;
104 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700105 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800106 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700107 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700108 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700110 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
113 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700114 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return true;
116 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700117 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700119}
120
Aart Bik37d6a3b2016-06-21 18:30:10 -0700121bool DexFile::Open(const char* filename,
122 const char* location,
123 bool verify_checksum,
124 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800125 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800126 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700127 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700128 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700129 File fd = OpenAndReadMagic(filename, &magic, error_msg);
130 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700131 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700132 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700133 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700134 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700135 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700136 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700137 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700138 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700139 location,
140 /* verify */ true,
141 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700142 error_msg));
143 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800144 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700145 return true;
146 } else {
147 return false;
148 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700149 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400151 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700152}
153
Andreas Gampe0cba0042015-04-29 20:47:16 -0700154static bool ContainsClassesDex(int fd, const char* filename) {
155 std::string error_msg;
156 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
157 if (zip_archive.get() == nullptr) {
158 return false;
159 }
160 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
161 return (zip_entry.get() != nullptr);
162}
163
164bool DexFile::MaybeDex(const char* filename) {
165 uint32_t magic;
166 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700167 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
168 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700169 return false;
170 }
171 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700172 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700173 } else if (IsDexMagic(magic)) {
174 return true;
175 }
176 return false;
177}
178
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800179int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800181 return 0;
182 } else {
183 return mem_map_->GetProtect();
184 }
185}
186
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200187bool DexFile::IsReadOnly() const {
188 return GetPermissions() == PROT_READ;
189}
190
Brian Carlstrome0948e12013-08-29 09:36:15 -0700191bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200192 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700193 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194 return false;
195 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700196 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200197 }
198}
199
Brian Carlstrome0948e12013-08-29 09:36:15 -0700200bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200201 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700202 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200203 return false;
204 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700205 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200206 }
207}
208
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800209std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
210 const std::string& location,
211 uint32_t location_checksum,
212 const OatDexFile* oat_dex_file,
213 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700214 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800215 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800216 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800217 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
218 size,
219 location,
220 location_checksum,
221 nullptr,
222 oat_dex_file,
223 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100224 if (dex_file == nullptr) {
225 return nullptr;
226 }
227
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800228 if (verify && !DexFileVerifier::Verify(dex_file.get(),
229 dex_file->Begin(),
230 dex_file->Size(),
231 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700232 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800233 error_msg)) {
234 return nullptr;
235 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100236 return dex_file;
237}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800238
Orion Hodsona4c2a052016-08-17 10:51:42 +0100239std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
240 uint32_t location_checksum,
241 std::unique_ptr<MemMap> mem_map,
242 bool verify,
243 bool verify_checksum,
244 std::string* error_msg) {
245 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
246 std::unique_ptr<const DexFile> dex_file = OpenMemory(location,
247 location_checksum,
248 std::move(mem_map),
249 error_msg);
250 if (dex_file == nullptr) {
251 return nullptr;
252 }
253
254 if (verify && !DexFileVerifier::Verify(dex_file.get(),
255 dex_file->Begin(),
256 dex_file->Size(),
257 location.c_str(),
258 verify_checksum,
259 error_msg)) {
260 return nullptr;
261 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800262 return dex_file;
263}
264
Aart Bik37d6a3b2016-06-21 18:30:10 -0700265std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
266 const char* location,
267 bool verify,
268 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800269 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800270 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700272 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000273 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700274 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000275 struct stat sbuf;
276 memset(&sbuf, 0, sizeof(sbuf));
277 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800278 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000279 return nullptr;
280 }
281 if (S_ISDIR(sbuf.st_mode)) {
282 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
283 return nullptr;
284 }
285 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800286 map.reset(MemMap::MapFile(length,
287 PROT_READ,
288 MAP_PRIVATE,
289 fd,
290 0,
291 /*low_4gb*/false,
292 location,
293 error_msg));
Orion Hodsona4c2a052016-08-17 10:51:42 +0100294 if (map == nullptr) {
Vladimir Markofd995762013-11-06 16:36:36 +0000295 DCHECK(!error_msg->empty());
296 return nullptr;
297 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700298 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800299
300 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700301 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800302 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800304 }
305
306 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
307
Orion Hodsona4c2a052016-08-17 10:51:42 +0100308 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
309 dex_header->checksum_,
310 std::move(map),
Andreas Gampe928f72b2014-09-09 19:53:48 -0700311 error_msg));
312 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700313 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
314 error_msg->c_str());
315 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800316 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800317
Andreas Gampe928f72b2014-09-09 19:53:48 -0700318 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700319 location,
320 verify_checksum,
321 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700322 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800323 }
324
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700326}
327
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700328const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700329
Aart Bik37d6a3b2016-06-21 18:30:10 -0700330bool DexFile::OpenZip(int fd,
331 const std::string& location,
332 bool verify_checksum,
333 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800334 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800335 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700336 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700337 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700338 if (zip_archive.get() == nullptr) {
339 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700341 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700342 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800343}
344
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800345std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
346 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100347 std::unique_ptr<MemMap> mem_map,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800348 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800349 return OpenMemory(mem_map->Begin(),
350 mem_map->Size(),
351 location,
352 location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100353 std::move(mem_map),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800354 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700355 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800356}
357
Aart Bik37d6a3b2016-06-21 18:30:10 -0700358std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
359 const char* entry_name,
360 const std::string& location,
361 bool verify_checksum,
362 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800363 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800364 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800365 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700367 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700368 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700369 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700370 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800371 if (zip_entry->GetUncompressedLength() == 0) {
372 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
373 *error_code = ZipOpenErrorCode::kDexFileError;
374 return nullptr;
375 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700376 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700377 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700378 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700379 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700380 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700381 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700382 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100383 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
384 zip_entry->GetCrc32(),
385 std::move(map),
386 error_msg));
387 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
389 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700390 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700391 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800392 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700393 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700395 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700396 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700397 }
398 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700399 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700400 location.c_str(),
401 verify_checksum,
402 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700403 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700404 return nullptr;
405 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700406 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800407 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700408}
409
Andreas Gampe90e34042015-04-27 20:01:52 -0700410// Technically we do not have a limitation with respect to the number of dex files that can be in a
411// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
412// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
413// seems an excessive number.
414static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
415
Aart Bik37d6a3b2016-06-21 18:30:10 -0700416bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
417 const std::string& location,
418 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800419 std::string* error_msg,
420 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800421 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700422 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700423 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700424 std::unique_ptr<const DexFile> dex_file(
425 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700426 if (dex_file.get() == nullptr) {
427 return false;
428 } else {
429 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800430 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700431
432 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700433
434 // We could try to avoid std::string allocations by working on a char array directly. As we
435 // do not expect a lot of iterations, this seems too involved and brittle.
436
Andreas Gampe90e34042015-04-27 20:01:52 -0700437 for (size_t i = 1; ; ++i) {
438 std::string name = GetMultiDexClassesDexName(i);
439 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700440 std::unique_ptr<const DexFile> next_dex_file(
441 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700442 if (next_dex_file.get() == nullptr) {
443 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
444 LOG(WARNING) << error_msg;
445 }
446 break;
447 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800448 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700449 }
450
Andreas Gampe90e34042015-04-27 20:01:52 -0700451 if (i == kWarnOnManyDexFilesThreshold) {
452 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
453 << " dex files. Please consider coalescing and shrinking the number to "
454 " avoid runtime overhead.";
455 }
456
457 if (i == std::numeric_limits<size_t>::max()) {
458 LOG(ERROR) << "Overflow in number of dex files!";
459 break;
460 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700461 }
462
463 return true;
464 }
465}
466
467
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800468std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
469 size_t size,
470 const std::string& location,
471 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100472 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700473 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800474 std::string* error_msg) {
ganxiaolincd16d0a2016-07-18 11:21:44 +0800475 DCHECK(base != nullptr);
David Sehrd81c0f82016-08-03 09:05:20 -0700476 DCHECK_NE(size, 0U);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700477 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800478 std::unique_ptr<DexFile> dex_file(
Orion Hodsona4c2a052016-08-17 10:51:42 +0100479 new DexFile(base, size, location, location_checksum, std::move(mem_map), oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700480 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800481 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700482 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800483 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700484}
485
Ian Rogers13735952014-10-08 12:43:28 -0700486DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800487 const std::string& location,
488 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100489 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700490 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800491 : begin_(base),
492 size_(size),
493 location_(location),
494 location_checksum_(location_checksum),
Orion Hodsona4c2a052016-08-17 10:51:42 +0100495 mem_map_(std::move(mem_map)),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800496 header_(reinterpret_cast<const Header*>(base)),
497 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
498 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
499 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
500 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
501 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700502 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700503 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700504 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800505 CHECK_GT(size_, 0U) << GetLocation();
506}
507
Jesse Wilson6bf19152011-09-29 13:12:33 -0400508DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700509 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
510 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
511 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
512 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400513}
514
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700515bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700516 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700517 return false;
518 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700519 return true;
520}
521
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700522bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800523 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700524 std::ostringstream oss;
525 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800526 << " " << header_->magic_[0]
527 << " " << header_->magic_[1]
528 << " " << header_->magic_[2]
529 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700530 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700531 return false;
532 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800533 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700534 std::ostringstream oss;
535 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800536 << " " << header_->magic_[4]
537 << " " << header_->magic_[5]
538 << " " << header_->magic_[6]
539 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700540 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700541 return false;
542 }
543 return true;
544}
545
Ian Rogers13735952014-10-08 12:43:28 -0700546bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800547 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
548}
549
Ian Rogers13735952014-10-08 12:43:28 -0700550bool DexFile::IsVersionValid(const uint8_t* magic) {
551 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700552 for (uint32_t i = 0; i < kNumDexVersions; i++) {
553 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
554 return true;
555 }
556 }
557 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800558}
559
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700560uint32_t DexFile::Header::GetVersion() const {
561 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700562 return atoi(version);
563}
564
David Sehr9aa352e2016-09-15 18:13:52 -0700565const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
566 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100567 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700568 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700569 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700570 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700571 for (size_t i = 0; i < num_class_defs; ++i) {
572 const ClassDef& class_def = GetClassDef(i);
573 if (class_def.class_idx_ == type_idx) {
574 return &class_def;
575 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700576 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700577 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700578}
579
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800580const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100581 const DexFile::StringId& name,
582 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800583 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
584 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
585 const uint32_t name_idx = GetIndexForStringId(name);
586 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700587 int32_t lo = 0;
588 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800589 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700590 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800591 const DexFile::FieldId& field = GetFieldId(mid);
592 if (class_idx > field.class_idx_) {
593 lo = mid + 1;
594 } else if (class_idx < field.class_idx_) {
595 hi = mid - 1;
596 } else {
597 if (name_idx > field.name_idx_) {
598 lo = mid + 1;
599 } else if (name_idx < field.name_idx_) {
600 hi = mid - 1;
601 } else {
602 if (type_idx > field.type_idx_) {
603 lo = mid + 1;
604 } else if (type_idx < field.type_idx_) {
605 hi = mid - 1;
606 } else {
607 return &field;
608 }
609 }
610 }
611 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700612 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800613}
614
615const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700616 const DexFile::StringId& name,
617 const DexFile::ProtoId& signature) const {
618 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800619 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700620 const uint32_t name_idx = GetIndexForStringId(name);
621 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700622 int32_t lo = 0;
623 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700624 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700625 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700626 const DexFile::MethodId& method = GetMethodId(mid);
627 if (class_idx > method.class_idx_) {
628 lo = mid + 1;
629 } else if (class_idx < method.class_idx_) {
630 hi = mid - 1;
631 } else {
632 if (name_idx > method.name_idx_) {
633 lo = mid + 1;
634 } else if (name_idx < method.name_idx_) {
635 hi = mid - 1;
636 } else {
637 if (proto_idx > method.proto_idx_) {
638 lo = mid + 1;
639 } else if (proto_idx < method.proto_idx_) {
640 hi = mid - 1;
641 } else {
642 return &method;
643 }
644 }
645 }
646 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700647 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700648}
649
Ian Rogers637c65b2013-05-31 11:46:00 -0700650const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700651 int32_t lo = 0;
652 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700653 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700654 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700655 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700656 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700657 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
658 if (compare > 0) {
659 lo = mid + 1;
660 } else if (compare < 0) {
661 hi = mid - 1;
662 } else {
663 return &str_id;
664 }
665 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700666 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700667}
668
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300669const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
670 int32_t lo = 0;
671 int32_t hi = NumTypeIds() - 1;
672 while (hi >= lo) {
673 int32_t mid = (hi + lo) / 2;
674 const TypeId& type_id = GetTypeId(mid);
675 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
676 const char* str = GetStringData(str_id);
677 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
678 if (compare > 0) {
679 lo = mid + 1;
680 } else if (compare < 0) {
681 hi = mid - 1;
682 } else {
683 return &type_id;
684 }
685 }
686 return nullptr;
687}
688
Vladimir Markoa48aef42014-12-03 17:53:53 +0000689const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700690 int32_t lo = 0;
691 int32_t hi = NumStringIds() - 1;
692 while (hi >= lo) {
693 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700694 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700695 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000696 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700697 if (compare > 0) {
698 lo = mid + 1;
699 } else if (compare < 0) {
700 hi = mid - 1;
701 } else {
702 return &str_id;
703 }
704 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700705 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700706}
707
708const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700709 int32_t lo = 0;
710 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700711 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700712 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700713 const TypeId& type_id = GetTypeId(mid);
714 if (string_idx > type_id.descriptor_idx_) {
715 lo = mid + 1;
716 } else if (string_idx < type_id.descriptor_idx_) {
717 hi = mid - 1;
718 } else {
719 return &type_id;
720 }
721 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700722 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700723}
724
725const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000726 const uint16_t* signature_type_idxs,
727 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700728 int32_t lo = 0;
729 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700730 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700731 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700732 const DexFile::ProtoId& proto = GetProtoId(mid);
733 int compare = return_type_idx - proto.return_type_idx_;
734 if (compare == 0) {
735 DexFileParameterIterator it(*this, proto);
736 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000737 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800738 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700739 it.Next();
740 i++;
741 }
742 if (compare == 0) {
743 if (it.HasNext()) {
744 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000745 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700746 compare = 1;
747 }
748 }
749 }
750 if (compare > 0) {
751 lo = mid + 1;
752 } else if (compare < 0) {
753 hi = mid - 1;
754 } else {
755 return &proto;
756 }
757 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700759}
760
761// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700762bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
763 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700764 if (signature[0] != '(') {
765 return false;
766 }
767 size_t offset = 1;
768 size_t end = signature.size();
769 bool process_return = false;
770 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000771 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700772 char c = signature[offset];
773 offset++;
774 if (c == ')') {
775 process_return = true;
776 continue;
777 }
Ian Rogers0571d352011-11-03 19:51:38 -0700778 while (c == '[') { // process array prefix
779 if (offset >= end) { // expect some descriptor following [
780 return false;
781 }
782 c = signature[offset];
783 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700784 }
785 if (c == 'L') { // process type descriptors
786 do {
787 if (offset >= end) { // unexpected early termination of descriptor
788 return false;
789 }
790 c = signature[offset];
791 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700792 } while (c != ';');
793 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000794 // TODO: avoid creating a std::string just to get a 0-terminated char array
795 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700796 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700797 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700798 return false;
799 }
800 uint16_t type_idx = GetIndexForTypeId(*type_id);
801 if (!process_return) {
802 param_type_idxs->push_back(type_idx);
803 } else {
804 *return_type_idx = type_idx;
805 return offset == end; // return true if the signature had reached a sensible end
806 }
807 }
808 return false; // failed to correctly parse return type
809}
810
Ian Rogersd91d6d62013-09-25 20:26:14 -0700811const Signature DexFile::CreateSignature(const StringPiece& signature) const {
812 uint16_t return_type_idx;
813 std::vector<uint16_t> param_type_indices;
814 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
815 if (!success) {
816 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700817 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700818 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700819 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700820 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700821 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700822 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700823}
824
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700825int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700826 // Note: Signed type is important for max and min.
827 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700828 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700829
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700830 while (min <= max) {
831 int32_t mid = min + ((max - min) / 2);
832
833 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
834 uint32_t start = ti->start_addr_;
835 uint32_t end = start + ti->insn_count_;
836
Ian Rogers0571d352011-11-03 19:51:38 -0700837 if (address < start) {
838 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700839 } else if (address >= end) {
840 min = mid + 1;
841 } else { // We have a winner!
842 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700843 }
844 }
845 // No match.
846 return -1;
847}
848
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700849int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
850 int32_t try_item = FindTryItem(code_item, address);
851 if (try_item == -1) {
852 return -1;
853 } else {
854 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
855 }
856}
857
David Srbeckyb06e28e2015-12-10 13:15:00 +0000858bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
859 DexDebugNewLocalCb local_cb, void* context) const {
860 DCHECK(local_cb != nullptr);
861 if (code_item == nullptr) {
862 return false;
863 }
864 const uint8_t* stream = GetDebugInfoStream(code_item);
865 if (stream == nullptr) {
866 return false;
867 }
868 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700869
David Srbeckyb06e28e2015-12-10 13:15:00 +0000870 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800871 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000872 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
873 local_in_reg[arg_reg].name_ = "this";
874 local_in_reg[arg_reg].descriptor_ = descriptor;
875 local_in_reg[arg_reg].signature_ = nullptr;
876 local_in_reg[arg_reg].start_address_ = 0;
877 local_in_reg[arg_reg].reg_ = arg_reg;
878 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700879 arg_reg++;
880 }
881
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800882 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000883 DecodeUnsignedLeb128(&stream); // Line.
884 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
885 uint32_t i;
886 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700888 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800889 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000890 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000892 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700893 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000894 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
895 local_in_reg[arg_reg].descriptor_ = descriptor;
896 local_in_reg[arg_reg].signature_ = nullptr;
897 local_in_reg[arg_reg].start_address_ = 0;
898 local_in_reg[arg_reg].reg_ = arg_reg;
899 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700900 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700901 case 'D':
902 case 'J':
903 arg_reg += 2;
904 break;
905 default:
906 arg_reg += 1;
907 break;
908 }
909 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000910 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800911 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
912 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000913 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 }
915
David Srbeckyb06e28e2015-12-10 13:15:00 +0000916 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700917 for (;;) {
918 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 switch (opcode) {
920 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000921 // Emit all variables which are still alive at the end of the method.
922 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
923 if (local_in_reg[reg].is_live_) {
924 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
925 local_cb(context, local_in_reg[reg]);
926 }
927 }
928 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 case DBG_ADVANCE_PC:
930 address += DecodeUnsignedLeb128(&stream);
931 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700932 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000933 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700934 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700935 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000936 case DBG_START_LOCAL_EXTENDED: {
937 uint16_t reg = DecodeUnsignedLeb128(&stream);
938 if (reg >= code_item->registers_size_) {
939 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800940 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000941 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 }
943
David Srbeckyb06e28e2015-12-10 13:15:00 +0000944 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
945 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
946 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700947 if (opcode == DBG_START_LOCAL_EXTENDED) {
948 signature_idx = DecodeUnsignedLeb128P1(&stream);
949 }
950
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000952 if (local_in_reg[reg].is_live_) {
953 local_in_reg[reg].end_address_ = address;
954 local_cb(context, local_in_reg[reg]);
955 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700956
David Srbeckyb06e28e2015-12-10 13:15:00 +0000957 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
958 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
959 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
960 local_in_reg[reg].start_address_ = address;
961 local_in_reg[reg].reg_ = reg;
962 local_in_reg[reg].is_live_ = true;
963 break;
964 }
965 case DBG_END_LOCAL: {
966 uint16_t reg = DecodeUnsignedLeb128(&stream);
967 if (reg >= code_item->registers_size_) {
968 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
969 << code_item->registers_size_ << ") in " << GetLocation();
970 return false;
971 }
972 if (!local_in_reg[reg].is_live_) {
973 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
974 return false;
975 }
976 local_in_reg[reg].end_address_ = address;
977 local_cb(context, local_in_reg[reg]);
978 local_in_reg[reg].is_live_ = false;
979 break;
980 }
981 case DBG_RESTART_LOCAL: {
982 uint16_t reg = DecodeUnsignedLeb128(&stream);
983 if (reg >= code_item->registers_size_) {
984 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
985 << code_item->registers_size_ << ") in " << GetLocation();
986 return false;
987 }
988 // If the register is live, the "restart" is superfluous,
989 // and we don't want to mess with the existing start address.
990 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700991 local_in_reg[reg].start_address_ = address;
992 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700993 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700994 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000995 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700996 case DBG_SET_PROLOGUE_END:
997 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700998 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000999 case DBG_SET_FILE:
1000 DecodeUnsignedLeb128P1(&stream); // name.
1001 break;
1002 default:
1003 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1004 break;
1005 }
1006 }
1007}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001008
David Srbeckyb06e28e2015-12-10 13:15:00 +00001009bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1010 void* context) const {
1011 DCHECK(position_cb != nullptr);
1012 if (code_item == nullptr) {
1013 return false;
1014 }
1015 const uint8_t* stream = GetDebugInfoStream(code_item);
1016 if (stream == nullptr) {
1017 return false;
1018 }
1019
1020 PositionInfo entry = PositionInfo();
1021 entry.line_ = DecodeUnsignedLeb128(&stream);
1022 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1023 for (uint32_t i = 0; i < parameters_size; ++i) {
1024 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1025 }
1026
1027 for (;;) {
1028 uint8_t opcode = *stream++;
1029 switch (opcode) {
1030 case DBG_END_SEQUENCE:
1031 return true; // end of stream.
1032 case DBG_ADVANCE_PC:
1033 entry.address_ += DecodeUnsignedLeb128(&stream);
1034 break;
1035 case DBG_ADVANCE_LINE:
1036 entry.line_ += DecodeSignedLeb128(&stream);
1037 break;
1038 case DBG_START_LOCAL:
1039 DecodeUnsignedLeb128(&stream); // reg.
1040 DecodeUnsignedLeb128P1(&stream); // name.
1041 DecodeUnsignedLeb128P1(&stream); // descriptor.
1042 break;
1043 case DBG_START_LOCAL_EXTENDED:
1044 DecodeUnsignedLeb128(&stream); // reg.
1045 DecodeUnsignedLeb128P1(&stream); // name.
1046 DecodeUnsignedLeb128P1(&stream); // descriptor.
1047 DecodeUnsignedLeb128P1(&stream); // signature.
1048 break;
1049 case DBG_END_LOCAL:
1050 case DBG_RESTART_LOCAL:
1051 DecodeUnsignedLeb128(&stream); // reg.
1052 break;
1053 case DBG_SET_PROLOGUE_END:
1054 entry.prologue_end_ = true;
1055 break;
1056 case DBG_SET_EPILOGUE_BEGIN:
1057 entry.epilogue_begin_ = true;
1058 break;
1059 case DBG_SET_FILE: {
1060 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1061 entry.source_file_ = StringDataByIdx(name_idx);
1062 break;
1063 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001064 default: {
1065 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001066 entry.address_ += adjopcode / DBG_LINE_RANGE;
1067 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1068 if (position_cb(context, entry)) {
1069 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001070 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001071 entry.prologue_end_ = false;
1072 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001073 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001074 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001075 }
1076 }
1077}
1078
David Srbeckyb06e28e2015-12-10 13:15:00 +00001079bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001080 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001081
1082 // We know that this callback will be called in
1083 // ascending address order, so keep going until we find
1084 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001085 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001086 // The line number from the previous positions callback
1087 // wil be the final result.
1088 return true;
1089 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001090 context->line_num_ = entry.line_;
1091 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001092 }
1093}
1094
Andreas Gampe833a4852014-05-21 18:46:59 -07001095bool DexFile::IsMultiDexLocation(const char* location) {
1096 return strrchr(location, kMultiDexSeparator) != nullptr;
1097}
1098
Andreas Gampe90e34042015-04-27 20:01:52 -07001099std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1100 if (index == 0) {
1101 return "classes.dex";
1102 } else {
1103 return StringPrintf("classes%zu.dex", index + 1);
1104 }
1105}
1106
1107std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1108 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001109 return dex_location;
1110 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001111 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001112 }
1113}
1114
1115std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1116 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001117 std::string base_location = GetBaseLocation(dex_location);
1118 const char* suffix = dex_location + base_location.size();
1119 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1120 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1121 if (path != nullptr && path.get() != base_location) {
1122 return std::string(path.get()) + suffix;
1123 } else if (suffix[0] == 0) {
1124 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001125 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001126 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001127 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001128}
1129
Jeff Hao13e748b2015-08-25 20:44:19 +00001130// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001131int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001132 int32_t val = 0;
1133 for (int i = zwidth; i >= 0; --i) {
1134 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1135 }
1136 val >>= (3 - zwidth) * 8;
1137 return val;
1138}
1139
1140// Read an unsigned integer. "zwidth" is the zero-based byte count,
1141// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001142uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001143 uint32_t val = 0;
1144 for (int i = zwidth; i >= 0; --i) {
1145 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1146 }
1147 if (!fill_on_right) {
1148 val >>= (3 - zwidth) * 8;
1149 }
1150 return val;
1151}
1152
1153// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001154int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001155 int64_t val = 0;
1156 for (int i = zwidth; i >= 0; --i) {
1157 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1158 }
1159 val >>= (7 - zwidth) * 8;
1160 return val;
1161}
1162
1163// Read an unsigned long. "zwidth" is the zero-based byte count,
1164// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001165uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001166 uint64_t val = 0;
1167 for (int i = zwidth; i >= 0; --i) {
1168 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1169 }
1170 if (!fill_on_right) {
1171 val >>= (7 - zwidth) * 8;
1172 }
1173 return val;
1174}
1175
Jeff Hao3d080862016-05-26 18:39:17 -07001176// Checks that visibility is as expected. Includes special behavior for M and
1177// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001178std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1179 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1180 dex_file.GetLocation().c_str(),
1181 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1182 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1183 return os;
1184}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001185
Ian Rogersd91d6d62013-09-25 20:26:14 -07001186std::string Signature::ToString() const {
1187 if (dex_file_ == nullptr) {
1188 CHECK(proto_id_ == nullptr);
1189 return "<no signature>";
1190 }
1191 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1192 std::string result;
1193 if (params == nullptr) {
1194 result += "()";
1195 } else {
1196 result += "(";
1197 for (uint32_t i = 0; i < params->Size(); ++i) {
1198 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1199 }
1200 result += ")";
1201 }
1202 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1203 return result;
1204}
1205
Vladimir Markod9cffea2013-11-25 15:08:02 +00001206bool Signature::operator==(const StringPiece& rhs) const {
1207 if (dex_file_ == nullptr) {
1208 return false;
1209 }
1210 StringPiece tail(rhs);
1211 if (!tail.starts_with("(")) {
1212 return false; // Invalid signature
1213 }
1214 tail.remove_prefix(1); // "(";
1215 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1216 if (params != nullptr) {
1217 for (uint32_t i = 0; i < params->Size(); ++i) {
1218 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1219 if (!tail.starts_with(param)) {
1220 return false;
1221 }
1222 tail.remove_prefix(param.length());
1223 }
1224 }
1225 if (!tail.starts_with(")")) {
1226 return false;
1227 }
1228 tail.remove_prefix(1); // ")";
1229 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1230}
1231
Ian Rogersd91d6d62013-09-25 20:26:14 -07001232std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1233 return os << sig.ToString();
1234}
1235
Ian Rogers0571d352011-11-03 19:51:38 -07001236// Decodes the header section from the class data bytes.
1237void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001238 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001239 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1240 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1241 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1242 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1243}
1244
1245void ClassDataItemIterator::ReadClassDataField() {
1246 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1247 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001248 // The user of the iterator is responsible for checking if there
1249 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001250}
1251
1252void ClassDataItemIterator::ReadClassDataMethod() {
1253 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1254 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1255 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001256 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001257 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001258 }
Ian Rogers0571d352011-11-03 19:51:38 -07001259}
1260
David Sehr9323e6e2016-09-13 08:58:35 -07001261EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1262 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001263 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001264 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001265 pos_(-1),
1266 type_(kByte) {
1267 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001268 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001269 array_size_ = 0;
1270 } else {
1271 array_size_ = DecodeUnsignedLeb128(&ptr_);
1272 }
1273 if (array_size_ > 0) {
1274 Next();
1275 }
1276}
1277
1278void EncodedStaticFieldValueIterator::Next() {
1279 pos_++;
1280 if (pos_ >= array_size_) {
1281 return;
1282 }
Ian Rogers13735952014-10-08 12:43:28 -07001283 uint8_t value_type = *ptr_++;
1284 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001285 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001286 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001287 switch (type_) {
1288 case kBoolean:
1289 jval_.i = (value_arg != 0) ? 1 : 0;
1290 width = 0;
1291 break;
1292 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001293 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001294 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001295 break;
1296 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001297 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001298 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001299 break;
1300 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001301 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001302 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001303 break;
1304 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001305 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001306 break;
1307 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001308 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001309 break;
1310 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001311 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001312 break;
1313 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001314 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001315 break;
1316 case kString:
1317 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001318 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001319 break;
1320 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001321 case kMethod:
1322 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001323 case kArray:
1324 case kAnnotation:
1325 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001326 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001327 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001328 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001329 width = 0;
1330 break;
1331 default:
1332 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001333 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001334 }
1335 ptr_ += width;
1336}
1337
Ian Rogers0571d352011-11-03 19:51:38 -07001338CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1339 handler_.address_ = -1;
1340 int32_t offset = -1;
1341
1342 // Short-circuit the overwhelmingly common cases.
1343 switch (code_item.tries_size_) {
1344 case 0:
1345 break;
1346 case 1: {
1347 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1348 uint32_t start = tries->start_addr_;
1349 if (address >= start) {
1350 uint32_t end = start + tries->insn_count_;
1351 if (address < end) {
1352 offset = tries->handler_off_;
1353 }
1354 }
1355 break;
1356 }
1357 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001358 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001359 }
Logan Chien736df022012-04-27 16:25:57 +08001360 Init(code_item, offset);
1361}
1362
1363CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1364 const DexFile::TryItem& try_item) {
1365 handler_.address_ = -1;
1366 Init(code_item, try_item.handler_off_);
1367}
1368
1369void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1370 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001371 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001372 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001373 } else {
1374 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001375 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001376 remaining_count_ = -1;
1377 catch_all_ = false;
1378 DCHECK(!HasNext());
1379 }
1380}
1381
Ian Rogers13735952014-10-08 12:43:28 -07001382void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001383 current_data_ = handler_data;
1384 remaining_count_ = DecodeSignedLeb128(&current_data_);
1385
1386 // If remaining_count_ is non-positive, then it is the negative of
1387 // the number of catch types, and the catches are followed by a
1388 // catch-all handler.
1389 if (remaining_count_ <= 0) {
1390 catch_all_ = true;
1391 remaining_count_ = -remaining_count_;
1392 } else {
1393 catch_all_ = false;
1394 }
1395 Next();
1396}
1397
1398void CatchHandlerIterator::Next() {
1399 if (remaining_count_ > 0) {
1400 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1401 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1402 remaining_count_--;
1403 return;
1404 }
1405
1406 if (catch_all_) {
1407 handler_.type_idx_ = DexFile::kDexNoIndex16;
1408 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1409 catch_all_ = false;
1410 return;
1411 }
1412
1413 // no more handler
1414 remaining_count_ = -1;
1415}
1416
Carl Shapiro1fb86202011-06-27 17:43:13 -07001417} // namespace art