blob: 20098e74821143b2e5e9d428f13003c0729c1f4a [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080031#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080032#include "base/stringprintf.h"
Ian Rogers0571d352011-11-03 19:51:38 -070033#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080035#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070037#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070038#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070040#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070041#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070043#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070044#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070045#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070046#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070047#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070048
Andreas Gampe277ccbd2014-11-03 21:36:10 -080049#pragma GCC diagnostic push
50#pragma GCC diagnostic ignored "-Wshadow"
51#include "ScopedFd.h"
52#pragma GCC diagnostic pop
53
Carl Shapiro1fb86202011-06-27 17:43:13 -070054namespace art {
55
Ian Rogers13735952014-10-08 12:43:28 -070056const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
57const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070058
Ian Rogers8d31bbd2013-10-13 10:44:14 -070059static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070060 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000061 ScopedFd fd(open(filename, O_RDONLY, 0));
62 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070063 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070064 return -1;
65 }
Vladimir Markofd995762013-11-06 16:36:36 +000066 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070067 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070068 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070069 return -1;
70 }
Vladimir Markofd995762013-11-06 16:36:36 +000071 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
73 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 return -1;
75 }
Vladimir Markofd995762013-11-06 16:36:36 +000076 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070077}
78
Ian Rogers8d31bbd2013-10-13 10:44:14 -070079bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070080 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070081 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070082
83 // Strip ":...", which is the location
84 const char* zip_entry_name = kClassesDex;
85 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010086 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070087
Vladimir Markoaa4497d2014-09-05 14:01:17 +010088 if (DexFile::IsMultiDexLocation(filename)) {
89 file_part_storage = GetBaseLocation(filename);
90 file_part = file_part_storage.c_str();
91 zip_entry_name = filename + file_part_storage.size() + 1;
92 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070093 }
94
95 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000096 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070097 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070098 return false;
99 }
100 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700101 std::unique_ptr<ZipArchive> zip_archive(
102 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
103 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800104 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
105 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800106 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700107 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700108 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700110 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
111 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
113 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700114 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700116 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700117 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 std::unique_ptr<const DexFile> dex_file(
119 DexFile::OpenFile(fd.release(), filename, false, error_msg));
120 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return false;
122 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700123 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800124 return true;
125 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700126 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800127 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700128}
129
Andreas Gampe833a4852014-05-21 18:46:59 -0700130bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800131 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700132 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000134 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
135 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700136 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700137 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700138 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700140 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700141 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700142 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
144 error_msg));
145 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800146 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700147 return true;
148 } else {
149 return false;
150 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700151 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700152 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400153 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700154}
155
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800156int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700157 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800158 return 0;
159 } else {
160 return mem_map_->GetProtect();
161 }
162}
163
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200164bool DexFile::IsReadOnly() const {
165 return GetPermissions() == PROT_READ;
166}
167
Brian Carlstrome0948e12013-08-29 09:36:15 -0700168bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200169 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700170 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200171 return false;
172 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700173 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200174 }
175}
176
Brian Carlstrome0948e12013-08-29 09:36:15 -0700177bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200178 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700179 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200180 return false;
181 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700182 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183 }
184}
185
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800186std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
187 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700188 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700189 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000190 {
191 ScopedFd delayed_close(fd);
192 struct stat sbuf;
193 memset(&sbuf, 0, sizeof(sbuf));
194 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800195 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000196 return nullptr;
197 }
198 if (S_ISDIR(sbuf.st_mode)) {
199 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
200 return nullptr;
201 }
202 size_t length = sbuf.st_size;
203 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
204 if (map.get() == nullptr) {
205 DCHECK(!error_msg->empty());
206 return nullptr;
207 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700208 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800209
210 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700211 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800212 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700213 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800214 }
215
216 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
217
Andreas Gampe928f72b2014-09-09 19:53:48 -0700218 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
219 error_msg));
220 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700221 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
222 error_msg->c_str());
223 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800224 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800225
Andreas Gampe928f72b2014-09-09 19:53:48 -0700226 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
227 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700228 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800229 }
230
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800231 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700232}
233
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700234const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700235
Andreas Gampe833a4852014-05-21 18:46:59 -0700236bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800237 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700238 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700239 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 if (zip_archive.get() == nullptr) {
241 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700242 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700243 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700244 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800245}
246
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800247std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
248 uint32_t location_checksum,
249 MemMap* mem_map,
250 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800251 return OpenMemory(mem_map->Begin(),
252 mem_map->Size(),
253 location,
254 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700255 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800256 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700257 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800258}
259
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800260std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
261 const std::string& location, std::string* error_msg,
262 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800263 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700264 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700265 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700266 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700267 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700268 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700269 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700270 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700271 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700274 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700275 }
Ian Rogers700a4022014-05-19 16:49:03 -0700276 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700277 error_msg));
278 if (dex_file.get() == nullptr) {
279 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
280 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700281 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700282 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800283 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700284 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700285 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700286 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700287 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700288 }
289 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700290 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
291 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700292 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700293 return nullptr;
294 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800296 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297}
298
Andreas Gampe90e34042015-04-27 20:01:52 -0700299// Technically we do not have a limitation with respect to the number of dex files that can be in a
300// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
301// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
302// seems an excessive number.
303static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
304
Andreas Gampe833a4852014-05-21 18:46:59 -0700305bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800306 std::string* error_msg,
307 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700308 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700309 ZipOpenErrorCode error_code;
310 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
311 &error_code));
312 if (dex_file.get() == nullptr) {
313 return false;
314 } else {
315 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800316 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700317
318 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700319
320 // We could try to avoid std::string allocations by working on a char array directly. As we
321 // do not expect a lot of iterations, this seems too involved and brittle.
322
Andreas Gampe90e34042015-04-27 20:01:52 -0700323 for (size_t i = 1; ; ++i) {
324 std::string name = GetMultiDexClassesDexName(i);
325 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700326 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
327 error_msg, &error_code));
328 if (next_dex_file.get() == nullptr) {
329 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
330 LOG(WARNING) << error_msg;
331 }
332 break;
333 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800334 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 }
336
Andreas Gampe90e34042015-04-27 20:01:52 -0700337 if (i == kWarnOnManyDexFilesThreshold) {
338 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
339 << " dex files. Please consider coalescing and shrinking the number to "
340 " avoid runtime overhead.";
341 }
342
343 if (i == std::numeric_limits<size_t>::max()) {
344 LOG(ERROR) << "Overflow in number of dex files!";
345 break;
346 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700347 }
348
349 return true;
350 }
351}
352
353
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800354std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
355 size_t size,
356 const std::string& location,
357 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800358 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700359 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800360 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700361 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800362 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700363 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700364 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800365 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700366 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800367 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700368}
369
Ian Rogers13735952014-10-08 12:43:28 -0700370DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800371 const std::string& location,
372 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800373 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700374 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800375 : begin_(base),
376 size_(size),
377 location_(location),
378 location_checksum_(location_checksum),
379 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800380 header_(reinterpret_cast<const Header*>(base)),
381 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
382 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
383 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
384 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
385 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700386 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
387 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800388 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700389 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700390 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800391 CHECK_GT(size_, 0U) << GetLocation();
392}
393
Jesse Wilson6bf19152011-09-29 13:12:33 -0400394DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700395 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
396 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
397 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
398 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700399 // Remove the index if one were created.
400 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400401}
402
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700403bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700404 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700405 return false;
406 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700407 return true;
408}
409
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700410bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800411 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700412 std::ostringstream oss;
413 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800414 << " " << header_->magic_[0]
415 << " " << header_->magic_[1]
416 << " " << header_->magic_[2]
417 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700418 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700419 return false;
420 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800421 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700422 std::ostringstream oss;
423 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800424 << " " << header_->magic_[4]
425 << " " << header_->magic_[5]
426 << " " << header_->magic_[6]
427 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700428 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700429 return false;
430 }
431 return true;
432}
433
Ian Rogers13735952014-10-08 12:43:28 -0700434bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800435 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
436}
437
Ian Rogers13735952014-10-08 12:43:28 -0700438bool DexFile::IsVersionValid(const uint8_t* magic) {
439 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800440 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
441}
442
Ian Rogersd81871c2011-10-03 13:57:23 -0700443uint32_t DexFile::GetVersion() const {
444 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
445 return atoi(version);
446}
447
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800448const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
449 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700450 // If we have an index lookup the descriptor via that as its constant time to search.
451 Index* index = class_def_index_.LoadSequentiallyConsistent();
452 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800453 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700454 return (it == index->end()) ? nullptr : it->second;
455 }
456 // Fast path for rate no class defs case.
457 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700458 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700459 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700460 }
Ian Rogers68b56852014-08-29 20:19:11 -0700461 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700462 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700463 if (string_id != nullptr) {
464 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
465 if (type_id != nullptr) {
466 uint16_t type_idx = GetIndexForTypeId(*type_id);
467 for (size_t i = 0; i < num_class_defs; ++i) {
468 const ClassDef& class_def = GetClassDef(i);
469 if (class_def.class_idx_ == type_idx) {
470 return &class_def;
471 }
472 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700473 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700474 }
Ian Rogers68b56852014-08-29 20:19:11 -0700475 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
476 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
477 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
478 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700479 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700480 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
481 if (old_misses == kMaxFailedDexClassDefLookups) {
482 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
483 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
484 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800485 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700486 for (uint32_t i = 0; i < num_class_defs; ++i) {
487 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800488 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800489 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700490 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700491 // Sanity check the index still doesn't exist, only 1 thread should build it.
492 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
493 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700494 }
495 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700496}
497
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700498const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
499 size_t num_class_defs = NumClassDefs();
500 for (size_t i = 0; i < num_class_defs; ++i) {
501 const ClassDef& class_def = GetClassDef(i);
502 if (class_def.class_idx_ == type_idx) {
503 return &class_def;
504 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700505 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700506 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700507}
508
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800509const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
510 const DexFile::StringId& name,
511 const DexFile::TypeId& type) const {
512 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
513 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
514 const uint32_t name_idx = GetIndexForStringId(name);
515 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700516 int32_t lo = 0;
517 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800518 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700519 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800520 const DexFile::FieldId& field = GetFieldId(mid);
521 if (class_idx > field.class_idx_) {
522 lo = mid + 1;
523 } else if (class_idx < field.class_idx_) {
524 hi = mid - 1;
525 } else {
526 if (name_idx > field.name_idx_) {
527 lo = mid + 1;
528 } else if (name_idx < field.name_idx_) {
529 hi = mid - 1;
530 } else {
531 if (type_idx > field.type_idx_) {
532 lo = mid + 1;
533 } else if (type_idx < field.type_idx_) {
534 hi = mid - 1;
535 } else {
536 return &field;
537 }
538 }
539 }
540 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700541 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800542}
543
544const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700545 const DexFile::StringId& name,
546 const DexFile::ProtoId& signature) const {
547 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800548 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700549 const uint32_t name_idx = GetIndexForStringId(name);
550 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700551 int32_t lo = 0;
552 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700553 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700554 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700555 const DexFile::MethodId& method = GetMethodId(mid);
556 if (class_idx > method.class_idx_) {
557 lo = mid + 1;
558 } else if (class_idx < method.class_idx_) {
559 hi = mid - 1;
560 } else {
561 if (name_idx > method.name_idx_) {
562 lo = mid + 1;
563 } else if (name_idx < method.name_idx_) {
564 hi = mid - 1;
565 } else {
566 if (proto_idx > method.proto_idx_) {
567 lo = mid + 1;
568 } else if (proto_idx < method.proto_idx_) {
569 hi = mid - 1;
570 } else {
571 return &method;
572 }
573 }
574 }
575 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700576 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700577}
578
Ian Rogers637c65b2013-05-31 11:46:00 -0700579const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t lo = 0;
581 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700582 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700583 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700584 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700585 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700586 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
587 if (compare > 0) {
588 lo = mid + 1;
589 } else if (compare < 0) {
590 hi = mid - 1;
591 } else {
592 return &str_id;
593 }
594 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700595 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700596}
597
Vladimir Markoa48aef42014-12-03 17:53:53 +0000598const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700599 int32_t lo = 0;
600 int32_t hi = NumStringIds() - 1;
601 while (hi >= lo) {
602 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700603 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700604 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000605 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700606 if (compare > 0) {
607 lo = mid + 1;
608 } else if (compare < 0) {
609 hi = mid - 1;
610 } else {
611 return &str_id;
612 }
613 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700614 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700615}
616
617const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700618 int32_t lo = 0;
619 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700620 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700621 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700622 const TypeId& type_id = GetTypeId(mid);
623 if (string_idx > type_id.descriptor_idx_) {
624 lo = mid + 1;
625 } else if (string_idx < type_id.descriptor_idx_) {
626 hi = mid - 1;
627 } else {
628 return &type_id;
629 }
630 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700631 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700632}
633
634const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000635 const uint16_t* signature_type_idxs,
636 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700637 int32_t lo = 0;
638 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700639 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700640 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700641 const DexFile::ProtoId& proto = GetProtoId(mid);
642 int compare = return_type_idx - proto.return_type_idx_;
643 if (compare == 0) {
644 DexFileParameterIterator it(*this, proto);
645 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000646 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700648 it.Next();
649 i++;
650 }
651 if (compare == 0) {
652 if (it.HasNext()) {
653 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000654 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700655 compare = 1;
656 }
657 }
658 }
659 if (compare > 0) {
660 lo = mid + 1;
661 } else if (compare < 0) {
662 hi = mid - 1;
663 } else {
664 return &proto;
665 }
666 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700667 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700668}
669
670// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700671bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
672 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700673 if (signature[0] != '(') {
674 return false;
675 }
676 size_t offset = 1;
677 size_t end = signature.size();
678 bool process_return = false;
679 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000680 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700681 char c = signature[offset];
682 offset++;
683 if (c == ')') {
684 process_return = true;
685 continue;
686 }
Ian Rogers0571d352011-11-03 19:51:38 -0700687 while (c == '[') { // process array prefix
688 if (offset >= end) { // expect some descriptor following [
689 return false;
690 }
691 c = signature[offset];
692 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700693 }
694 if (c == 'L') { // process type descriptors
695 do {
696 if (offset >= end) { // unexpected early termination of descriptor
697 return false;
698 }
699 c = signature[offset];
700 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700701 } while (c != ';');
702 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000703 // TODO: avoid creating a std::string just to get a 0-terminated char array
704 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700705 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700706 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700707 return false;
708 }
709 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700710 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700711 return false;
712 }
713 uint16_t type_idx = GetIndexForTypeId(*type_id);
714 if (!process_return) {
715 param_type_idxs->push_back(type_idx);
716 } else {
717 *return_type_idx = type_idx;
718 return offset == end; // return true if the signature had reached a sensible end
719 }
720 }
721 return false; // failed to correctly parse return type
722}
723
Ian Rogersd91d6d62013-09-25 20:26:14 -0700724const Signature DexFile::CreateSignature(const StringPiece& signature) const {
725 uint16_t return_type_idx;
726 std::vector<uint16_t> param_type_indices;
727 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
728 if (!success) {
729 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700730 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700731 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700732 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700733 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700734 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700735 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700736}
737
Ian Rogersef7d42f2014-01-06 12:55:46 -0800738int32_t DexFile::GetLineNumFromPC(mirror::ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700739 // For native method, lineno should be -2 to indicate it is native. Note that
740 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700742 return -2;
743 }
744
TDYa127c8dc1012012-04-19 07:03:33 -0700745 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700747
748 // A method with no line number info should return -1
749 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700750 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700751 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700752 return context.line_num_;
753}
754
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700755int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700756 // Note: Signed type is important for max and min.
757 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700758 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700759
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700760 while (min <= max) {
761 int32_t mid = min + ((max - min) / 2);
762
763 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
764 uint32_t start = ti->start_addr_;
765 uint32_t end = start + ti->insn_count_;
766
Ian Rogers0571d352011-11-03 19:51:38 -0700767 if (address < start) {
768 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700769 } else if (address >= end) {
770 min = mid + 1;
771 } else { // We have a winner!
772 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700773 }
774 }
775 // No match.
776 return -1;
777}
778
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700779int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
780 int32_t try_item = FindTryItem(code_item, address);
781 if (try_item == -1) {
782 return -1;
783 } else {
784 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
785 }
786}
787
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800788void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800789 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
791 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700792 uint32_t line = DecodeUnsignedLeb128(&stream);
793 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
794 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
795 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700796 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700797
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800798 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700799 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800800 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700801 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800802 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700803 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700804 local_in_reg[arg_reg].start_address_ = 0;
805 local_in_reg[arg_reg].is_live_ = true;
806 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700807 arg_reg++;
808 }
809
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800810 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700811 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700812 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700813 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800814 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700815 return;
816 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800817 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700818 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800819 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700820 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700821 local_in_reg[arg_reg].name_ = name;
822 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700823 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700824 local_in_reg[arg_reg].start_address_ = address;
825 local_in_reg[arg_reg].is_live_ = true;
826 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700827 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700828 case 'D':
829 case 'J':
830 arg_reg += 2;
831 break;
832 default:
833 arg_reg += 1;
834 break;
835 }
836 }
837
Ian Rogers0571d352011-11-03 19:51:38 -0700838 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800839 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
840 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 return;
842 }
843
844 for (;;) {
845 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700846 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800847 uint32_t name_idx;
848 uint32_t descriptor_idx;
849 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700850
Shih-wei Liao195487c2011-08-20 13:29:04 -0700851 switch (opcode) {
852 case DBG_END_SEQUENCE:
853 return;
854
855 case DBG_ADVANCE_PC:
856 address += DecodeUnsignedLeb128(&stream);
857 break;
858
859 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700860 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700861 break;
862
863 case DBG_START_LOCAL:
864 case DBG_START_LOCAL_EXTENDED:
865 reg = DecodeUnsignedLeb128(&stream);
866 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700867 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800868 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700869 return;
870 }
871
jeffhaof8728872011-10-28 19:11:13 -0700872 name_idx = DecodeUnsignedLeb128P1(&stream);
873 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
874 if (opcode == DBG_START_LOCAL_EXTENDED) {
875 signature_idx = DecodeUnsignedLeb128P1(&stream);
876 }
877
Shih-wei Liao195487c2011-08-20 13:29:04 -0700878 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700879 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800880 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881
Ian Rogers0571d352011-11-03 19:51:38 -0700882 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
883 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700884 if (opcode == DBG_START_LOCAL_EXTENDED) {
Ian Rogers0571d352011-11-03 19:51:38 -0700885 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
Elliott Hughes30646832011-10-13 16:59:46 -0700886 }
887 local_in_reg[reg].start_address_ = address;
888 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700889 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890 break;
891
892 case DBG_END_LOCAL:
893 reg = DecodeUnsignedLeb128(&stream);
894 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700895 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800896 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700897 return;
898 }
899
Elliott Hughes30646832011-10-13 16:59:46 -0700900 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800901 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700902 local_in_reg[reg].is_live_ = false;
903 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 break;
905
906 case DBG_RESTART_LOCAL:
907 reg = DecodeUnsignedLeb128(&stream);
908 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700909 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800910 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700911 return;
912 }
913
Elliott Hughes30646832011-10-13 16:59:46 -0700914 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700915 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800916 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700917 return;
918 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919
Elliott Hughes30646832011-10-13 16:59:46 -0700920 // If the register is live, the "restart" is superfluous,
921 // and we don't want to mess with the existing start address.
922 if (!local_in_reg[reg].is_live_) {
923 local_in_reg[reg].start_address_ = address;
924 local_in_reg[reg].is_live_ = true;
925 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 }
927 break;
928
929 case DBG_SET_PROLOGUE_END:
930 case DBG_SET_EPILOGUE_BEGIN:
931 case DBG_SET_FILE:
932 break;
933
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700934 default: {
935 int adjopcode = opcode - DBG_FIRST_SPECIAL;
936
Shih-wei Liao195487c2011-08-20 13:29:04 -0700937 address += adjopcode / DBG_LINE_RANGE;
938 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
939
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700940 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800941 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 // early exit
943 return;
944 }
945 }
946 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700947 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948 }
949 }
950}
951
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800952void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800953 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
954 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100955 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700956 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700957 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700958 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700959 nullptr);
960 if (stream != nullptr) {
961 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
962 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700963 }
964 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700965 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
966 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700967 }
968}
969
Elliott Hughes2435a572012-02-17 16:07:41 -0800970bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
971 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700972
973 // We know that this callback will be called in
974 // ascending address order, so keep going until we find
975 // a match or we've just gone past it.
976 if (address > context->address_) {
977 // The line number from the previous positions callback
978 // wil be the final result.
979 return true;
980 } else {
981 context->line_num_ = line_num;
982 return address == context->address_;
983 }
984}
985
Andreas Gampe833a4852014-05-21 18:46:59 -0700986bool DexFile::IsMultiDexLocation(const char* location) {
987 return strrchr(location, kMultiDexSeparator) != nullptr;
988}
989
Andreas Gampe90e34042015-04-27 20:01:52 -0700990std::string DexFile::GetMultiDexClassesDexName(size_t index) {
991 if (index == 0) {
992 return "classes.dex";
993 } else {
994 return StringPrintf("classes%zu.dex", index + 1);
995 }
996}
997
998std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
999 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001000 return dex_location;
1001 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001002 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001003 }
1004}
1005
1006std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1007 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001008 std::string base_location = GetBaseLocation(dex_location);
1009 const char* suffix = dex_location + base_location.size();
1010 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1011 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1012 if (path != nullptr && path.get() != base_location) {
1013 return std::string(path.get()) + suffix;
1014 } else if (suffix[0] == 0) {
1015 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001016 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001017 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001018 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001019}
1020
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001021std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1022 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1023 dex_file.GetLocation().c_str(),
1024 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1025 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1026 return os;
1027}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001028
Ian Rogersd91d6d62013-09-25 20:26:14 -07001029std::string Signature::ToString() const {
1030 if (dex_file_ == nullptr) {
1031 CHECK(proto_id_ == nullptr);
1032 return "<no signature>";
1033 }
1034 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1035 std::string result;
1036 if (params == nullptr) {
1037 result += "()";
1038 } else {
1039 result += "(";
1040 for (uint32_t i = 0; i < params->Size(); ++i) {
1041 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1042 }
1043 result += ")";
1044 }
1045 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1046 return result;
1047}
1048
Vladimir Markod9cffea2013-11-25 15:08:02 +00001049bool Signature::operator==(const StringPiece& rhs) const {
1050 if (dex_file_ == nullptr) {
1051 return false;
1052 }
1053 StringPiece tail(rhs);
1054 if (!tail.starts_with("(")) {
1055 return false; // Invalid signature
1056 }
1057 tail.remove_prefix(1); // "(";
1058 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1059 if (params != nullptr) {
1060 for (uint32_t i = 0; i < params->Size(); ++i) {
1061 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
1062 if (!tail.starts_with(param)) {
1063 return false;
1064 }
1065 tail.remove_prefix(param.length());
1066 }
1067 }
1068 if (!tail.starts_with(")")) {
1069 return false;
1070 }
1071 tail.remove_prefix(1); // ")";
1072 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1073}
1074
Ian Rogersd91d6d62013-09-25 20:26:14 -07001075std::ostream& operator<<(std::ostream& os, const Signature& sig) {
1076 return os << sig.ToString();
1077}
1078
Ian Rogers0571d352011-11-03 19:51:38 -07001079// Decodes the header section from the class data bytes.
1080void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001081 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001082 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1083 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1084 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1085 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
1086}
1087
1088void ClassDataItemIterator::ReadClassDataField() {
1089 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1090 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001091 if (last_idx_ != 0 && field_.field_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001092 LOG(WARNING) << "Duplicate field in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001093 }
Ian Rogers0571d352011-11-03 19:51:38 -07001094}
1095
1096void ClassDataItemIterator::ReadClassDataMethod() {
1097 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
1098 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
1099 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001100 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07001101 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001102 }
Ian Rogers0571d352011-11-03 19:51:38 -07001103}
1104
1105// Read a signed integer. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001106static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001107 int32_t val = 0;
1108 for (int i = zwidth; i >= 0; --i) {
1109 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1110 }
1111 val >>= (3 - zwidth) * 8;
1112 return val;
1113}
1114
1115// Read an unsigned integer. "zwidth" is the zero-based byte count,
1116// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001117static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001118 uint32_t val = 0;
1119 if (!fill_on_right) {
1120 for (int i = zwidth; i >= 0; --i) {
1121 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1122 }
1123 val >>= (3 - zwidth) * 8;
1124 } else {
1125 for (int i = zwidth; i >= 0; --i) {
1126 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1127 }
1128 }
1129 return val;
1130}
1131
1132// Read a signed long. "zwidth" is the zero-based byte count.
Ian Rogers13735952014-10-08 12:43:28 -07001133static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
Ian Rogers0571d352011-11-03 19:51:38 -07001134 int64_t val = 0;
1135 for (int i = zwidth; i >= 0; --i) {
1136 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1137 }
1138 val >>= (7 - zwidth) * 8;
1139 return val;
1140}
1141
1142// Read an unsigned long. "zwidth" is the zero-based byte count,
1143// "fill_on_right" indicates which side we want to zero-fill from.
Ian Rogers13735952014-10-08 12:43:28 -07001144static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Ian Rogers0571d352011-11-03 19:51:38 -07001145 uint64_t val = 0;
1146 if (!fill_on_right) {
1147 for (int i = zwidth; i >= 0; --i) {
1148 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1149 }
1150 val >>= (7 - zwidth) * 8;
1151 } else {
1152 for (int i = zwidth; i >= 0; --i) {
1153 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1154 }
1155 }
1156 return val;
1157}
1158
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001159EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
1160 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
1161 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
1162 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07001163 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
1164 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001165 DCHECK(dex_cache != nullptr);
1166 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07001167 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001168 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001169 array_size_ = 0;
1170 } else {
1171 array_size_ = DecodeUnsignedLeb128(&ptr_);
1172 }
1173 if (array_size_ > 0) {
1174 Next();
1175 }
1176}
1177
1178void EncodedStaticFieldValueIterator::Next() {
1179 pos_++;
1180 if (pos_ >= array_size_) {
1181 return;
1182 }
Ian Rogers13735952014-10-08 12:43:28 -07001183 uint8_t value_type = *ptr_++;
1184 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07001185 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07001186 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07001187 switch (type_) {
1188 case kBoolean:
1189 jval_.i = (value_arg != 0) ? 1 : 0;
1190 width = 0;
1191 break;
1192 case kByte:
1193 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001194 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001195 break;
1196 case kShort:
1197 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001198 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001199 break;
1200 case kChar:
1201 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001202 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001203 break;
1204 case kInt:
1205 jval_.i = ReadSignedInt(ptr_, value_arg);
1206 break;
1207 case kLong:
1208 jval_.j = ReadSignedLong(ptr_, value_arg);
1209 break;
1210 case kFloat:
1211 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
1212 break;
1213 case kDouble:
1214 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
1215 break;
1216 case kString:
1217 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07001218 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
1219 break;
1220 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001221 case kMethod:
1222 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001223 case kArray:
1224 case kAnnotation:
1225 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001226 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001227 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001228 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001229 width = 0;
1230 break;
1231 default:
1232 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001233 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001234 }
1235 ptr_ += width;
1236}
1237
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001238template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07001239void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07001240 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001241 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
1242 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001243 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1244 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1245 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1246 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1247 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1248 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1249 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001250 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07001251 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001252 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001253 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07001254 break;
1255 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07001256 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001257 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
1258 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001259 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07001260 break;
1261 }
Ian Rogers0571d352011-11-03 19:51:38 -07001262 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1263 }
1264}
Mathieu Chartierc7853442015-03-27 14:35:38 -07001265template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
1266template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07001267
1268CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1269 handler_.address_ = -1;
1270 int32_t offset = -1;
1271
1272 // Short-circuit the overwhelmingly common cases.
1273 switch (code_item.tries_size_) {
1274 case 0:
1275 break;
1276 case 1: {
1277 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1278 uint32_t start = tries->start_addr_;
1279 if (address >= start) {
1280 uint32_t end = start + tries->insn_count_;
1281 if (address < end) {
1282 offset = tries->handler_off_;
1283 }
1284 }
1285 break;
1286 }
1287 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001288 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001289 }
Logan Chien736df022012-04-27 16:25:57 +08001290 Init(code_item, offset);
1291}
1292
1293CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1294 const DexFile::TryItem& try_item) {
1295 handler_.address_ = -1;
1296 Init(code_item, try_item.handler_off_);
1297}
1298
1299void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1300 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001301 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001302 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001303 } else {
1304 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001305 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001306 remaining_count_ = -1;
1307 catch_all_ = false;
1308 DCHECK(!HasNext());
1309 }
1310}
1311
Ian Rogers13735952014-10-08 12:43:28 -07001312void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001313 current_data_ = handler_data;
1314 remaining_count_ = DecodeSignedLeb128(&current_data_);
1315
1316 // If remaining_count_ is non-positive, then it is the negative of
1317 // the number of catch types, and the catches are followed by a
1318 // catch-all handler.
1319 if (remaining_count_ <= 0) {
1320 catch_all_ = true;
1321 remaining_count_ = -remaining_count_;
1322 } else {
1323 catch_all_ = false;
1324 }
1325 Next();
1326}
1327
1328void CatchHandlerIterator::Next() {
1329 if (remaining_count_ > 0) {
1330 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
1331 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1332 remaining_count_--;
1333 return;
1334 }
1335
1336 if (catch_all_) {
1337 handler_.type_idx_ = DexFile::kDexNoIndex16;
1338 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1339 catch_all_ = false;
1340 return;
1341 }
1342
1343 // no more handler
1344 remaining_count_ = -1;
1345}
1346
Carl Shapiro1fb86202011-06-27 17:43:13 -07001347} // namespace art