blob: 35e9d5db293f3f63b8d0d62a805aeec861d0bd33 [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
Richard Uhler69bcf2c2017-01-24 10:25:21 +000075bool DexFile::GetMultiDexChecksums(const char* filename,
76 std::vector<uint32_t>* checksums,
77 std::string* error_msg) {
78 CHECK(checksums != nullptr);
79 uint32_t magic;
80
81 File fd = OpenAndReadMagic(filename, &magic, error_msg);
Andreas Gampe43e10b02016-07-15 17:17:34 -070082 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070083 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070084 return false;
85 }
86 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070087 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070088 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070089 if (zip_archive.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +000090 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", filename,
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080091 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080092 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070093 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +000094
95 uint32_t i = 0;
96 std::string zip_entry_name = GetMultiDexClassesDexName(i++);
97 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name.c_str(), error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070098 if (zip_entry.get() == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +000099 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", filename,
100 zip_entry_name.c_str(), error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800101 return false;
102 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000103
104 do {
105 checksums->push_back(zip_entry->GetCrc32());
106 zip_entry_name = DexFile::GetMultiDexClassesDexName(i++);
107 zip_entry.reset(zip_archive->Find(zip_entry_name.c_str(), error_msg));
108 } while (zip_entry.get() != nullptr);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800109 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700110 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700111 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700112 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700113 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700114 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return false;
116 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000117 checksums->push_back(dex_file->GetHeader().checksum_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 return true;
119 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700120 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700122}
123
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800124int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700125 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800126 return 0;
127 } else {
128 return mem_map_->GetProtect();
129 }
130}
131
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200132bool DexFile::IsReadOnly() const {
133 return GetPermissions() == PROT_READ;
134}
135
Brian Carlstrome0948e12013-08-29 09:36:15 -0700136bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200137 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700138 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200139 return false;
140 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700141 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200142 }
143}
144
Brian Carlstrome0948e12013-08-29 09:36:15 -0700145bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200146 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700147 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200148 return false;
149 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700150 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200151 }
152}
153
David Sehr733ddb22016-09-19 15:02:18 -0700154
155std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base,
156 size_t size,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800157 const std::string& location,
158 uint32_t location_checksum,
159 const OatDexFile* oat_dex_file,
160 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700161 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800162 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800163 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700164 return OpenCommon(base,
165 size,
166 location,
167 location_checksum,
168 oat_dex_file,
169 verify,
170 verify_checksum,
171 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100172}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800173
Orion Hodsona4c2a052016-08-17 10:51:42 +0100174std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
175 uint32_t location_checksum,
David Sehr733ddb22016-09-19 15:02:18 -0700176 std::unique_ptr<MemMap> map,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100177 bool verify,
178 bool verify_checksum,
179 std::string* error_msg) {
180 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
David Sehr733ddb22016-09-19 15:02:18 -0700181 CHECK(map.get() != nullptr);
Jeff Hao41b2f532017-03-02 16:36:31 -0800182
183 if (map->Size() < sizeof(DexFile::Header)) {
184 *error_msg = StringPrintf(
185 "DexFile: failed to open dex file '%s' that is too short to have a header",
186 location.c_str());
187 return nullptr;
188 }
189
David Sehr733ddb22016-09-19 15:02:18 -0700190 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
191 map->Size(),
192 location,
193 location_checksum,
194 kNoOatDexFile,
195 verify,
196 verify_checksum,
197 error_msg);
198 if (dex_file != nullptr) {
199 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100200 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800201 return dex_file;
202}
203
David Sehr733ddb22016-09-19 15:02:18 -0700204bool DexFile::Open(const char* filename,
205 const std::string& location,
206 bool verify_checksum,
207 std::string* error_msg,
208 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
209 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
210 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
211 uint32_t magic;
212 File fd = OpenAndReadMagic(filename, &magic, error_msg);
213 if (fd.Fd() == -1) {
214 DCHECK(!error_msg->empty());
215 return false;
216 }
217 if (IsZipMagic(magic)) {
218 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
219 }
220 if (IsDexMagic(magic)) {
221 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
222 location,
223 /* verify */ true,
224 verify_checksum,
225 error_msg));
226 if (dex_file.get() != nullptr) {
227 dex_files->push_back(std::move(dex_file));
228 return true;
229 } else {
230 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000231 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700232 }
David Sehr733ddb22016-09-19 15:02:18 -0700233 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
234 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700235}
236
David Sehr733ddb22016-09-19 15:02:18 -0700237std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
238 const std::string& location,
239 bool verify_checksum,
240 std::string* error_msg) {
241 ScopedTrace trace("Open dex file " + std::string(location));
242 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
243}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700244
Aart Bik37d6a3b2016-06-21 18:30:10 -0700245bool DexFile::OpenZip(int fd,
246 const std::string& location,
247 bool verify_checksum,
248 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800249 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800250 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700251 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700252 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700253 if (zip_archive.get() == nullptr) {
254 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700255 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700256 }
David Sehr733ddb22016-09-19 15:02:18 -0700257 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
258 location,
259 verify_checksum,
260 error_msg,
261 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800262}
263
David Sehr733ddb22016-09-19 15:02:18 -0700264std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
265 const std::string& location,
266 bool verify,
267 bool verify_checksum,
268 std::string* error_msg) {
269 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
270 CHECK(!location.empty());
271 std::unique_ptr<MemMap> map;
272 {
273 File delayed_close(fd, /* check_usage */ false);
274 struct stat sbuf;
275 memset(&sbuf, 0, sizeof(sbuf));
276 if (fstat(fd, &sbuf) == -1) {
277 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
278 strerror(errno));
279 return nullptr;
280 }
281 if (S_ISDIR(sbuf.st_mode)) {
282 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
283 return nullptr;
284 }
285 size_t length = sbuf.st_size;
286 map.reset(MemMap::MapFile(length,
287 PROT_READ,
288 MAP_PRIVATE,
289 fd,
290 0,
291 /*low_4gb*/false,
292 location.c_str(),
293 error_msg));
294 if (map == nullptr) {
295 DCHECK(!error_msg->empty());
296 return nullptr;
297 }
298 }
299
300 if (map->Size() < sizeof(DexFile::Header)) {
301 *error_msg = StringPrintf(
302 "DexFile: failed to open dex file '%s' that is too short to have a header",
303 location.c_str());
304 return nullptr;
305 }
306
307 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
308
309 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
310 map->Size(),
311 location,
312 dex_header->checksum_,
313 kNoOatDexFile,
314 verify,
315 verify_checksum,
316 error_msg);
317 if (dex_file != nullptr) {
318 dex_file->mem_map_.reset(map.release());
319 }
320
321 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800322}
323
David Sehr733ddb22016-09-19 15:02:18 -0700324std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
325 const char* entry_name,
326 const std::string& location,
327 bool verify_checksum,
328 std::string* error_msg,
329 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800330 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800331 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700332 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700333 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700334 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700335 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700336 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800337 if (zip_entry->GetUncompressedLength() == 0) {
338 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
339 *error_code = ZipOpenErrorCode::kDexFileError;
340 return nullptr;
341 }
Igor Murashkin271a0f82017-02-14 21:14:17 +0000342
343 std::unique_ptr<MemMap> map;
344 if (zip_entry->IsUncompressed()) {
345 if (!zip_entry->IsAlignedTo(alignof(Header))) {
346 // Do not mmap unaligned ZIP entries because
347 // doing so would fail dex verification which requires 4 byte alignment.
348 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
349 << "please zipalign to " << alignof(Header) << " bytes. "
350 << "Falling back to extracting file.";
351 } else {
352 // Map uncompressed files within zip as file-backed to avoid a dirty copy.
353 map.reset(zip_entry->MapDirectlyFromFile(location.c_str(), /*out*/error_msg));
354 if (map == nullptr) {
355 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
356 << "is your ZIP file corrupted? Falling back to extraction.";
357 // Try again with Extraction which still has a chance of recovery.
358 }
359 }
360 }
361
362 if (map == nullptr) {
363 // Default path for compressed ZIP entries,
364 // and fallback for stored ZIP entries.
365 map.reset(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
366 }
367
David Sehr9fddd362016-09-22 14:05:37 -0700368 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700370 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700371 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700372 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700373 }
David Sehr733ddb22016-09-19 15:02:18 -0700374 VerifyResult verify_result;
375 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
376 map->Size(),
377 location,
378 zip_entry->GetCrc32(),
379 kNoOatDexFile,
380 /* verify */ true,
381 verify_checksum,
382 error_msg,
383 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700384 if (dex_file == nullptr) {
385 if (verify_result == VerifyResult::kVerifyNotAttempted) {
386 *error_code = ZipOpenErrorCode::kDexFileError;
387 } else {
388 *error_code = ZipOpenErrorCode::kVerifyError;
389 }
390 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800391 }
David Sehr9fddd362016-09-22 14:05:37 -0700392 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700393 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700395 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700396 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700397 }
398 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700399 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700400 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700401 return nullptr;
402 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700403 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800404 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700405}
406
Andreas Gampe90e34042015-04-27 20:01:52 -0700407// Technically we do not have a limitation with respect to the number of dex files that can be in a
408// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
409// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
410// seems an excessive number.
411static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
412
David Sehr733ddb22016-09-19 15:02:18 -0700413bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
414 const std::string& location,
415 bool verify_checksum,
416 std::string* error_msg,
417 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800418 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700420 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700421 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
422 kClassesDex,
423 location,
424 verify_checksum,
425 error_msg,
426 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700427 if (dex_file.get() == nullptr) {
428 return false;
429 } else {
430 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800431 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700432
433 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700434
435 // We could try to avoid std::string allocations by working on a char array directly. As we
436 // do not expect a lot of iterations, this seems too involved and brittle.
437
Andreas Gampe90e34042015-04-27 20:01:52 -0700438 for (size_t i = 1; ; ++i) {
439 std::string name = GetMultiDexClassesDexName(i);
440 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700441 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
442 name.c_str(),
443 fake_location,
444 verify_checksum,
445 error_msg,
446 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700447 if (next_dex_file.get() == nullptr) {
448 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
David Sehrc9229222017-02-14 10:57:47 -0800449 LOG(WARNING) << "Zip open failed: " << *error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700450 }
451 break;
452 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800453 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700454 }
455
Andreas Gampe90e34042015-04-27 20:01:52 -0700456 if (i == kWarnOnManyDexFilesThreshold) {
457 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
458 << " dex files. Please consider coalescing and shrinking the number to "
459 " avoid runtime overhead.";
460 }
461
462 if (i == std::numeric_limits<size_t>::max()) {
463 LOG(ERROR) << "Overflow in number of dex files!";
464 break;
465 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700466 }
467
468 return true;
469 }
470}
471
David Sehr733ddb22016-09-19 15:02:18 -0700472std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
473 size_t size,
474 const std::string& location,
475 uint32_t location_checksum,
476 const OatDexFile* oat_dex_file,
477 bool verify,
478 bool verify_checksum,
479 std::string* error_msg,
480 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700481 if (verify_result != nullptr) {
482 *verify_result = VerifyResult::kVerifyNotAttempted;
483 }
David Sehr733ddb22016-09-19 15:02:18 -0700484 std::unique_ptr<DexFile> dex_file(new DexFile(base,
485 size,
486 location,
487 location_checksum,
488 oat_dex_file));
489 if (dex_file == nullptr) {
490 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
491 error_msg->c_str());
492 return nullptr;
493 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700494 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800495 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700496 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700497 }
David Sehr733ddb22016-09-19 15:02:18 -0700498 if (verify && !DexFileVerifier::Verify(dex_file.get(),
499 dex_file->Begin(),
500 dex_file->Size(),
501 location.c_str(),
502 verify_checksum,
503 error_msg)) {
504 if (verify_result != nullptr) {
505 *verify_result = VerifyResult::kVerifyFailed;
506 }
507 return nullptr;
508 }
509 if (verify_result != nullptr) {
510 *verify_result = VerifyResult::kVerifySucceeded;
511 }
512 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700513}
514
David Sehr733ddb22016-09-19 15:02:18 -0700515DexFile::DexFile(const uint8_t* base,
516 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800517 const std::string& location,
518 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700519 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800520 : begin_(base),
521 size_(size),
522 location_(location),
523 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800524 header_(reinterpret_cast<const Header*>(base)),
525 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
526 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
527 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
528 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
529 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700530 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000531 method_handles_(nullptr),
532 num_method_handles_(0),
533 call_site_ids_(nullptr),
534 num_call_site_ids_(0),
Richard Uhler07b3c232015-03-31 15:57:54 -0700535 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700536 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800537 CHECK_GT(size_, 0U) << GetLocation();
Igor Murashkin271a0f82017-02-14 21:14:17 +0000538 // Check base (=header) alignment.
539 // Must be 4-byte aligned to avoid undefined behavior when accessing
540 // any of the sections via a pointer.
541 CHECK_ALIGNED(begin_, alignof(Header));
542
Orion Hodson12f4ff42017-01-13 16:43:12 +0000543 InitializeSectionsFromMapList();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800544}
545
Jesse Wilson6bf19152011-09-29 13:12:33 -0400546DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700547 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
548 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
549 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
550 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400551}
552
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700553bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700554 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700555 return false;
556 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700557 return true;
558}
559
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700560bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800561 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700562 std::ostringstream oss;
563 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800564 << " " << header_->magic_[0]
565 << " " << header_->magic_[1]
566 << " " << header_->magic_[2]
567 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700568 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700569 return false;
570 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800571 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700572 std::ostringstream oss;
573 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800574 << " " << header_->magic_[4]
575 << " " << header_->magic_[5]
576 << " " << header_->magic_[6]
577 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700578 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700579 return false;
580 }
581 return true;
582}
583
Orion Hodson12f4ff42017-01-13 16:43:12 +0000584void DexFile::InitializeSectionsFromMapList() {
585 const MapList* map_list = reinterpret_cast<const MapList*>(begin_ + header_->map_off_);
586 const size_t count = map_list->size_;
587
588 size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
589 if (header_->map_off_ >= map_limit || map_limit > size_) {
590 // Overflow or out out of bounds. The dex file verifier runs after
591 // this method and will reject the file as it is malformed.
592 return;
593 }
594
595 for (size_t i = 0; i < count; ++i) {
596 const MapItem& map_item = map_list->list_[i];
597 if (map_item.type_ == kDexTypeMethodHandleItem) {
598 method_handles_ = reinterpret_cast<const MethodHandleItem*>(begin_ + map_item.offset_);
599 num_method_handles_ = map_item.size_;
600 } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
601 call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(begin_ + map_item.offset_);
602 num_call_site_ids_ = map_item.size_;
603 }
604 }
605}
606
Ian Rogers13735952014-10-08 12:43:28 -0700607bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800608 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
609}
610
Ian Rogers13735952014-10-08 12:43:28 -0700611bool DexFile::IsVersionValid(const uint8_t* magic) {
612 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700613 for (uint32_t i = 0; i < kNumDexVersions; i++) {
614 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
615 return true;
616 }
617 }
618 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800619}
620
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700621uint32_t DexFile::Header::GetVersion() const {
622 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700623 return atoi(version);
624}
625
Andreas Gampea5b09a62016-11-17 15:21:22 -0800626const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700627 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100628 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700629 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700630 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700631 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700632 for (size_t i = 0; i < num_class_defs; ++i) {
633 const ClassDef& class_def = GetClassDef(i);
634 if (class_def.class_idx_ == type_idx) {
635 return &class_def;
636 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700637 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700638 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700639}
640
Alex Light9c20a142016-08-23 15:05:12 -0700641uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
642 uint32_t method_idx) const {
643 const uint8_t* class_data = GetClassData(class_def);
644 CHECK(class_data != nullptr);
645 ClassDataItemIterator it(*this, class_data);
646 // Skip fields
647 while (it.HasNextStaticField()) {
648 it.Next();
649 }
650 while (it.HasNextInstanceField()) {
651 it.Next();
652 }
653 while (it.HasNextDirectMethod()) {
654 if (it.GetMemberIndex() == method_idx) {
655 return it.GetMethodCodeItemOffset();
656 }
657 it.Next();
658 }
659 while (it.HasNextVirtualMethod()) {
660 if (it.GetMemberIndex() == method_idx) {
661 return it.GetMethodCodeItemOffset();
662 }
663 it.Next();
664 }
665 LOG(FATAL) << "Unable to find method " << method_idx;
666 UNREACHABLE();
667}
668
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800669const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100670 const DexFile::StringId& name,
671 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800672 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800673 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800674 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800675 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700676 int32_t lo = 0;
677 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800678 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700679 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800680 const DexFile::FieldId& field = GetFieldId(mid);
681 if (class_idx > field.class_idx_) {
682 lo = mid + 1;
683 } else if (class_idx < field.class_idx_) {
684 hi = mid - 1;
685 } else {
686 if (name_idx > field.name_idx_) {
687 lo = mid + 1;
688 } else if (name_idx < field.name_idx_) {
689 hi = mid - 1;
690 } else {
691 if (type_idx > field.type_idx_) {
692 lo = mid + 1;
693 } else if (type_idx < field.type_idx_) {
694 hi = mid - 1;
695 } else {
696 return &field;
697 }
698 }
699 }
700 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700701 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800702}
703
704const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700705 const DexFile::StringId& name,
706 const DexFile::ProtoId& signature) const {
707 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800708 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800709 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700710 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700711 int32_t lo = 0;
712 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700713 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700714 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700715 const DexFile::MethodId& method = GetMethodId(mid);
716 if (class_idx > method.class_idx_) {
717 lo = mid + 1;
718 } else if (class_idx < method.class_idx_) {
719 hi = mid - 1;
720 } else {
721 if (name_idx > method.name_idx_) {
722 lo = mid + 1;
723 } else if (name_idx < method.name_idx_) {
724 hi = mid - 1;
725 } else {
726 if (proto_idx > method.proto_idx_) {
727 lo = mid + 1;
728 } else if (proto_idx < method.proto_idx_) {
729 hi = mid - 1;
730 } else {
731 return &method;
732 }
733 }
734 }
735 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700736 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700737}
738
Ian Rogers637c65b2013-05-31 11:46:00 -0700739const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700740 int32_t lo = 0;
741 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700742 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700743 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800744 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700745 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700746 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
747 if (compare > 0) {
748 lo = mid + 1;
749 } else if (compare < 0) {
750 hi = mid - 1;
751 } else {
752 return &str_id;
753 }
754 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700755 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700756}
757
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300758const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
759 int32_t lo = 0;
760 int32_t hi = NumTypeIds() - 1;
761 while (hi >= lo) {
762 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800763 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300764 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
765 const char* str = GetStringData(str_id);
766 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
767 if (compare > 0) {
768 lo = mid + 1;
769 } else if (compare < 0) {
770 hi = mid - 1;
771 } else {
772 return &type_id;
773 }
774 }
775 return nullptr;
776}
777
Vladimir Markoa48aef42014-12-03 17:53:53 +0000778const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700779 int32_t lo = 0;
780 int32_t hi = NumStringIds() - 1;
781 while (hi >= lo) {
782 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800783 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700784 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000785 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700786 if (compare > 0) {
787 lo = mid + 1;
788 } else if (compare < 0) {
789 hi = mid - 1;
790 } else {
791 return &str_id;
792 }
793 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700794 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700795}
796
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800797const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700798 int32_t lo = 0;
799 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700800 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700801 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800802 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700803 if (string_idx > type_id.descriptor_idx_) {
804 lo = mid + 1;
805 } else if (string_idx < type_id.descriptor_idx_) {
806 hi = mid - 1;
807 } else {
808 return &type_id;
809 }
810 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700811 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700812}
813
Andreas Gampea5b09a62016-11-17 15:21:22 -0800814const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
815 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000816 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700817 int32_t lo = 0;
818 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700819 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700820 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700821 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800822 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700823 if (compare == 0) {
824 DexFileParameterIterator it(*this, proto);
825 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000826 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800827 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700828 it.Next();
829 i++;
830 }
831 if (compare == 0) {
832 if (it.HasNext()) {
833 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000834 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700835 compare = 1;
836 }
837 }
838 }
839 if (compare > 0) {
840 lo = mid + 1;
841 } else if (compare < 0) {
842 hi = mid - 1;
843 } else {
844 return &proto;
845 }
846 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700847 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700848}
849
850// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800851bool DexFile::CreateTypeList(const StringPiece& signature,
852 dex::TypeIndex* return_type_idx,
853 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700854 if (signature[0] != '(') {
855 return false;
856 }
857 size_t offset = 1;
858 size_t end = signature.size();
859 bool process_return = false;
860 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000861 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700862 char c = signature[offset];
863 offset++;
864 if (c == ')') {
865 process_return = true;
866 continue;
867 }
Ian Rogers0571d352011-11-03 19:51:38 -0700868 while (c == '[') { // process array prefix
869 if (offset >= end) { // expect some descriptor following [
870 return false;
871 }
872 c = signature[offset];
873 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700874 }
875 if (c == 'L') { // process type descriptors
876 do {
877 if (offset >= end) { // unexpected early termination of descriptor
878 return false;
879 }
880 c = signature[offset];
881 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700882 } while (c != ';');
883 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000884 // TODO: avoid creating a std::string just to get a 0-terminated char array
885 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700886 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700887 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700888 return false;
889 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800890 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700891 if (!process_return) {
892 param_type_idxs->push_back(type_idx);
893 } else {
894 *return_type_idx = type_idx;
895 return offset == end; // return true if the signature had reached a sensible end
896 }
897 }
898 return false; // failed to correctly parse return type
899}
900
Ian Rogersd91d6d62013-09-25 20:26:14 -0700901const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800902 dex::TypeIndex return_type_idx;
903 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700904 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
905 if (!success) {
906 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700907 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700908 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700909 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700910 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700911 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700912 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700913}
914
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700915int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700916 // Note: Signed type is important for max and min.
917 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700918 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700919
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700920 while (min <= max) {
921 int32_t mid = min + ((max - min) / 2);
922
923 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
924 uint32_t start = ti->start_addr_;
925 uint32_t end = start + ti->insn_count_;
926
Ian Rogers0571d352011-11-03 19:51:38 -0700927 if (address < start) {
928 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700929 } else if (address >= end) {
930 min = mid + 1;
931 } else { // We have a winner!
932 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700933 }
934 }
935 // No match.
936 return -1;
937}
938
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700939int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
940 int32_t try_item = FindTryItem(code_item, address);
941 if (try_item == -1) {
942 return -1;
943 } else {
944 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
945 }
946}
947
David Srbeckyb06e28e2015-12-10 13:15:00 +0000948bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
949 DexDebugNewLocalCb local_cb, void* context) const {
950 DCHECK(local_cb != nullptr);
951 if (code_item == nullptr) {
952 return false;
953 }
954 const uint8_t* stream = GetDebugInfoStream(code_item);
955 if (stream == nullptr) {
956 return false;
957 }
958 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700959
David Srbeckyb06e28e2015-12-10 13:15:00 +0000960 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800961 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000962 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
963 local_in_reg[arg_reg].name_ = "this";
964 local_in_reg[arg_reg].descriptor_ = descriptor;
965 local_in_reg[arg_reg].signature_ = nullptr;
966 local_in_reg[arg_reg].start_address_ = 0;
967 local_in_reg[arg_reg].reg_ = arg_reg;
968 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969 arg_reg++;
970 }
971
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800972 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000973 DecodeUnsignedLeb128(&stream); // Line.
974 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
975 uint32_t i;
976 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700977 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700978 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800979 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000980 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000982 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700983 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800984 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000985 local_in_reg[arg_reg].descriptor_ = descriptor;
986 local_in_reg[arg_reg].signature_ = nullptr;
987 local_in_reg[arg_reg].start_address_ = 0;
988 local_in_reg[arg_reg].reg_ = arg_reg;
989 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700990 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700991 case 'D':
992 case 'J':
993 arg_reg += 2;
994 break;
995 default:
996 arg_reg += 1;
997 break;
998 }
999 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001000 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001001 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -07001002 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +00001003 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001004 }
1005
David Srbeckyb06e28e2015-12-10 13:15:00 +00001006 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001007 for (;;) {
1008 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001009 switch (opcode) {
1010 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001011 // Emit all variables which are still alive at the end of the method.
1012 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
1013 if (local_in_reg[reg].is_live_) {
1014 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
1015 local_cb(context, local_in_reg[reg]);
1016 }
1017 }
1018 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001019 case DBG_ADVANCE_PC:
1020 address += DecodeUnsignedLeb128(&stream);
1021 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001022 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001023 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001024 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001025 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001026 case DBG_START_LOCAL_EXTENDED: {
1027 uint16_t reg = DecodeUnsignedLeb128(&stream);
1028 if (reg >= code_item->registers_size_) {
1029 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -08001030 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +00001031 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001032 }
1033
David Srbeckyb06e28e2015-12-10 13:15:00 +00001034 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1035 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
1036 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -07001037 if (opcode == DBG_START_LOCAL_EXTENDED) {
1038 signature_idx = DecodeUnsignedLeb128P1(&stream);
1039 }
1040
Shih-wei Liao195487c2011-08-20 13:29:04 -07001041 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +00001042 if (local_in_reg[reg].is_live_) {
1043 local_in_reg[reg].end_address_ = address;
1044 local_cb(context, local_in_reg[reg]);
1045 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001046
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001047 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -08001048 local_in_reg[reg].descriptor_ =
1049 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001050 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001051 local_in_reg[reg].start_address_ = address;
1052 local_in_reg[reg].reg_ = reg;
1053 local_in_reg[reg].is_live_ = true;
1054 break;
1055 }
1056 case DBG_END_LOCAL: {
1057 uint16_t reg = DecodeUnsignedLeb128(&stream);
1058 if (reg >= code_item->registers_size_) {
1059 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1060 << code_item->registers_size_ << ") in " << GetLocation();
1061 return false;
1062 }
1063 if (!local_in_reg[reg].is_live_) {
1064 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
1065 return false;
1066 }
1067 local_in_reg[reg].end_address_ = address;
1068 local_cb(context, local_in_reg[reg]);
1069 local_in_reg[reg].is_live_ = false;
1070 break;
1071 }
1072 case DBG_RESTART_LOCAL: {
1073 uint16_t reg = DecodeUnsignedLeb128(&stream);
1074 if (reg >= code_item->registers_size_) {
1075 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1076 << code_item->registers_size_ << ") in " << GetLocation();
1077 return false;
1078 }
1079 // If the register is live, the "restart" is superfluous,
1080 // and we don't want to mess with the existing start address.
1081 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001082 local_in_reg[reg].start_address_ = address;
1083 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001084 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001085 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001086 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001087 case DBG_SET_PROLOGUE_END:
1088 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001089 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001090 case DBG_SET_FILE:
1091 DecodeUnsignedLeb128P1(&stream); // name.
1092 break;
1093 default:
1094 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1095 break;
1096 }
1097 }
1098}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001099
David Srbeckyb06e28e2015-12-10 13:15:00 +00001100bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1101 void* context) const {
1102 DCHECK(position_cb != nullptr);
1103 if (code_item == nullptr) {
1104 return false;
1105 }
1106 const uint8_t* stream = GetDebugInfoStream(code_item);
1107 if (stream == nullptr) {
1108 return false;
1109 }
1110
1111 PositionInfo entry = PositionInfo();
1112 entry.line_ = DecodeUnsignedLeb128(&stream);
1113 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1114 for (uint32_t i = 0; i < parameters_size; ++i) {
1115 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1116 }
1117
1118 for (;;) {
1119 uint8_t opcode = *stream++;
1120 switch (opcode) {
1121 case DBG_END_SEQUENCE:
1122 return true; // end of stream.
1123 case DBG_ADVANCE_PC:
1124 entry.address_ += DecodeUnsignedLeb128(&stream);
1125 break;
1126 case DBG_ADVANCE_LINE:
1127 entry.line_ += DecodeSignedLeb128(&stream);
1128 break;
1129 case DBG_START_LOCAL:
1130 DecodeUnsignedLeb128(&stream); // reg.
1131 DecodeUnsignedLeb128P1(&stream); // name.
1132 DecodeUnsignedLeb128P1(&stream); // descriptor.
1133 break;
1134 case DBG_START_LOCAL_EXTENDED:
1135 DecodeUnsignedLeb128(&stream); // reg.
1136 DecodeUnsignedLeb128P1(&stream); // name.
1137 DecodeUnsignedLeb128P1(&stream); // descriptor.
1138 DecodeUnsignedLeb128P1(&stream); // signature.
1139 break;
1140 case DBG_END_LOCAL:
1141 case DBG_RESTART_LOCAL:
1142 DecodeUnsignedLeb128(&stream); // reg.
1143 break;
1144 case DBG_SET_PROLOGUE_END:
1145 entry.prologue_end_ = true;
1146 break;
1147 case DBG_SET_EPILOGUE_BEGIN:
1148 entry.epilogue_begin_ = true;
1149 break;
1150 case DBG_SET_FILE: {
1151 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001152 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001153 break;
1154 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001155 default: {
1156 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001157 entry.address_ += adjopcode / DBG_LINE_RANGE;
1158 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1159 if (position_cb(context, entry)) {
1160 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001161 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001162 entry.prologue_end_ = false;
1163 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001164 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001165 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001166 }
1167 }
1168}
1169
David Srbeckyb06e28e2015-12-10 13:15:00 +00001170bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001171 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001172
1173 // We know that this callback will be called in
1174 // ascending address order, so keep going until we find
1175 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001176 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001177 // The line number from the previous positions callback
1178 // wil be the final result.
1179 return true;
1180 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001181 context->line_num_ = entry.line_;
1182 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001183 }
1184}
1185
Andreas Gampe833a4852014-05-21 18:46:59 -07001186bool DexFile::IsMultiDexLocation(const char* location) {
1187 return strrchr(location, kMultiDexSeparator) != nullptr;
1188}
1189
Andreas Gampe90e34042015-04-27 20:01:52 -07001190std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1191 if (index == 0) {
1192 return "classes.dex";
1193 } else {
1194 return StringPrintf("classes%zu.dex", index + 1);
1195 }
1196}
1197
1198std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1199 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001200 return dex_location;
1201 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001202 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001203 }
1204}
1205
1206std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1207 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001208 std::string base_location = GetBaseLocation(dex_location);
1209 const char* suffix = dex_location + base_location.size();
1210 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1211 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1212 if (path != nullptr && path.get() != base_location) {
1213 return std::string(path.get()) + suffix;
1214 } else if (suffix[0] == 0) {
1215 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001216 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001217 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001218 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001219}
1220
Jeff Hao13e748b2015-08-25 20:44:19 +00001221// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001222int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001223 int32_t val = 0;
1224 for (int i = zwidth; i >= 0; --i) {
1225 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1226 }
1227 val >>= (3 - zwidth) * 8;
1228 return val;
1229}
1230
1231// Read an unsigned integer. "zwidth" is the zero-based byte count,
1232// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001233uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001234 uint32_t val = 0;
1235 for (int i = zwidth; i >= 0; --i) {
1236 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1237 }
1238 if (!fill_on_right) {
1239 val >>= (3 - zwidth) * 8;
1240 }
1241 return val;
1242}
1243
1244// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001245int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001246 int64_t val = 0;
1247 for (int i = zwidth; i >= 0; --i) {
1248 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1249 }
1250 val >>= (7 - zwidth) * 8;
1251 return val;
1252}
1253
1254// Read an unsigned long. "zwidth" is the zero-based byte count,
1255// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001256uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001257 uint64_t val = 0;
1258 for (int i = zwidth; i >= 0; --i) {
1259 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1260 }
1261 if (!fill_on_right) {
1262 val >>= (7 - zwidth) * 8;
1263 }
1264 return val;
1265}
1266
David Sehr709b0702016-10-13 09:12:37 -07001267std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1268 if (method_idx >= NumMethodIds()) {
1269 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1270 }
1271 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1272 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1273 result += '.';
1274 result += GetMethodName(method_id);
1275 if (with_signature) {
1276 const Signature signature = GetMethodSignature(method_id);
1277 std::string sig_as_string(signature.ToString());
1278 if (signature == Signature::NoSignature()) {
1279 return result + sig_as_string;
1280 }
1281 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1282 PrettyArguments(sig_as_string.c_str());
1283 }
1284 return result;
1285}
1286
1287std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1288 if (field_idx >= NumFieldIds()) {
1289 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1290 }
1291 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1292 std::string result;
1293 if (with_type) {
1294 result += GetFieldTypeDescriptor(field_id);
1295 result += ' ';
1296 }
1297 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1298 result += '.';
1299 result += GetFieldName(field_id);
1300 return result;
1301}
1302
Andreas Gampea5b09a62016-11-17 15:21:22 -08001303std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1304 if (type_idx.index_ >= NumTypeIds()) {
1305 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001306 }
1307 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1308 return PrettyDescriptor(GetTypeDescriptor(type_id));
1309}
1310
Jeff Hao3d080862016-05-26 18:39:17 -07001311// Checks that visibility is as expected. Includes special behavior for M and
1312// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001313std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1314 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1315 dex_file.GetLocation().c_str(),
1316 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1317 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1318 return os;
1319}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001320
Ian Rogersd91d6d62013-09-25 20:26:14 -07001321std::string Signature::ToString() const {
1322 if (dex_file_ == nullptr) {
1323 CHECK(proto_id_ == nullptr);
1324 return "<no signature>";
1325 }
1326 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1327 std::string result;
1328 if (params == nullptr) {
1329 result += "()";
1330 } else {
1331 result += "(";
1332 for (uint32_t i = 0; i < params->Size(); ++i) {
1333 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1334 }
1335 result += ")";
1336 }
1337 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1338 return result;
1339}
1340
Orion Hodson6c4921b2016-09-21 15:41:06 +01001341uint32_t Signature::GetNumberOfParameters() const {
1342 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1343 return (params != nullptr) ? params->Size() : 0;
1344}
1345
1346bool Signature::IsVoid() const {
1347 const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
1348 return strcmp(return_type, "V") == 0;
1349}
1350
Vladimir Markod9cffea2013-11-25 15:08:02 +00001351bool Signature::operator==(const StringPiece& rhs) const {
1352 if (dex_file_ == nullptr) {
1353 return false;
1354 }
1355 StringPiece tail(rhs);
1356 if (!tail.starts_with("(")) {
1357 return false; // Invalid signature
1358 }
1359 tail.remove_prefix(1); // "(";
1360 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1361 if (params != nullptr) {
1362 for (uint32_t i = 0; i < params->Size(); ++i) {
1363 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1364 if (!tail.starts_with(param)) {
1365 return false;
1366 }
1367 tail.remove_prefix(param.length());
1368 }
1369 }
1370 if (!tail.starts_with(")")) {
1371 return false;
1372 }
1373 tail.remove_prefix(1); // ")";
1374 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1375}
1376
Ian Rogersd91d6d62013-09-25 20:26:14 -07001377std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1378 return os << sig.ToString();
1379}
1380
Ian Rogers0571d352011-11-03 19:51:38 -07001381// Decodes the header section from the class data bytes.
1382void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001383 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001384 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1385 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1386 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1387 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1388}
1389
1390void ClassDataItemIterator::ReadClassDataField() {
1391 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1392 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001393 // The user of the iterator is responsible for checking if there
1394 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001395}
1396
1397void ClassDataItemIterator::ReadClassDataMethod() {
1398 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1399 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1400 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001401 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001402 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001403 }
Ian Rogers0571d352011-11-03 19:51:38 -07001404}
1405
Orion Hodson12f4ff42017-01-13 16:43:12 +00001406EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
1407 const uint8_t* array_data)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001408 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001409 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001410 pos_(-1),
Orion Hodson12f4ff42017-01-13 16:43:12 +00001411 ptr_(array_data),
David Sehr9323e6e2016-09-13 08:58:35 -07001412 type_(kByte) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001413 array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001414 if (array_size_ > 0) {
1415 Next();
1416 }
1417}
1418
Orion Hodson12f4ff42017-01-13 16:43:12 +00001419void EncodedArrayValueIterator::Next() {
Ian Rogers0571d352011-11-03 19:51:38 -07001420 pos_++;
1421 if (pos_ >= array_size_) {
1422 return;
1423 }
Ian Rogers13735952014-10-08 12:43:28 -07001424 uint8_t value_type = *ptr_++;
1425 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001426 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001427 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001428 switch (type_) {
1429 case kBoolean:
1430 jval_.i = (value_arg != 0) ? 1 : 0;
1431 width = 0;
1432 break;
1433 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001434 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001435 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001436 break;
1437 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001438 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001439 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001440 break;
1441 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001442 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001443 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001444 break;
1445 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001446 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001447 break;
1448 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001449 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001450 break;
1451 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001452 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001453 break;
1454 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001455 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001456 break;
1457 case kString:
1458 case kType:
Orion Hodson12f4ff42017-01-13 16:43:12 +00001459 case kMethodType:
1460 case kMethodHandle:
David Sehr9323e6e2016-09-13 08:58:35 -07001461 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001462 break;
1463 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001464 case kMethod:
1465 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001466 case kArray:
1467 case kAnnotation:
1468 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001469 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001470 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001471 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001472 width = 0;
1473 break;
1474 default:
1475 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001476 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001477 }
1478 ptr_ += width;
1479}
1480
Ian Rogers0571d352011-11-03 19:51:38 -07001481CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1482 handler_.address_ = -1;
1483 int32_t offset = -1;
1484
1485 // Short-circuit the overwhelmingly common cases.
1486 switch (code_item.tries_size_) {
1487 case 0:
1488 break;
1489 case 1: {
1490 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1491 uint32_t start = tries->start_addr_;
1492 if (address >= start) {
1493 uint32_t end = start + tries->insn_count_;
1494 if (address < end) {
1495 offset = tries->handler_off_;
1496 }
1497 }
1498 break;
1499 }
1500 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001501 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001502 }
Logan Chien736df022012-04-27 16:25:57 +08001503 Init(code_item, offset);
1504}
1505
1506CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1507 const DexFile::TryItem& try_item) {
1508 handler_.address_ = -1;
1509 Init(code_item, try_item.handler_off_);
1510}
1511
1512void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1513 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001514 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001515 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001516 } else {
1517 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001518 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001519 remaining_count_ = -1;
1520 catch_all_ = false;
1521 DCHECK(!HasNext());
1522 }
1523}
1524
Ian Rogers13735952014-10-08 12:43:28 -07001525void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001526 current_data_ = handler_data;
1527 remaining_count_ = DecodeSignedLeb128(&current_data_);
1528
1529 // If remaining_count_ is non-positive, then it is the negative of
1530 // the number of catch types, and the catches are followed by a
1531 // catch-all handler.
1532 if (remaining_count_ <= 0) {
1533 catch_all_ = true;
1534 remaining_count_ = -remaining_count_;
1535 } else {
1536 catch_all_ = false;
1537 }
1538 Next();
1539}
1540
1541void CatchHandlerIterator::Next() {
1542 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001543 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001544 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1545 remaining_count_--;
1546 return;
1547 }
1548
1549 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001550 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001551 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1552 catch_all_ = false;
1553 return;
1554 }
1555
1556 // no more handler
1557 remaining_count_ = -1;
1558}
1559
Andreas Gampea5b09a62016-11-17 15:21:22 -08001560namespace dex {
1561
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001562std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1563 os << "StringIndex[" << index.index_ << "]";
1564 return os;
1565}
1566
Andreas Gampea5b09a62016-11-17 15:21:22 -08001567std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1568 os << "TypeIndex[" << index.index_ << "]";
1569 return os;
1570}
1571
1572} // namespace dex
1573
Carl Shapiro1fb86202011-06-27 17:43:13 -07001574} // namespace art