blob: 2ef7509b689fa39f3d219f45cf614b5a72eebdba [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"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080032#include "base/logging.h"
David Sehr9aa352e2016-09-15 18:13:52 -070033#include "base/stringprintf.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080034#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070035#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080037#include "dex_file_verifier.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010038#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "leb128.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070040#include "os.h"
Ian Rogersa6724902013-09-23 09:23:37 -070041#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070042#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070043#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070044
45namespace art {
46
David Sehr733ddb22016-09-19 15:02:18 -070047static constexpr OatDexFile* kNoOatDexFile = nullptr;
48
49const char* DexFile::kClassesDex = "classes.dex";
50
Ian Rogers13735952014-10-08 12:43:28 -070051const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070052const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
53 {'0', '3', '5', '\0'},
54 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
55 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010056 {'0', '3', '7', '\0'},
57 // Dex version 038: Android "O" and beyond.
58 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070059};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070060
Vladimir Marko3a21e382016-09-02 12:38:38 +010061struct DexFile::AnnotationValue {
62 JValue value_;
63 uint8_t type_;
64};
65
Ian Rogers8d31bbd2013-10-13 10:44:14 -070066bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070067 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070069
70 // Strip ":...", which is the location
71 const char* zip_entry_name = kClassesDex;
72 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010073 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070074
Vladimir Markoaa4497d2014-09-05 14:01:17 +010075 if (DexFile::IsMultiDexLocation(filename)) {
76 file_part_storage = GetBaseLocation(filename);
77 file_part = file_part_storage.c_str();
78 zip_entry_name = filename + file_part_storage.size() + 1;
79 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070080 }
81
Andreas Gampe43e10b02016-07-15 17:17:34 -070082 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
83 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070084 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085 return false;
86 }
87 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070089 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070090 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080091 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
92 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080093 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070094 }
Andreas Gampe833a4852014-05-21 18:46:59 -070095 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -070097 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
98 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
100 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700101 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700103 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700105 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700106 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700107 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return false;
109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return true;
112 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700113 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700115}
116
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800119 return 0;
120 } else {
121 return mem_map_->GetProtect();
122 }
123}
124
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200125bool DexFile::IsReadOnly() const {
126 return GetPermissions() == PROT_READ;
127}
128
Brian Carlstrome0948e12013-08-29 09:36:15 -0700129bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200130 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700131 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200132 return false;
133 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700134 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200135 }
136}
137
Brian Carlstrome0948e12013-08-29 09:36:15 -0700138bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200139 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700140 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200141 return false;
142 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700143 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200144 }
145}
146
David Sehr733ddb22016-09-19 15:02:18 -0700147
148std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
149 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800150 const std::string& location,
151 uint32_t location_checksum,
152 const OatDexFile* oat_dex_file,
153 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700154 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800155 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800156 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700157 return OpenCommon(base,
158 size,
159 location,
160 location_checksum,
161 oat_dex_file,
162 verify,
163 verify_checksum,
164 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100165}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800166
Orion Hodsona4c2a052016-08-17 10:51:42 +0100167std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
168 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700169 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100170 bool verify,
171 bool verify_checksum,
172 std::string* error_msg) {
173 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700174 CHECK(map.get() != nullptr);
175 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
176 map->Size(),
177 location,
178 location_checksum,
179 kNoOatDexFile,
180 verify,
181 verify_checksum,
182 error_msg);
183 if (dex_file != nullptr) {
184 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100185 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800186 return dex_file;
187}
188
David Sehr733ddb22016-09-19 15:02:18 -0700189bool DexFile::Open(const char* filename,
190 const std::string& location,
191 bool verify_checksum,
192 std::string* error_msg,
193 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
194 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
195 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
196 uint32_t magic;
197 File fd = OpenAndReadMagic(filename, &magic, error_msg);
198 if (fd.Fd() == -1) {
199 DCHECK(!error_msg->empty());
200 return false;
201 }
202 if (IsZipMagic(magic)) {
203 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
204 }
205 if (IsDexMagic(magic)) {
206 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
207 location,
208 /* verify */ true,
209 verify_checksum,
210 error_msg));
211 if (dex_file.get() != nullptr) {
212 dex_files->push_back(std::move(dex_file));
213 return true;
214 } else {
215 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000216 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700217 }
David Sehr733ddb22016-09-19 15:02:18 -0700218 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
219 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700220}
221
David Sehr733ddb22016-09-19 15:02:18 -0700222std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
223 const std::string& location,
224 bool verify_checksum,
225 std::string* error_msg) {
226 ScopedTrace trace("Open dex file " + std::string(location));
227 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
228}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700229
Aart Bik37d6a3b2016-06-21 18:30:10 -0700230bool DexFile::OpenZip(int fd,
231 const std::string& location,
232 bool verify_checksum,
233 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800234 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800235 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700236 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700237 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700238 if (zip_archive.get() == nullptr) {
239 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700240 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700241 }
David Sehr733ddb22016-09-19 15:02:18 -0700242 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
243 location,
244 verify_checksum,
245 error_msg,
246 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800247}
248
David Sehr733ddb22016-09-19 15:02:18 -0700249std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
250 const std::string& location,
251 bool verify,
252 bool verify_checksum,
253 std::string* error_msg) {
254 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
255 CHECK(!location.empty());
256 std::unique_ptr<MemMap> map;
257 {
258 File delayed_close(fd, /* check_usage */ false);
259 struct stat sbuf;
260 memset(&sbuf, 0, sizeof(sbuf));
261 if (fstat(fd, &sbuf) == -1) {
262 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
263 strerror(errno));
264 return nullptr;
265 }
266 if (S_ISDIR(sbuf.st_mode)) {
267 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
268 return nullptr;
269 }
270 size_t length = sbuf.st_size;
271 map.reset(MemMap::MapFile(length,
272 PROT_READ,
273 MAP_PRIVATE,
274 fd,
275 0,
276 /*low_4gb*/false,
277 location.c_str(),
278 error_msg));
279 if (map == nullptr) {
280 DCHECK(!error_msg->empty());
281 return nullptr;
282 }
283 }
284
285 if (map->Size() < sizeof(DexFile::Header)) {
286 *error_msg = StringPrintf(
287 "DexFile: failed to open dex file '%s' that is too short to have a header",
288 location.c_str());
289 return nullptr;
290 }
291
292 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
293
294 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
295 map->Size(),
296 location,
297 dex_header->checksum_,
298 kNoOatDexFile,
299 verify,
300 verify_checksum,
301 error_msg);
302 if (dex_file != nullptr) {
303 dex_file->mem_map_.reset(map.release());
304 }
305
306 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800307}
308
David Sehr733ddb22016-09-19 15:02:18 -0700309std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
310 const char* entry_name,
311 const std::string& location,
312 bool verify_checksum,
313 std::string* error_msg,
314 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800315 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800316 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700318 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700319 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700321 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800322 if (zip_entry->GetUncompressedLength() == 0) {
323 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
324 *error_code = ZipOpenErrorCode::kDexFileError;
325 return nullptr;
326 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700327 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700328 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700329 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700330 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700331 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700332 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700333 }
David Sehr733ddb22016-09-19 15:02:18 -0700334 VerifyResult verify_result;
335 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
336 map->Size(),
337 location,
338 zip_entry->GetCrc32(),
339 kNoOatDexFile,
340 /* verify */ true,
341 verify_checksum,
342 error_msg,
343 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700344 if (dex_file == nullptr) {
345 if (verify_result == VerifyResult::kVerifyNotAttempted) {
346 *error_code = ZipOpenErrorCode::kDexFileError;
347 } else {
348 *error_code = ZipOpenErrorCode::kVerifyError;
349 }
350 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800351 }
David Sehr9fddd362016-09-22 14:05:37 -0700352 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700353 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700355 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700356 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700357 }
358 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700359 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700360 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700361 return nullptr;
362 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700363 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800364 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700365}
366
Andreas Gampe90e34042015-04-27 20:01:52 -0700367// Technically we do not have a limitation with respect to the number of dex files that can be in a
368// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
369// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
370// seems an excessive number.
371static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
372
David Sehr733ddb22016-09-19 15:02:18 -0700373bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
374 const std::string& location,
375 bool verify_checksum,
376 std::string* error_msg,
377 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800378 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700379 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700380 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700381 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
382 kClassesDex,
383 location,
384 verify_checksum,
385 error_msg,
386 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700387 if (dex_file.get() == nullptr) {
388 return false;
389 } else {
390 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800391 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700392
393 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700394
395 // We could try to avoid std::string allocations by working on a char array directly. As we
396 // do not expect a lot of iterations, this seems too involved and brittle.
397
Andreas Gampe90e34042015-04-27 20:01:52 -0700398 for (size_t i = 1; ; ++i) {
399 std::string name = GetMultiDexClassesDexName(i);
400 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700401 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
402 name.c_str(),
403 fake_location,
404 verify_checksum,
405 error_msg,
406 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700407 if (next_dex_file.get() == nullptr) {
408 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
409 LOG(WARNING) << error_msg;
410 }
411 break;
412 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800413 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700414 }
415
Andreas Gampe90e34042015-04-27 20:01:52 -0700416 if (i == kWarnOnManyDexFilesThreshold) {
417 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
418 << " dex files. Please consider coalescing and shrinking the number to "
419 " avoid runtime overhead.";
420 }
421
422 if (i == std::numeric_limits<size_t>::max()) {
423 LOG(ERROR) << "Overflow in number of dex files!";
424 break;
425 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700426 }
427
428 return true;
429 }
430}
431
David Sehr733ddb22016-09-19 15:02:18 -0700432std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
433 size_t size,
434 const std::string& location,
435 uint32_t location_checksum,
436 const OatDexFile* oat_dex_file,
437 bool verify,
438 bool verify_checksum,
439 std::string* error_msg,
440 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700441 if (verify_result != nullptr) {
442 *verify_result = VerifyResult::kVerifyNotAttempted;
443 }
David Sehr733ddb22016-09-19 15:02:18 -0700444 std::unique_ptr<DexFile> dex_file(new DexFile(base,
445 size,
446 location,
447 location_checksum,
448 oat_dex_file));
449 if (dex_file == nullptr) {
450 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
451 error_msg->c_str());
452 return nullptr;
453 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700454 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800455 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700456 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700457 }
David Sehr733ddb22016-09-19 15:02:18 -0700458 if (verify && !DexFileVerifier::Verify(dex_file.get(),
459 dex_file->Begin(),
460 dex_file->Size(),
461 location.c_str(),
462 verify_checksum,
463 error_msg)) {
464 if (verify_result != nullptr) {
465 *verify_result = VerifyResult::kVerifyFailed;
466 }
467 return nullptr;
468 }
469 if (verify_result != nullptr) {
470 *verify_result = VerifyResult::kVerifySucceeded;
471 }
472 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700473}
474
David Sehr733ddb22016-09-19 15:02:18 -0700475DexFile::DexFile(const uint8_t* base,
476 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800477 const std::string& location,
478 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700479 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800480 : begin_(base),
481 size_(size),
482 location_(location),
483 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800484 header_(reinterpret_cast<const Header*>(base)),
485 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
486 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
487 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
488 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
489 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700490 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700491 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700492 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800493 CHECK_GT(size_, 0U) << GetLocation();
494}
495
Jesse Wilson6bf19152011-09-29 13:12:33 -0400496DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700497 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
498 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
499 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
500 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400501}
502
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700503bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700504 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700505 return false;
506 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700507 return true;
508}
509
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700510bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800511 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700512 std::ostringstream oss;
513 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800514 << " " << header_->magic_[0]
515 << " " << header_->magic_[1]
516 << " " << header_->magic_[2]
517 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700518 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700519 return false;
520 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800521 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700522 std::ostringstream oss;
523 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800524 << " " << header_->magic_[4]
525 << " " << header_->magic_[5]
526 << " " << header_->magic_[6]
527 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700528 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700529 return false;
530 }
531 return true;
532}
533
Ian Rogers13735952014-10-08 12:43:28 -0700534bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800535 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
536}
537
Ian Rogers13735952014-10-08 12:43:28 -0700538bool DexFile::IsVersionValid(const uint8_t* magic) {
539 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700540 for (uint32_t i = 0; i < kNumDexVersions; i++) {
541 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
542 return true;
543 }
544 }
545 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800546}
547
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700548uint32_t DexFile::Header::GetVersion() const {
549 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700550 return atoi(version);
551}
552
David Sehr9aa352e2016-09-15 18:13:52 -0700553const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
554 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100555 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700556 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700557 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700558 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700559 for (size_t i = 0; i < num_class_defs; ++i) {
560 const ClassDef& class_def = GetClassDef(i);
561 if (class_def.class_idx_ == type_idx) {
562 return &class_def;
563 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700564 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700565 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700566}
567
Alex Light9c20a142016-08-23 15:05:12 -0700568uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
569 uint32_t method_idx) const {
570 const uint8_t* class_data = GetClassData(class_def);
571 CHECK(class_data != nullptr);
572 ClassDataItemIterator it(*this, class_data);
573 // Skip fields
574 while (it.HasNextStaticField()) {
575 it.Next();
576 }
577 while (it.HasNextInstanceField()) {
578 it.Next();
579 }
580 while (it.HasNextDirectMethod()) {
581 if (it.GetMemberIndex() == method_idx) {
582 return it.GetMethodCodeItemOffset();
583 }
584 it.Next();
585 }
586 while (it.HasNextVirtualMethod()) {
587 if (it.GetMemberIndex() == method_idx) {
588 return it.GetMethodCodeItemOffset();
589 }
590 it.Next();
591 }
592 LOG(FATAL) << "Unable to find method " << method_idx;
593 UNREACHABLE();
594}
595
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800596const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100597 const DexFile::StringId& name,
598 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800599 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
600 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
601 const uint32_t name_idx = GetIndexForStringId(name);
602 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700603 int32_t lo = 0;
604 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800605 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700606 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800607 const DexFile::FieldId& field = GetFieldId(mid);
608 if (class_idx > field.class_idx_) {
609 lo = mid + 1;
610 } else if (class_idx < field.class_idx_) {
611 hi = mid - 1;
612 } else {
613 if (name_idx > field.name_idx_) {
614 lo = mid + 1;
615 } else if (name_idx < field.name_idx_) {
616 hi = mid - 1;
617 } else {
618 if (type_idx > field.type_idx_) {
619 lo = mid + 1;
620 } else if (type_idx < field.type_idx_) {
621 hi = mid - 1;
622 } else {
623 return &field;
624 }
625 }
626 }
627 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700628 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800629}
630
631const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700632 const DexFile::StringId& name,
633 const DexFile::ProtoId& signature) const {
634 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800635 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700636 const uint32_t name_idx = GetIndexForStringId(name);
637 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700638 int32_t lo = 0;
639 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700640 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700641 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700642 const DexFile::MethodId& method = GetMethodId(mid);
643 if (class_idx > method.class_idx_) {
644 lo = mid + 1;
645 } else if (class_idx < method.class_idx_) {
646 hi = mid - 1;
647 } else {
648 if (name_idx > method.name_idx_) {
649 lo = mid + 1;
650 } else if (name_idx < method.name_idx_) {
651 hi = mid - 1;
652 } else {
653 if (proto_idx > method.proto_idx_) {
654 lo = mid + 1;
655 } else if (proto_idx < method.proto_idx_) {
656 hi = mid - 1;
657 } else {
658 return &method;
659 }
660 }
661 }
662 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700663 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700664}
665
Ian Rogers637c65b2013-05-31 11:46:00 -0700666const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700667 int32_t lo = 0;
668 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700669 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700670 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700671 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700672 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700673 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
674 if (compare > 0) {
675 lo = mid + 1;
676 } else if (compare < 0) {
677 hi = mid - 1;
678 } else {
679 return &str_id;
680 }
681 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700682 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700683}
684
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300685const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
686 int32_t lo = 0;
687 int32_t hi = NumTypeIds() - 1;
688 while (hi >= lo) {
689 int32_t mid = (hi + lo) / 2;
690 const TypeId& type_id = GetTypeId(mid);
691 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
692 const char* str = GetStringData(str_id);
693 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
694 if (compare > 0) {
695 lo = mid + 1;
696 } else if (compare < 0) {
697 hi = mid - 1;
698 } else {
699 return &type_id;
700 }
701 }
702 return nullptr;
703}
704
Vladimir Markoa48aef42014-12-03 17:53:53 +0000705const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700706 int32_t lo = 0;
707 int32_t hi = NumStringIds() - 1;
708 while (hi >= lo) {
709 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700710 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700711 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000712 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700713 if (compare > 0) {
714 lo = mid + 1;
715 } else if (compare < 0) {
716 hi = mid - 1;
717 } else {
718 return &str_id;
719 }
720 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700721 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700722}
723
724const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700725 int32_t lo = 0;
726 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700727 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700728 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700729 const TypeId& type_id = GetTypeId(mid);
730 if (string_idx > type_id.descriptor_idx_) {
731 lo = mid + 1;
732 } else if (string_idx < type_id.descriptor_idx_) {
733 hi = mid - 1;
734 } else {
735 return &type_id;
736 }
737 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700738 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700739}
740
741const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000742 const uint16_t* signature_type_idxs,
743 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700744 int32_t lo = 0;
745 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700746 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700747 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700748 const DexFile::ProtoId& proto = GetProtoId(mid);
749 int compare = return_type_idx - proto.return_type_idx_;
750 if (compare == 0) {
751 DexFileParameterIterator it(*this, proto);
752 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000753 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800754 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700755 it.Next();
756 i++;
757 }
758 if (compare == 0) {
759 if (it.HasNext()) {
760 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000761 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700762 compare = 1;
763 }
764 }
765 }
766 if (compare > 0) {
767 lo = mid + 1;
768 } else if (compare < 0) {
769 hi = mid - 1;
770 } else {
771 return &proto;
772 }
773 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700774 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700775}
776
777// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700778bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
779 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700780 if (signature[0] != '(') {
781 return false;
782 }
783 size_t offset = 1;
784 size_t end = signature.size();
785 bool process_return = false;
786 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000787 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700788 char c = signature[offset];
789 offset++;
790 if (c == ')') {
791 process_return = true;
792 continue;
793 }
Ian Rogers0571d352011-11-03 19:51:38 -0700794 while (c == '[') { // process array prefix
795 if (offset >= end) { // expect some descriptor following [
796 return false;
797 }
798 c = signature[offset];
799 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700800 }
801 if (c == 'L') { // process type descriptors
802 do {
803 if (offset >= end) { // unexpected early termination of descriptor
804 return false;
805 }
806 c = signature[offset];
807 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700808 } while (c != ';');
809 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000810 // TODO: avoid creating a std::string just to get a 0-terminated char array
811 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700812 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700813 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700814 return false;
815 }
816 uint16_t type_idx = GetIndexForTypeId(*type_id);
817 if (!process_return) {
818 param_type_idxs->push_back(type_idx);
819 } else {
820 *return_type_idx = type_idx;
821 return offset == end; // return true if the signature had reached a sensible end
822 }
823 }
824 return false; // failed to correctly parse return type
825}
826
Ian Rogersd91d6d62013-09-25 20:26:14 -0700827const Signature DexFile::CreateSignature(const StringPiece& signature) const {
828 uint16_t return_type_idx;
829 std::vector<uint16_t> param_type_indices;
830 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
831 if (!success) {
832 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700833 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700834 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700835 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700836 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700837 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700838 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700839}
840
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700841int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700842 // Note: Signed type is important for max and min.
843 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700844 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700845
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700846 while (min <= max) {
847 int32_t mid = min + ((max - min) / 2);
848
849 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
850 uint32_t start = ti->start_addr_;
851 uint32_t end = start + ti->insn_count_;
852
Ian Rogers0571d352011-11-03 19:51:38 -0700853 if (address < start) {
854 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700855 } else if (address >= end) {
856 min = mid + 1;
857 } else { // We have a winner!
858 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700859 }
860 }
861 // No match.
862 return -1;
863}
864
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700865int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
866 int32_t try_item = FindTryItem(code_item, address);
867 if (try_item == -1) {
868 return -1;
869 } else {
870 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
871 }
872}
873
David Srbeckyb06e28e2015-12-10 13:15:00 +0000874bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
875 DexDebugNewLocalCb local_cb, void* context) const {
876 DCHECK(local_cb != nullptr);
877 if (code_item == nullptr) {
878 return false;
879 }
880 const uint8_t* stream = GetDebugInfoStream(code_item);
881 if (stream == nullptr) {
882 return false;
883 }
884 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700885
David Srbeckyb06e28e2015-12-10 13:15:00 +0000886 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800887 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000888 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
889 local_in_reg[arg_reg].name_ = "this";
890 local_in_reg[arg_reg].descriptor_ = descriptor;
891 local_in_reg[arg_reg].signature_ = nullptr;
892 local_in_reg[arg_reg].start_address_ = 0;
893 local_in_reg[arg_reg].reg_ = arg_reg;
894 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700895 arg_reg++;
896 }
897
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800898 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000899 DecodeUnsignedLeb128(&stream); // Line.
900 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
901 uint32_t i;
902 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700903 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700904 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800905 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000908 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700909 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000910 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
911 local_in_reg[arg_reg].descriptor_ = descriptor;
912 local_in_reg[arg_reg].signature_ = nullptr;
913 local_in_reg[arg_reg].start_address_ = 0;
914 local_in_reg[arg_reg].reg_ = arg_reg;
915 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700916 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700917 case 'D':
918 case 'J':
919 arg_reg += 2;
920 break;
921 default:
922 arg_reg += 1;
923 break;
924 }
925 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800927 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700928 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000929 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700930 }
931
David Srbeckyb06e28e2015-12-10 13:15:00 +0000932 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700933 for (;;) {
934 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700935 switch (opcode) {
936 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000937 // Emit all variables which are still alive at the end of the method.
938 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
939 if (local_in_reg[reg].is_live_) {
940 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
941 local_cb(context, local_in_reg[reg]);
942 }
943 }
944 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945 case DBG_ADVANCE_PC:
946 address += DecodeUnsignedLeb128(&stream);
947 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000949 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700950 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000952 case DBG_START_LOCAL_EXTENDED: {
953 uint16_t reg = DecodeUnsignedLeb128(&stream);
954 if (reg >= code_item->registers_size_) {
955 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800956 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000957 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700958 }
959
David Srbeckyb06e28e2015-12-10 13:15:00 +0000960 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
961 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
962 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700963 if (opcode == DBG_START_LOCAL_EXTENDED) {
964 signature_idx = DecodeUnsignedLeb128P1(&stream);
965 }
966
Shih-wei Liao195487c2011-08-20 13:29:04 -0700967 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000968 if (local_in_reg[reg].is_live_) {
969 local_in_reg[reg].end_address_ = address;
970 local_cb(context, local_in_reg[reg]);
971 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700972
David Srbeckyb06e28e2015-12-10 13:15:00 +0000973 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
974 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
975 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
976 local_in_reg[reg].start_address_ = address;
977 local_in_reg[reg].reg_ = reg;
978 local_in_reg[reg].is_live_ = true;
979 break;
980 }
981 case DBG_END_LOCAL: {
982 uint16_t reg = DecodeUnsignedLeb128(&stream);
983 if (reg >= code_item->registers_size_) {
984 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
985 << code_item->registers_size_ << ") in " << GetLocation();
986 return false;
987 }
988 if (!local_in_reg[reg].is_live_) {
989 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
990 return false;
991 }
992 local_in_reg[reg].end_address_ = address;
993 local_cb(context, local_in_reg[reg]);
994 local_in_reg[reg].is_live_ = false;
995 break;
996 }
997 case DBG_RESTART_LOCAL: {
998 uint16_t reg = DecodeUnsignedLeb128(&stream);
999 if (reg >= code_item->registers_size_) {
1000 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1001 << code_item->registers_size_ << ") in " << GetLocation();
1002 return false;
1003 }
1004 // If the register is live, the "restart" is superfluous,
1005 // and we don't want to mess with the existing start address.
1006 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001007 local_in_reg[reg].start_address_ = address;
1008 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001009 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001010 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001011 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001012 case DBG_SET_PROLOGUE_END:
1013 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001014 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001015 case DBG_SET_FILE:
1016 DecodeUnsignedLeb128P1(&stream); // name.
1017 break;
1018 default:
1019 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1020 break;
1021 }
1022 }
1023}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001024
David Srbeckyb06e28e2015-12-10 13:15:00 +00001025bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1026 void* context) const {
1027 DCHECK(position_cb != nullptr);
1028 if (code_item == nullptr) {
1029 return false;
1030 }
1031 const uint8_t* stream = GetDebugInfoStream(code_item);
1032 if (stream == nullptr) {
1033 return false;
1034 }
1035
1036 PositionInfo entry = PositionInfo();
1037 entry.line_ = DecodeUnsignedLeb128(&stream);
1038 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1039 for (uint32_t i = 0; i < parameters_size; ++i) {
1040 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1041 }
1042
1043 for (;;) {
1044 uint8_t opcode = *stream++;
1045 switch (opcode) {
1046 case DBG_END_SEQUENCE:
1047 return true; // end of stream.
1048 case DBG_ADVANCE_PC:
1049 entry.address_ += DecodeUnsignedLeb128(&stream);
1050 break;
1051 case DBG_ADVANCE_LINE:
1052 entry.line_ += DecodeSignedLeb128(&stream);
1053 break;
1054 case DBG_START_LOCAL:
1055 DecodeUnsignedLeb128(&stream); // reg.
1056 DecodeUnsignedLeb128P1(&stream); // name.
1057 DecodeUnsignedLeb128P1(&stream); // descriptor.
1058 break;
1059 case DBG_START_LOCAL_EXTENDED:
1060 DecodeUnsignedLeb128(&stream); // reg.
1061 DecodeUnsignedLeb128P1(&stream); // name.
1062 DecodeUnsignedLeb128P1(&stream); // descriptor.
1063 DecodeUnsignedLeb128P1(&stream); // signature.
1064 break;
1065 case DBG_END_LOCAL:
1066 case DBG_RESTART_LOCAL:
1067 DecodeUnsignedLeb128(&stream); // reg.
1068 break;
1069 case DBG_SET_PROLOGUE_END:
1070 entry.prologue_end_ = true;
1071 break;
1072 case DBG_SET_EPILOGUE_BEGIN:
1073 entry.epilogue_begin_ = true;
1074 break;
1075 case DBG_SET_FILE: {
1076 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1077 entry.source_file_ = StringDataByIdx(name_idx);
1078 break;
1079 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001080 default: {
1081 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001082 entry.address_ += adjopcode / DBG_LINE_RANGE;
1083 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1084 if (position_cb(context, entry)) {
1085 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001086 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001087 entry.prologue_end_ = false;
1088 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001089 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001090 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001091 }
1092 }
1093}
1094
David Srbeckyb06e28e2015-12-10 13:15:00 +00001095bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001096 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001097
1098 // We know that this callback will be called in
1099 // ascending address order, so keep going until we find
1100 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001101 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001102 // The line number from the previous positions callback
1103 // wil be the final result.
1104 return true;
1105 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001106 context->line_num_ = entry.line_;
1107 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001108 }
1109}
1110
Andreas Gampe833a4852014-05-21 18:46:59 -07001111bool DexFile::IsMultiDexLocation(const char* location) {
1112 return strrchr(location, kMultiDexSeparator) != nullptr;
1113}
1114
Andreas Gampe90e34042015-04-27 20:01:52 -07001115std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1116 if (index == 0) {
1117 return "classes.dex";
1118 } else {
1119 return StringPrintf("classes%zu.dex", index + 1);
1120 }
1121}
1122
1123std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1124 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001125 return dex_location;
1126 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001127 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001128 }
1129}
1130
1131std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1132 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001133 std::string base_location = GetBaseLocation(dex_location);
1134 const char* suffix = dex_location + base_location.size();
1135 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1136 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1137 if (path != nullptr && path.get() != base_location) {
1138 return std::string(path.get()) + suffix;
1139 } else if (suffix[0] == 0) {
1140 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001141 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001142 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001143 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001144}
1145
Jeff Hao13e748b2015-08-25 20:44:19 +00001146// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001147int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001148 int32_t val = 0;
1149 for (int i = zwidth; i >= 0; --i) {
1150 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1151 }
1152 val >>= (3 - zwidth) * 8;
1153 return val;
1154}
1155
1156// Read an unsigned integer. "zwidth" is the zero-based byte count,
1157// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001158uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001159 uint32_t val = 0;
1160 for (int i = zwidth; i >= 0; --i) {
1161 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1162 }
1163 if (!fill_on_right) {
1164 val >>= (3 - zwidth) * 8;
1165 }
1166 return val;
1167}
1168
1169// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001170int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001171 int64_t val = 0;
1172 for (int i = zwidth; i >= 0; --i) {
1173 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1174 }
1175 val >>= (7 - zwidth) * 8;
1176 return val;
1177}
1178
1179// Read an unsigned long. "zwidth" is the zero-based byte count,
1180// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001181uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001182 uint64_t val = 0;
1183 for (int i = zwidth; i >= 0; --i) {
1184 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1185 }
1186 if (!fill_on_right) {
1187 val >>= (7 - zwidth) * 8;
1188 }
1189 return val;
1190}
1191
David Sehr709b0702016-10-13 09:12:37 -07001192std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1193 if (method_idx >= NumMethodIds()) {
1194 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1195 }
1196 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1197 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1198 result += '.';
1199 result += GetMethodName(method_id);
1200 if (with_signature) {
1201 const Signature signature = GetMethodSignature(method_id);
1202 std::string sig_as_string(signature.ToString());
1203 if (signature == Signature::NoSignature()) {
1204 return result + sig_as_string;
1205 }
1206 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1207 PrettyArguments(sig_as_string.c_str());
1208 }
1209 return result;
1210}
1211
1212std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1213 if (field_idx >= NumFieldIds()) {
1214 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1215 }
1216 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1217 std::string result;
1218 if (with_type) {
1219 result += GetFieldTypeDescriptor(field_id);
1220 result += ' ';
1221 }
1222 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1223 result += '.';
1224 result += GetFieldName(field_id);
1225 return result;
1226}
1227
1228std::string DexFile::PrettyType(uint32_t type_idx) const {
1229 if (type_idx >= NumTypeIds()) {
1230 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
1231 }
1232 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1233 return PrettyDescriptor(GetTypeDescriptor(type_id));
1234}
1235
Jeff Hao3d080862016-05-26 18:39:17 -07001236// Checks that visibility is as expected. Includes special behavior for M and
1237// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001238std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1239 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1240 dex_file.GetLocation().c_str(),
1241 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1242 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1243 return os;
1244}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001245
Ian Rogersd91d6d62013-09-25 20:26:14 -07001246std::string Signature::ToString() const {
1247 if (dex_file_ == nullptr) {
1248 CHECK(proto_id_ == nullptr);
1249 return "<no signature>";
1250 }
1251 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1252 std::string result;
1253 if (params == nullptr) {
1254 result += "()";
1255 } else {
1256 result += "(";
1257 for (uint32_t i = 0; i < params->Size(); ++i) {
1258 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1259 }
1260 result += ")";
1261 }
1262 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1263 return result;
1264}
1265
Vladimir Markod9cffea2013-11-25 15:08:02 +00001266bool Signature::operator==(const StringPiece& rhs) const {
1267 if (dex_file_ == nullptr) {
1268 return false;
1269 }
1270 StringPiece tail(rhs);
1271 if (!tail.starts_with("(")) {
1272 return false; // Invalid signature
1273 }
1274 tail.remove_prefix(1); // "(";
1275 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1276 if (params != nullptr) {
1277 for (uint32_t i = 0; i < params->Size(); ++i) {
1278 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1279 if (!tail.starts_with(param)) {
1280 return false;
1281 }
1282 tail.remove_prefix(param.length());
1283 }
1284 }
1285 if (!tail.starts_with(")")) {
1286 return false;
1287 }
1288 tail.remove_prefix(1); // ")";
1289 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1290}
1291
Ian Rogersd91d6d62013-09-25 20:26:14 -07001292std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1293 return os << sig.ToString();
1294}
1295
Ian Rogers0571d352011-11-03 19:51:38 -07001296// Decodes the header section from the class data bytes.
1297void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001298 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001299 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1300 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1301 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1302 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1303}
1304
1305void ClassDataItemIterator::ReadClassDataField() {
1306 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1307 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001308 // The user of the iterator is responsible for checking if there
1309 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001310}
1311
1312void ClassDataItemIterator::ReadClassDataMethod() {
1313 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1314 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1315 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001316 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001317 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001318 }
Ian Rogers0571d352011-11-03 19:51:38 -07001319}
1320
David Sehr9323e6e2016-09-13 08:58:35 -07001321EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(const DexFile& dex_file,
1322 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001323 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001324 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001325 pos_(-1),
1326 type_(kByte) {
1327 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001328 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001329 array_size_ = 0;
1330 } else {
1331 array_size_ = DecodeUnsignedLeb128(&ptr_);
1332 }
1333 if (array_size_ > 0) {
1334 Next();
1335 }
1336}
1337
1338void EncodedStaticFieldValueIterator::Next() {
1339 pos_++;
1340 if (pos_ >= array_size_) {
1341 return;
1342 }
Ian Rogers13735952014-10-08 12:43:28 -07001343 uint8_t value_type = *ptr_++;
1344 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001345 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001346 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001347 switch (type_) {
1348 case kBoolean:
1349 jval_.i = (value_arg != 0) ? 1 : 0;
1350 width = 0;
1351 break;
1352 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001353 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001354 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001355 break;
1356 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001357 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001358 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001359 break;
1360 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001361 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001362 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001363 break;
1364 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001365 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001366 break;
1367 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001368 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001369 break;
1370 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001371 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001372 break;
1373 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001374 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001375 break;
1376 case kString:
1377 case kType:
David Sehr9323e6e2016-09-13 08:58:35 -07001378 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001379 break;
1380 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001381 case kMethod:
1382 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001383 case kArray:
1384 case kAnnotation:
1385 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001386 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001387 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001388 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001389 width = 0;
1390 break;
1391 default:
1392 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001393 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001394 }
1395 ptr_ += width;
1396}
1397
Ian Rogers0571d352011-11-03 19:51:38 -07001398CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1399 handler_.address_ = -1;
1400 int32_t offset = -1;
1401
1402 // Short-circuit the overwhelmingly common cases.
1403 switch (code_item.tries_size_) {
1404 case 0:
1405 break;
1406 case 1: {
1407 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1408 uint32_t start = tries->start_addr_;
1409 if (address >= start) {
1410 uint32_t end = start + tries->insn_count_;
1411 if (address < end) {
1412 offset = tries->handler_off_;
1413 }
1414 }
1415 break;
1416 }
1417 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001418 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001419 }
Logan Chien736df022012-04-27 16:25:57 +08001420 Init(code_item, offset);
1421}
1422
1423CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1424 const DexFile::TryItem& try_item) {
1425 handler_.address_ = -1;
1426 Init(code_item, try_item.handler_off_);
1427}
1428
1429void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1430 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001431 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001432 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001433 } else {
1434 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001435 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001436 remaining_count_ = -1;
1437 catch_all_ = false;
1438 DCHECK(!HasNext());
1439 }
1440}
1441
Ian Rogers13735952014-10-08 12:43:28 -07001442void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001443 current_data_ = handler_data;
1444 remaining_count_ = DecodeSignedLeb128(&current_data_);
1445
1446 // If remaining_count_ is non-positive, then it is the negative of
1447 // the number of catch types, and the catches are followed by a
1448 // catch-all handler.
1449 if (remaining_count_ <= 0) {
1450 catch_all_ = true;
1451 remaining_count_ = -remaining_count_;
1452 } else {
1453 catch_all_ = false;
1454 }
1455 Next();
1456}
1457
1458void CatchHandlerIterator::Next() {
1459 if (remaining_count_ > 0) {
1460 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1461 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1462 remaining_count_--;
1463 return;
1464 }
1465
1466 if (catch_all_) {
1467 handler_.type_idx_ = DexFile::kDexNoIndex16;
1468 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1469 catch_all_ = false;
1470 return;
1471 }
1472
1473 // no more handler
1474 remaining_count_ = -1;
1475}
1476
Carl Shapiro1fb86202011-06-27 17:43:13 -07001477} // namespace art