blob: 48db7e5cd30edd703fd9f5a5e129353a73b82046 [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>
Andreas Gampea5b09a62016-11-17 15:21:22 -080029#include <type_traits>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070030
Andreas Gampe46ee31b2016-12-14 10:11:49 -080031#include "android-base/stringprintf.h"
32
Andreas Gampe542451c2016-07-26 09:02:02 -070033#include "base/enums.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000034#include "base/file_magic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080035#include "base/logging.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"
Vladimir Marko3a21e382016-09-02 12:38:38 +010040#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070041#include "leb128.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070042#include "os.h"
Ian Rogersa6724902013-09-23 09:23:37 -070043#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070044#include "utils.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070045#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070046
47namespace art {
48
Andreas Gampe46ee31b2016-12-14 10:11:49 -080049using android::base::StringPrintf;
50
Andreas Gampe8a0128a2016-11-28 07:38:35 -080051static_assert(sizeof(dex::StringIndex) == sizeof(uint32_t), "StringIndex size is wrong");
52static_assert(std::is_trivially_copyable<dex::StringIndex>::value, "StringIndex not trivial");
Andreas Gampea5b09a62016-11-17 15:21:22 -080053static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
54static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
55
David Sehr733ddb22016-09-19 15:02:18 -070056static constexpr OatDexFile* kNoOatDexFile = nullptr;
57
58const char* DexFile::kClassesDex = "classes.dex";
59
Ian Rogers13735952014-10-08 12:43:28 -070060const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070061const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
62 {'0', '3', '5', '\0'},
63 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
64 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010065 {'0', '3', '7', '\0'},
66 // Dex version 038: Android "O" and beyond.
67 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070068};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070069
Vladimir Marko3a21e382016-09-02 12:38:38 +010070struct DexFile::AnnotationValue {
71 JValue value_;
72 uint8_t type_;
73};
74
Ian Rogers8d31bbd2013-10-13 10:44:14 -070075bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070076 CHECK(checksum != nullptr);
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
Richard Uhler69bcf2c2017-01-24 10:25:21 +000090 std::vector<uint32_t> checksums;
91 if (!GetMultiDexChecksums(file_part, &checksums, error_msg)) {
92 return false;
93 }
94
95 for (size_t i = 0; i < checksums.size(); i++) {
96 if (GetMultiDexClassesDexName(i) == std::string(zip_entry_name)) {
97 *checksum = checksums[i];
98 return true;
99 }
100 }
101
102 *error_msg = StringPrintf("Failed to find entry '%s' in '%s'", zip_entry_name, file_part);
103 return false;
104}
105
106bool DexFile::GetMultiDexChecksums(const char* filename,
107 std::vector<uint32_t>* checksums,
108 std::string* error_msg) {
109 CHECK(checksums != nullptr);
110 uint32_t magic;
111
112 File fd = OpenAndReadMagic(filename, &magic, error_msg);
Andreas Gampe43e10b02016-07-15 17:17:34 -0700113 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700114 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700115 return false;
116 }
117 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700119 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700120 if (zip_archive.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000121 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", filename,
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800122 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800123 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700124 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000125
126 uint32_t i = 0;
127 std::string zip_entry_name = GetMultiDexClassesDexName(i++);
128 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name.c_str(), error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700129 if (zip_entry.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000130 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", filename,
131 zip_entry_name.c_str(), error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800132 return false;
133 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000134
135 do {
136 checksums->push_back(zip_entry->GetCrc32());
137 zip_entry_name = DexFile::GetMultiDexClassesDexName(i++);
138 zip_entry.reset(zip_archive->Find(zip_entry_name.c_str(), error_msg));
139 } while (zip_entry.get() != nullptr);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800140 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700141 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700142 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700143 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700144 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700145 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800146 return false;
147 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000148 checksums->push_back(dex_file->GetHeader().checksum_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800149 return true;
150 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700151 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800152 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700153}
154
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800155int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700156 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800157 return 0;
158 } else {
159 return mem_map_->GetProtect();
160 }
161}
162
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200163bool DexFile::IsReadOnly() const {
164 return GetPermissions() == PROT_READ;
165}
166
Brian Carlstrome0948e12013-08-29 09:36:15 -0700167bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200168 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700169 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200170 return false;
171 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700172 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200173 }
174}
175
Brian Carlstrome0948e12013-08-29 09:36:15 -0700176bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200177 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700178 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200179 return false;
180 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700181 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200182 }
183}
184
David Sehr733ddb22016-09-19 15:02:18 -0700185
186std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
187 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800188 const std::string& location,
189 uint32_t location_checksum,
190 const OatDexFile* oat_dex_file,
191 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700192 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800193 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800194 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700195 return OpenCommon(base,
196 size,
197 location,
198 location_checksum,
199 oat_dex_file,
200 verify,
201 verify_checksum,
202 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100203}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800204
Orion Hodsona4c2a052016-08-17 10:51:42 +0100205std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
206 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700207 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100208 bool verify,
209 bool verify_checksum,
210 std::string* error_msg) {
211 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700212 CHECK(map.get() != nullptr);
213 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
214 map->Size(),
215 location,
216 location_checksum,
217 kNoOatDexFile,
218 verify,
219 verify_checksum,
220 error_msg);
221 if (dex_file != nullptr) {
222 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100223 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800224 return dex_file;
225}
226
David Sehr733ddb22016-09-19 15:02:18 -0700227bool DexFile::Open(const char* filename,
228 const std::string& location,
229 bool verify_checksum,
230 std::string* error_msg,
231 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
232 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
233 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
234 uint32_t magic;
235 File fd = OpenAndReadMagic(filename, &magic, error_msg);
236 if (fd.Fd() == -1) {
237 DCHECK(!error_msg->empty());
238 return false;
239 }
240 if (IsZipMagic(magic)) {
241 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
242 }
243 if (IsDexMagic(magic)) {
244 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
245 location,
246 /* verify */ true,
247 verify_checksum,
248 error_msg));
249 if (dex_file.get() != nullptr) {
250 dex_files->push_back(std::move(dex_file));
251 return true;
252 } else {
253 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000254 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700255 }
David Sehr733ddb22016-09-19 15:02:18 -0700256 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
257 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700258}
259
David Sehr733ddb22016-09-19 15:02:18 -0700260std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
261 const std::string& location,
262 bool verify_checksum,
263 std::string* error_msg) {
264 ScopedTrace trace("Open dex file " + std::string(location));
265 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
266}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700267
Aart Bik37d6a3b2016-06-21 18:30:10 -0700268bool DexFile::OpenZip(int fd,
269 const std::string& location,
270 bool verify_checksum,
271 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800272 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800273 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700274 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700275 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700276 if (zip_archive.get() == nullptr) {
277 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700278 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700279 }
David Sehr733ddb22016-09-19 15:02:18 -0700280 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
281 location,
282 verify_checksum,
283 error_msg,
284 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800285}
286
David Sehr733ddb22016-09-19 15:02:18 -0700287std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
288 const std::string& location,
289 bool verify,
290 bool verify_checksum,
291 std::string* error_msg) {
292 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
293 CHECK(!location.empty());
294 std::unique_ptr<MemMap> map;
295 {
296 File delayed_close(fd, /* check_usage */ false);
297 struct stat sbuf;
298 memset(&sbuf, 0, sizeof(sbuf));
299 if (fstat(fd, &sbuf) == -1) {
300 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
301 strerror(errno));
302 return nullptr;
303 }
304 if (S_ISDIR(sbuf.st_mode)) {
305 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
306 return nullptr;
307 }
308 size_t length = sbuf.st_size;
309 map.reset(MemMap::MapFile(length,
310 PROT_READ,
311 MAP_PRIVATE,
312 fd,
313 0,
314 /*low_4gb*/false,
315 location.c_str(),
316 error_msg));
317 if (map == nullptr) {
318 DCHECK(!error_msg->empty());
319 return nullptr;
320 }
321 }
322
323 if (map->Size() < sizeof(DexFile::Header)) {
324 *error_msg = StringPrintf(
325 "DexFile: failed to open dex file '%s' that is too short to have a header",
326 location.c_str());
327 return nullptr;
328 }
329
330 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
331
332 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
333 map->Size(),
334 location,
335 dex_header->checksum_,
336 kNoOatDexFile,
337 verify,
338 verify_checksum,
339 error_msg);
340 if (dex_file != nullptr) {
341 dex_file->mem_map_.reset(map.release());
342 }
343
344 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800345}
346
David Sehr733ddb22016-09-19 15:02:18 -0700347std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
348 const char* entry_name,
349 const std::string& location,
350 bool verify_checksum,
351 std::string* error_msg,
352 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800353 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800354 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700355 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700356 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700357 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700359 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800360 if (zip_entry->GetUncompressedLength() == 0) {
361 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
362 *error_code = ZipOpenErrorCode::kDexFileError;
363 return nullptr;
364 }
Nicolas Geoffray960b2af2017-02-12 15:48:07 +0000365 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700366 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700367 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700370 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700371 }
David Sehr733ddb22016-09-19 15:02:18 -0700372 VerifyResult verify_result;
373 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
374 map->Size(),
375 location,
376 zip_entry->GetCrc32(),
377 kNoOatDexFile,
378 /* verify */ true,
379 verify_checksum,
380 error_msg,
381 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700382 if (dex_file == nullptr) {
383 if (verify_result == VerifyResult::kVerifyNotAttempted) {
384 *error_code = ZipOpenErrorCode::kDexFileError;
385 } else {
386 *error_code = ZipOpenErrorCode::kVerifyError;
387 }
388 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800389 }
David Sehr9fddd362016-09-22 14:05:37 -0700390 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700391 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700392 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700393 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700395 }
396 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700397 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700398 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700399 return nullptr;
400 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700401 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800402 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700403}
404
Andreas Gampe90e34042015-04-27 20:01:52 -0700405// Technically we do not have a limitation with respect to the number of dex files that can be in a
406// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
407// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
408// seems an excessive number.
409static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
410
David Sehr733ddb22016-09-19 15:02:18 -0700411bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
412 const std::string& location,
413 bool verify_checksum,
414 std::string* error_msg,
415 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800416 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700417 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700418 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700419 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
420 kClassesDex,
421 location,
422 verify_checksum,
423 error_msg,
424 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700425 if (dex_file.get() == nullptr) {
426 return false;
427 } else {
428 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800429 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700430
431 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700432
433 // We could try to avoid std::string allocations by working on a char array directly. As we
434 // do not expect a lot of iterations, this seems too involved and brittle.
435
Andreas Gampe90e34042015-04-27 20:01:52 -0700436 for (size_t i = 1; ; ++i) {
437 std::string name = GetMultiDexClassesDexName(i);
438 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700439 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
440 name.c_str(),
441 fake_location,
442 verify_checksum,
443 error_msg,
444 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700445 if (next_dex_file.get() == nullptr) {
446 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
447 LOG(WARNING) << error_msg;
448 }
449 break;
450 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800451 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700452 }
453
Andreas Gampe90e34042015-04-27 20:01:52 -0700454 if (i == kWarnOnManyDexFilesThreshold) {
455 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
456 << " dex files. Please consider coalescing and shrinking the number to "
457 " avoid runtime overhead.";
458 }
459
460 if (i == std::numeric_limits<size_t>::max()) {
461 LOG(ERROR) << "Overflow in number of dex files!";
462 break;
463 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700464 }
465
466 return true;
467 }
468}
469
David Sehr733ddb22016-09-19 15:02:18 -0700470std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
471 size_t size,
472 const std::string& location,
473 uint32_t location_checksum,
474 const OatDexFile* oat_dex_file,
475 bool verify,
476 bool verify_checksum,
477 std::string* error_msg,
478 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700479 if (verify_result != nullptr) {
480 *verify_result = VerifyResult::kVerifyNotAttempted;
481 }
David Sehr733ddb22016-09-19 15:02:18 -0700482 std::unique_ptr<DexFile> dex_file(new DexFile(base,
483 size,
484 location,
485 location_checksum,
486 oat_dex_file));
487 if (dex_file == nullptr) {
488 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
489 error_msg->c_str());
490 return nullptr;
491 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700492 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800493 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700494 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700495 }
David Sehr733ddb22016-09-19 15:02:18 -0700496 if (verify && !DexFileVerifier::Verify(dex_file.get(),
497 dex_file->Begin(),
498 dex_file->Size(),
499 location.c_str(),
500 verify_checksum,
501 error_msg)) {
502 if (verify_result != nullptr) {
503 *verify_result = VerifyResult::kVerifyFailed;
504 }
505 return nullptr;
506 }
507 if (verify_result != nullptr) {
508 *verify_result = VerifyResult::kVerifySucceeded;
509 }
510 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700511}
512
David Sehr733ddb22016-09-19 15:02:18 -0700513DexFile::DexFile(const uint8_t* base,
514 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800515 const std::string& location,
516 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700517 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800518 : begin_(base),
519 size_(size),
520 location_(location),
521 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800522 header_(reinterpret_cast<const Header*>(base)),
523 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
524 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
525 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
526 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
527 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700528 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000529 method_handles_(nullptr),
530 num_method_handles_(0),
531 call_site_ids_(nullptr),
532 num_call_site_ids_(0),
Richard Uhler07b3c232015-03-31 15:57:54 -0700533 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700534 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800535 CHECK_GT(size_, 0U) << GetLocation();
Orion Hodson12f4ff42017-01-13 16:43:12 +0000536 InitializeSectionsFromMapList();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800537}
538
Jesse Wilson6bf19152011-09-29 13:12:33 -0400539DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700540 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
541 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
542 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
543 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400544}
545
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700546bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700547 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700548 return false;
549 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700550 return true;
551}
552
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700553bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800554 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700555 std::ostringstream oss;
556 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800557 << " " << header_->magic_[0]
558 << " " << header_->magic_[1]
559 << " " << header_->magic_[2]
560 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700561 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700562 return false;
563 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800564 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700565 std::ostringstream oss;
566 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800567 << " " << header_->magic_[4]
568 << " " << header_->magic_[5]
569 << " " << header_->magic_[6]
570 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700571 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700572 return false;
573 }
574 return true;
575}
576
Orion Hodson12f4ff42017-01-13 16:43:12 +0000577void DexFile::InitializeSectionsFromMapList() {
578 const MapList* map_list = reinterpret_cast<const MapList*>(begin_ + header_->map_off_);
579 const size_t count = map_list->size_;
580
581 size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
582 if (header_->map_off_ >= map_limit || map_limit > size_) {
583 // Overflow or out out of bounds. The dex file verifier runs after
584 // this method and will reject the file as it is malformed.
585 return;
586 }
587
588 for (size_t i = 0; i < count; ++i) {
589 const MapItem& map_item = map_list->list_[i];
590 if (map_item.type_ == kDexTypeMethodHandleItem) {
591 method_handles_ = reinterpret_cast<const MethodHandleItem*>(begin_ + map_item.offset_);
592 num_method_handles_ = map_item.size_;
593 } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
594 call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(begin_ + map_item.offset_);
595 num_call_site_ids_ = map_item.size_;
596 }
597 }
598}
599
Ian Rogers13735952014-10-08 12:43:28 -0700600bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800601 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
602}
603
Ian Rogers13735952014-10-08 12:43:28 -0700604bool DexFile::IsVersionValid(const uint8_t* magic) {
605 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700606 for (uint32_t i = 0; i < kNumDexVersions; i++) {
607 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
608 return true;
609 }
610 }
611 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800612}
613
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700614uint32_t DexFile::Header::GetVersion() const {
615 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700616 return atoi(version);
617}
618
Andreas Gampea5b09a62016-11-17 15:21:22 -0800619const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700620 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100621 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700622 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700623 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700624 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700625 for (size_t i = 0; i < num_class_defs; ++i) {
626 const ClassDef& class_def = GetClassDef(i);
627 if (class_def.class_idx_ == type_idx) {
628 return &class_def;
629 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700630 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700631 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700632}
633
Alex Light9c20a142016-08-23 15:05:12 -0700634uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
635 uint32_t method_idx) const {
636 const uint8_t* class_data = GetClassData(class_def);
637 CHECK(class_data != nullptr);
638 ClassDataItemIterator it(*this, class_data);
639 // Skip fields
640 while (it.HasNextStaticField()) {
641 it.Next();
642 }
643 while (it.HasNextInstanceField()) {
644 it.Next();
645 }
646 while (it.HasNextDirectMethod()) {
647 if (it.GetMemberIndex() == method_idx) {
648 return it.GetMethodCodeItemOffset();
649 }
650 it.Next();
651 }
652 while (it.HasNextVirtualMethod()) {
653 if (it.GetMemberIndex() == method_idx) {
654 return it.GetMethodCodeItemOffset();
655 }
656 it.Next();
657 }
658 LOG(FATAL) << "Unable to find method " << method_idx;
659 UNREACHABLE();
660}
661
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800662const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100663 const DexFile::StringId& name,
664 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800665 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800666 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800667 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800668 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t lo = 0;
670 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800671 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700672 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800673 const DexFile::FieldId& field = GetFieldId(mid);
674 if (class_idx > field.class_idx_) {
675 lo = mid + 1;
676 } else if (class_idx < field.class_idx_) {
677 hi = mid - 1;
678 } else {
679 if (name_idx > field.name_idx_) {
680 lo = mid + 1;
681 } else if (name_idx < field.name_idx_) {
682 hi = mid - 1;
683 } else {
684 if (type_idx > field.type_idx_) {
685 lo = mid + 1;
686 } else if (type_idx < field.type_idx_) {
687 hi = mid - 1;
688 } else {
689 return &field;
690 }
691 }
692 }
693 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700694 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800695}
696
697const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700698 const DexFile::StringId& name,
699 const DexFile::ProtoId& signature) const {
700 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800701 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800702 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700703 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700704 int32_t lo = 0;
705 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700706 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700707 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700708 const DexFile::MethodId& method = GetMethodId(mid);
709 if (class_idx > method.class_idx_) {
710 lo = mid + 1;
711 } else if (class_idx < method.class_idx_) {
712 hi = mid - 1;
713 } else {
714 if (name_idx > method.name_idx_) {
715 lo = mid + 1;
716 } else if (name_idx < method.name_idx_) {
717 hi = mid - 1;
718 } else {
719 if (proto_idx > method.proto_idx_) {
720 lo = mid + 1;
721 } else if (proto_idx < method.proto_idx_) {
722 hi = mid - 1;
723 } else {
724 return &method;
725 }
726 }
727 }
728 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700730}
731
Ian Rogers637c65b2013-05-31 11:46:00 -0700732const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700733 int32_t lo = 0;
734 int32_t hi = NumStringIds() - 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;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800737 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700738 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700739 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
740 if (compare > 0) {
741 lo = mid + 1;
742 } else if (compare < 0) {
743 hi = mid - 1;
744 } else {
745 return &str_id;
746 }
747 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700748 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700749}
750
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300751const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
752 int32_t lo = 0;
753 int32_t hi = NumTypeIds() - 1;
754 while (hi >= lo) {
755 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800756 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300757 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
758 const char* str = GetStringData(str_id);
759 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
760 if (compare > 0) {
761 lo = mid + 1;
762 } else if (compare < 0) {
763 hi = mid - 1;
764 } else {
765 return &type_id;
766 }
767 }
768 return nullptr;
769}
770
Vladimir Markoa48aef42014-12-03 17:53:53 +0000771const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700772 int32_t lo = 0;
773 int32_t hi = NumStringIds() - 1;
774 while (hi >= lo) {
775 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800776 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700777 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000778 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700779 if (compare > 0) {
780 lo = mid + 1;
781 } else if (compare < 0) {
782 hi = mid - 1;
783 } else {
784 return &str_id;
785 }
786 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700787 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700788}
789
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800790const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700791 int32_t lo = 0;
792 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700793 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700794 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800795 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700796 if (string_idx > type_id.descriptor_idx_) {
797 lo = mid + 1;
798 } else if (string_idx < type_id.descriptor_idx_) {
799 hi = mid - 1;
800 } else {
801 return &type_id;
802 }
803 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700804 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700805}
806
Andreas Gampea5b09a62016-11-17 15:21:22 -0800807const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
808 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000809 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700810 int32_t lo = 0;
811 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700812 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700813 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700814 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800815 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700816 if (compare == 0) {
817 DexFileParameterIterator it(*this, proto);
818 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000819 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800820 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700821 it.Next();
822 i++;
823 }
824 if (compare == 0) {
825 if (it.HasNext()) {
826 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000827 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700828 compare = 1;
829 }
830 }
831 }
832 if (compare > 0) {
833 lo = mid + 1;
834 } else if (compare < 0) {
835 hi = mid - 1;
836 } else {
837 return &proto;
838 }
839 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700840 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700841}
842
843// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800844bool DexFile::CreateTypeList(const StringPiece& signature,
845 dex::TypeIndex* return_type_idx,
846 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700847 if (signature[0] != '(') {
848 return false;
849 }
850 size_t offset = 1;
851 size_t end = signature.size();
852 bool process_return = false;
853 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000854 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700855 char c = signature[offset];
856 offset++;
857 if (c == ')') {
858 process_return = true;
859 continue;
860 }
Ian Rogers0571d352011-11-03 19:51:38 -0700861 while (c == '[') { // process array prefix
862 if (offset >= end) { // expect some descriptor following [
863 return false;
864 }
865 c = signature[offset];
866 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700867 }
868 if (c == 'L') { // process type descriptors
869 do {
870 if (offset >= end) { // unexpected early termination of descriptor
871 return false;
872 }
873 c = signature[offset];
874 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700875 } while (c != ';');
876 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000877 // TODO: avoid creating a std::string just to get a 0-terminated char array
878 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700879 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700880 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700881 return false;
882 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800883 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700884 if (!process_return) {
885 param_type_idxs->push_back(type_idx);
886 } else {
887 *return_type_idx = type_idx;
888 return offset == end; // return true if the signature had reached a sensible end
889 }
890 }
891 return false; // failed to correctly parse return type
892}
893
Ian Rogersd91d6d62013-09-25 20:26:14 -0700894const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800895 dex::TypeIndex return_type_idx;
896 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700897 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
898 if (!success) {
899 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700900 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700901 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700902 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700903 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700904 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700905 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700906}
907
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700908int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700909 // Note: Signed type is important for max and min.
910 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700911 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700912
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700913 while (min <= max) {
914 int32_t mid = min + ((max - min) / 2);
915
916 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
917 uint32_t start = ti->start_addr_;
918 uint32_t end = start + ti->insn_count_;
919
Ian Rogers0571d352011-11-03 19:51:38 -0700920 if (address < start) {
921 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700922 } else if (address >= end) {
923 min = mid + 1;
924 } else { // We have a winner!
925 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700926 }
927 }
928 // No match.
929 return -1;
930}
931
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700932int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
933 int32_t try_item = FindTryItem(code_item, address);
934 if (try_item == -1) {
935 return -1;
936 } else {
937 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
938 }
939}
940
David Srbeckyb06e28e2015-12-10 13:15:00 +0000941bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
942 DexDebugNewLocalCb local_cb, void* context) const {
943 DCHECK(local_cb != nullptr);
944 if (code_item == nullptr) {
945 return false;
946 }
947 const uint8_t* stream = GetDebugInfoStream(code_item);
948 if (stream == nullptr) {
949 return false;
950 }
951 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700952
David Srbeckyb06e28e2015-12-10 13:15:00 +0000953 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800954 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000955 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
956 local_in_reg[arg_reg].name_ = "this";
957 local_in_reg[arg_reg].descriptor_ = descriptor;
958 local_in_reg[arg_reg].signature_ = nullptr;
959 local_in_reg[arg_reg].start_address_ = 0;
960 local_in_reg[arg_reg].reg_ = arg_reg;
961 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700962 arg_reg++;
963 }
964
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800965 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000966 DecodeUnsignedLeb128(&stream); // Line.
967 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
968 uint32_t i;
969 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700970 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700971 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800972 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000973 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700974 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000975 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700976 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800977 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000978 local_in_reg[arg_reg].descriptor_ = descriptor;
979 local_in_reg[arg_reg].signature_ = nullptr;
980 local_in_reg[arg_reg].start_address_ = 0;
981 local_in_reg[arg_reg].reg_ = arg_reg;
982 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700983 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700984 case 'D':
985 case 'J':
986 arg_reg += 2;
987 break;
988 default:
989 arg_reg += 1;
990 break;
991 }
992 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000993 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800994 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700995 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000996 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700997 }
998
David Srbeckyb06e28e2015-12-10 13:15:00 +0000999 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001000 for (;;) {
1001 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001002 switch (opcode) {
1003 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001004 // Emit all variables which are still alive at the end of the method.
1005 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
1006 if (local_in_reg[reg].is_live_) {
1007 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
1008 local_cb(context, local_in_reg[reg]);
1009 }
1010 }
1011 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001012 case DBG_ADVANCE_PC:
1013 address += DecodeUnsignedLeb128(&stream);
1014 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001015 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001016 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001019 case DBG_START_LOCAL_EXTENDED: {
1020 uint16_t reg = DecodeUnsignedLeb128(&stream);
1021 if (reg >= code_item->registers_size_) {
1022 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -08001023 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +00001024 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001025 }
1026
David Srbeckyb06e28e2015-12-10 13:15:00 +00001027 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1028 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
1029 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -07001030 if (opcode == DBG_START_LOCAL_EXTENDED) {
1031 signature_idx = DecodeUnsignedLeb128P1(&stream);
1032 }
1033
Shih-wei Liao195487c2011-08-20 13:29:04 -07001034 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +00001035 if (local_in_reg[reg].is_live_) {
1036 local_in_reg[reg].end_address_ = address;
1037 local_cb(context, local_in_reg[reg]);
1038 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001039
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001040 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -08001041 local_in_reg[reg].descriptor_ =
1042 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001043 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001044 local_in_reg[reg].start_address_ = address;
1045 local_in_reg[reg].reg_ = reg;
1046 local_in_reg[reg].is_live_ = true;
1047 break;
1048 }
1049 case DBG_END_LOCAL: {
1050 uint16_t reg = DecodeUnsignedLeb128(&stream);
1051 if (reg >= code_item->registers_size_) {
1052 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1053 << code_item->registers_size_ << ") in " << GetLocation();
1054 return false;
1055 }
1056 if (!local_in_reg[reg].is_live_) {
1057 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
1058 return false;
1059 }
1060 local_in_reg[reg].end_address_ = address;
1061 local_cb(context, local_in_reg[reg]);
1062 local_in_reg[reg].is_live_ = false;
1063 break;
1064 }
1065 case DBG_RESTART_LOCAL: {
1066 uint16_t reg = DecodeUnsignedLeb128(&stream);
1067 if (reg >= code_item->registers_size_) {
1068 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1069 << code_item->registers_size_ << ") in " << GetLocation();
1070 return false;
1071 }
1072 // If the register is live, the "restart" is superfluous,
1073 // and we don't want to mess with the existing start address.
1074 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001075 local_in_reg[reg].start_address_ = address;
1076 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001077 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001078 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001079 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001080 case DBG_SET_PROLOGUE_END:
1081 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001082 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001083 case DBG_SET_FILE:
1084 DecodeUnsignedLeb128P1(&stream); // name.
1085 break;
1086 default:
1087 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1088 break;
1089 }
1090 }
1091}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001092
David Srbeckyb06e28e2015-12-10 13:15:00 +00001093bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1094 void* context) const {
1095 DCHECK(position_cb != nullptr);
1096 if (code_item == nullptr) {
1097 return false;
1098 }
1099 const uint8_t* stream = GetDebugInfoStream(code_item);
1100 if (stream == nullptr) {
1101 return false;
1102 }
1103
1104 PositionInfo entry = PositionInfo();
1105 entry.line_ = DecodeUnsignedLeb128(&stream);
1106 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1107 for (uint32_t i = 0; i < parameters_size; ++i) {
1108 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1109 }
1110
1111 for (;;) {
1112 uint8_t opcode = *stream++;
1113 switch (opcode) {
1114 case DBG_END_SEQUENCE:
1115 return true; // end of stream.
1116 case DBG_ADVANCE_PC:
1117 entry.address_ += DecodeUnsignedLeb128(&stream);
1118 break;
1119 case DBG_ADVANCE_LINE:
1120 entry.line_ += DecodeSignedLeb128(&stream);
1121 break;
1122 case DBG_START_LOCAL:
1123 DecodeUnsignedLeb128(&stream); // reg.
1124 DecodeUnsignedLeb128P1(&stream); // name.
1125 DecodeUnsignedLeb128P1(&stream); // descriptor.
1126 break;
1127 case DBG_START_LOCAL_EXTENDED:
1128 DecodeUnsignedLeb128(&stream); // reg.
1129 DecodeUnsignedLeb128P1(&stream); // name.
1130 DecodeUnsignedLeb128P1(&stream); // descriptor.
1131 DecodeUnsignedLeb128P1(&stream); // signature.
1132 break;
1133 case DBG_END_LOCAL:
1134 case DBG_RESTART_LOCAL:
1135 DecodeUnsignedLeb128(&stream); // reg.
1136 break;
1137 case DBG_SET_PROLOGUE_END:
1138 entry.prologue_end_ = true;
1139 break;
1140 case DBG_SET_EPILOGUE_BEGIN:
1141 entry.epilogue_begin_ = true;
1142 break;
1143 case DBG_SET_FILE: {
1144 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001145 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001146 break;
1147 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001148 default: {
1149 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001150 entry.address_ += adjopcode / DBG_LINE_RANGE;
1151 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1152 if (position_cb(context, entry)) {
1153 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001154 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001155 entry.prologue_end_ = false;
1156 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001157 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001158 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001159 }
1160 }
1161}
1162
David Srbeckyb06e28e2015-12-10 13:15:00 +00001163bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001164 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001165
1166 // We know that this callback will be called in
1167 // ascending address order, so keep going until we find
1168 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001169 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001170 // The line number from the previous positions callback
1171 // wil be the final result.
1172 return true;
1173 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001174 context->line_num_ = entry.line_;
1175 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001176 }
1177}
1178
Andreas Gampe833a4852014-05-21 18:46:59 -07001179bool DexFile::IsMultiDexLocation(const char* location) {
1180 return strrchr(location, kMultiDexSeparator) != nullptr;
1181}
1182
Andreas Gampe90e34042015-04-27 20:01:52 -07001183std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1184 if (index == 0) {
1185 return "classes.dex";
1186 } else {
1187 return StringPrintf("classes%zu.dex", index + 1);
1188 }
1189}
1190
1191std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1192 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001193 return dex_location;
1194 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001195 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001196 }
1197}
1198
1199std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1200 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001201 std::string base_location = GetBaseLocation(dex_location);
1202 const char* suffix = dex_location + base_location.size();
1203 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1204 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1205 if (path != nullptr && path.get() != base_location) {
1206 return std::string(path.get()) + suffix;
1207 } else if (suffix[0] == 0) {
1208 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001209 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001210 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001211 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001212}
1213
Jeff Hao13e748b2015-08-25 20:44:19 +00001214// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001215int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001216 int32_t val = 0;
1217 for (int i = zwidth; i >= 0; --i) {
1218 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1219 }
1220 val >>= (3 - zwidth) * 8;
1221 return val;
1222}
1223
1224// Read an unsigned integer. "zwidth" is the zero-based byte count,
1225// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001226uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001227 uint32_t val = 0;
1228 for (int i = zwidth; i >= 0; --i) {
1229 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1230 }
1231 if (!fill_on_right) {
1232 val >>= (3 - zwidth) * 8;
1233 }
1234 return val;
1235}
1236
1237// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001238int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001239 int64_t val = 0;
1240 for (int i = zwidth; i >= 0; --i) {
1241 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1242 }
1243 val >>= (7 - zwidth) * 8;
1244 return val;
1245}
1246
1247// Read an unsigned long. "zwidth" is the zero-based byte count,
1248// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001249uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001250 uint64_t val = 0;
1251 for (int i = zwidth; i >= 0; --i) {
1252 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1253 }
1254 if (!fill_on_right) {
1255 val >>= (7 - zwidth) * 8;
1256 }
1257 return val;
1258}
1259
David Sehr709b0702016-10-13 09:12:37 -07001260std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1261 if (method_idx >= NumMethodIds()) {
1262 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1263 }
1264 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1265 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1266 result += '.';
1267 result += GetMethodName(method_id);
1268 if (with_signature) {
1269 const Signature signature = GetMethodSignature(method_id);
1270 std::string sig_as_string(signature.ToString());
1271 if (signature == Signature::NoSignature()) {
1272 return result + sig_as_string;
1273 }
1274 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1275 PrettyArguments(sig_as_string.c_str());
1276 }
1277 return result;
1278}
1279
1280std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1281 if (field_idx >= NumFieldIds()) {
1282 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1283 }
1284 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1285 std::string result;
1286 if (with_type) {
1287 result += GetFieldTypeDescriptor(field_id);
1288 result += ' ';
1289 }
1290 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1291 result += '.';
1292 result += GetFieldName(field_id);
1293 return result;
1294}
1295
Andreas Gampea5b09a62016-11-17 15:21:22 -08001296std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1297 if (type_idx.index_ >= NumTypeIds()) {
1298 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001299 }
1300 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1301 return PrettyDescriptor(GetTypeDescriptor(type_id));
1302}
1303
Jeff Hao3d080862016-05-26 18:39:17 -07001304// Checks that visibility is as expected. Includes special behavior for M and
1305// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001306std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1307 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1308 dex_file.GetLocation().c_str(),
1309 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1310 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1311 return os;
1312}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001313
Ian Rogersd91d6d62013-09-25 20:26:14 -07001314std::string Signature::ToString() const {
1315 if (dex_file_ == nullptr) {
1316 CHECK(proto_id_ == nullptr);
1317 return "<no signature>";
1318 }
1319 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1320 std::string result;
1321 if (params == nullptr) {
1322 result += "()";
1323 } else {
1324 result += "(";
1325 for (uint32_t i = 0; i < params->Size(); ++i) {
1326 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1327 }
1328 result += ")";
1329 }
1330 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1331 return result;
1332}
1333
Orion Hodson6c4921b2016-09-21 15:41:06 +01001334uint32_t Signature::GetNumberOfParameters() const {
1335 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1336 return (params != nullptr) ? params->Size() : 0;
1337}
1338
1339bool Signature::IsVoid() const {
1340 const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
1341 return strcmp(return_type, "V") == 0;
1342}
1343
Vladimir Markod9cffea2013-11-25 15:08:02 +00001344bool Signature::operator==(const StringPiece& rhs) const {
1345 if (dex_file_ == nullptr) {
1346 return false;
1347 }
1348 StringPiece tail(rhs);
1349 if (!tail.starts_with("(")) {
1350 return false; // Invalid signature
1351 }
1352 tail.remove_prefix(1); // "(";
1353 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1354 if (params != nullptr) {
1355 for (uint32_t i = 0; i < params->Size(); ++i) {
1356 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1357 if (!tail.starts_with(param)) {
1358 return false;
1359 }
1360 tail.remove_prefix(param.length());
1361 }
1362 }
1363 if (!tail.starts_with(")")) {
1364 return false;
1365 }
1366 tail.remove_prefix(1); // ")";
1367 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1368}
1369
Ian Rogersd91d6d62013-09-25 20:26:14 -07001370std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1371 return os << sig.ToString();
1372}
1373
Ian Rogers0571d352011-11-03 19:51:38 -07001374// Decodes the header section from the class data bytes.
1375void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001376 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001377 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1378 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1379 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1380 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1381}
1382
1383void ClassDataItemIterator::ReadClassDataField() {
1384 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1385 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001386 // The user of the iterator is responsible for checking if there
1387 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001388}
1389
1390void ClassDataItemIterator::ReadClassDataMethod() {
1391 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1392 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1393 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001394 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001395 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001396 }
Ian Rogers0571d352011-11-03 19:51:38 -07001397}
1398
Orion Hodson12f4ff42017-01-13 16:43:12 +00001399EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
1400 const uint8_t* array_data)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001401 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001402 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001403 pos_(-1),
Orion Hodson12f4ff42017-01-13 16:43:12 +00001404 ptr_(array_data),
David Sehr9323e6e2016-09-13 08:58:35 -07001405 type_(kByte) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001406 array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001407 if (array_size_ > 0) {
1408 Next();
1409 }
1410}
1411
Orion Hodson12f4ff42017-01-13 16:43:12 +00001412void EncodedArrayValueIterator::Next() {
Ian Rogers0571d352011-11-03 19:51:38 -07001413 pos_++;
1414 if (pos_ >= array_size_) {
1415 return;
1416 }
Ian Rogers13735952014-10-08 12:43:28 -07001417 uint8_t value_type = *ptr_++;
1418 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001419 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001420 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001421 switch (type_) {
1422 case kBoolean:
1423 jval_.i = (value_arg != 0) ? 1 : 0;
1424 width = 0;
1425 break;
1426 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001427 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001428 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001429 break;
1430 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001431 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001432 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001433 break;
1434 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001435 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001436 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001437 break;
1438 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001439 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001440 break;
1441 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001442 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001443 break;
1444 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001445 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001446 break;
1447 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001448 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001449 break;
1450 case kString:
1451 case kType:
Orion Hodson12f4ff42017-01-13 16:43:12 +00001452 case kMethodType:
1453 case kMethodHandle:
David Sehr9323e6e2016-09-13 08:58:35 -07001454 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001455 break;
1456 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001457 case kMethod:
1458 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001459 case kArray:
1460 case kAnnotation:
1461 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001462 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001463 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001464 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001465 width = 0;
1466 break;
1467 default:
1468 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001469 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001470 }
1471 ptr_ += width;
1472}
1473
Ian Rogers0571d352011-11-03 19:51:38 -07001474CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1475 handler_.address_ = -1;
1476 int32_t offset = -1;
1477
1478 // Short-circuit the overwhelmingly common cases.
1479 switch (code_item.tries_size_) {
1480 case 0:
1481 break;
1482 case 1: {
1483 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1484 uint32_t start = tries->start_addr_;
1485 if (address >= start) {
1486 uint32_t end = start + tries->insn_count_;
1487 if (address < end) {
1488 offset = tries->handler_off_;
1489 }
1490 }
1491 break;
1492 }
1493 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001494 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001495 }
Logan Chien736df022012-04-27 16:25:57 +08001496 Init(code_item, offset);
1497}
1498
1499CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1500 const DexFile::TryItem& try_item) {
1501 handler_.address_ = -1;
1502 Init(code_item, try_item.handler_off_);
1503}
1504
1505void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1506 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001507 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001508 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001509 } else {
1510 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001511 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001512 remaining_count_ = -1;
1513 catch_all_ = false;
1514 DCHECK(!HasNext());
1515 }
1516}
1517
Ian Rogers13735952014-10-08 12:43:28 -07001518void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001519 current_data_ = handler_data;
1520 remaining_count_ = DecodeSignedLeb128(&current_data_);
1521
1522 // If remaining_count_ is non-positive, then it is the negative of
1523 // the number of catch types, and the catches are followed by a
1524 // catch-all handler.
1525 if (remaining_count_ <= 0) {
1526 catch_all_ = true;
1527 remaining_count_ = -remaining_count_;
1528 } else {
1529 catch_all_ = false;
1530 }
1531 Next();
1532}
1533
1534void CatchHandlerIterator::Next() {
1535 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001536 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001537 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1538 remaining_count_--;
1539 return;
1540 }
1541
1542 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001543 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001544 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1545 catch_all_ = false;
1546 return;
1547 }
1548
1549 // no more handler
1550 remaining_count_ = -1;
1551}
1552
Andreas Gampea5b09a62016-11-17 15:21:22 -08001553namespace dex {
1554
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001555std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1556 os << "StringIndex[" << index.index_ << "]";
1557 return os;
1558}
1559
Andreas Gampea5b09a62016-11-17 15:21:22 -08001560std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1561 os << "TypeIndex[" << index.index_ << "]";
1562 return os;
1563}
1564
1565} // namespace dex
1566
Carl Shapiro1fb86202011-06-27 17:43:13 -07001567} // namespace art