blob: 70b7f877bcecb52057dacf321dd077e3b85f1a1d [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
David Sehr733ddb22016-09-19 15:02:18 -070055static constexpr OatDexFile* kNoOatDexFile = nullptr;
56
57const char* DexFile::kClassesDex = "classes.dex";
58
Ian Rogers13735952014-10-08 12:43:28 -070059const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070060const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
61 {'0', '3', '5', '\0'},
62 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
63 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010064 {'0', '3', '7', '\0'},
65 // Dex version 038: Android "O" and beyond.
66 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070067};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070068
Vladimir Marko3a21e382016-09-02 12:38:38 +010069struct DexFile::AnnotationValue {
70 JValue value_;
71 uint8_t type_;
72};
73
Ian Rogers8d31bbd2013-10-13 10:44:14 -070074bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070075 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070076 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070077
78 // Strip ":...", which is the location
79 const char* zip_entry_name = kClassesDex;
80 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010081 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070082
Vladimir Markoaa4497d2014-09-05 14:01:17 +010083 if (DexFile::IsMultiDexLocation(filename)) {
84 file_part_storage = GetBaseLocation(filename);
85 file_part = file_part_storage.c_str();
86 zip_entry_name = filename + file_part_storage.size() + 1;
87 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070088 }
89
Andreas Gampe43e10b02016-07-15 17:17:34 -070090 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
91 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070092 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070093 return false;
94 }
95 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070097 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070098 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080099 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
100 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800101 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700102 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700103 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700104 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700105 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
106 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800107 return false;
108 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700109 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700111 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700112 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700114 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700115 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return false;
117 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700118 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return true;
120 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700121 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800122 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700123}
124
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800125int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800127 return 0;
128 } else {
129 return mem_map_->GetProtect();
130 }
131}
132
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200133bool DexFile::IsReadOnly() const {
134 return GetPermissions() == PROT_READ;
135}
136
Brian Carlstrome0948e12013-08-29 09:36:15 -0700137bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200138 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700139 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200140 return false;
141 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700142 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200143 }
144}
145
Brian Carlstrome0948e12013-08-29 09:36:15 -0700146bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200147 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700148 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200149 return false;
150 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700151 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200152 }
153}
154
David Sehr733ddb22016-09-19 15:02:18 -0700155
156std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
157 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800158 const std::string& location,
159 uint32_t location_checksum,
160 const OatDexFile* oat_dex_file,
161 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700162 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800163 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800164 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700165 return OpenCommon(base,
166 size,
167 location,
168 location_checksum,
169 oat_dex_file,
170 verify,
171 verify_checksum,
172 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100173}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800174
Orion Hodsona4c2a052016-08-17 10:51:42 +0100175std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
176 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700177 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100178 bool verify,
179 bool verify_checksum,
180 std::string* error_msg) {
181 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700182 CHECK(map.get() != nullptr);
183 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
184 map->Size(),
185 location,
186 location_checksum,
187 kNoOatDexFile,
188 verify,
189 verify_checksum,
190 error_msg);
191 if (dex_file != nullptr) {
192 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100193 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800194 return dex_file;
195}
196
David Sehr733ddb22016-09-19 15:02:18 -0700197bool DexFile::Open(const char* filename,
198 const std::string& location,
199 bool verify_checksum,
200 std::string* error_msg,
201 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
202 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
203 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
204 uint32_t magic;
205 File fd = OpenAndReadMagic(filename, &magic, error_msg);
206 if (fd.Fd() == -1) {
207 DCHECK(!error_msg->empty());
208 return false;
209 }
210 if (IsZipMagic(magic)) {
211 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
212 }
213 if (IsDexMagic(magic)) {
214 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
215 location,
216 /* verify */ true,
217 verify_checksum,
218 error_msg));
219 if (dex_file.get() != nullptr) {
220 dex_files->push_back(std::move(dex_file));
221 return true;
222 } else {
223 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000224 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700225 }
David Sehr733ddb22016-09-19 15:02:18 -0700226 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
227 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700228}
229
David Sehr733ddb22016-09-19 15:02:18 -0700230std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
231 const std::string& location,
232 bool verify_checksum,
233 std::string* error_msg) {
234 ScopedTrace trace("Open dex file " + std::string(location));
235 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
236}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700237
Aart Bik37d6a3b2016-06-21 18:30:10 -0700238bool DexFile::OpenZip(int fd,
239 const std::string& location,
240 bool verify_checksum,
241 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800242 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800243 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700244 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700245 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700246 if (zip_archive.get() == nullptr) {
247 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700248 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700249 }
David Sehr733ddb22016-09-19 15:02:18 -0700250 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
251 location,
252 verify_checksum,
253 error_msg,
254 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800255}
256
David Sehr733ddb22016-09-19 15:02:18 -0700257std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
258 const std::string& location,
259 bool verify,
260 bool verify_checksum,
261 std::string* error_msg) {
262 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
263 CHECK(!location.empty());
264 std::unique_ptr<MemMap> map;
265 {
266 File delayed_close(fd, /* check_usage */ false);
267 struct stat sbuf;
268 memset(&sbuf, 0, sizeof(sbuf));
269 if (fstat(fd, &sbuf) == -1) {
270 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
271 strerror(errno));
272 return nullptr;
273 }
274 if (S_ISDIR(sbuf.st_mode)) {
275 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
276 return nullptr;
277 }
278 size_t length = sbuf.st_size;
279 map.reset(MemMap::MapFile(length,
280 PROT_READ,
281 MAP_PRIVATE,
282 fd,
283 0,
284 /*low_4gb*/false,
285 location.c_str(),
286 error_msg));
287 if (map == nullptr) {
288 DCHECK(!error_msg->empty());
289 return nullptr;
290 }
291 }
292
293 if (map->Size() < sizeof(DexFile::Header)) {
294 *error_msg = StringPrintf(
295 "DexFile: failed to open dex file '%s' that is too short to have a header",
296 location.c_str());
297 return nullptr;
298 }
299
300 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
301
302 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
303 map->Size(),
304 location,
305 dex_header->checksum_,
306 kNoOatDexFile,
307 verify,
308 verify_checksum,
309 error_msg);
310 if (dex_file != nullptr) {
311 dex_file->mem_map_.reset(map.release());
312 }
313
314 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800315}
316
David Sehr733ddb22016-09-19 15:02:18 -0700317std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
318 const char* entry_name,
319 const std::string& location,
320 bool verify_checksum,
321 std::string* error_msg,
322 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800323 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800324 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700325 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700326 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700327 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700328 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700329 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800330 if (zip_entry->GetUncompressedLength() == 0) {
331 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
332 *error_code = ZipOpenErrorCode::kDexFileError;
333 return nullptr;
334 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700336 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700337 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700338 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700339 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700340 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700341 }
David Sehr733ddb22016-09-19 15:02:18 -0700342 VerifyResult verify_result;
343 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
344 map->Size(),
345 location,
346 zip_entry->GetCrc32(),
347 kNoOatDexFile,
348 /* verify */ true,
349 verify_checksum,
350 error_msg,
351 &verify_result);
352 if (dex_file != nullptr) {
353 dex_file->mem_map_.reset(map.release());
jeffhaof6174e82012-01-31 16:14:17 -0800354 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700355 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700356 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700357 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700359 }
360 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700361 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700362 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700363 return nullptr;
364 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700365 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800366 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700367}
368
Andreas Gampe90e34042015-04-27 20:01:52 -0700369// Technically we do not have a limitation with respect to the number of dex files that can be in a
370// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
371// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
372// seems an excessive number.
373static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
374
David Sehr733ddb22016-09-19 15:02:18 -0700375bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
376 const std::string& location,
377 bool verify_checksum,
378 std::string* error_msg,
379 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800380 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700381 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700382 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700383 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
384 kClassesDex,
385 location,
386 verify_checksum,
387 error_msg,
388 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700389 if (dex_file.get() == nullptr) {
390 return false;
391 } else {
392 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800393 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700394
395 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700396
397 // We could try to avoid std::string allocations by working on a char array directly. As we
398 // do not expect a lot of iterations, this seems too involved and brittle.
399
Andreas Gampe90e34042015-04-27 20:01:52 -0700400 for (size_t i = 1; ; ++i) {
401 std::string name = GetMultiDexClassesDexName(i);
402 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700403 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
404 name.c_str(),
405 fake_location,
406 verify_checksum,
407 error_msg,
408 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700409 if (next_dex_file.get() == nullptr) {
410 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
411 LOG(WARNING) << error_msg;
412 }
413 break;
414 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800415 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700416 }
417
Andreas Gampe90e34042015-04-27 20:01:52 -0700418 if (i == kWarnOnManyDexFilesThreshold) {
419 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
420 << " dex files. Please consider coalescing and shrinking the number to "
421 " avoid runtime overhead.";
422 }
423
424 if (i == std::numeric_limits<size_t>::max()) {
425 LOG(ERROR) << "Overflow in number of dex files!";
426 break;
427 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700428 }
429
430 return true;
431 }
432}
433
David Sehr733ddb22016-09-19 15:02:18 -0700434std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
435 size_t size,
436 const std::string& location,
437 uint32_t location_checksum,
438 const OatDexFile* oat_dex_file,
439 bool verify,
440 bool verify_checksum,
441 std::string* error_msg,
442 VerifyResult* verify_result) {
443 std::unique_ptr<DexFile> dex_file(new DexFile(base,
444 size,
445 location,
446 location_checksum,
447 oat_dex_file));
448 if (dex_file == nullptr) {
449 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
450 error_msg->c_str());
451 return nullptr;
452 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700453 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800454 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700455 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700456 }
David Sehr733ddb22016-09-19 15:02:18 -0700457 if (verify && !DexFileVerifier::Verify(dex_file.get(),
458 dex_file->Begin(),
459 dex_file->Size(),
460 location.c_str(),
461 verify_checksum,
462 error_msg)) {
463 if (verify_result != nullptr) {
464 *verify_result = VerifyResult::kVerifyFailed;
465 }
466 return nullptr;
467 }
468 if (verify_result != nullptr) {
469 *verify_result = VerifyResult::kVerifySucceeded;
470 }
471 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700472}
473
David Sehr733ddb22016-09-19 15:02:18 -0700474DexFile::DexFile(const uint8_t* base,
475 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800476 const std::string& location,
477 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700478 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800479 : begin_(base),
480 size_(size),
481 location_(location),
482 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800483 header_(reinterpret_cast<const Header*>(base)),
484 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
485 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
486 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
487 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
488 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700489 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700490 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700491 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800492 CHECK_GT(size_, 0U) << GetLocation();
493}
494
Jesse Wilson6bf19152011-09-29 13:12:33 -0400495DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700496 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
497 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
498 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
499 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400500}
501
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700503 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700504 return false;
505 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700506 return true;
507}
508
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800510 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511 std::ostringstream oss;
512 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800513 << " " << header_->magic_[0]
514 << " " << header_->magic_[1]
515 << " " << header_->magic_[2]
516 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700517 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700518 return false;
519 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800520 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700521 std::ostringstream oss;
522 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800523 << " " << header_->magic_[4]
524 << " " << header_->magic_[5]
525 << " " << header_->magic_[6]
526 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700527 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700528 return false;
529 }
530 return true;
531}
532
Ian Rogers13735952014-10-08 12:43:28 -0700533bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800534 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
535}
536
Ian Rogers13735952014-10-08 12:43:28 -0700537bool DexFile::IsVersionValid(const uint8_t* magic) {
538 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700539 for (uint32_t i = 0; i < kNumDexVersions; i++) {
540 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
541 return true;
542 }
543 }
544 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800545}
546
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700547uint32_t DexFile::Header::GetVersion() const {
548 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700549 return atoi(version);
550}
551
David Sehr9aa352e2016-09-15 18:13:52 -0700552const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
553 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100554 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700555 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700556 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700557 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700558 for (size_t i = 0; i < num_class_defs; ++i) {
559 const ClassDef& class_def = GetClassDef(i);
560 if (class_def.class_idx_ == type_idx) {
561 return &class_def;
562 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700563 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700564 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700565}
566
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800567const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100568 const DexFile::StringId& name,
569 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800570 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
571 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
572 const uint32_t name_idx = GetIndexForStringId(name);
573 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700574 int32_t lo = 0;
575 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800576 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700577 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800578 const DexFile::FieldId& field = GetFieldId(mid);
579 if (class_idx > field.class_idx_) {
580 lo = mid + 1;
581 } else if (class_idx < field.class_idx_) {
582 hi = mid - 1;
583 } else {
584 if (name_idx > field.name_idx_) {
585 lo = mid + 1;
586 } else if (name_idx < field.name_idx_) {
587 hi = mid - 1;
588 } else {
589 if (type_idx > field.type_idx_) {
590 lo = mid + 1;
591 } else if (type_idx < field.type_idx_) {
592 hi = mid - 1;
593 } else {
594 return &field;
595 }
596 }
597 }
598 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700599 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800600}
601
602const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700603 const DexFile::StringId& name,
604 const DexFile::ProtoId& signature) const {
605 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800606 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700607 const uint32_t name_idx = GetIndexForStringId(name);
608 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700609 int32_t lo = 0;
610 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700611 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700612 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700613 const DexFile::MethodId& method = GetMethodId(mid);
614 if (class_idx > method.class_idx_) {
615 lo = mid + 1;
616 } else if (class_idx < method.class_idx_) {
617 hi = mid - 1;
618 } else {
619 if (name_idx > method.name_idx_) {
620 lo = mid + 1;
621 } else if (name_idx < method.name_idx_) {
622 hi = mid - 1;
623 } else {
624 if (proto_idx > method.proto_idx_) {
625 lo = mid + 1;
626 } else if (proto_idx < method.proto_idx_) {
627 hi = mid - 1;
628 } else {
629 return &method;
630 }
631 }
632 }
633 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700634 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700635}
636
Ian Rogers637c65b2013-05-31 11:46:00 -0700637const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700638 int32_t lo = 0;
639 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700640 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700641 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700642 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700643 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700644 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
645 if (compare > 0) {
646 lo = mid + 1;
647 } else if (compare < 0) {
648 hi = mid - 1;
649 } else {
650 return &str_id;
651 }
652 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700653 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700654}
655
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300656const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
657 int32_t lo = 0;
658 int32_t hi = NumTypeIds() - 1;
659 while (hi >= lo) {
660 int32_t mid = (hi + lo) / 2;
661 const TypeId& type_id = GetTypeId(mid);
662 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
663 const char* str = GetStringData(str_id);
664 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
665 if (compare > 0) {
666 lo = mid + 1;
667 } else if (compare < 0) {
668 hi = mid - 1;
669 } else {
670 return &type_id;
671 }
672 }
673 return nullptr;
674}
675
Vladimir Markoa48aef42014-12-03 17:53:53 +0000676const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700677 int32_t lo = 0;
678 int32_t hi = NumStringIds() - 1;
679 while (hi >= lo) {
680 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700681 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700682 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000683 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700684 if (compare > 0) {
685 lo = mid + 1;
686 } else if (compare < 0) {
687 hi = mid - 1;
688 } else {
689 return &str_id;
690 }
691 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700692 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700693}
694
695const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700696 int32_t lo = 0;
697 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700698 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700699 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700700 const TypeId& type_id = GetTypeId(mid);
701 if (string_idx > type_id.descriptor_idx_) {
702 lo = mid + 1;
703 } else if (string_idx < type_id.descriptor_idx_) {
704 hi = mid - 1;
705 } else {
706 return &type_id;
707 }
708 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700709 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700710}
711
712const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000713 const uint16_t* signature_type_idxs,
714 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700715 int32_t lo = 0;
716 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700717 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700718 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700719 const DexFile::ProtoId& proto = GetProtoId(mid);
720 int compare = return_type_idx - proto.return_type_idx_;
721 if (compare == 0) {
722 DexFileParameterIterator it(*this, proto);
723 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000724 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800725 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700726 it.Next();
727 i++;
728 }
729 if (compare == 0) {
730 if (it.HasNext()) {
731 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000732 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700733 compare = 1;
734 }
735 }
736 }
737 if (compare > 0) {
738 lo = mid + 1;
739 } else if (compare < 0) {
740 hi = mid - 1;
741 } else {
742 return &proto;
743 }
744 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700745 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700746}
747
748// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700749bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
750 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700751 if (signature[0] != '(') {
752 return false;
753 }
754 size_t offset = 1;
755 size_t end = signature.size();
756 bool process_return = false;
757 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000758 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700759 char c = signature[offset];
760 offset++;
761 if (c == ')') {
762 process_return = true;
763 continue;
764 }
Ian Rogers0571d352011-11-03 19:51:38 -0700765 while (c == '[') { // process array prefix
766 if (offset >= end) { // expect some descriptor following [
767 return false;
768 }
769 c = signature[offset];
770 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700771 }
772 if (c == 'L') { // process type descriptors
773 do {
774 if (offset >= end) { // unexpected early termination of descriptor
775 return false;
776 }
777 c = signature[offset];
778 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700779 } while (c != ';');
780 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000781 // TODO: avoid creating a std::string just to get a 0-terminated char array
782 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700783 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700784 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700785 return false;
786 }
787 uint16_t type_idx = GetIndexForTypeId(*type_id);
788 if (!process_return) {
789 param_type_idxs->push_back(type_idx);
790 } else {
791 *return_type_idx = type_idx;
792 return offset == end; // return true if the signature had reached a sensible end
793 }
794 }
795 return false; // failed to correctly parse return type
796}
797
Ian Rogersd91d6d62013-09-25 20:26:14 -0700798const Signature DexFile::CreateSignature(const StringPiece& signature) const {
799 uint16_t return_type_idx;
800 std::vector<uint16_t> param_type_indices;
801 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
802 if (!success) {
803 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700804 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700805 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700806 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700807 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700808 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700809 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700810}
811
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700812int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700813 // Note: Signed type is important for max and min.
814 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700815 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700816
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700817 while (min <= max) {
818 int32_t mid = min + ((max - min) / 2);
819
820 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
821 uint32_t start = ti->start_addr_;
822 uint32_t end = start + ti->insn_count_;
823
Ian Rogers0571d352011-11-03 19:51:38 -0700824 if (address < start) {
825 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700826 } else if (address >= end) {
827 min = mid + 1;
828 } else { // We have a winner!
829 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700830 }
831 }
832 // No match.
833 return -1;
834}
835
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700836int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
837 int32_t try_item = FindTryItem(code_item, address);
838 if (try_item == -1) {
839 return -1;
840 } else {
841 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
842 }
843}
844
David Srbeckyb06e28e2015-12-10 13:15:00 +0000845bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
846 DexDebugNewLocalCb local_cb, void* context) const {
847 DCHECK(local_cb != nullptr);
848 if (code_item == nullptr) {
849 return false;
850 }
851 const uint8_t* stream = GetDebugInfoStream(code_item);
852 if (stream == nullptr) {
853 return false;
854 }
855 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700856
David Srbeckyb06e28e2015-12-10 13:15:00 +0000857 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800858 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000859 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
860 local_in_reg[arg_reg].name_ = "this";
861 local_in_reg[arg_reg].descriptor_ = descriptor;
862 local_in_reg[arg_reg].signature_ = nullptr;
863 local_in_reg[arg_reg].start_address_ = 0;
864 local_in_reg[arg_reg].reg_ = arg_reg;
865 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700866 arg_reg++;
867 }
868
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800869 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000870 DecodeUnsignedLeb128(&stream); // Line.
871 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
872 uint32_t i;
873 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700874 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700875 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800876 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000877 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700878 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000879 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700880 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000881 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
882 local_in_reg[arg_reg].descriptor_ = descriptor;
883 local_in_reg[arg_reg].signature_ = nullptr;
884 local_in_reg[arg_reg].start_address_ = 0;
885 local_in_reg[arg_reg].reg_ = arg_reg;
886 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700887 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700888 case 'D':
889 case 'J':
890 arg_reg += 2;
891 break;
892 default:
893 arg_reg += 1;
894 break;
895 }
896 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000897 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800898 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
899 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000900 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700901 }
902
David Srbeckyb06e28e2015-12-10 13:15:00 +0000903 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 for (;;) {
905 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700906 switch (opcode) {
907 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000908 // Emit all variables which are still alive at the end of the method.
909 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
910 if (local_in_reg[reg].is_live_) {
911 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
912 local_cb(context, local_in_reg[reg]);
913 }
914 }
915 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700916 case DBG_ADVANCE_PC:
917 address += DecodeUnsignedLeb128(&stream);
918 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000920 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700921 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000923 case DBG_START_LOCAL_EXTENDED: {
924 uint16_t reg = DecodeUnsignedLeb128(&stream);
925 if (reg >= code_item->registers_size_) {
926 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800927 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000928 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 }
930
David Srbeckyb06e28e2015-12-10 13:15:00 +0000931 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
932 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
933 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700934 if (opcode == DBG_START_LOCAL_EXTENDED) {
935 signature_idx = DecodeUnsignedLeb128P1(&stream);
936 }
937
Shih-wei Liao195487c2011-08-20 13:29:04 -0700938 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000939 if (local_in_reg[reg].is_live_) {
940 local_in_reg[reg].end_address_ = address;
941 local_cb(context, local_in_reg[reg]);
942 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943
David Srbeckyb06e28e2015-12-10 13:15:00 +0000944 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
945 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
946 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
947 local_in_reg[reg].start_address_ = address;
948 local_in_reg[reg].reg_ = reg;
949 local_in_reg[reg].is_live_ = true;
950 break;
951 }
952 case DBG_END_LOCAL: {
953 uint16_t reg = DecodeUnsignedLeb128(&stream);
954 if (reg >= code_item->registers_size_) {
955 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
956 << code_item->registers_size_ << ") in " << GetLocation();
957 return false;
958 }
959 if (!local_in_reg[reg].is_live_) {
960 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
961 return false;
962 }
963 local_in_reg[reg].end_address_ = address;
964 local_cb(context, local_in_reg[reg]);
965 local_in_reg[reg].is_live_ = false;
966 break;
967 }
968 case DBG_RESTART_LOCAL: {
969 uint16_t reg = DecodeUnsignedLeb128(&stream);
970 if (reg >= code_item->registers_size_) {
971 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
972 << code_item->registers_size_ << ") in " << GetLocation();
973 return false;
974 }
975 // If the register is live, the "restart" is superfluous,
976 // and we don't want to mess with the existing start address.
977 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700978 local_in_reg[reg].start_address_ = address;
979 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700980 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000982 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700983 case DBG_SET_PROLOGUE_END:
984 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700985 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000986 case DBG_SET_FILE:
987 DecodeUnsignedLeb128P1(&stream); // name.
988 break;
989 default:
990 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
991 break;
992 }
993 }
994}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700995
David Srbeckyb06e28e2015-12-10 13:15:00 +0000996bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
997 void* context) const {
998 DCHECK(position_cb != nullptr);
999 if (code_item == nullptr) {
1000 return false;
1001 }
1002 const uint8_t* stream = GetDebugInfoStream(code_item);
1003 if (stream == nullptr) {
1004 return false;
1005 }
1006
1007 PositionInfo entry = PositionInfo();
1008 entry.line_ = DecodeUnsignedLeb128(&stream);
1009 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1010 for (uint32_t i = 0; i < parameters_size; ++i) {
1011 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1012 }
1013
1014 for (;;) {
1015 uint8_t opcode = *stream++;
1016 switch (opcode) {
1017 case DBG_END_SEQUENCE:
1018 return true; // end of stream.
1019 case DBG_ADVANCE_PC:
1020 entry.address_ += DecodeUnsignedLeb128(&stream);
1021 break;
1022 case DBG_ADVANCE_LINE:
1023 entry.line_ += DecodeSignedLeb128(&stream);
1024 break;
1025 case DBG_START_LOCAL:
1026 DecodeUnsignedLeb128(&stream); // reg.
1027 DecodeUnsignedLeb128P1(&stream); // name.
1028 DecodeUnsignedLeb128P1(&stream); // descriptor.
1029 break;
1030 case DBG_START_LOCAL_EXTENDED:
1031 DecodeUnsignedLeb128(&stream); // reg.
1032 DecodeUnsignedLeb128P1(&stream); // name.
1033 DecodeUnsignedLeb128P1(&stream); // descriptor.
1034 DecodeUnsignedLeb128P1(&stream); // signature.
1035 break;
1036 case DBG_END_LOCAL:
1037 case DBG_RESTART_LOCAL:
1038 DecodeUnsignedLeb128(&stream); // reg.
1039 break;
1040 case DBG_SET_PROLOGUE_END:
1041 entry.prologue_end_ = true;
1042 break;
1043 case DBG_SET_EPILOGUE_BEGIN:
1044 entry.epilogue_begin_ = true;
1045 break;
1046 case DBG_SET_FILE: {
1047 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1048 entry.source_file_ = StringDataByIdx(name_idx);
1049 break;
1050 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001051 default: {
1052 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001053 entry.address_ += adjopcode / DBG_LINE_RANGE;
1054 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1055 if (position_cb(context, entry)) {
1056 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001057 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001058 entry.prologue_end_ = false;
1059 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001060 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001061 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001062 }
1063 }
1064}
1065
David Srbeckyb06e28e2015-12-10 13:15:00 +00001066bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001067 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001068
1069 // We know that this callback will be called in
1070 // ascending address order, so keep going until we find
1071 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001072 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001073 // The line number from the previous positions callback
1074 // wil be the final result.
1075 return true;
1076 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001077 context->line_num_ = entry.line_;
1078 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001079 }
1080}
1081
Andreas Gampe833a4852014-05-21 18:46:59 -07001082bool DexFile::IsMultiDexLocation(const char* location) {
1083 return strrchr(location, kMultiDexSeparator) != nullptr;
1084}
1085
Andreas Gampe90e34042015-04-27 20:01:52 -07001086std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1087 if (index == 0) {
1088 return "classes.dex";
1089 } else {
1090 return StringPrintf("classes%zu.dex", index + 1);
1091 }
1092}
1093
1094std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1095 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001096 return dex_location;
1097 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001098 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001099 }
1100}
1101
1102std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1103 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001104 std::string base_location = GetBaseLocation(dex_location);
1105 const char* suffix = dex_location + base_location.size();
1106 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1107 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1108 if (path != nullptr && path.get() != base_location) {
1109 return std::string(path.get()) + suffix;
1110 } else if (suffix[0] == 0) {
1111 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001112 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001113 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001114 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001115}
1116
Jeff Hao13e748b2015-08-25 20:44:19 +00001117// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001118int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001119 int32_t val = 0;
1120 for (int i = zwidth; i >= 0; --i) {
1121 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1122 }
1123 val >>= (3 - zwidth) * 8;
1124 return val;
1125}
1126
1127// Read an unsigned integer. "zwidth" is the zero-based byte count,
1128// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001129uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001130 uint32_t val = 0;
1131 for (int i = zwidth; i >= 0; --i) {
1132 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1133 }
1134 if (!fill_on_right) {
1135 val >>= (3 - zwidth) * 8;
1136 }
1137 return val;
1138}
1139
1140// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001141int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001142 int64_t val = 0;
1143 for (int i = zwidth; i >= 0; --i) {
1144 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1145 }
1146 val >>= (7 - zwidth) * 8;
1147 return val;
1148}
1149
1150// Read an unsigned long. "zwidth" is the zero-based byte count,
1151// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001152uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001153 uint64_t val = 0;
1154 for (int i = zwidth; i >= 0; --i) {
1155 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1156 }
1157 if (!fill_on_right) {
1158 val >>= (7 - zwidth) * 8;
1159 }
1160 return val;
1161}
1162
Jeff Hao3d080862016-05-26 18:39:17 -07001163// Checks that visibility is as expected. Includes special behavior for M and
1164// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001165std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1166 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1167 dex_file.GetLocation().c_str(),
1168 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1169 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1170 return os;
1171}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001172
Ian Rogersd91d6d62013-09-25 20:26:14 -07001173std::string Signature::ToString() const {
1174 if (dex_file_ == nullptr) {
1175 CHECK(proto_id_ == nullptr);
1176 return "<no signature>";
1177 }
1178 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1179 std::string result;
1180 if (params == nullptr) {
1181 result += "()";
1182 } else {
1183 result += "(";
1184 for (uint32_t i = 0; i < params->Size(); ++i) {
1185 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1186 }
1187 result += ")";
1188 }
1189 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1190 return result;
1191}
1192
Vladimir Markod9cffea2013-11-25 15:08:02 +00001193bool Signature::operator==(const StringPiece& rhs) const {
1194 if (dex_file_ == nullptr) {
1195 return false;
1196 }
1197 StringPiece tail(rhs);
1198 if (!tail.starts_with("(")) {
1199 return false; // Invalid signature
1200 }
1201 tail.remove_prefix(1); // "(";
1202 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1203 if (params != nullptr) {
1204 for (uint32_t i = 0; i < params->Size(); ++i) {
1205 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1206 if (!tail.starts_with(param)) {
1207 return false;
1208 }
1209 tail.remove_prefix(param.length());
1210 }
1211 }
1212 if (!tail.starts_with(")")) {
1213 return false;
1214 }
1215 tail.remove_prefix(1); // ")";
1216 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1217}
1218
Ian Rogersd91d6d62013-09-25 20:26:14 -07001219std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1220 return os << sig.ToString();
1221}
1222
Ian Rogers0571d352011-11-03 19:51:38 -07001223// Decodes the header section from the class data bytes.
1224void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001225 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001226 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1227 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1228 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1229 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1230}
1231
1232void ClassDataItemIterator::ReadClassDataField() {
1233 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1234 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001235 // The user of the iterator is responsible for checking if there
1236 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001237}
1238
1239void ClassDataItemIterator::ReadClassDataMethod() {
1240 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1241 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1242 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001243 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001244 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001245 }
Ian Rogers0571d352011-11-03 19:51:38 -07001246}
1247
David Sehr9323e6e2016-09-13 08:58:35 -07001248EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1249 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001250 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001251 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001252 pos_(-1),
1253 type_(kByte) {
1254 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001255 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001256 array_size_ = 0;
1257 } else {
1258 array_size_ = DecodeUnsignedLeb128(&ptr_);
1259 }
1260 if (array_size_ > 0) {
1261 Next();
1262 }
1263}
1264
1265void EncodedStaticFieldValueIterator::Next() {
1266 pos_++;
1267 if (pos_ >= array_size_) {
1268 return;
1269 }
Ian Rogers13735952014-10-08 12:43:28 -07001270 uint8_t value_type = *ptr_++;
1271 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001272 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001273 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001274 switch (type_) {
1275 case kBoolean:
1276 jval_.i = (value_arg != 0) ? 1 : 0;
1277 width = 0;
1278 break;
1279 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001280 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001281 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001282 break;
1283 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001284 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001285 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001286 break;
1287 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001288 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001289 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001290 break;
1291 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001292 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001293 break;
1294 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001295 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001296 break;
1297 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001298 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001299 break;
1300 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001301 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001302 break;
1303 case kString:
1304 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001305 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001306 break;
1307 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001308 case kMethod:
1309 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001310 case kArray:
1311 case kAnnotation:
1312 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001313 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001314 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001315 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001316 width = 0;
1317 break;
1318 default:
1319 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001320 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001321 }
1322 ptr_ += width;
1323}
1324
Ian Rogers0571d352011-11-03 19:51:38 -07001325CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1326 handler_.address_ = -1;
1327 int32_t offset = -1;
1328
1329 // Short-circuit the overwhelmingly common cases.
1330 switch (code_item.tries_size_) {
1331 case 0:
1332 break;
1333 case 1: {
1334 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1335 uint32_t start = tries->start_addr_;
1336 if (address >= start) {
1337 uint32_t end = start + tries->insn_count_;
1338 if (address < end) {
1339 offset = tries->handler_off_;
1340 }
1341 }
1342 break;
1343 }
1344 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001345 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001346 }
Logan Chien736df022012-04-27 16:25:57 +08001347 Init(code_item, offset);
1348}
1349
1350CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1351 const DexFile::TryItem& try_item) {
1352 handler_.address_ = -1;
1353 Init(code_item, try_item.handler_off_);
1354}
1355
1356void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1357 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001358 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001359 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001360 } else {
1361 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001362 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001363 remaining_count_ = -1;
1364 catch_all_ = false;
1365 DCHECK(!HasNext());
1366 }
1367}
1368
Ian Rogers13735952014-10-08 12:43:28 -07001369void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001370 current_data_ = handler_data;
1371 remaining_count_ = DecodeSignedLeb128(&current_data_);
1372
1373 // If remaining_count_ is non-positive, then it is the negative of
1374 // the number of catch types, and the catches are followed by a
1375 // catch-all handler.
1376 if (remaining_count_ <= 0) {
1377 catch_all_ = true;
1378 remaining_count_ = -remaining_count_;
1379 } else {
1380 catch_all_ = false;
1381 }
1382 Next();
1383}
1384
1385void CatchHandlerIterator::Next() {
1386 if (remaining_count_ > 0) {
1387 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1388 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1389 remaining_count_--;
1390 return;
1391 }
1392
1393 if (catch_all_) {
1394 handler_.type_idx_ = DexFile::kDexNoIndex16;
1395 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1396 catch_all_ = false;
1397 return;
1398 }
1399
1400 // no more handler
1401 remaining_count_ = -1;
1402}
1403
Carl Shapiro1fb86202011-06-27 17:43:13 -07001404} // namespace art