blob: 0af086c89676402e5e3785e99c97de18e7fa3f05 [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));
David Sehr9fddd362016-09-22 14:05:37 -0700326 if (zip_entry == 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));
David Sehr9fddd362016-09-22 14:05:37 -0700336 if (map == 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);
David Sehr9fddd362016-09-22 14:05:37 -0700352 if (dex_file == nullptr) {
353 if (verify_result == VerifyResult::kVerifyNotAttempted) {
354 *error_code = ZipOpenErrorCode::kDexFileError;
355 } else {
356 *error_code = ZipOpenErrorCode::kVerifyError;
357 }
358 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800359 }
David Sehr9fddd362016-09-22 14:05:37 -0700360 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700361 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700363 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700364 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700365 }
366 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700367 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700368 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700369 return nullptr;
370 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700371 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800372 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700373}
374
Andreas Gampe90e34042015-04-27 20:01:52 -0700375// Technically we do not have a limitation with respect to the number of dex files that can be in a
376// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
377// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
378// seems an excessive number.
379static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
380
David Sehr733ddb22016-09-19 15:02:18 -0700381bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
382 const std::string& location,
383 bool verify_checksum,
384 std::string* error_msg,
385 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800386 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700387 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700388 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700389 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
390 kClassesDex,
391 location,
392 verify_checksum,
393 error_msg,
394 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700395 if (dex_file.get() == nullptr) {
396 return false;
397 } else {
398 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800399 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700400
401 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700402
403 // We could try to avoid std::string allocations by working on a char array directly. As we
404 // do not expect a lot of iterations, this seems too involved and brittle.
405
Andreas Gampe90e34042015-04-27 20:01:52 -0700406 for (size_t i = 1; ; ++i) {
407 std::string name = GetMultiDexClassesDexName(i);
408 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700409 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
410 name.c_str(),
411 fake_location,
412 verify_checksum,
413 error_msg,
414 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700415 if (next_dex_file.get() == nullptr) {
416 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
417 LOG(WARNING) << error_msg;
418 }
419 break;
420 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800421 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700422 }
423
Andreas Gampe90e34042015-04-27 20:01:52 -0700424 if (i == kWarnOnManyDexFilesThreshold) {
425 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
426 << " dex files. Please consider coalescing and shrinking the number to "
427 " avoid runtime overhead.";
428 }
429
430 if (i == std::numeric_limits<size_t>::max()) {
431 LOG(ERROR) << "Overflow in number of dex files!";
432 break;
433 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700434 }
435
436 return true;
437 }
438}
439
David Sehr733ddb22016-09-19 15:02:18 -0700440std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
441 size_t size,
442 const std::string& location,
443 uint32_t location_checksum,
444 const OatDexFile* oat_dex_file,
445 bool verify,
446 bool verify_checksum,
447 std::string* error_msg,
448 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700449 if (verify_result != nullptr) {
450 *verify_result = VerifyResult::kVerifyNotAttempted;
451 }
David Sehr733ddb22016-09-19 15:02:18 -0700452 std::unique_ptr<DexFile> dex_file(new DexFile(base,
453 size,
454 location,
455 location_checksum,
456 oat_dex_file));
457 if (dex_file == nullptr) {
458 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
459 error_msg->c_str());
460 return nullptr;
461 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700462 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800463 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700464 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700465 }
David Sehr733ddb22016-09-19 15:02:18 -0700466 if (verify && !DexFileVerifier::Verify(dex_file.get(),
467 dex_file->Begin(),
468 dex_file->Size(),
469 location.c_str(),
470 verify_checksum,
471 error_msg)) {
472 if (verify_result != nullptr) {
473 *verify_result = VerifyResult::kVerifyFailed;
474 }
475 return nullptr;
476 }
477 if (verify_result != nullptr) {
478 *verify_result = VerifyResult::kVerifySucceeded;
479 }
480 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700481}
482
David Sehr733ddb22016-09-19 15:02:18 -0700483DexFile::DexFile(const uint8_t* base,
484 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800485 const std::string& location,
486 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700487 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800488 : begin_(base),
489 size_(size),
490 location_(location),
491 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800492 header_(reinterpret_cast<const Header*>(base)),
493 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
494 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
495 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
496 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
497 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700498 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700499 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700500 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800501 CHECK_GT(size_, 0U) << GetLocation();
502}
503
Jesse Wilson6bf19152011-09-29 13:12:33 -0400504DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700505 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
506 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
507 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
508 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400509}
510
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700512 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700513 return false;
514 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700515 return true;
516}
517
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700518bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800519 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700520 std::ostringstream oss;
521 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800522 << " " << header_->magic_[0]
523 << " " << header_->magic_[1]
524 << " " << header_->magic_[2]
525 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700526 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700527 return false;
528 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800529 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700530 std::ostringstream oss;
531 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800532 << " " << header_->magic_[4]
533 << " " << header_->magic_[5]
534 << " " << header_->magic_[6]
535 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700536 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537 return false;
538 }
539 return true;
540}
541
Ian Rogers13735952014-10-08 12:43:28 -0700542bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800543 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
544}
545
Ian Rogers13735952014-10-08 12:43:28 -0700546bool DexFile::IsVersionValid(const uint8_t* magic) {
547 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700548 for (uint32_t i = 0; i < kNumDexVersions; i++) {
549 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
550 return true;
551 }
552 }
553 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800554}
555
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700556uint32_t DexFile::Header::GetVersion() const {
557 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700558 return atoi(version);
559}
560
David Sehr9aa352e2016-09-15 18:13:52 -0700561const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
562 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100563 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700564 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700565 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700566 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700567 for (size_t i = 0; i < num_class_defs; ++i) {
568 const ClassDef& class_def = GetClassDef(i);
569 if (class_def.class_idx_ == type_idx) {
570 return &class_def;
571 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700572 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700573 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700574}
575
Alex Light9c20a142016-08-23 15:05:12 -0700576uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
577 uint32_t method_idx) const {
578 const uint8_t* class_data = GetClassData(class_def);
579 CHECK(class_data != nullptr);
580 ClassDataItemIterator it(*this, class_data);
581 // Skip fields
582 while (it.HasNextStaticField()) {
583 it.Next();
584 }
585 while (it.HasNextInstanceField()) {
586 it.Next();
587 }
588 while (it.HasNextDirectMethod()) {
589 if (it.GetMemberIndex() == method_idx) {
590 return it.GetMethodCodeItemOffset();
591 }
592 it.Next();
593 }
594 while (it.HasNextVirtualMethod()) {
595 if (it.GetMemberIndex() == method_idx) {
596 return it.GetMethodCodeItemOffset();
597 }
598 it.Next();
599 }
600 LOG(FATAL) << "Unable to find method " << method_idx;
601 UNREACHABLE();
602}
603
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800604const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100605 const DexFile::StringId& name,
606 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800607 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
608 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
609 const uint32_t name_idx = GetIndexForStringId(name);
610 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700611 int32_t lo = 0;
612 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800613 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700614 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800615 const DexFile::FieldId& field = GetFieldId(mid);
616 if (class_idx > field.class_idx_) {
617 lo = mid + 1;
618 } else if (class_idx < field.class_idx_) {
619 hi = mid - 1;
620 } else {
621 if (name_idx > field.name_idx_) {
622 lo = mid + 1;
623 } else if (name_idx < field.name_idx_) {
624 hi = mid - 1;
625 } else {
626 if (type_idx > field.type_idx_) {
627 lo = mid + 1;
628 } else if (type_idx < field.type_idx_) {
629 hi = mid - 1;
630 } else {
631 return &field;
632 }
633 }
634 }
635 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800637}
638
639const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700640 const DexFile::StringId& name,
641 const DexFile::ProtoId& signature) const {
642 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800643 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700644 const uint32_t name_idx = GetIndexForStringId(name);
645 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700646 int32_t lo = 0;
647 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700648 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700649 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700650 const DexFile::MethodId& method = GetMethodId(mid);
651 if (class_idx > method.class_idx_) {
652 lo = mid + 1;
653 } else if (class_idx < method.class_idx_) {
654 hi = mid - 1;
655 } else {
656 if (name_idx > method.name_idx_) {
657 lo = mid + 1;
658 } else if (name_idx < method.name_idx_) {
659 hi = mid - 1;
660 } else {
661 if (proto_idx > method.proto_idx_) {
662 lo = mid + 1;
663 } else if (proto_idx < method.proto_idx_) {
664 hi = mid - 1;
665 } else {
666 return &method;
667 }
668 }
669 }
670 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700671 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700672}
673
Ian Rogers637c65b2013-05-31 11:46:00 -0700674const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700675 int32_t lo = 0;
676 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700677 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700678 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700679 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700680 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700681 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
682 if (compare > 0) {
683 lo = mid + 1;
684 } else if (compare < 0) {
685 hi = mid - 1;
686 } else {
687 return &str_id;
688 }
689 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700690 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700691}
692
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300693const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
694 int32_t lo = 0;
695 int32_t hi = NumTypeIds() - 1;
696 while (hi >= lo) {
697 int32_t mid = (hi + lo) / 2;
698 const TypeId& type_id = GetTypeId(mid);
699 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
700 const char* str = GetStringData(str_id);
701 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
702 if (compare > 0) {
703 lo = mid + 1;
704 } else if (compare < 0) {
705 hi = mid - 1;
706 } else {
707 return &type_id;
708 }
709 }
710 return nullptr;
711}
712
Vladimir Markoa48aef42014-12-03 17:53:53 +0000713const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700714 int32_t lo = 0;
715 int32_t hi = NumStringIds() - 1;
716 while (hi >= lo) {
717 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700718 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700719 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000720 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700721 if (compare > 0) {
722 lo = mid + 1;
723 } else if (compare < 0) {
724 hi = mid - 1;
725 } else {
726 return &str_id;
727 }
728 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700730}
731
732const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700733 int32_t lo = 0;
734 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700735 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700736 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700737 const TypeId& type_id = GetTypeId(mid);
738 if (string_idx > type_id.descriptor_idx_) {
739 lo = mid + 1;
740 } else if (string_idx < type_id.descriptor_idx_) {
741 hi = mid - 1;
742 } else {
743 return &type_id;
744 }
745 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700747}
748
749const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000750 const uint16_t* signature_type_idxs,
751 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700752 int32_t lo = 0;
753 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700754 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700755 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700756 const DexFile::ProtoId& proto = GetProtoId(mid);
757 int compare = return_type_idx - proto.return_type_idx_;
758 if (compare == 0) {
759 DexFileParameterIterator it(*this, proto);
760 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000761 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800762 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700763 it.Next();
764 i++;
765 }
766 if (compare == 0) {
767 if (it.HasNext()) {
768 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000769 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700770 compare = 1;
771 }
772 }
773 }
774 if (compare > 0) {
775 lo = mid + 1;
776 } else if (compare < 0) {
777 hi = mid - 1;
778 } else {
779 return &proto;
780 }
781 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700782 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700783}
784
785// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700786bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
787 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700788 if (signature[0] != '(') {
789 return false;
790 }
791 size_t offset = 1;
792 size_t end = signature.size();
793 bool process_return = false;
794 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000795 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700796 char c = signature[offset];
797 offset++;
798 if (c == ')') {
799 process_return = true;
800 continue;
801 }
Ian Rogers0571d352011-11-03 19:51:38 -0700802 while (c == '[') { // process array prefix
803 if (offset >= end) { // expect some descriptor following [
804 return false;
805 }
806 c = signature[offset];
807 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700808 }
809 if (c == 'L') { // process type descriptors
810 do {
811 if (offset >= end) { // unexpected early termination of descriptor
812 return false;
813 }
814 c = signature[offset];
815 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700816 } while (c != ';');
817 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000818 // TODO: avoid creating a std::string just to get a 0-terminated char array
819 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700820 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700821 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700822 return false;
823 }
824 uint16_t type_idx = GetIndexForTypeId(*type_id);
825 if (!process_return) {
826 param_type_idxs->push_back(type_idx);
827 } else {
828 *return_type_idx = type_idx;
829 return offset == end; // return true if the signature had reached a sensible end
830 }
831 }
832 return false; // failed to correctly parse return type
833}
834
Ian Rogersd91d6d62013-09-25 20:26:14 -0700835const Signature DexFile::CreateSignature(const StringPiece& signature) const {
836 uint16_t return_type_idx;
837 std::vector<uint16_t> param_type_indices;
838 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
839 if (!success) {
840 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700841 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700842 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700843 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700844 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700845 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700846 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700847}
848
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700849int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700850 // Note: Signed type is important for max and min.
851 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700852 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700853
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700854 while (min <= max) {
855 int32_t mid = min + ((max - min) / 2);
856
857 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
858 uint32_t start = ti->start_addr_;
859 uint32_t end = start + ti->insn_count_;
860
Ian Rogers0571d352011-11-03 19:51:38 -0700861 if (address < start) {
862 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700863 } else if (address >= end) {
864 min = mid + 1;
865 } else { // We have a winner!
866 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700867 }
868 }
869 // No match.
870 return -1;
871}
872
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700873int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
874 int32_t try_item = FindTryItem(code_item, address);
875 if (try_item == -1) {
876 return -1;
877 } else {
878 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
879 }
880}
881
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
883 DexDebugNewLocalCb local_cb, void* context) const {
884 DCHECK(local_cb != nullptr);
885 if (code_item == nullptr) {
886 return false;
887 }
888 const uint8_t* stream = GetDebugInfoStream(code_item);
889 if (stream == nullptr) {
890 return false;
891 }
892 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700893
David Srbeckyb06e28e2015-12-10 13:15:00 +0000894 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800895 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000896 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
897 local_in_reg[arg_reg].name_ = "this";
898 local_in_reg[arg_reg].descriptor_ = descriptor;
899 local_in_reg[arg_reg].signature_ = nullptr;
900 local_in_reg[arg_reg].start_address_ = 0;
901 local_in_reg[arg_reg].reg_ = arg_reg;
902 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700903 arg_reg++;
904 }
905
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000907 DecodeUnsignedLeb128(&stream); // Line.
908 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
909 uint32_t i;
910 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700911 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700912 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800913 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000914 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700915 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000916 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700917 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000918 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
919 local_in_reg[arg_reg].descriptor_ = descriptor;
920 local_in_reg[arg_reg].signature_ = nullptr;
921 local_in_reg[arg_reg].start_address_ = 0;
922 local_in_reg[arg_reg].reg_ = arg_reg;
923 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700924 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 case 'D':
926 case 'J':
927 arg_reg += 2;
928 break;
929 default:
930 arg_reg += 1;
931 break;
932 }
933 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000934 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800935 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
936 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000937 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700938 }
939
David Srbeckyb06e28e2015-12-10 13:15:00 +0000940 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 for (;;) {
942 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943 switch (opcode) {
944 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000945 // Emit all variables which are still alive at the end of the method.
946 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
947 if (local_in_reg[reg].is_live_) {
948 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
949 local_cb(context, local_in_reg[reg]);
950 }
951 }
952 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700953 case DBG_ADVANCE_PC:
954 address += DecodeUnsignedLeb128(&stream);
955 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700956 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000957 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700958 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700959 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000960 case DBG_START_LOCAL_EXTENDED: {
961 uint16_t reg = DecodeUnsignedLeb128(&stream);
962 if (reg >= code_item->registers_size_) {
963 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800964 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000965 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 }
967
David Srbeckyb06e28e2015-12-10 13:15:00 +0000968 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
969 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
970 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700971 if (opcode == DBG_START_LOCAL_EXTENDED) {
972 signature_idx = DecodeUnsignedLeb128P1(&stream);
973 }
974
Shih-wei Liao195487c2011-08-20 13:29:04 -0700975 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000976 if (local_in_reg[reg].is_live_) {
977 local_in_reg[reg].end_address_ = address;
978 local_cb(context, local_in_reg[reg]);
979 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700980
David Srbeckyb06e28e2015-12-10 13:15:00 +0000981 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
982 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
983 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
984 local_in_reg[reg].start_address_ = address;
985 local_in_reg[reg].reg_ = reg;
986 local_in_reg[reg].is_live_ = true;
987 break;
988 }
989 case DBG_END_LOCAL: {
990 uint16_t reg = DecodeUnsignedLeb128(&stream);
991 if (reg >= code_item->registers_size_) {
992 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
993 << code_item->registers_size_ << ") in " << GetLocation();
994 return false;
995 }
996 if (!local_in_reg[reg].is_live_) {
997 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
998 return false;
999 }
1000 local_in_reg[reg].end_address_ = address;
1001 local_cb(context, local_in_reg[reg]);
1002 local_in_reg[reg].is_live_ = false;
1003 break;
1004 }
1005 case DBG_RESTART_LOCAL: {
1006 uint16_t reg = DecodeUnsignedLeb128(&stream);
1007 if (reg >= code_item->registers_size_) {
1008 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1009 << code_item->registers_size_ << ") in " << GetLocation();
1010 return false;
1011 }
1012 // If the register is live, the "restart" is superfluous,
1013 // and we don't want to mess with the existing start address.
1014 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001015 local_in_reg[reg].start_address_ = address;
1016 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001019 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001020 case DBG_SET_PROLOGUE_END:
1021 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001022 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001023 case DBG_SET_FILE:
1024 DecodeUnsignedLeb128P1(&stream); // name.
1025 break;
1026 default:
1027 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1028 break;
1029 }
1030 }
1031}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001032
David Srbeckyb06e28e2015-12-10 13:15:00 +00001033bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1034 void* context) const {
1035 DCHECK(position_cb != nullptr);
1036 if (code_item == nullptr) {
1037 return false;
1038 }
1039 const uint8_t* stream = GetDebugInfoStream(code_item);
1040 if (stream == nullptr) {
1041 return false;
1042 }
1043
1044 PositionInfo entry = PositionInfo();
1045 entry.line_ = DecodeUnsignedLeb128(&stream);
1046 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1047 for (uint32_t i = 0; i < parameters_size; ++i) {
1048 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1049 }
1050
1051 for (;;) {
1052 uint8_t opcode = *stream++;
1053 switch (opcode) {
1054 case DBG_END_SEQUENCE:
1055 return true; // end of stream.
1056 case DBG_ADVANCE_PC:
1057 entry.address_ += DecodeUnsignedLeb128(&stream);
1058 break;
1059 case DBG_ADVANCE_LINE:
1060 entry.line_ += DecodeSignedLeb128(&stream);
1061 break;
1062 case DBG_START_LOCAL:
1063 DecodeUnsignedLeb128(&stream); // reg.
1064 DecodeUnsignedLeb128P1(&stream); // name.
1065 DecodeUnsignedLeb128P1(&stream); // descriptor.
1066 break;
1067 case DBG_START_LOCAL_EXTENDED:
1068 DecodeUnsignedLeb128(&stream); // reg.
1069 DecodeUnsignedLeb128P1(&stream); // name.
1070 DecodeUnsignedLeb128P1(&stream); // descriptor.
1071 DecodeUnsignedLeb128P1(&stream); // signature.
1072 break;
1073 case DBG_END_LOCAL:
1074 case DBG_RESTART_LOCAL:
1075 DecodeUnsignedLeb128(&stream); // reg.
1076 break;
1077 case DBG_SET_PROLOGUE_END:
1078 entry.prologue_end_ = true;
1079 break;
1080 case DBG_SET_EPILOGUE_BEGIN:
1081 entry.epilogue_begin_ = true;
1082 break;
1083 case DBG_SET_FILE: {
1084 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1085 entry.source_file_ = StringDataByIdx(name_idx);
1086 break;
1087 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001088 default: {
1089 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001090 entry.address_ += adjopcode / DBG_LINE_RANGE;
1091 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1092 if (position_cb(context, entry)) {
1093 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001094 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001095 entry.prologue_end_ = false;
1096 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001097 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001098 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001099 }
1100 }
1101}
1102
David Srbeckyb06e28e2015-12-10 13:15:00 +00001103bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001104 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001105
1106 // We know that this callback will be called in
1107 // ascending address order, so keep going until we find
1108 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001109 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001110 // The line number from the previous positions callback
1111 // wil be the final result.
1112 return true;
1113 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001114 context->line_num_ = entry.line_;
1115 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001116 }
1117}
1118
Andreas Gampe833a4852014-05-21 18:46:59 -07001119bool DexFile::IsMultiDexLocation(const char* location) {
1120 return strrchr(location, kMultiDexSeparator) != nullptr;
1121}
1122
Andreas Gampe90e34042015-04-27 20:01:52 -07001123std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1124 if (index == 0) {
1125 return "classes.dex";
1126 } else {
1127 return StringPrintf("classes%zu.dex", index + 1);
1128 }
1129}
1130
1131std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1132 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001133 return dex_location;
1134 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001135 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001136 }
1137}
1138
1139std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1140 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001141 std::string base_location = GetBaseLocation(dex_location);
1142 const char* suffix = dex_location + base_location.size();
1143 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1144 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1145 if (path != nullptr && path.get() != base_location) {
1146 return std::string(path.get()) + suffix;
1147 } else if (suffix[0] == 0) {
1148 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001149 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001150 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001151 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001152}
1153
Jeff Hao13e748b2015-08-25 20:44:19 +00001154// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001155int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001156 int32_t val = 0;
1157 for (int i = zwidth; i >= 0; --i) {
1158 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1159 }
1160 val >>= (3 - zwidth) * 8;
1161 return val;
1162}
1163
1164// Read an unsigned integer. "zwidth" is the zero-based byte count,
1165// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001166uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001167 uint32_t val = 0;
1168 for (int i = zwidth; i >= 0; --i) {
1169 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1170 }
1171 if (!fill_on_right) {
1172 val >>= (3 - zwidth) * 8;
1173 }
1174 return val;
1175}
1176
1177// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001178int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001179 int64_t val = 0;
1180 for (int i = zwidth; i >= 0; --i) {
1181 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1182 }
1183 val >>= (7 - zwidth) * 8;
1184 return val;
1185}
1186
1187// Read an unsigned long. "zwidth" is the zero-based byte count,
1188// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001189uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001190 uint64_t val = 0;
1191 for (int i = zwidth; i >= 0; --i) {
1192 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1193 }
1194 if (!fill_on_right) {
1195 val >>= (7 - zwidth) * 8;
1196 }
1197 return val;
1198}
1199
Jeff Hao3d080862016-05-26 18:39:17 -07001200// Checks that visibility is as expected. Includes special behavior for M and
1201// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001202std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1203 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1204 dex_file.GetLocation().c_str(),
1205 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1206 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1207 return os;
1208}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001209
Ian Rogersd91d6d62013-09-25 20:26:14 -07001210std::string Signature::ToString() const {
1211 if (dex_file_ == nullptr) {
1212 CHECK(proto_id_ == nullptr);
1213 return "<no signature>";
1214 }
1215 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1216 std::string result;
1217 if (params == nullptr) {
1218 result += "()";
1219 } else {
1220 result += "(";
1221 for (uint32_t i = 0; i < params->Size(); ++i) {
1222 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1223 }
1224 result += ")";
1225 }
1226 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1227 return result;
1228}
1229
Vladimir Markod9cffea2013-11-25 15:08:02 +00001230bool Signature::operator==(const StringPiece& rhs) const {
1231 if (dex_file_ == nullptr) {
1232 return false;
1233 }
1234 StringPiece tail(rhs);
1235 if (!tail.starts_with("(")) {
1236 return false; // Invalid signature
1237 }
1238 tail.remove_prefix(1); // "(";
1239 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1240 if (params != nullptr) {
1241 for (uint32_t i = 0; i < params->Size(); ++i) {
1242 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1243 if (!tail.starts_with(param)) {
1244 return false;
1245 }
1246 tail.remove_prefix(param.length());
1247 }
1248 }
1249 if (!tail.starts_with(")")) {
1250 return false;
1251 }
1252 tail.remove_prefix(1); // ")";
1253 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1254}
1255
Ian Rogersd91d6d62013-09-25 20:26:14 -07001256std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1257 return os << sig.ToString();
1258}
1259
Ian Rogers0571d352011-11-03 19:51:38 -07001260// Decodes the header section from the class data bytes.
1261void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001262 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001263 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1264 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1265 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1266 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1267}
1268
1269void ClassDataItemIterator::ReadClassDataField() {
1270 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1271 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001272 // The user of the iterator is responsible for checking if there
1273 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001274}
1275
1276void ClassDataItemIterator::ReadClassDataMethod() {
1277 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1278 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1279 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001280 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001281 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001282 }
Ian Rogers0571d352011-11-03 19:51:38 -07001283}
1284
David Sehr9323e6e2016-09-13 08:58:35 -07001285EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1286 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001287 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001288 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001289 pos_(-1),
1290 type_(kByte) {
1291 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001292 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001293 array_size_ = 0;
1294 } else {
1295 array_size_ = DecodeUnsignedLeb128(&ptr_);
1296 }
1297 if (array_size_ > 0) {
1298 Next();
1299 }
1300}
1301
1302void EncodedStaticFieldValueIterator::Next() {
1303 pos_++;
1304 if (pos_ >= array_size_) {
1305 return;
1306 }
Ian Rogers13735952014-10-08 12:43:28 -07001307 uint8_t value_type = *ptr_++;
1308 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001309 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001310 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001311 switch (type_) {
1312 case kBoolean:
1313 jval_.i = (value_arg != 0) ? 1 : 0;
1314 width = 0;
1315 break;
1316 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001317 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001318 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001319 break;
1320 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001321 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001322 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001323 break;
1324 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001325 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001326 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001327 break;
1328 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001329 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001330 break;
1331 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001332 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001333 break;
1334 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001335 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001336 break;
1337 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001338 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001339 break;
1340 case kString:
1341 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001342 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001343 break;
1344 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001345 case kMethod:
1346 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001347 case kArray:
1348 case kAnnotation:
1349 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001350 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001351 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001352 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001353 width = 0;
1354 break;
1355 default:
1356 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001357 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001358 }
1359 ptr_ += width;
1360}
1361
Ian Rogers0571d352011-11-03 19:51:38 -07001362CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1363 handler_.address_ = -1;
1364 int32_t offset = -1;
1365
1366 // Short-circuit the overwhelmingly common cases.
1367 switch (code_item.tries_size_) {
1368 case 0:
1369 break;
1370 case 1: {
1371 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1372 uint32_t start = tries->start_addr_;
1373 if (address >= start) {
1374 uint32_t end = start + tries->insn_count_;
1375 if (address < end) {
1376 offset = tries->handler_off_;
1377 }
1378 }
1379 break;
1380 }
1381 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001382 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001383 }
Logan Chien736df022012-04-27 16:25:57 +08001384 Init(code_item, offset);
1385}
1386
1387CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1388 const DexFile::TryItem& try_item) {
1389 handler_.address_ = -1;
1390 Init(code_item, try_item.handler_off_);
1391}
1392
1393void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1394 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001395 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001396 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001397 } else {
1398 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001399 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001400 remaining_count_ = -1;
1401 catch_all_ = false;
1402 DCHECK(!HasNext());
1403 }
1404}
1405
Ian Rogers13735952014-10-08 12:43:28 -07001406void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001407 current_data_ = handler_data;
1408 remaining_count_ = DecodeSignedLeb128(&current_data_);
1409
1410 // If remaining_count_ is non-positive, then it is the negative of
1411 // the number of catch types, and the catches are followed by a
1412 // catch-all handler.
1413 if (remaining_count_ <= 0) {
1414 catch_all_ = true;
1415 remaining_count_ = -remaining_count_;
1416 } else {
1417 catch_all_ = false;
1418 }
1419 Next();
1420}
1421
1422void CatchHandlerIterator::Next() {
1423 if (remaining_count_ > 0) {
1424 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1425 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1426 remaining_count_--;
1427 return;
1428 }
1429
1430 if (catch_all_) {
1431 handler_.type_idx_ = DexFile::kDexNoIndex16;
1432 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1433 catch_all_ = false;
1434 return;
1435 }
1436
1437 // no more handler
1438 remaining_count_ = -1;
1439}
1440
Carl Shapiro1fb86202011-06-27 17:43:13 -07001441} // namespace art