blob: 409fbba66af076eae92dad8058999cebde88a466 [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
Alex Light9c20a142016-08-23 15:05:12 -0700567uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
568 uint32_t method_idx) const {
569 const uint8_t* class_data = GetClassData(class_def);
570 CHECK(class_data != nullptr);
571 ClassDataItemIterator it(*this, class_data);
572 // Skip fields
573 while (it.HasNextStaticField()) {
574 it.Next();
575 }
576 while (it.HasNextInstanceField()) {
577 it.Next();
578 }
579 while (it.HasNextDirectMethod()) {
580 if (it.GetMemberIndex() == method_idx) {
581 return it.GetMethodCodeItemOffset();
582 }
583 it.Next();
584 }
585 while (it.HasNextVirtualMethod()) {
586 if (it.GetMemberIndex() == method_idx) {
587 return it.GetMethodCodeItemOffset();
588 }
589 it.Next();
590 }
591 LOG(FATAL) << "Unable to find method " << method_idx;
592 UNREACHABLE();
593}
594
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800595const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100596 const DexFile::StringId& name,
597 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800598 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
599 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
600 const uint32_t name_idx = GetIndexForStringId(name);
601 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700602 int32_t lo = 0;
603 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800604 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700605 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800606 const DexFile::FieldId& field = GetFieldId(mid);
607 if (class_idx > field.class_idx_) {
608 lo = mid + 1;
609 } else if (class_idx < field.class_idx_) {
610 hi = mid - 1;
611 } else {
612 if (name_idx > field.name_idx_) {
613 lo = mid + 1;
614 } else if (name_idx < field.name_idx_) {
615 hi = mid - 1;
616 } else {
617 if (type_idx > field.type_idx_) {
618 lo = mid + 1;
619 } else if (type_idx < field.type_idx_) {
620 hi = mid - 1;
621 } else {
622 return &field;
623 }
624 }
625 }
626 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700627 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800628}
629
630const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700631 const DexFile::StringId& name,
632 const DexFile::ProtoId& signature) const {
633 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800634 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700635 const uint32_t name_idx = GetIndexForStringId(name);
636 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700637 int32_t lo = 0;
638 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700639 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700640 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700641 const DexFile::MethodId& method = GetMethodId(mid);
642 if (class_idx > method.class_idx_) {
643 lo = mid + 1;
644 } else if (class_idx < method.class_idx_) {
645 hi = mid - 1;
646 } else {
647 if (name_idx > method.name_idx_) {
648 lo = mid + 1;
649 } else if (name_idx < method.name_idx_) {
650 hi = mid - 1;
651 } else {
652 if (proto_idx > method.proto_idx_) {
653 lo = mid + 1;
654 } else if (proto_idx < method.proto_idx_) {
655 hi = mid - 1;
656 } else {
657 return &method;
658 }
659 }
660 }
661 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700662 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700663}
664
Ian Rogers637c65b2013-05-31 11:46:00 -0700665const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700666 int32_t lo = 0;
667 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700668 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700670 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700671 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700672 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
673 if (compare > 0) {
674 lo = mid + 1;
675 } else if (compare < 0) {
676 hi = mid - 1;
677 } else {
678 return &str_id;
679 }
680 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700681 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700682}
683
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300684const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
685 int32_t lo = 0;
686 int32_t hi = NumTypeIds() - 1;
687 while (hi >= lo) {
688 int32_t mid = (hi + lo) / 2;
689 const TypeId& type_id = GetTypeId(mid);
690 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
691 const char* str = GetStringData(str_id);
692 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
693 if (compare > 0) {
694 lo = mid + 1;
695 } else if (compare < 0) {
696 hi = mid - 1;
697 } else {
698 return &type_id;
699 }
700 }
701 return nullptr;
702}
703
Vladimir Markoa48aef42014-12-03 17:53:53 +0000704const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700705 int32_t lo = 0;
706 int32_t hi = NumStringIds() - 1;
707 while (hi >= lo) {
708 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700709 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700710 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000711 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700712 if (compare > 0) {
713 lo = mid + 1;
714 } else if (compare < 0) {
715 hi = mid - 1;
716 } else {
717 return &str_id;
718 }
719 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700720 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700721}
722
723const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700724 int32_t lo = 0;
725 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700726 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700727 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700728 const TypeId& type_id = GetTypeId(mid);
729 if (string_idx > type_id.descriptor_idx_) {
730 lo = mid + 1;
731 } else if (string_idx < type_id.descriptor_idx_) {
732 hi = mid - 1;
733 } else {
734 return &type_id;
735 }
736 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700737 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700738}
739
740const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000741 const uint16_t* signature_type_idxs,
742 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700743 int32_t lo = 0;
744 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700745 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700746 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700747 const DexFile::ProtoId& proto = GetProtoId(mid);
748 int compare = return_type_idx - proto.return_type_idx_;
749 if (compare == 0) {
750 DexFileParameterIterator it(*this, proto);
751 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000752 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800753 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700754 it.Next();
755 i++;
756 }
757 if (compare == 0) {
758 if (it.HasNext()) {
759 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000760 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700761 compare = 1;
762 }
763 }
764 }
765 if (compare > 0) {
766 lo = mid + 1;
767 } else if (compare < 0) {
768 hi = mid - 1;
769 } else {
770 return &proto;
771 }
772 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700774}
775
776// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700777bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
778 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700779 if (signature[0] != '(') {
780 return false;
781 }
782 size_t offset = 1;
783 size_t end = signature.size();
784 bool process_return = false;
785 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000786 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700787 char c = signature[offset];
788 offset++;
789 if (c == ')') {
790 process_return = true;
791 continue;
792 }
Ian Rogers0571d352011-11-03 19:51:38 -0700793 while (c == '[') { // process array prefix
794 if (offset >= end) { // expect some descriptor following [
795 return false;
796 }
797 c = signature[offset];
798 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700799 }
800 if (c == 'L') { // process type descriptors
801 do {
802 if (offset >= end) { // unexpected early termination of descriptor
803 return false;
804 }
805 c = signature[offset];
806 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700807 } while (c != ';');
808 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000809 // TODO: avoid creating a std::string just to get a 0-terminated char array
810 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700811 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700812 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700813 return false;
814 }
815 uint16_t type_idx = GetIndexForTypeId(*type_id);
816 if (!process_return) {
817 param_type_idxs->push_back(type_idx);
818 } else {
819 *return_type_idx = type_idx;
820 return offset == end; // return true if the signature had reached a sensible end
821 }
822 }
823 return false; // failed to correctly parse return type
824}
825
Ian Rogersd91d6d62013-09-25 20:26:14 -0700826const Signature DexFile::CreateSignature(const StringPiece& signature) const {
827 uint16_t return_type_idx;
828 std::vector<uint16_t> param_type_indices;
829 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
830 if (!success) {
831 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700832 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700833 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700834 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700835 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700836 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700837 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700838}
839
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700840int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700841 // Note: Signed type is important for max and min.
842 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700843 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700844
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700845 while (min <= max) {
846 int32_t mid = min + ((max - min) / 2);
847
848 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
849 uint32_t start = ti->start_addr_;
850 uint32_t end = start + ti->insn_count_;
851
Ian Rogers0571d352011-11-03 19:51:38 -0700852 if (address < start) {
853 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700854 } else if (address >= end) {
855 min = mid + 1;
856 } else { // We have a winner!
857 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700858 }
859 }
860 // No match.
861 return -1;
862}
863
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700864int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
865 int32_t try_item = FindTryItem(code_item, address);
866 if (try_item == -1) {
867 return -1;
868 } else {
869 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
870 }
871}
872
David Srbeckyb06e28e2015-12-10 13:15:00 +0000873bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
874 DexDebugNewLocalCb local_cb, void* context) const {
875 DCHECK(local_cb != nullptr);
876 if (code_item == nullptr) {
877 return false;
878 }
879 const uint8_t* stream = GetDebugInfoStream(code_item);
880 if (stream == nullptr) {
881 return false;
882 }
883 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700884
David Srbeckyb06e28e2015-12-10 13:15:00 +0000885 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000887 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
888 local_in_reg[arg_reg].name_ = "this";
889 local_in_reg[arg_reg].descriptor_ = descriptor;
890 local_in_reg[arg_reg].signature_ = nullptr;
891 local_in_reg[arg_reg].start_address_ = 0;
892 local_in_reg[arg_reg].reg_ = arg_reg;
893 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700894 arg_reg++;
895 }
896
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800897 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000898 DecodeUnsignedLeb128(&stream); // Line.
899 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
900 uint32_t i;
901 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700902 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700903 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800904 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000905 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700906 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000907 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700908 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000909 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
910 local_in_reg[arg_reg].descriptor_ = descriptor;
911 local_in_reg[arg_reg].signature_ = nullptr;
912 local_in_reg[arg_reg].start_address_ = 0;
913 local_in_reg[arg_reg].reg_ = arg_reg;
914 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700915 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700916 case 'D':
917 case 'J':
918 arg_reg += 2;
919 break;
920 default:
921 arg_reg += 1;
922 break;
923 }
924 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000925 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800926 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
927 << " for method " << PrettyMethod(method_idx, *this);
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 address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700932 for (;;) {
933 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700934 switch (opcode) {
935 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000936 // Emit all variables which are still alive at the end of the method.
937 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
938 if (local_in_reg[reg].is_live_) {
939 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
940 local_cb(context, local_in_reg[reg]);
941 }
942 }
943 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944 case DBG_ADVANCE_PC:
945 address += DecodeUnsignedLeb128(&stream);
946 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700947 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000948 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700949 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700950 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000951 case DBG_START_LOCAL_EXTENDED: {
952 uint16_t reg = DecodeUnsignedLeb128(&stream);
953 if (reg >= code_item->registers_size_) {
954 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800955 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000956 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700957 }
958
David Srbeckyb06e28e2015-12-10 13:15:00 +0000959 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
960 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
961 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700962 if (opcode == DBG_START_LOCAL_EXTENDED) {
963 signature_idx = DecodeUnsignedLeb128P1(&stream);
964 }
965
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000967 if (local_in_reg[reg].is_live_) {
968 local_in_reg[reg].end_address_ = address;
969 local_cb(context, local_in_reg[reg]);
970 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700971
David Srbeckyb06e28e2015-12-10 13:15:00 +0000972 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
973 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
974 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
975 local_in_reg[reg].start_address_ = address;
976 local_in_reg[reg].reg_ = reg;
977 local_in_reg[reg].is_live_ = true;
978 break;
979 }
980 case DBG_END_LOCAL: {
981 uint16_t reg = DecodeUnsignedLeb128(&stream);
982 if (reg >= code_item->registers_size_) {
983 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
984 << code_item->registers_size_ << ") in " << GetLocation();
985 return false;
986 }
987 if (!local_in_reg[reg].is_live_) {
988 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
989 return false;
990 }
991 local_in_reg[reg].end_address_ = address;
992 local_cb(context, local_in_reg[reg]);
993 local_in_reg[reg].is_live_ = false;
994 break;
995 }
996 case DBG_RESTART_LOCAL: {
997 uint16_t reg = DecodeUnsignedLeb128(&stream);
998 if (reg >= code_item->registers_size_) {
999 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1000 << code_item->registers_size_ << ") in " << GetLocation();
1001 return false;
1002 }
1003 // If the register is live, the "restart" is superfluous,
1004 // and we don't want to mess with the existing start address.
1005 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001006 local_in_reg[reg].start_address_ = address;
1007 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001008 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001009 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001010 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001011 case DBG_SET_PROLOGUE_END:
1012 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001013 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001014 case DBG_SET_FILE:
1015 DecodeUnsignedLeb128P1(&stream); // name.
1016 break;
1017 default:
1018 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1019 break;
1020 }
1021 }
1022}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001023
David Srbeckyb06e28e2015-12-10 13:15:00 +00001024bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1025 void* context) const {
1026 DCHECK(position_cb != nullptr);
1027 if (code_item == nullptr) {
1028 return false;
1029 }
1030 const uint8_t* stream = GetDebugInfoStream(code_item);
1031 if (stream == nullptr) {
1032 return false;
1033 }
1034
1035 PositionInfo entry = PositionInfo();
1036 entry.line_ = DecodeUnsignedLeb128(&stream);
1037 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1038 for (uint32_t i = 0; i < parameters_size; ++i) {
1039 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1040 }
1041
1042 for (;;) {
1043 uint8_t opcode = *stream++;
1044 switch (opcode) {
1045 case DBG_END_SEQUENCE:
1046 return true; // end of stream.
1047 case DBG_ADVANCE_PC:
1048 entry.address_ += DecodeUnsignedLeb128(&stream);
1049 break;
1050 case DBG_ADVANCE_LINE:
1051 entry.line_ += DecodeSignedLeb128(&stream);
1052 break;
1053 case DBG_START_LOCAL:
1054 DecodeUnsignedLeb128(&stream); // reg.
1055 DecodeUnsignedLeb128P1(&stream); // name.
1056 DecodeUnsignedLeb128P1(&stream); // descriptor.
1057 break;
1058 case DBG_START_LOCAL_EXTENDED:
1059 DecodeUnsignedLeb128(&stream); // reg.
1060 DecodeUnsignedLeb128P1(&stream); // name.
1061 DecodeUnsignedLeb128P1(&stream); // descriptor.
1062 DecodeUnsignedLeb128P1(&stream); // signature.
1063 break;
1064 case DBG_END_LOCAL:
1065 case DBG_RESTART_LOCAL:
1066 DecodeUnsignedLeb128(&stream); // reg.
1067 break;
1068 case DBG_SET_PROLOGUE_END:
1069 entry.prologue_end_ = true;
1070 break;
1071 case DBG_SET_EPILOGUE_BEGIN:
1072 entry.epilogue_begin_ = true;
1073 break;
1074 case DBG_SET_FILE: {
1075 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1076 entry.source_file_ = StringDataByIdx(name_idx);
1077 break;
1078 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001079 default: {
1080 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001081 entry.address_ += adjopcode / DBG_LINE_RANGE;
1082 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1083 if (position_cb(context, entry)) {
1084 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001085 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001086 entry.prologue_end_ = false;
1087 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001088 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001089 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001090 }
1091 }
1092}
1093
David Srbeckyb06e28e2015-12-10 13:15:00 +00001094bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001095 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001096
1097 // We know that this callback will be called in
1098 // ascending address order, so keep going until we find
1099 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001100 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001101 // The line number from the previous positions callback
1102 // wil be the final result.
1103 return true;
1104 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001105 context->line_num_ = entry.line_;
1106 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001107 }
1108}
1109
Andreas Gampe833a4852014-05-21 18:46:59 -07001110bool DexFile::IsMultiDexLocation(const char* location) {
1111 return strrchr(location, kMultiDexSeparator) != nullptr;
1112}
1113
Andreas Gampe90e34042015-04-27 20:01:52 -07001114std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1115 if (index == 0) {
1116 return "classes.dex";
1117 } else {
1118 return StringPrintf("classes%zu.dex", index + 1);
1119 }
1120}
1121
1122std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1123 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001124 return dex_location;
1125 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001126 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001127 }
1128}
1129
1130std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1131 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001132 std::string base_location = GetBaseLocation(dex_location);
1133 const char* suffix = dex_location + base_location.size();
1134 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1135 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1136 if (path != nullptr && path.get() != base_location) {
1137 return std::string(path.get()) + suffix;
1138 } else if (suffix[0] == 0) {
1139 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001140 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001141 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001142 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001143}
1144
Jeff Hao13e748b2015-08-25 20:44:19 +00001145// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001146int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001147 int32_t val = 0;
1148 for (int i = zwidth; i >= 0; --i) {
1149 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1150 }
1151 val >>= (3 - zwidth) * 8;
1152 return val;
1153}
1154
1155// Read an unsigned integer. "zwidth" is the zero-based byte count,
1156// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001157uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001158 uint32_t val = 0;
1159 for (int i = zwidth; i >= 0; --i) {
1160 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1161 }
1162 if (!fill_on_right) {
1163 val >>= (3 - zwidth) * 8;
1164 }
1165 return val;
1166}
1167
1168// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001169int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001170 int64_t val = 0;
1171 for (int i = zwidth; i >= 0; --i) {
1172 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1173 }
1174 val >>= (7 - zwidth) * 8;
1175 return val;
1176}
1177
1178// Read an unsigned long. "zwidth" is the zero-based byte count,
1179// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001180uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001181 uint64_t val = 0;
1182 for (int i = zwidth; i >= 0; --i) {
1183 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1184 }
1185 if (!fill_on_right) {
1186 val >>= (7 - zwidth) * 8;
1187 }
1188 return val;
1189}
1190
Jeff Hao3d080862016-05-26 18:39:17 -07001191// Checks that visibility is as expected. Includes special behavior for M and
1192// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001193std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1194 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1195 dex_file.GetLocation().c_str(),
1196 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1197 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1198 return os;
1199}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001200
Ian Rogersd91d6d62013-09-25 20:26:14 -07001201std::string Signature::ToString() const {
1202 if (dex_file_ == nullptr) {
1203 CHECK(proto_id_ == nullptr);
1204 return "<no signature>";
1205 }
1206 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1207 std::string result;
1208 if (params == nullptr) {
1209 result += "()";
1210 } else {
1211 result += "(";
1212 for (uint32_t i = 0; i < params->Size(); ++i) {
1213 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1214 }
1215 result += ")";
1216 }
1217 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1218 return result;
1219}
1220
Vladimir Markod9cffea2013-11-25 15:08:02 +00001221bool Signature::operator==(const StringPiece& rhs) const {
1222 if (dex_file_ == nullptr) {
1223 return false;
1224 }
1225 StringPiece tail(rhs);
1226 if (!tail.starts_with("(")) {
1227 return false; // Invalid signature
1228 }
1229 tail.remove_prefix(1); // "(";
1230 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1231 if (params != nullptr) {
1232 for (uint32_t i = 0; i < params->Size(); ++i) {
1233 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1234 if (!tail.starts_with(param)) {
1235 return false;
1236 }
1237 tail.remove_prefix(param.length());
1238 }
1239 }
1240 if (!tail.starts_with(")")) {
1241 return false;
1242 }
1243 tail.remove_prefix(1); // ")";
1244 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1245}
1246
Ian Rogersd91d6d62013-09-25 20:26:14 -07001247std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1248 return os << sig.ToString();
1249}
1250
Ian Rogers0571d352011-11-03 19:51:38 -07001251// Decodes the header section from the class data bytes.
1252void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001253 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001254 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1255 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1256 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1257 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1258}
1259
1260void ClassDataItemIterator::ReadClassDataField() {
1261 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1262 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001263 // The user of the iterator is responsible for checking if there
1264 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001265}
1266
1267void ClassDataItemIterator::ReadClassDataMethod() {
1268 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1269 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1270 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001271 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001272 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001273 }
Ian Rogers0571d352011-11-03 19:51:38 -07001274}
1275
David Sehr9323e6e2016-09-13 08:58:35 -07001276EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1277 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001278 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001279 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001280 pos_(-1),
1281 type_(kByte) {
1282 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001283 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001284 array_size_ = 0;
1285 } else {
1286 array_size_ = DecodeUnsignedLeb128(&ptr_);
1287 }
1288 if (array_size_ > 0) {
1289 Next();
1290 }
1291}
1292
1293void EncodedStaticFieldValueIterator::Next() {
1294 pos_++;
1295 if (pos_ >= array_size_) {
1296 return;
1297 }
Ian Rogers13735952014-10-08 12:43:28 -07001298 uint8_t value_type = *ptr_++;
1299 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001300 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001301 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001302 switch (type_) {
1303 case kBoolean:
1304 jval_.i = (value_arg != 0) ? 1 : 0;
1305 width = 0;
1306 break;
1307 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001308 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001309 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001310 break;
1311 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001312 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001313 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001314 break;
1315 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001316 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001317 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001318 break;
1319 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001320 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001321 break;
1322 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001323 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001324 break;
1325 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001326 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001327 break;
1328 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001329 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001330 break;
1331 case kString:
1332 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001333 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001334 break;
1335 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001336 case kMethod:
1337 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001338 case kArray:
1339 case kAnnotation:
1340 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001341 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001342 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001343 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001344 width = 0;
1345 break;
1346 default:
1347 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001348 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001349 }
1350 ptr_ += width;
1351}
1352
Ian Rogers0571d352011-11-03 19:51:38 -07001353CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1354 handler_.address_ = -1;
1355 int32_t offset = -1;
1356
1357 // Short-circuit the overwhelmingly common cases.
1358 switch (code_item.tries_size_) {
1359 case 0:
1360 break;
1361 case 1: {
1362 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1363 uint32_t start = tries->start_addr_;
1364 if (address >= start) {
1365 uint32_t end = start + tries->insn_count_;
1366 if (address < end) {
1367 offset = tries->handler_off_;
1368 }
1369 }
1370 break;
1371 }
1372 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001373 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001374 }
Logan Chien736df022012-04-27 16:25:57 +08001375 Init(code_item, offset);
1376}
1377
1378CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1379 const DexFile::TryItem& try_item) {
1380 handler_.address_ = -1;
1381 Init(code_item, try_item.handler_off_);
1382}
1383
1384void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1385 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001386 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001387 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001388 } else {
1389 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001390 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001391 remaining_count_ = -1;
1392 catch_all_ = false;
1393 DCHECK(!HasNext());
1394 }
1395}
1396
Ian Rogers13735952014-10-08 12:43:28 -07001397void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001398 current_data_ = handler_data;
1399 remaining_count_ = DecodeSignedLeb128(&current_data_);
1400
1401 // If remaining_count_ is non-positive, then it is the negative of
1402 // the number of catch types, and the catches are followed by a
1403 // catch-all handler.
1404 if (remaining_count_ <= 0) {
1405 catch_all_ = true;
1406 remaining_count_ = -remaining_count_;
1407 } else {
1408 catch_all_ = false;
1409 }
1410 Next();
1411}
1412
1413void CatchHandlerIterator::Next() {
1414 if (remaining_count_ > 0) {
1415 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1416 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1417 remaining_count_--;
1418 return;
1419 }
1420
1421 if (catch_all_) {
1422 handler_.type_idx_ = DexFile::kDexNoIndex16;
1423 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1424 catch_all_ = false;
1425 return;
1426 }
1427
1428 // no more handler
1429 remaining_count_ = -1;
1430}
1431
Carl Shapiro1fb86202011-06-27 17:43:13 -07001432} // namespace art