blob: 973ac83ac63664e2a6b2ac55a7aded5cc449ee73 [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);
182 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
183 map->Size(),
184 location,
185 location_checksum,
186 kNoOatDexFile,
187 verify,
188 verify_checksum,
189 error_msg);
190 if (dex_file != nullptr) {
191 dex_file->mem_map_.reset(map.release());
Orion Hodsona4c2a052016-08-17 10:51:42 +0100192 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800193 return dex_file;
194}
195
David Sehr733ddb22016-09-19 15:02:18 -0700196bool DexFile::Open(const char* filename,
197 const std::string& location,
198 bool verify_checksum,
199 std::string* error_msg,
200 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
201 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
202 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
203 uint32_t magic;
204 File fd = OpenAndReadMagic(filename, &magic, error_msg);
205 if (fd.Fd() == -1) {
206 DCHECK(!error_msg->empty());
207 return false;
208 }
209 if (IsZipMagic(magic)) {
210 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
211 }
212 if (IsDexMagic(magic)) {
213 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
214 location,
215 /* verify */ true,
216 verify_checksum,
217 error_msg));
218 if (dex_file.get() != nullptr) {
219 dex_files->push_back(std::move(dex_file));
220 return true;
221 } else {
222 return false;
Vladimir Markofd995762013-11-06 16:36:36 +0000223 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700224 }
David Sehr733ddb22016-09-19 15:02:18 -0700225 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
226 return false;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700227}
228
David Sehr733ddb22016-09-19 15:02:18 -0700229std::unique_ptr<const DexFile> DexFile::OpenDex(int fd,
230 const std::string& location,
231 bool verify_checksum,
232 std::string* error_msg) {
233 ScopedTrace trace("Open dex file " + std::string(location));
234 return OpenFile(fd, location, true /* verify */, verify_checksum, error_msg);
235}
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700236
Aart Bik37d6a3b2016-06-21 18:30:10 -0700237bool DexFile::OpenZip(int fd,
238 const std::string& location,
239 bool verify_checksum,
240 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800241 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800242 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700243 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700244 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700245 if (zip_archive.get() == nullptr) {
246 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700247 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700248 }
David Sehr733ddb22016-09-19 15:02:18 -0700249 return DexFile::OpenAllDexFilesFromZip(*zip_archive,
250 location,
251 verify_checksum,
252 error_msg,
253 dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800254}
255
David Sehr733ddb22016-09-19 15:02:18 -0700256std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
257 const std::string& location,
258 bool verify,
259 bool verify_checksum,
260 std::string* error_msg) {
261 ScopedTrace trace(std::string("Open dex file ") + std::string(location));
262 CHECK(!location.empty());
263 std::unique_ptr<MemMap> map;
264 {
265 File delayed_close(fd, /* check_usage */ false);
266 struct stat sbuf;
267 memset(&sbuf, 0, sizeof(sbuf));
268 if (fstat(fd, &sbuf) == -1) {
269 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location.c_str(),
270 strerror(errno));
271 return nullptr;
272 }
273 if (S_ISDIR(sbuf.st_mode)) {
274 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location.c_str());
275 return nullptr;
276 }
277 size_t length = sbuf.st_size;
278 map.reset(MemMap::MapFile(length,
279 PROT_READ,
280 MAP_PRIVATE,
281 fd,
282 0,
283 /*low_4gb*/false,
284 location.c_str(),
285 error_msg));
286 if (map == nullptr) {
287 DCHECK(!error_msg->empty());
288 return nullptr;
289 }
290 }
291
292 if (map->Size() < sizeof(DexFile::Header)) {
293 *error_msg = StringPrintf(
294 "DexFile: failed to open dex file '%s' that is too short to have a header",
295 location.c_str());
296 return nullptr;
297 }
298
299 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
300
301 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
302 map->Size(),
303 location,
304 dex_header->checksum_,
305 kNoOatDexFile,
306 verify,
307 verify_checksum,
308 error_msg);
309 if (dex_file != nullptr) {
310 dex_file->mem_map_.reset(map.release());
311 }
312
313 return dex_file;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800314}
315
David Sehr733ddb22016-09-19 15:02:18 -0700316std::unique_ptr<const DexFile> DexFile::OpenOneDexFileFromZip(const ZipArchive& zip_archive,
317 const char* entry_name,
318 const std::string& location,
319 bool verify_checksum,
320 std::string* error_msg,
321 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800322 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800323 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700324 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
David Sehr9fddd362016-09-22 14:05:37 -0700325 if (zip_entry == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700326 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700327 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700328 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800329 if (zip_entry->GetUncompressedLength() == 0) {
330 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
331 *error_code = ZipOpenErrorCode::kDexFileError;
332 return nullptr;
333 }
Igor Murashkin271a0f82017-02-14 21:14:17 +0000334
335 std::unique_ptr<MemMap> map;
336 if (zip_entry->IsUncompressed()) {
337 if (!zip_entry->IsAlignedTo(alignof(Header))) {
338 // Do not mmap unaligned ZIP entries because
339 // doing so would fail dex verification which requires 4 byte alignment.
340 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
341 << "please zipalign to " << alignof(Header) << " bytes. "
342 << "Falling back to extracting file.";
343 } else {
344 // Map uncompressed files within zip as file-backed to avoid a dirty copy.
345 map.reset(zip_entry->MapDirectlyFromFile(location.c_str(), /*out*/error_msg));
346 if (map == nullptr) {
347 LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
348 << "is your ZIP file corrupted? Falling back to extraction.";
349 // Try again with Extraction which still has a chance of recovery.
350 }
351 }
352 }
353
354 if (map == nullptr) {
355 // Default path for compressed ZIP entries,
356 // and fallback for stored ZIP entries.
357 map.reset(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
358 }
359
David Sehr9fddd362016-09-22 14:05:37 -0700360 if (map == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700361 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700363 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700364 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700365 }
David Sehr733ddb22016-09-19 15:02:18 -0700366 VerifyResult verify_result;
367 std::unique_ptr<DexFile> dex_file = OpenCommon(map->Begin(),
368 map->Size(),
369 location,
370 zip_entry->GetCrc32(),
371 kNoOatDexFile,
372 /* verify */ true,
373 verify_checksum,
374 error_msg,
375 &verify_result);
David Sehr9fddd362016-09-22 14:05:37 -0700376 if (dex_file == nullptr) {
377 if (verify_result == VerifyResult::kVerifyNotAttempted) {
378 *error_code = ZipOpenErrorCode::kDexFileError;
379 } else {
380 *error_code = ZipOpenErrorCode::kVerifyError;
381 }
382 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800383 }
David Sehr9fddd362016-09-22 14:05:37 -0700384 dex_file->mem_map_.reset(map.release());
Brian Carlstrome0948e12013-08-29 09:36:15 -0700385 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700386 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700387 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700389 }
390 CHECK(dex_file->IsReadOnly()) << location;
David Sehr733ddb22016-09-19 15:02:18 -0700391 if (verify_result != VerifyResult::kVerifySucceeded) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700392 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700393 return nullptr;
394 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700395 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800396 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700397}
398
Andreas Gampe90e34042015-04-27 20:01:52 -0700399// Technically we do not have a limitation with respect to the number of dex files that can be in a
400// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
401// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
402// seems an excessive number.
403static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
404
David Sehr733ddb22016-09-19 15:02:18 -0700405bool DexFile::OpenAllDexFilesFromZip(const ZipArchive& zip_archive,
406 const std::string& location,
407 bool verify_checksum,
408 std::string* error_msg,
409 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800410 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700411 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700412 ZipOpenErrorCode error_code;
David Sehr733ddb22016-09-19 15:02:18 -0700413 std::unique_ptr<const DexFile> dex_file(OpenOneDexFileFromZip(zip_archive,
414 kClassesDex,
415 location,
416 verify_checksum,
417 error_msg,
418 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700419 if (dex_file.get() == nullptr) {
420 return false;
421 } else {
422 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800423 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700424
425 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700426
427 // We could try to avoid std::string allocations by working on a char array directly. As we
428 // do not expect a lot of iterations, this seems too involved and brittle.
429
Andreas Gampe90e34042015-04-27 20:01:52 -0700430 for (size_t i = 1; ; ++i) {
431 std::string name = GetMultiDexClassesDexName(i);
432 std::string fake_location = GetMultiDexLocation(i, location.c_str());
David Sehr733ddb22016-09-19 15:02:18 -0700433 std::unique_ptr<const DexFile> next_dex_file(OpenOneDexFileFromZip(zip_archive,
434 name.c_str(),
435 fake_location,
436 verify_checksum,
437 error_msg,
438 &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700439 if (next_dex_file.get() == nullptr) {
440 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
441 LOG(WARNING) << error_msg;
442 }
443 break;
444 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800445 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700446 }
447
Andreas Gampe90e34042015-04-27 20:01:52 -0700448 if (i == kWarnOnManyDexFilesThreshold) {
449 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
450 << " dex files. Please consider coalescing and shrinking the number to "
451 " avoid runtime overhead.";
452 }
453
454 if (i == std::numeric_limits<size_t>::max()) {
455 LOG(ERROR) << "Overflow in number of dex files!";
456 break;
457 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700458 }
459
460 return true;
461 }
462}
463
David Sehr733ddb22016-09-19 15:02:18 -0700464std::unique_ptr<DexFile> DexFile::OpenCommon(const uint8_t* base,
465 size_t size,
466 const std::string& location,
467 uint32_t location_checksum,
468 const OatDexFile* oat_dex_file,
469 bool verify,
470 bool verify_checksum,
471 std::string* error_msg,
472 VerifyResult* verify_result) {
David Sehr9fddd362016-09-22 14:05:37 -0700473 if (verify_result != nullptr) {
474 *verify_result = VerifyResult::kVerifyNotAttempted;
475 }
David Sehr733ddb22016-09-19 15:02:18 -0700476 std::unique_ptr<DexFile> dex_file(new DexFile(base,
477 size,
478 location,
479 location_checksum,
480 oat_dex_file));
481 if (dex_file == nullptr) {
482 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
483 error_msg->c_str());
484 return nullptr;
485 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800487 dex_file.reset();
David Sehr733ddb22016-09-19 15:02:18 -0700488 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700489 }
David Sehr733ddb22016-09-19 15:02:18 -0700490 if (verify && !DexFileVerifier::Verify(dex_file.get(),
491 dex_file->Begin(),
492 dex_file->Size(),
493 location.c_str(),
494 verify_checksum,
495 error_msg)) {
496 if (verify_result != nullptr) {
497 *verify_result = VerifyResult::kVerifyFailed;
498 }
499 return nullptr;
500 }
501 if (verify_result != nullptr) {
502 *verify_result = VerifyResult::kVerifySucceeded;
503 }
504 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700505}
506
David Sehr733ddb22016-09-19 15:02:18 -0700507DexFile::DexFile(const uint8_t* base,
508 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800509 const std::string& location,
510 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700511 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800512 : begin_(base),
513 size_(size),
514 location_(location),
515 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800516 header_(reinterpret_cast<const Header*>(base)),
517 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
518 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
519 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
520 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
521 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700522 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000523 method_handles_(nullptr),
524 num_method_handles_(0),
525 call_site_ids_(nullptr),
526 num_call_site_ids_(0),
Richard Uhler07b3c232015-03-31 15:57:54 -0700527 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700528 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800529 CHECK_GT(size_, 0U) << GetLocation();
Igor Murashkin271a0f82017-02-14 21:14:17 +0000530 // Check base (=header) alignment.
531 // Must be 4-byte aligned to avoid undefined behavior when accessing
532 // any of the sections via a pointer.
533 CHECK_ALIGNED(begin_, alignof(Header));
534
Orion Hodson12f4ff42017-01-13 16:43:12 +0000535 InitializeSectionsFromMapList();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800536}
537
Jesse Wilson6bf19152011-09-29 13:12:33 -0400538DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700539 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
540 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
541 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
542 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400543}
544
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700545bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700546 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700547 return false;
548 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700549 return true;
550}
551
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700552bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800553 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700554 std::ostringstream oss;
555 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800556 << " " << header_->magic_[0]
557 << " " << header_->magic_[1]
558 << " " << header_->magic_[2]
559 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700560 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700561 return false;
562 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800563 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700564 std::ostringstream oss;
565 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800566 << " " << header_->magic_[4]
567 << " " << header_->magic_[5]
568 << " " << header_->magic_[6]
569 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700570 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700571 return false;
572 }
573 return true;
574}
575
Orion Hodson12f4ff42017-01-13 16:43:12 +0000576void DexFile::InitializeSectionsFromMapList() {
577 const MapList* map_list = reinterpret_cast<const MapList*>(begin_ + header_->map_off_);
578 const size_t count = map_list->size_;
579
580 size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
581 if (header_->map_off_ >= map_limit || map_limit > size_) {
582 // Overflow or out out of bounds. The dex file verifier runs after
583 // this method and will reject the file as it is malformed.
584 return;
585 }
586
587 for (size_t i = 0; i < count; ++i) {
588 const MapItem& map_item = map_list->list_[i];
589 if (map_item.type_ == kDexTypeMethodHandleItem) {
590 method_handles_ = reinterpret_cast<const MethodHandleItem*>(begin_ + map_item.offset_);
591 num_method_handles_ = map_item.size_;
592 } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
593 call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(begin_ + map_item.offset_);
594 num_call_site_ids_ = map_item.size_;
595 }
596 }
597}
598
Ian Rogers13735952014-10-08 12:43:28 -0700599bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800600 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
601}
602
Ian Rogers13735952014-10-08 12:43:28 -0700603bool DexFile::IsVersionValid(const uint8_t* magic) {
604 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700605 for (uint32_t i = 0; i < kNumDexVersions; i++) {
606 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
607 return true;
608 }
609 }
610 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800611}
612
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700613uint32_t DexFile::Header::GetVersion() const {
614 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700615 return atoi(version);
616}
617
Andreas Gampea5b09a62016-11-17 15:21:22 -0800618const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700619 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100620 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700621 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700622 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700623 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700624 for (size_t i = 0; i < num_class_defs; ++i) {
625 const ClassDef& class_def = GetClassDef(i);
626 if (class_def.class_idx_ == type_idx) {
627 return &class_def;
628 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700629 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700630 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700631}
632
Alex Light9c20a142016-08-23 15:05:12 -0700633uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
634 uint32_t method_idx) const {
635 const uint8_t* class_data = GetClassData(class_def);
636 CHECK(class_data != nullptr);
637 ClassDataItemIterator it(*this, class_data);
638 // Skip fields
639 while (it.HasNextStaticField()) {
640 it.Next();
641 }
642 while (it.HasNextInstanceField()) {
643 it.Next();
644 }
645 while (it.HasNextDirectMethod()) {
646 if (it.GetMemberIndex() == method_idx) {
647 return it.GetMethodCodeItemOffset();
648 }
649 it.Next();
650 }
651 while (it.HasNextVirtualMethod()) {
652 if (it.GetMemberIndex() == method_idx) {
653 return it.GetMethodCodeItemOffset();
654 }
655 it.Next();
656 }
657 LOG(FATAL) << "Unable to find method " << method_idx;
658 UNREACHABLE();
659}
660
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800661const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100662 const DexFile::StringId& name,
663 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800664 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800665 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800666 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800667 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700668 int32_t lo = 0;
669 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800670 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700671 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800672 const DexFile::FieldId& field = GetFieldId(mid);
673 if (class_idx > field.class_idx_) {
674 lo = mid + 1;
675 } else if (class_idx < field.class_idx_) {
676 hi = mid - 1;
677 } else {
678 if (name_idx > field.name_idx_) {
679 lo = mid + 1;
680 } else if (name_idx < field.name_idx_) {
681 hi = mid - 1;
682 } else {
683 if (type_idx > field.type_idx_) {
684 lo = mid + 1;
685 } else if (type_idx < field.type_idx_) {
686 hi = mid - 1;
687 } else {
688 return &field;
689 }
690 }
691 }
692 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700693 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800694}
695
696const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700697 const DexFile::StringId& name,
698 const DexFile::ProtoId& signature) const {
699 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800700 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800701 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700702 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700703 int32_t lo = 0;
704 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700705 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700706 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700707 const DexFile::MethodId& method = GetMethodId(mid);
708 if (class_idx > method.class_idx_) {
709 lo = mid + 1;
710 } else if (class_idx < method.class_idx_) {
711 hi = mid - 1;
712 } else {
713 if (name_idx > method.name_idx_) {
714 lo = mid + 1;
715 } else if (name_idx < method.name_idx_) {
716 hi = mid - 1;
717 } else {
718 if (proto_idx > method.proto_idx_) {
719 lo = mid + 1;
720 } else if (proto_idx < method.proto_idx_) {
721 hi = mid - 1;
722 } else {
723 return &method;
724 }
725 }
726 }
727 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700729}
730
Ian Rogers637c65b2013-05-31 11:46:00 -0700731const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700732 int32_t lo = 0;
733 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700734 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700735 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800736 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700737 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700738 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
739 if (compare > 0) {
740 lo = mid + 1;
741 } else if (compare < 0) {
742 hi = mid - 1;
743 } else {
744 return &str_id;
745 }
746 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700747 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700748}
749
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300750const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
751 int32_t lo = 0;
752 int32_t hi = NumTypeIds() - 1;
753 while (hi >= lo) {
754 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800755 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300756 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
757 const char* str = GetStringData(str_id);
758 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
759 if (compare > 0) {
760 lo = mid + 1;
761 } else if (compare < 0) {
762 hi = mid - 1;
763 } else {
764 return &type_id;
765 }
766 }
767 return nullptr;
768}
769
Vladimir Markoa48aef42014-12-03 17:53:53 +0000770const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700771 int32_t lo = 0;
772 int32_t hi = NumStringIds() - 1;
773 while (hi >= lo) {
774 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800775 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700776 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000777 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700778 if (compare > 0) {
779 lo = mid + 1;
780 } else if (compare < 0) {
781 hi = mid - 1;
782 } else {
783 return &str_id;
784 }
785 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700786 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700787}
788
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800789const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700790 int32_t lo = 0;
791 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700792 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700793 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800794 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700795 if (string_idx > type_id.descriptor_idx_) {
796 lo = mid + 1;
797 } else if (string_idx < type_id.descriptor_idx_) {
798 hi = mid - 1;
799 } else {
800 return &type_id;
801 }
802 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700803 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700804}
805
Andreas Gampea5b09a62016-11-17 15:21:22 -0800806const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
807 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000808 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700809 int32_t lo = 0;
810 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700811 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700812 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700813 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800814 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700815 if (compare == 0) {
816 DexFileParameterIterator it(*this, proto);
817 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000818 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800819 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700820 it.Next();
821 i++;
822 }
823 if (compare == 0) {
824 if (it.HasNext()) {
825 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000826 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700827 compare = 1;
828 }
829 }
830 }
831 if (compare > 0) {
832 lo = mid + 1;
833 } else if (compare < 0) {
834 hi = mid - 1;
835 } else {
836 return &proto;
837 }
838 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700840}
841
842// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800843bool DexFile::CreateTypeList(const StringPiece& signature,
844 dex::TypeIndex* return_type_idx,
845 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700846 if (signature[0] != '(') {
847 return false;
848 }
849 size_t offset = 1;
850 size_t end = signature.size();
851 bool process_return = false;
852 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000853 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700854 char c = signature[offset];
855 offset++;
856 if (c == ')') {
857 process_return = true;
858 continue;
859 }
Ian Rogers0571d352011-11-03 19:51:38 -0700860 while (c == '[') { // process array prefix
861 if (offset >= end) { // expect some descriptor following [
862 return false;
863 }
864 c = signature[offset];
865 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700866 }
867 if (c == 'L') { // process type descriptors
868 do {
869 if (offset >= end) { // unexpected early termination of descriptor
870 return false;
871 }
872 c = signature[offset];
873 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700874 } while (c != ';');
875 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000876 // TODO: avoid creating a std::string just to get a 0-terminated char array
877 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700878 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700879 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700880 return false;
881 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800882 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700883 if (!process_return) {
884 param_type_idxs->push_back(type_idx);
885 } else {
886 *return_type_idx = type_idx;
887 return offset == end; // return true if the signature had reached a sensible end
888 }
889 }
890 return false; // failed to correctly parse return type
891}
892
Ian Rogersd91d6d62013-09-25 20:26:14 -0700893const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800894 dex::TypeIndex return_type_idx;
895 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700896 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
897 if (!success) {
898 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700899 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700900 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700901 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700902 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700903 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700904 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700905}
906
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700907int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700908 // Note: Signed type is important for max and min.
909 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700910 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700911
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700912 while (min <= max) {
913 int32_t mid = min + ((max - min) / 2);
914
915 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
916 uint32_t start = ti->start_addr_;
917 uint32_t end = start + ti->insn_count_;
918
Ian Rogers0571d352011-11-03 19:51:38 -0700919 if (address < start) {
920 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700921 } else if (address >= end) {
922 min = mid + 1;
923 } else { // We have a winner!
924 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700925 }
926 }
927 // No match.
928 return -1;
929}
930
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700931int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
932 int32_t try_item = FindTryItem(code_item, address);
933 if (try_item == -1) {
934 return -1;
935 } else {
936 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
937 }
938}
939
David Srbeckyb06e28e2015-12-10 13:15:00 +0000940bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
941 DexDebugNewLocalCb local_cb, void* context) const {
942 DCHECK(local_cb != nullptr);
943 if (code_item == nullptr) {
944 return false;
945 }
946 const uint8_t* stream = GetDebugInfoStream(code_item);
947 if (stream == nullptr) {
948 return false;
949 }
950 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951
David Srbeckyb06e28e2015-12-10 13:15:00 +0000952 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800953 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000954 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
955 local_in_reg[arg_reg].name_ = "this";
956 local_in_reg[arg_reg].descriptor_ = descriptor;
957 local_in_reg[arg_reg].signature_ = nullptr;
958 local_in_reg[arg_reg].start_address_ = 0;
959 local_in_reg[arg_reg].reg_ = arg_reg;
960 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700961 arg_reg++;
962 }
963
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800964 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000965 DecodeUnsignedLeb128(&stream); // Line.
966 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
967 uint32_t i;
968 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700970 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800971 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000972 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700973 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000974 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700975 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800976 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000977 local_in_reg[arg_reg].descriptor_ = descriptor;
978 local_in_reg[arg_reg].signature_ = nullptr;
979 local_in_reg[arg_reg].start_address_ = 0;
980 local_in_reg[arg_reg].reg_ = arg_reg;
981 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700982 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700983 case 'D':
984 case 'J':
985 arg_reg += 2;
986 break;
987 default:
988 arg_reg += 1;
989 break;
990 }
991 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000992 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800993 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700994 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000995 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700996 }
997
David Srbeckyb06e28e2015-12-10 13:15:00 +0000998 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700999 for (;;) {
1000 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001001 switch (opcode) {
1002 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001003 // Emit all variables which are still alive at the end of the method.
1004 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
1005 if (local_in_reg[reg].is_live_) {
1006 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
1007 local_cb(context, local_in_reg[reg]);
1008 }
1009 }
1010 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001011 case DBG_ADVANCE_PC:
1012 address += DecodeUnsignedLeb128(&stream);
1013 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001014 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001015 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001016 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +00001018 case DBG_START_LOCAL_EXTENDED: {
1019 uint16_t reg = DecodeUnsignedLeb128(&stream);
1020 if (reg >= code_item->registers_size_) {
1021 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -08001022 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +00001023 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001024 }
1025
David Srbeckyb06e28e2015-12-10 13:15:00 +00001026 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1027 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
1028 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -07001029 if (opcode == DBG_START_LOCAL_EXTENDED) {
1030 signature_idx = DecodeUnsignedLeb128P1(&stream);
1031 }
1032
Shih-wei Liao195487c2011-08-20 13:29:04 -07001033 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +00001034 if (local_in_reg[reg].is_live_) {
1035 local_in_reg[reg].end_address_ = address;
1036 local_cb(context, local_in_reg[reg]);
1037 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001038
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001039 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -08001040 local_in_reg[reg].descriptor_ =
1041 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001042 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001043 local_in_reg[reg].start_address_ = address;
1044 local_in_reg[reg].reg_ = reg;
1045 local_in_reg[reg].is_live_ = true;
1046 break;
1047 }
1048 case DBG_END_LOCAL: {
1049 uint16_t reg = DecodeUnsignedLeb128(&stream);
1050 if (reg >= code_item->registers_size_) {
1051 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1052 << code_item->registers_size_ << ") in " << GetLocation();
1053 return false;
1054 }
1055 if (!local_in_reg[reg].is_live_) {
1056 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
1057 return false;
1058 }
1059 local_in_reg[reg].end_address_ = address;
1060 local_cb(context, local_in_reg[reg]);
1061 local_in_reg[reg].is_live_ = false;
1062 break;
1063 }
1064 case DBG_RESTART_LOCAL: {
1065 uint16_t reg = DecodeUnsignedLeb128(&stream);
1066 if (reg >= code_item->registers_size_) {
1067 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1068 << code_item->registers_size_ << ") in " << GetLocation();
1069 return false;
1070 }
1071 // If the register is live, the "restart" is superfluous,
1072 // and we don't want to mess with the existing start address.
1073 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001074 local_in_reg[reg].start_address_ = address;
1075 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001076 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001077 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001078 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001079 case DBG_SET_PROLOGUE_END:
1080 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001081 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001082 case DBG_SET_FILE:
1083 DecodeUnsignedLeb128P1(&stream); // name.
1084 break;
1085 default:
1086 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1087 break;
1088 }
1089 }
1090}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001091
David Srbeckyb06e28e2015-12-10 13:15:00 +00001092bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1093 void* context) const {
1094 DCHECK(position_cb != nullptr);
1095 if (code_item == nullptr) {
1096 return false;
1097 }
1098 const uint8_t* stream = GetDebugInfoStream(code_item);
1099 if (stream == nullptr) {
1100 return false;
1101 }
1102
1103 PositionInfo entry = PositionInfo();
1104 entry.line_ = DecodeUnsignedLeb128(&stream);
1105 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1106 for (uint32_t i = 0; i < parameters_size; ++i) {
1107 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1108 }
1109
1110 for (;;) {
1111 uint8_t opcode = *stream++;
1112 switch (opcode) {
1113 case DBG_END_SEQUENCE:
1114 return true; // end of stream.
1115 case DBG_ADVANCE_PC:
1116 entry.address_ += DecodeUnsignedLeb128(&stream);
1117 break;
1118 case DBG_ADVANCE_LINE:
1119 entry.line_ += DecodeSignedLeb128(&stream);
1120 break;
1121 case DBG_START_LOCAL:
1122 DecodeUnsignedLeb128(&stream); // reg.
1123 DecodeUnsignedLeb128P1(&stream); // name.
1124 DecodeUnsignedLeb128P1(&stream); // descriptor.
1125 break;
1126 case DBG_START_LOCAL_EXTENDED:
1127 DecodeUnsignedLeb128(&stream); // reg.
1128 DecodeUnsignedLeb128P1(&stream); // name.
1129 DecodeUnsignedLeb128P1(&stream); // descriptor.
1130 DecodeUnsignedLeb128P1(&stream); // signature.
1131 break;
1132 case DBG_END_LOCAL:
1133 case DBG_RESTART_LOCAL:
1134 DecodeUnsignedLeb128(&stream); // reg.
1135 break;
1136 case DBG_SET_PROLOGUE_END:
1137 entry.prologue_end_ = true;
1138 break;
1139 case DBG_SET_EPILOGUE_BEGIN:
1140 entry.epilogue_begin_ = true;
1141 break;
1142 case DBG_SET_FILE: {
1143 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001144 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +00001145 break;
1146 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001147 default: {
1148 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001149 entry.address_ += adjopcode / DBG_LINE_RANGE;
1150 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1151 if (position_cb(context, entry)) {
1152 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001153 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001154 entry.prologue_end_ = false;
1155 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001156 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001157 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001158 }
1159 }
1160}
1161
David Srbeckyb06e28e2015-12-10 13:15:00 +00001162bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001163 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001164
1165 // We know that this callback will be called in
1166 // ascending address order, so keep going until we find
1167 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001168 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001169 // The line number from the previous positions callback
1170 // wil be the final result.
1171 return true;
1172 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001173 context->line_num_ = entry.line_;
1174 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001175 }
1176}
1177
Andreas Gampe833a4852014-05-21 18:46:59 -07001178bool DexFile::IsMultiDexLocation(const char* location) {
1179 return strrchr(location, kMultiDexSeparator) != nullptr;
1180}
1181
Andreas Gampe90e34042015-04-27 20:01:52 -07001182std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1183 if (index == 0) {
1184 return "classes.dex";
1185 } else {
1186 return StringPrintf("classes%zu.dex", index + 1);
1187 }
1188}
1189
1190std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1191 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001192 return dex_location;
1193 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001194 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001195 }
1196}
1197
1198std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1199 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001200 std::string base_location = GetBaseLocation(dex_location);
1201 const char* suffix = dex_location + base_location.size();
1202 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1203 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1204 if (path != nullptr && path.get() != base_location) {
1205 return std::string(path.get()) + suffix;
1206 } else if (suffix[0] == 0) {
1207 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001208 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001209 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001210 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001211}
1212
Jeff Hao13e748b2015-08-25 20:44:19 +00001213// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001214int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001215 int32_t val = 0;
1216 for (int i = zwidth; i >= 0; --i) {
1217 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1218 }
1219 val >>= (3 - zwidth) * 8;
1220 return val;
1221}
1222
1223// Read an unsigned integer. "zwidth" is the zero-based byte count,
1224// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001225uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001226 uint32_t val = 0;
1227 for (int i = zwidth; i >= 0; --i) {
1228 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1229 }
1230 if (!fill_on_right) {
1231 val >>= (3 - zwidth) * 8;
1232 }
1233 return val;
1234}
1235
1236// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -07001237int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001238 int64_t val = 0;
1239 for (int i = zwidth; i >= 0; --i) {
1240 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1241 }
1242 val >>= (7 - zwidth) * 8;
1243 return val;
1244}
1245
1246// Read an unsigned long. "zwidth" is the zero-based byte count,
1247// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -07001248uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001249 uint64_t val = 0;
1250 for (int i = zwidth; i >= 0; --i) {
1251 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1252 }
1253 if (!fill_on_right) {
1254 val >>= (7 - zwidth) * 8;
1255 }
1256 return val;
1257}
1258
David Sehr709b0702016-10-13 09:12:37 -07001259std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
1260 if (method_idx >= NumMethodIds()) {
1261 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
1262 }
1263 const DexFile::MethodId& method_id = GetMethodId(method_idx);
1264 std::string result(PrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id)));
1265 result += '.';
1266 result += GetMethodName(method_id);
1267 if (with_signature) {
1268 const Signature signature = GetMethodSignature(method_id);
1269 std::string sig_as_string(signature.ToString());
1270 if (signature == Signature::NoSignature()) {
1271 return result + sig_as_string;
1272 }
1273 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
1274 PrettyArguments(sig_as_string.c_str());
1275 }
1276 return result;
1277}
1278
1279std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
1280 if (field_idx >= NumFieldIds()) {
1281 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
1282 }
1283 const DexFile::FieldId& field_id = GetFieldId(field_idx);
1284 std::string result;
1285 if (with_type) {
1286 result += GetFieldTypeDescriptor(field_id);
1287 result += ' ';
1288 }
1289 result += PrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id));
1290 result += '.';
1291 result += GetFieldName(field_id);
1292 return result;
1293}
1294
Andreas Gampea5b09a62016-11-17 15:21:22 -08001295std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
1296 if (type_idx.index_ >= NumTypeIds()) {
1297 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -07001298 }
1299 const DexFile::TypeId& type_id = GetTypeId(type_idx);
1300 return PrettyDescriptor(GetTypeDescriptor(type_id));
1301}
1302
Jeff Hao3d080862016-05-26 18:39:17 -07001303// Checks that visibility is as expected. Includes special behavior for M and
1304// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001305std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1306 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1307 dex_file.GetLocation().c_str(),
1308 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1309 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1310 return os;
1311}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001312
Ian Rogersd91d6d62013-09-25 20:26:14 -07001313std::string Signature::ToString() const {
1314 if (dex_file_ == nullptr) {
1315 CHECK(proto_id_ == nullptr);
1316 return "<no signature>";
1317 }
1318 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1319 std::string result;
1320 if (params == nullptr) {
1321 result += "()";
1322 } else {
1323 result += "(";
1324 for (uint32_t i = 0; i < params->Size(); ++i) {
1325 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1326 }
1327 result += ")";
1328 }
1329 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1330 return result;
1331}
1332
Orion Hodson6c4921b2016-09-21 15:41:06 +01001333uint32_t Signature::GetNumberOfParameters() const {
1334 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1335 return (params != nullptr) ? params->Size() : 0;
1336}
1337
1338bool Signature::IsVoid() const {
1339 const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
1340 return strcmp(return_type, "V") == 0;
1341}
1342
Vladimir Markod9cffea2013-11-25 15:08:02 +00001343bool Signature::operator==(const StringPiece& rhs) const {
1344 if (dex_file_ == nullptr) {
1345 return false;
1346 }
1347 StringPiece tail(rhs);
1348 if (!tail.starts_with("(")) {
1349 return false; // Invalid signature
1350 }
1351 tail.remove_prefix(1); // "(";
1352 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1353 if (params != nullptr) {
1354 for (uint32_t i = 0; i < params->Size(); ++i) {
1355 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1356 if (!tail.starts_with(param)) {
1357 return false;
1358 }
1359 tail.remove_prefix(param.length());
1360 }
1361 }
1362 if (!tail.starts_with(")")) {
1363 return false;
1364 }
1365 tail.remove_prefix(1); // ")";
1366 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1367}
1368
Ian Rogersd91d6d62013-09-25 20:26:14 -07001369std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1370 return os << sig.ToString();
1371}
1372
Ian Rogers0571d352011-11-03 19:51:38 -07001373// Decodes the header section from the class data bytes.
1374void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001375 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001376 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1377 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1378 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1379 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1380}
1381
1382void ClassDataItemIterator::ReadClassDataField() {
1383 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1384 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01001385 // The user of the iterator is responsible for checking if there
1386 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07001387}
1388
1389void ClassDataItemIterator::ReadClassDataMethod() {
1390 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1391 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1392 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001393 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001394 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001395 }
Ian Rogers0571d352011-11-03 19:51:38 -07001396}
1397
Orion Hodson12f4ff42017-01-13 16:43:12 +00001398EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
1399 const uint8_t* array_data)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001400 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001401 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -07001402 pos_(-1),
Orion Hodson12f4ff42017-01-13 16:43:12 +00001403 ptr_(array_data),
David Sehr9323e6e2016-09-13 08:58:35 -07001404 type_(kByte) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001405 array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001406 if (array_size_ > 0) {
1407 Next();
1408 }
1409}
1410
Orion Hodson12f4ff42017-01-13 16:43:12 +00001411void EncodedArrayValueIterator::Next() {
Ian Rogers0571d352011-11-03 19:51:38 -07001412 pos_++;
1413 if (pos_ >= array_size_) {
1414 return;
1415 }
Ian Rogers13735952014-10-08 12:43:28 -07001416 uint8_t value_type = *ptr_++;
1417 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001418 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001419 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001420 switch (type_) {
1421 case kBoolean:
1422 jval_.i = (value_arg != 0) ? 1 : 0;
1423 width = 0;
1424 break;
1425 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001426 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001427 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001428 break;
1429 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001430 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001431 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001432 break;
1433 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001434 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001435 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001436 break;
1437 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001438 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001439 break;
1440 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001441 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001442 break;
1443 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001444 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001445 break;
1446 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001447 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001448 break;
1449 case kString:
1450 case kType:
Orion Hodson12f4ff42017-01-13 16:43:12 +00001451 case kMethodType:
1452 case kMethodHandle:
David Sehr9323e6e2016-09-13 08:58:35 -07001453 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001454 break;
1455 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001456 case kMethod:
1457 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001458 case kArray:
1459 case kAnnotation:
1460 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001461 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001462 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001463 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001464 width = 0;
1465 break;
1466 default:
1467 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001468 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001469 }
1470 ptr_ += width;
1471}
1472
Ian Rogers0571d352011-11-03 19:51:38 -07001473CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1474 handler_.address_ = -1;
1475 int32_t offset = -1;
1476
1477 // Short-circuit the overwhelmingly common cases.
1478 switch (code_item.tries_size_) {
1479 case 0:
1480 break;
1481 case 1: {
1482 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1483 uint32_t start = tries->start_addr_;
1484 if (address >= start) {
1485 uint32_t end = start + tries->insn_count_;
1486 if (address < end) {
1487 offset = tries->handler_off_;
1488 }
1489 }
1490 break;
1491 }
1492 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001493 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001494 }
Logan Chien736df022012-04-27 16:25:57 +08001495 Init(code_item, offset);
1496}
1497
1498CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1499 const DexFile::TryItem& try_item) {
1500 handler_.address_ = -1;
1501 Init(code_item, try_item.handler_off_);
1502}
1503
1504void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1505 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001506 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001507 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001508 } else {
1509 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001510 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001511 remaining_count_ = -1;
1512 catch_all_ = false;
1513 DCHECK(!HasNext());
1514 }
1515}
1516
Ian Rogers13735952014-10-08 12:43:28 -07001517void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001518 current_data_ = handler_data;
1519 remaining_count_ = DecodeSignedLeb128(&current_data_);
1520
1521 // If remaining_count_ is non-positive, then it is the negative of
1522 // the number of catch types, and the catches are followed by a
1523 // catch-all handler.
1524 if (remaining_count_ <= 0) {
1525 catch_all_ = true;
1526 remaining_count_ = -remaining_count_;
1527 } else {
1528 catch_all_ = false;
1529 }
1530 Next();
1531}
1532
1533void CatchHandlerIterator::Next() {
1534 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001535 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001536 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1537 remaining_count_--;
1538 return;
1539 }
1540
1541 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001542 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001543 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1544 catch_all_ = false;
1545 return;
1546 }
1547
1548 // no more handler
1549 remaining_count_ = -1;
1550}
1551
Andreas Gampea5b09a62016-11-17 15:21:22 -08001552namespace dex {
1553
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001554std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1555 os << "StringIndex[" << index.index_ << "]";
1556 return os;
1557}
1558
Andreas Gampea5b09a62016-11-17 15:21:22 -08001559std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1560 os << "TypeIndex[" << index.index_ << "]";
1561 return os;
1562}
1563
1564} // namespace dex
1565
Carl Shapiro1fb86202011-06-27 17:43:13 -07001566} // namespace art