blob: 213f25dfdb4e2d0bc482c95e9a6db6635dacf15e [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"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080034#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000035#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080037#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000040#include "mirror/field.h"
41#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070043#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000044#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070046#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070047#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070048#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070049#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070050#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070051#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070052
Andreas Gampe277ccbd2014-11-03 21:36:10 -080053#pragma GCC diagnostic push
54#pragma GCC diagnostic ignored "-Wshadow"
55#include "ScopedFd.h"
56#pragma GCC diagnostic pop
57
Carl Shapiro1fb86202011-06-27 17:43:13 -070058namespace art {
59
Ian Rogers13735952014-10-08 12:43:28 -070060const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
61const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070062
Ian Rogers8d31bbd2013-10-13 10:44:14 -070063static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070064 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000065 ScopedFd fd(open(filename, O_RDONLY, 0));
66 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070067 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 return -1;
69 }
Vladimir Markofd995762013-11-06 16:36:36 +000070 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070071 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070073 return -1;
74 }
Vladimir Markofd995762013-11-06 16:36:36 +000075 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070076 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
77 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070078 return -1;
79 }
Vladimir Markofd995762013-11-06 16:36:36 +000080 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070081}
82
Ian Rogers8d31bbd2013-10-13 10:44:14 -070083bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070084 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070086
87 // Strip ":...", which is the location
88 const char* zip_entry_name = kClassesDex;
89 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010090 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070091
Vladimir Markoaa4497d2014-09-05 14:01:17 +010092 if (DexFile::IsMultiDexLocation(filename)) {
93 file_part_storage = GetBaseLocation(filename);
94 file_part = file_part_storage.c_str();
95 zip_entry_name = filename + file_part_storage.size() + 1;
96 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070097 }
98
99 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000100 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700101 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700102 return false;
103 }
104 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700105 std::unique_ptr<ZipArchive> zip_archive(
106 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
107 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800108 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
109 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700111 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700112 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700114 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
115 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return false;
117 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700118 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700120 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700121 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 std::unique_ptr<const DexFile> dex_file(
123 DexFile::OpenFile(fd.release(), filename, false, error_msg));
124 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800125 return false;
126 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800128 return true;
129 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800131 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700132}
133
Andreas Gampe833a4852014-05-21 18:46:59 -0700134bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800135 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700136 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700137 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000138 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
139 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700140 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700142 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700143 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700145 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700146 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700147 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
148 error_msg));
149 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800150 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700151 return true;
152 } else {
153 return false;
154 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700155 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700156 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400157 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700158}
159
Andreas Gampe0cba0042015-04-29 20:47:16 -0700160static bool ContainsClassesDex(int fd, const char* filename) {
161 std::string error_msg;
162 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
163 if (zip_archive.get() == nullptr) {
164 return false;
165 }
166 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
167 return (zip_entry.get() != nullptr);
168}
169
170bool DexFile::MaybeDex(const char* filename) {
171 uint32_t magic;
172 std::string error_msg;
173 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
174 if (fd.get() == -1) {
175 return false;
176 }
177 if (IsZipMagic(magic)) {
178 return ContainsClassesDex(fd.release(), filename);
179 } else if (IsDexMagic(magic)) {
180 return true;
181 }
182 return false;
183}
184
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800185int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700186 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800187 return 0;
188 } else {
189 return mem_map_->GetProtect();
190 }
191}
192
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193bool DexFile::IsReadOnly() const {
194 return GetPermissions() == PROT_READ;
195}
196
Brian Carlstrome0948e12013-08-29 09:36:15 -0700197bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200198 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700199 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 return false;
201 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700202 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200203 }
204}
205
Brian Carlstrome0948e12013-08-29 09:36:15 -0700206bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200207 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700208 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200209 return false;
210 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700211 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200212 }
213}
214
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800215std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
216 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700217 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700218 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000219 {
220 ScopedFd delayed_close(fd);
221 struct stat sbuf;
222 memset(&sbuf, 0, sizeof(sbuf));
223 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800224 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000225 return nullptr;
226 }
227 if (S_ISDIR(sbuf.st_mode)) {
228 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
229 return nullptr;
230 }
231 size_t length = sbuf.st_size;
232 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
233 if (map.get() == nullptr) {
234 DCHECK(!error_msg->empty());
235 return nullptr;
236 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700237 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800238
239 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800241 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700242 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800243 }
244
245 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
246
Andreas Gampe928f72b2014-09-09 19:53:48 -0700247 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
248 error_msg));
249 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700250 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
251 error_msg->c_str());
252 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800253 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800254
Andreas Gampe928f72b2014-09-09 19:53:48 -0700255 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
256 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700257 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800258 }
259
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800260 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700261}
262
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700263const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264
Andreas Gampe833a4852014-05-21 18:46:59 -0700265bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800266 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700267 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700268 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700269 if (zip_archive.get() == nullptr) {
270 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700271 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700272 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800274}
275
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800276std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
277 uint32_t location_checksum,
278 MemMap* mem_map,
279 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800280 return OpenMemory(mem_map->Begin(),
281 mem_map->Size(),
282 location,
283 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700284 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800285 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700286 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800287}
288
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
290 const std::string& location, std::string* error_msg,
291 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800292 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700293 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700294 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700296 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700298 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700299 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700300 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700301 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700302 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700304 }
Ian Rogers700a4022014-05-19 16:49:03 -0700305 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700306 error_msg));
307 if (dex_file.get() == nullptr) {
308 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
309 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700310 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700311 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800312 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700313 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700314 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700315 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700317 }
318 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700319 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
320 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700321 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700322 return nullptr;
323 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700324 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700326}
327
Andreas Gampe90e34042015-04-27 20:01:52 -0700328// Technically we do not have a limitation with respect to the number of dex files that can be in a
329// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
330// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
331// seems an excessive number.
332static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
333
Andreas Gampe833a4852014-05-21 18:46:59 -0700334bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800335 std::string* error_msg,
336 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700337 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700338 ZipOpenErrorCode error_code;
339 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
340 &error_code));
341 if (dex_file.get() == nullptr) {
342 return false;
343 } else {
344 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800345 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700346
347 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700348
349 // We could try to avoid std::string allocations by working on a char array directly. As we
350 // do not expect a lot of iterations, this seems too involved and brittle.
351
Andreas Gampe90e34042015-04-27 20:01:52 -0700352 for (size_t i = 1; ; ++i) {
353 std::string name = GetMultiDexClassesDexName(i);
354 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700355 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
356 error_msg, &error_code));
357 if (next_dex_file.get() == nullptr) {
358 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
359 LOG(WARNING) << error_msg;
360 }
361 break;
362 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800363 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 }
365
Andreas Gampe90e34042015-04-27 20:01:52 -0700366 if (i == kWarnOnManyDexFilesThreshold) {
367 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
368 << " dex files. Please consider coalescing and shrinking the number to "
369 " avoid runtime overhead.";
370 }
371
372 if (i == std::numeric_limits<size_t>::max()) {
373 LOG(ERROR) << "Overflow in number of dex files!";
374 break;
375 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700376 }
377
378 return true;
379 }
380}
381
382
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800383std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
384 size_t size,
385 const std::string& location,
386 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800387 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700388 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800389 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700390 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800391 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700392 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700393 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800394 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700395 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800396 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700397}
398
Ian Rogers13735952014-10-08 12:43:28 -0700399DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800400 const std::string& location,
401 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800402 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700403 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800404 : begin_(base),
405 size_(size),
406 location_(location),
407 location_checksum_(location_checksum),
408 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800409 header_(reinterpret_cast<const Header*>(base)),
410 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
411 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
412 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
413 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
414 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700415 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
416 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800417 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800420 CHECK_GT(size_, 0U) << GetLocation();
421}
422
Jesse Wilson6bf19152011-09-29 13:12:33 -0400423DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700424 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
425 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
426 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
427 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700428 // Remove the index if one were created.
429 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400430}
431
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700434 return false;
435 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700436 return true;
437}
438
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800440 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 std::ostringstream oss;
442 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800443 << " " << header_->magic_[0]
444 << " " << header_->magic_[1]
445 << " " << header_->magic_[2]
446 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700448 return false;
449 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800450 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700451 std::ostringstream oss;
452 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800453 << " " << header_->magic_[4]
454 << " " << header_->magic_[5]
455 << " " << header_->magic_[6]
456 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700457 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700458 return false;
459 }
460 return true;
461}
462
Ian Rogers13735952014-10-08 12:43:28 -0700463bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800464 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
465}
466
Ian Rogers13735952014-10-08 12:43:28 -0700467bool DexFile::IsVersionValid(const uint8_t* magic) {
468 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800469 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
470}
471
Ian Rogersd81871c2011-10-03 13:57:23 -0700472uint32_t DexFile::GetVersion() const {
473 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
474 return atoi(version);
475}
476
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800477const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
478 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700479 // If we have an index lookup the descriptor via that as its constant time to search.
480 Index* index = class_def_index_.LoadSequentiallyConsistent();
481 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800482 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700483 return (it == index->end()) ? nullptr : it->second;
484 }
485 // Fast path for rate no class defs case.
486 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700487 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700488 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700489 }
Ian Rogers68b56852014-08-29 20:19:11 -0700490 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700491 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700492 if (string_id != nullptr) {
493 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
494 if (type_id != nullptr) {
495 uint16_t type_idx = GetIndexForTypeId(*type_id);
496 for (size_t i = 0; i < num_class_defs; ++i) {
497 const ClassDef& class_def = GetClassDef(i);
498 if (class_def.class_idx_ == type_idx) {
499 return &class_def;
500 }
501 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700502 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700503 }
Ian Rogers68b56852014-08-29 20:19:11 -0700504 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
505 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
506 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
507 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700508 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700509 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
510 if (old_misses == kMaxFailedDexClassDefLookups) {
511 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
512 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
513 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800514 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700515 for (uint32_t i = 0; i < num_class_defs; ++i) {
516 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800517 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800518 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700519 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700520 // Sanity check the index still doesn't exist, only 1 thread should build it.
521 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
522 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700523 }
524 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700525}
526
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700527const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
528 size_t num_class_defs = NumClassDefs();
529 for (size_t i = 0; i < num_class_defs; ++i) {
530 const ClassDef& class_def = GetClassDef(i);
531 if (class_def.class_idx_ == type_idx) {
532 return &class_def;
533 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700534 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700535 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700536}
537
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800538const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
539 const DexFile::StringId& name,
540 const DexFile::TypeId& type) const {
541 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
542 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
543 const uint32_t name_idx = GetIndexForStringId(name);
544 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700545 int32_t lo = 0;
546 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800547 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700548 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800549 const DexFile::FieldId& field = GetFieldId(mid);
550 if (class_idx > field.class_idx_) {
551 lo = mid + 1;
552 } else if (class_idx < field.class_idx_) {
553 hi = mid - 1;
554 } else {
555 if (name_idx > field.name_idx_) {
556 lo = mid + 1;
557 } else if (name_idx < field.name_idx_) {
558 hi = mid - 1;
559 } else {
560 if (type_idx > field.type_idx_) {
561 lo = mid + 1;
562 } else if (type_idx < field.type_idx_) {
563 hi = mid - 1;
564 } else {
565 return &field;
566 }
567 }
568 }
569 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700570 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800571}
572
573const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700574 const DexFile::StringId& name,
575 const DexFile::ProtoId& signature) const {
576 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800577 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700578 const uint32_t name_idx = GetIndexForStringId(name);
579 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t lo = 0;
581 int32_t hi = NumMethodIds() - 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::MethodId& method = GetMethodId(mid);
585 if (class_idx > method.class_idx_) {
586 lo = mid + 1;
587 } else if (class_idx < method.class_idx_) {
588 hi = mid - 1;
589 } else {
590 if (name_idx > method.name_idx_) {
591 lo = mid + 1;
592 } else if (name_idx < method.name_idx_) {
593 hi = mid - 1;
594 } else {
595 if (proto_idx > method.proto_idx_) {
596 lo = mid + 1;
597 } else if (proto_idx < method.proto_idx_) {
598 hi = mid - 1;
599 } else {
600 return &method;
601 }
602 }
603 }
604 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700605 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700606}
607
Ian Rogers637c65b2013-05-31 11:46:00 -0700608const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700609 int32_t lo = 0;
610 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700611 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700612 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700613 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700614 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700615 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
616 if (compare > 0) {
617 lo = mid + 1;
618 } else if (compare < 0) {
619 hi = mid - 1;
620 } else {
621 return &str_id;
622 }
623 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700624 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700625}
626
Vladimir Markoa48aef42014-12-03 17:53:53 +0000627const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700628 int32_t lo = 0;
629 int32_t hi = NumStringIds() - 1;
630 while (hi >= lo) {
631 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700632 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700633 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000634 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700635 if (compare > 0) {
636 lo = mid + 1;
637 } else if (compare < 0) {
638 hi = mid - 1;
639 } else {
640 return &str_id;
641 }
642 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700643 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700644}
645
646const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700647 int32_t lo = 0;
648 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700649 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700650 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700651 const TypeId& type_id = GetTypeId(mid);
652 if (string_idx > type_id.descriptor_idx_) {
653 lo = mid + 1;
654 } else if (string_idx < type_id.descriptor_idx_) {
655 hi = mid - 1;
656 } else {
657 return &type_id;
658 }
659 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700660 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700661}
662
663const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000664 const uint16_t* signature_type_idxs,
665 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700666 int32_t lo = 0;
667 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700668 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700670 const DexFile::ProtoId& proto = GetProtoId(mid);
671 int compare = return_type_idx - proto.return_type_idx_;
672 if (compare == 0) {
673 DexFileParameterIterator it(*this, proto);
674 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000675 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800676 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700677 it.Next();
678 i++;
679 }
680 if (compare == 0) {
681 if (it.HasNext()) {
682 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000683 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700684 compare = 1;
685 }
686 }
687 }
688 if (compare > 0) {
689 lo = mid + 1;
690 } else if (compare < 0) {
691 hi = mid - 1;
692 } else {
693 return &proto;
694 }
695 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700696 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700697}
698
699// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700700bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
701 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700702 if (signature[0] != '(') {
703 return false;
704 }
705 size_t offset = 1;
706 size_t end = signature.size();
707 bool process_return = false;
708 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000709 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700710 char c = signature[offset];
711 offset++;
712 if (c == ')') {
713 process_return = true;
714 continue;
715 }
Ian Rogers0571d352011-11-03 19:51:38 -0700716 while (c == '[') { // process array prefix
717 if (offset >= end) { // expect some descriptor following [
718 return false;
719 }
720 c = signature[offset];
721 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700722 }
723 if (c == 'L') { // process type descriptors
724 do {
725 if (offset >= end) { // unexpected early termination of descriptor
726 return false;
727 }
728 c = signature[offset];
729 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700730 } while (c != ';');
731 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000732 // TODO: avoid creating a std::string just to get a 0-terminated char array
733 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700734 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700735 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700736 return false;
737 }
738 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700739 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700740 return false;
741 }
742 uint16_t type_idx = GetIndexForTypeId(*type_id);
743 if (!process_return) {
744 param_type_idxs->push_back(type_idx);
745 } else {
746 *return_type_idx = type_idx;
747 return offset == end; // return true if the signature had reached a sensible end
748 }
749 }
750 return false; // failed to correctly parse return type
751}
752
Ian Rogersd91d6d62013-09-25 20:26:14 -0700753const Signature DexFile::CreateSignature(const StringPiece& signature) const {
754 uint16_t return_type_idx;
755 std::vector<uint16_t> param_type_indices;
756 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
757 if (!success) {
758 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700759 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700760 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700761 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700762 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700763 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700764 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700765}
766
Mathieu Chartiere401d142015-04-22 13:56:20 -0700767int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700768 // For native method, lineno should be -2 to indicate it is native. Note that
769 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700770 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700771 return -2;
772 }
773
TDYa127c8dc1012012-04-19 07:03:33 -0700774 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700775 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700776
777 // A method with no line number info should return -1
778 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700779 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700780 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700781 return context.line_num_;
782}
783
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700784int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700785 // Note: Signed type is important for max and min.
786 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700787 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700788
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700789 while (min <= max) {
790 int32_t mid = min + ((max - min) / 2);
791
792 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
793 uint32_t start = ti->start_addr_;
794 uint32_t end = start + ti->insn_count_;
795
Ian Rogers0571d352011-11-03 19:51:38 -0700796 if (address < start) {
797 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700798 } else if (address >= end) {
799 min = mid + 1;
800 } else { // We have a winner!
801 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700802 }
803 }
804 // No match.
805 return -1;
806}
807
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700808int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
809 int32_t try_item = FindTryItem(code_item, address);
810 if (try_item == -1) {
811 return -1;
812 } else {
813 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
814 }
815}
816
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800817void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800818 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700819 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
820 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700821 uint32_t line = DecodeUnsignedLeb128(&stream);
822 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
823 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
824 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700825 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700826
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700828 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800829 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700830 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800831 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700832 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700833 local_in_reg[arg_reg].start_address_ = 0;
834 local_in_reg[arg_reg].is_live_ = true;
835 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700836 arg_reg++;
837 }
838
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800839 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700840 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700842 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800843 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700844 return;
845 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800846 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700847 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800848 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700849 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700850 local_in_reg[arg_reg].name_ = name;
851 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700852 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700853 local_in_reg[arg_reg].start_address_ = address;
854 local_in_reg[arg_reg].is_live_ = true;
855 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700856 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700857 case 'D':
858 case 'J':
859 arg_reg += 2;
860 break;
861 default:
862 arg_reg += 1;
863 break;
864 }
865 }
866
Ian Rogers0571d352011-11-03 19:51:38 -0700867 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800868 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
869 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700870 return;
871 }
872
873 for (;;) {
874 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700875 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800876 uint32_t name_idx;
877 uint32_t descriptor_idx;
878 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700879
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 switch (opcode) {
881 case DBG_END_SEQUENCE:
882 return;
883
884 case DBG_ADVANCE_PC:
885 address += DecodeUnsignedLeb128(&stream);
886 break;
887
888 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700889 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890 break;
891
892 case DBG_START_LOCAL:
893 case DBG_START_LOCAL_EXTENDED:
894 reg = DecodeUnsignedLeb128(&stream);
895 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700896 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800897 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700898 return;
899 }
900
jeffhaof8728872011-10-28 19:11:13 -0700901 name_idx = DecodeUnsignedLeb128P1(&stream);
902 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
903 if (opcode == DBG_START_LOCAL_EXTENDED) {
904 signature_idx = DecodeUnsignedLeb128P1(&stream);
905 }
906
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700908 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800909 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910
Ian Rogers0571d352011-11-03 19:51:38 -0700911 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
912 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700913 local_in_reg[reg].signature_ =
914 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
915 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700916 local_in_reg[reg].start_address_ = address;
917 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700918 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 break;
920
921 case DBG_END_LOCAL:
922 reg = DecodeUnsignedLeb128(&stream);
923 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700924 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800925 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 return;
927 }
928
Elliott Hughes30646832011-10-13 16:59:46 -0700929 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800930 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700931 local_in_reg[reg].is_live_ = false;
932 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700933 break;
934
935 case DBG_RESTART_LOCAL:
936 reg = DecodeUnsignedLeb128(&stream);
937 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700938 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800939 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700940 return;
941 }
942
Elliott Hughes30646832011-10-13 16:59:46 -0700943 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700944 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800945 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700946 return;
947 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948
Elliott Hughes30646832011-10-13 16:59:46 -0700949 // If the register is live, the "restart" is superfluous,
950 // and we don't want to mess with the existing start address.
951 if (!local_in_reg[reg].is_live_) {
952 local_in_reg[reg].start_address_ = address;
953 local_in_reg[reg].is_live_ = true;
954 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955 }
956 break;
957
958 case DBG_SET_PROLOGUE_END:
959 case DBG_SET_EPILOGUE_BEGIN:
960 case DBG_SET_FILE:
961 break;
962
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700963 default: {
964 int adjopcode = opcode - DBG_FIRST_SPECIAL;
965
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 address += adjopcode / DBG_LINE_RANGE;
967 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
968
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700969 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800970 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700971 // early exit
972 return;
973 }
974 }
975 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700976 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700977 }
978 }
979}
980
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800981void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800982 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
983 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100984 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700985 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700986 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700987 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700988 nullptr);
989 if (stream != nullptr) {
990 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
991 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700992 }
993 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700994 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
995 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700996 }
997}
998
Elliott Hughes2435a572012-02-17 16:07:41 -0800999bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1000 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001001
1002 // We know that this callback will be called in
1003 // ascending address order, so keep going until we find
1004 // a match or we've just gone past it.
1005 if (address > context->address_) {
1006 // The line number from the previous positions callback
1007 // wil be the final result.
1008 return true;
1009 } else {
1010 context->line_num_ = line_num;
1011 return address == context->address_;
1012 }
1013}
1014
Andreas Gampe833a4852014-05-21 18:46:59 -07001015bool DexFile::IsMultiDexLocation(const char* location) {
1016 return strrchr(location, kMultiDexSeparator) != nullptr;
1017}
1018
Andreas Gampe90e34042015-04-27 20:01:52 -07001019std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1020 if (index == 0) {
1021 return "classes.dex";
1022 } else {
1023 return StringPrintf("classes%zu.dex", index + 1);
1024 }
1025}
1026
1027std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1028 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001029 return dex_location;
1030 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001031 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001032 }
1033}
1034
1035std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1036 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001037 std::string base_location = GetBaseLocation(dex_location);
1038 const char* suffix = dex_location + base_location.size();
1039 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1040 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1041 if (path != nullptr && path.get() != base_location) {
1042 return std::string(path.get()) + suffix;
1043 } else if (suffix[0] == 0) {
1044 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001045 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001046 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001047 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001048}
1049
Jeff Hao13e748b2015-08-25 20:44:19 +00001050// Read a signed integer. "zwidth" is the zero-based byte count.
1051static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1052 int32_t val = 0;
1053 for (int i = zwidth; i >= 0; --i) {
1054 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1055 }
1056 val >>= (3 - zwidth) * 8;
1057 return val;
1058}
1059
1060// Read an unsigned integer. "zwidth" is the zero-based byte count,
1061// "fill_on_right" indicates which side we want to zero-fill from.
1062static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1063 uint32_t val = 0;
1064 for (int i = zwidth; i >= 0; --i) {
1065 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1066 }
1067 if (!fill_on_right) {
1068 val >>= (3 - zwidth) * 8;
1069 }
1070 return val;
1071}
1072
1073// Read a signed long. "zwidth" is the zero-based byte count.
1074static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1075 int64_t val = 0;
1076 for (int i = zwidth; i >= 0; --i) {
1077 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1078 }
1079 val >>= (7 - zwidth) * 8;
1080 return val;
1081}
1082
1083// Read an unsigned long. "zwidth" is the zero-based byte count,
1084// "fill_on_right" indicates which side we want to zero-fill from.
1085static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1086 uint64_t val = 0;
1087 for (int i = zwidth; i >= 0; --i) {
1088 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1089 }
1090 if (!fill_on_right) {
1091 val >>= (7 - zwidth) * 8;
1092 }
1093 return val;
1094}
1095
1096const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1097 mirror::Class* klass = field->GetDeclaringClass();
1098 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1099 if (annotations_dir == nullptr) {
1100 return nullptr;
1101 }
1102 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1103 if (field_annotations == nullptr) {
1104 return nullptr;
1105 }
1106 uint32_t field_index = field->GetDexFieldIndex();
1107 uint32_t field_count = annotations_dir->fields_size_;
1108 for (uint32_t i = 0; i < field_count; ++i) {
1109 if (field_annotations[i].field_idx_ == field_index) {
1110 return GetFieldAnnotationSetItem(field_annotations[i]);
1111 }
1112 }
1113 return nullptr;
1114}
1115
1116mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1117 Handle<mirror::Class> annotation_class) const {
1118 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1119 if (annotation_set == nullptr) {
1120 return nullptr;
1121 }
1122 StackHandleScope<1> hs(Thread::Current());
1123 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1124 return GetAnnotationObjectFromAnnotationSet(
1125 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1126}
1127
1128mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1129 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1130 StackHandleScope<1> hs(Thread::Current());
1131 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1132 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1133}
1134
1135mirror::ObjectArray<mirror::Object>* DexFile::GetSignatureAnnotationForField(ArtField* field)
1136 const {
1137 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1138 if (annotation_set == nullptr) {
1139 return nullptr;
1140 }
1141 StackHandleScope<1> hs(Thread::Current());
1142 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1143 return GetSignatureValue(field_class, annotation_set);
1144}
1145
1146bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1147 const {
1148 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1149 if (annotation_set == nullptr) {
1150 return false;
1151 }
1152 StackHandleScope<1> hs(Thread::Current());
1153 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1154 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1155 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1156 return annotation_item != nullptr;
1157}
1158
1159const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1160 mirror::Class* klass = method->GetDeclaringClass();
1161 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1162 if (annotations_dir == nullptr) {
1163 return nullptr;
1164 }
1165 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1166 if (method_annotations == nullptr) {
1167 return nullptr;
1168 }
1169 uint32_t method_index = method->GetDexMethodIndex();
1170 uint32_t method_count = annotations_dir->methods_size_;
1171 for (uint32_t i = 0; i < method_count; ++i) {
1172 if (method_annotations[i].method_idx_ == method_index) {
1173 return GetMethodAnnotationSetItem(method_annotations[i]);
1174 }
1175 }
1176 return nullptr;
1177}
1178
1179const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1180 const {
1181 mirror::Class* klass = method->GetDeclaringClass();
1182 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1183 if (annotations_dir == nullptr) {
1184 return nullptr;
1185 }
1186 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1187 if (parameter_annotations == nullptr) {
1188 return nullptr;
1189 }
1190 uint32_t method_index = method->GetDexMethodIndex();
1191 uint32_t parameter_count = annotations_dir->parameters_size_;
1192 for (uint32_t i = 0; i < parameter_count; ++i) {
1193 if (parameter_annotations[i].method_idx_ == method_index) {
1194 return &parameter_annotations[i];
1195 }
1196 }
1197 return nullptr;
1198}
1199
1200mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1201 mirror::Class* klass = method->GetDeclaringClass();
1202 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1203 if (annotations_dir == nullptr) {
1204 return nullptr;
1205 }
1206 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1207 if (annotation_set == nullptr) {
1208 return nullptr;
1209 }
1210 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1211 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1212 if (annotation_item == nullptr) {
1213 return nullptr;
1214 }
1215 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1216 if (annotation == nullptr) {
1217 return nullptr;
1218 }
1219 uint8_t header_byte = *(annotation++);
1220 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1221 return nullptr;
1222 }
1223 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1224 if (annotation == nullptr) {
1225 return nullptr;
1226 }
1227 AnnotationValue annotation_value;
1228 StackHandleScope<2> hs(Thread::Current());
1229 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
1230 Handle<mirror::Class> return_type(hs.NewHandle(method->GetReturnType()));
1231 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1232 return nullptr;
1233 }
1234 return annotation_value.value_.GetL();
1235}
1236
1237mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1238 Handle<mirror::Class> annotation_class) const {
1239 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1240 if (annotation_set == nullptr) {
1241 return nullptr;
1242 }
1243 StackHandleScope<1> hs(Thread::Current());
1244 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1245 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1246 kDexVisibilityRuntime, annotation_class);
1247}
1248
1249mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1250 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1251 StackHandleScope<1> hs(Thread::Current());
1252 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1253 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1254}
1255
1256mirror::ObjectArray<mirror::Object>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
1257 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1258 if (annotation_set == nullptr) {
1259 return nullptr;
1260 }
1261 StackHandleScope<1> hs(Thread::Current());
1262 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1263 return GetThrowsValue(method_class, annotation_set);
1264}
1265
1266mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1267 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1268 if (parameter_annotations == nullptr) {
1269 return nullptr;
1270 }
1271 const AnnotationSetRefList* set_ref_list =
1272 GetParameterAnnotationSetRefList(parameter_annotations);
1273 if (set_ref_list == nullptr) {
1274 return nullptr;
1275 }
1276 uint32_t size = set_ref_list->size_;
1277 StackHandleScope<1> hs(Thread::Current());
1278 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1279 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1280}
1281
1282bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1283 const {
1284 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1285 if (annotation_set == nullptr) {
1286 return false;
1287 }
1288 StackHandleScope<1> hs(Thread::Current());
1289 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1290 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1291 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1292 return (annotation_item != nullptr);
1293}
1294
1295const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1296 const {
1297 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1298 if (annotations_dir == nullptr) {
1299 return nullptr;
1300 }
1301 return GetClassAnnotationSet(annotations_dir);
1302}
1303
1304mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1305 Handle<mirror::Class> annotation_class) const {
1306 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1307 if (annotation_set == nullptr) {
1308 return nullptr;
1309 }
1310 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1311 annotation_class);
1312}
1313
1314mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1315 const {
1316 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1317 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1318}
1319
1320bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1321 Handle<mirror::Class> annotation_class) const {
1322 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1323 if (annotation_set == nullptr) {
1324 return false;
1325 }
1326 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1327 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
1328 return (annotation_item != nullptr);
1329}
1330
1331mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1332 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1333 Thread* self = Thread::Current();
1334 ScopedObjectAccessUnchecked soa(self);
1335 StackHandleScope<5> hs(self);
1336 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1337 const char* name = StringDataByIdx(element_name_index);
1338 Handle<mirror::String> string_name(
1339 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1340
1341 ArtMethod* annotation_method =
1342 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1343 if (annotation_method == nullptr) {
1344 return nullptr;
1345 }
1346 Handle<mirror::Class> method_return(hs.NewHandle(annotation_method->GetReturnType()));
1347
1348 AnnotationValue annotation_value;
1349 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1350 return nullptr;
1351 }
1352 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1353
1354 mirror::Class* annotation_member_class =
1355 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1356 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1357 Handle<mirror::Method> method_object(
1358 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1359
1360 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1361 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1362 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1363 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1364 return nullptr;
1365 }
1366
1367 JValue result;
1368 ArtMethod* annotation_member_init =
1369 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1370 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1371 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1372 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1373 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1374 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1375 };
1376 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1377 if (self->IsExceptionPending()) {
1378 LOG(INFO) << "Exception in AnnotationMember.<init>";
1379 return nullptr;
1380 }
1381
1382 return new_member.Get();
1383}
1384
1385const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1386 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1387 Handle<mirror::Class> annotation_class) const {
1388 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1389 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1390 if (annotation_item->visibility_ != visibility) {
1391 continue;
1392 }
1393 const uint8_t* annotation = annotation_item->annotation_;
1394 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1395 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1396 klass->GetDexFile(), type_index, klass.Get());
1397 if (resolved_class == nullptr) {
1398 std::string temp;
1399 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1400 klass->GetDescriptor(&temp), type_index);
1401 CHECK(Thread::Current()->IsExceptionPending());
1402 Thread::Current()->ClearException();
1403 continue;
1404 }
1405 if (resolved_class == annotation_class.Get()) {
1406 return annotation_item;
1407 }
1408 }
1409
1410 return nullptr;
1411}
1412
1413mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1414 const AnnotationSetItem* annotation_set, uint32_t visibility,
1415 Handle<mirror::Class> annotation_class) const {
1416 const AnnotationItem* annotation_item =
1417 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1418 if (annotation_item == nullptr) {
1419 return nullptr;
1420 }
1421 const uint8_t* annotation = annotation_item->annotation_;
1422 return ProcessEncodedAnnotation(klass, &annotation);
1423}
1424
1425mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1426 const AnnotationItem* annotation_item, const char* annotation_name,
1427 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1428 const uint8_t* annotation =
1429 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1430 if (annotation == nullptr) {
1431 return nullptr;
1432 }
1433 AnnotationValue annotation_value;
1434 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1435 return nullptr;
1436 }
1437 if (annotation_value.type_ != expected_type) {
1438 return nullptr;
1439 }
1440 return annotation_value.value_.GetL();
1441}
1442
1443mirror::ObjectArray<mirror::Object>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
1444 const AnnotationSetItem* annotation_set) const {
1445 StackHandleScope<1> hs(Thread::Current());
1446 const AnnotationItem* annotation_item =
1447 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1448 if (annotation_item == nullptr) {
1449 return nullptr;
1450 }
1451 mirror::Class* string_class = mirror::String::GetJavaLangString();
1452 Handle<mirror::Class> string_array_class(hs.NewHandle(
1453 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
1454 mirror::Object* obj =
1455 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1456 if (obj == nullptr) {
1457 return nullptr;
1458 }
1459 return obj->AsObjectArray<mirror::Object>();
1460}
1461
1462mirror::ObjectArray<mirror::Object>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
1463 const AnnotationSetItem* annotation_set) const {
1464 StackHandleScope<1> hs(Thread::Current());
1465 const AnnotationItem* annotation_item =
1466 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1467 if (annotation_item == nullptr) {
1468 return nullptr;
1469 }
1470 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1471 Handle<mirror::Class> class_array_class(hs.NewHandle(
1472 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
1473 mirror::Object* obj =
1474 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1475 if (obj == nullptr) {
1476 return nullptr;
1477 }
1478 return obj->AsObjectArray<mirror::Object>();
1479}
1480
1481mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1482 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1483 Thread* self = Thread::Current();
1484 ScopedObjectAccessUnchecked soa(self);
1485 StackHandleScope<2> hs(self);
1486 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1487 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1488 if (annotation_set == nullptr) {
1489 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1490 }
1491
1492 uint32_t size = annotation_set->size_;
1493 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1494 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1495 if (result.Get() == nullptr) {
1496 return nullptr;
1497 }
1498
1499 uint32_t dest_index = 0;
1500 for (uint32_t i = 0; i < size; ++i) {
1501 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1502 if (annotation_item->visibility_ != visibility) {
1503 continue;
1504 }
1505 const uint8_t* annotation = annotation_item->annotation_;
1506 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1507 if (annotation_obj != nullptr) {
1508 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1509 ++dest_index;
1510 }
1511 }
1512
1513 if (dest_index == size) {
1514 return result.Get();
1515 }
1516
1517 mirror::ObjectArray<mirror::Object>* trimmed_result =
1518 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
1519 for (uint32_t i = 0; i < dest_index; ++i) {
1520 mirror::Object* obj = result->GetWithoutChecks(i);
1521 trimmed_result->SetWithoutChecks<false>(i, obj);
1522 }
1523
1524 return trimmed_result;
1525}
1526
1527mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1528 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1529 Thread* self = Thread::Current();
1530 ScopedObjectAccessUnchecked soa(self);
1531 StackHandleScope<1> hs(self);
1532 mirror::Class* annotation_array_class =
1533 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1534 mirror::Class* annotation_array_array_class =
1535 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
1536 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1537 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1538 if (annotation_array_array.Get() == nullptr) {
1539 LOG(ERROR) << "Annotation set ref array allocation failed";
1540 return nullptr;
1541 }
1542 for (uint32_t index = 0; index < size; ++index) {
1543 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1544 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1545 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1546 if (annotation_set == nullptr) {
1547 return nullptr;
1548 }
1549 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1550 }
1551 return annotation_array_array.Get();
1552}
1553
1554bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1555 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1556 DexFile::AnnotationResultStyle result_style) const {
1557 Thread* self = Thread::Current();
1558 mirror::Object* element_object = nullptr;
1559 bool set_object = false;
1560 Primitive::Type primitive_type = Primitive::kPrimVoid;
1561 const uint8_t* annotation = *annotation_ptr;
1562 uint8_t header_byte = *(annotation++);
1563 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1564 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1565 int32_t width = value_arg + 1;
1566 annotation_value->type_ = value_type;
1567
1568 switch (value_type) {
1569 case kDexAnnotationByte:
1570 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1571 primitive_type = Primitive::kPrimByte;
1572 break;
1573 case kDexAnnotationShort:
1574 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1575 primitive_type = Primitive::kPrimShort;
1576 break;
1577 case kDexAnnotationChar:
1578 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1579 false)));
1580 primitive_type = Primitive::kPrimChar;
1581 break;
1582 case kDexAnnotationInt:
1583 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1584 primitive_type = Primitive::kPrimInt;
1585 break;
1586 case kDexAnnotationLong:
1587 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1588 primitive_type = Primitive::kPrimLong;
1589 break;
1590 case kDexAnnotationFloat:
1591 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1592 primitive_type = Primitive::kPrimFloat;
1593 break;
1594 case kDexAnnotationDouble:
1595 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1596 primitive_type = Primitive::kPrimDouble;
1597 break;
1598 case kDexAnnotationBoolean:
1599 annotation_value->value_.SetZ(value_arg != 0);
1600 primitive_type = Primitive::kPrimBoolean;
1601 width = 0;
1602 break;
1603 case kDexAnnotationString: {
1604 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1605 if (result_style == kAllRaw) {
1606 annotation_value->value_.SetI(index);
1607 } else {
1608 StackHandleScope<1> hs(self);
1609 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1610 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1611 klass->GetDexFile(), index, dex_cache);
1612 set_object = true;
1613 if (element_object == nullptr) {
1614 return false;
1615 }
1616 }
1617 break;
1618 }
1619 case kDexAnnotationType: {
1620 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1621 if (result_style == kAllRaw) {
1622 annotation_value->value_.SetI(index);
1623 } else {
1624 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1625 klass->GetDexFile(), index, klass.Get());
1626 set_object = true;
1627 if (element_object == nullptr) {
1628 self->ClearException();
1629 const char* msg = StringByTypeIdx(index);
1630 self->ThrowNewException("Ljava/lang/TypeNotPresentException;", msg);
1631 }
1632 }
1633 break;
1634 }
1635 case kDexAnnotationMethod: {
1636 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1637 if (result_style == kAllRaw) {
1638 annotation_value->value_.SetI(index);
1639 } else {
1640 StackHandleScope<2> hs(self);
1641 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1642 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1643 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1644 klass->GetDexFile(), index, dex_cache, class_loader);
1645 if (method == nullptr) {
1646 return false;
1647 }
1648 set_object = true;
1649 if (method->IsConstructor()) {
1650 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1651 } else {
1652 element_object = mirror::Method::CreateFromArtMethod(self, method);
1653 }
1654 if (element_object == nullptr) {
1655 return false;
1656 }
1657 }
1658 break;
1659 }
1660 case kDexAnnotationField: {
1661 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1662 if (result_style == kAllRaw) {
1663 annotation_value->value_.SetI(index);
1664 } else {
1665 StackHandleScope<2> hs(self);
1666 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1667 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1668 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1669 klass->GetDexFile(), index, dex_cache, class_loader);
1670 if (field == nullptr) {
1671 return false;
1672 }
1673 set_object = true;
1674 element_object = mirror::Field::CreateFromArtField(self, field, true);
1675 if (element_object == nullptr) {
1676 return false;
1677 }
1678 }
1679 break;
1680 }
1681 case kDexAnnotationEnum: {
1682 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1683 if (result_style == kAllRaw) {
1684 annotation_value->value_.SetI(index);
1685 } else {
1686 StackHandleScope<3> hs(self);
1687 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1688 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1689 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1690 klass->GetDexFile(), index, dex_cache, class_loader, true);
1691 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1692 if (enum_field == nullptr) {
1693 return false;
1694 } else {
1695 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1696 element_object = enum_field->GetObject(field_class.Get());
1697 set_object = true;
1698 }
1699 }
1700 break;
1701 }
1702 case kDexAnnotationArray:
1703 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1704 return false;
1705 } else {
1706 ScopedObjectAccessUnchecked soa(self);
1707 StackHandleScope<2> hs(self);
1708 uint32_t size = DecodeUnsignedLeb128(&annotation);
1709 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1710 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1711 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1712 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1713 if (new_array.Get() == nullptr) {
1714 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1715 return false;
1716 }
1717 AnnotationValue new_annotation_value;
1718 for (uint32_t i = 0; i < size; ++i) {
1719 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1720 kPrimitivesOrObjects)) {
1721 return false;
1722 }
1723 if (!component_type->IsPrimitive()) {
1724 mirror::Object* obj = new_annotation_value.value_.GetL();
1725 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1726 } else {
1727 switch (new_annotation_value.type_) {
1728 case kDexAnnotationByte:
1729 new_array->AsByteArray()->SetWithoutChecks<false>(
1730 i, new_annotation_value.value_.GetB());
1731 break;
1732 case kDexAnnotationShort:
1733 new_array->AsShortArray()->SetWithoutChecks<false>(
1734 i, new_annotation_value.value_.GetS());
1735 break;
1736 case kDexAnnotationChar:
1737 new_array->AsCharArray()->SetWithoutChecks<false>(
1738 i, new_annotation_value.value_.GetC());
1739 break;
1740 case kDexAnnotationInt:
1741 new_array->AsIntArray()->SetWithoutChecks<false>(
1742 i, new_annotation_value.value_.GetI());
1743 break;
1744 case kDexAnnotationLong:
1745 new_array->AsLongArray()->SetWithoutChecks<false>(
1746 i, new_annotation_value.value_.GetJ());
1747 break;
1748 case kDexAnnotationFloat:
1749 new_array->AsFloatArray()->SetWithoutChecks<false>(
1750 i, new_annotation_value.value_.GetF());
1751 break;
1752 case kDexAnnotationDouble:
1753 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1754 i, new_annotation_value.value_.GetD());
1755 break;
1756 case kDexAnnotationBoolean:
1757 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1758 i, new_annotation_value.value_.GetZ());
1759 break;
1760 default:
1761 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1762 return false;
1763 }
1764 }
1765 }
1766 element_object = new_array.Get();
1767 set_object = true;
1768 width = 0;
1769 }
1770 break;
1771 case kDexAnnotationAnnotation:
1772 if (result_style == kAllRaw) {
1773 return false;
1774 }
1775 element_object = ProcessEncodedAnnotation(klass, &annotation);
1776 if (element_object == nullptr) {
1777 return false;
1778 }
1779 set_object = true;
1780 width = 0;
1781 break;
1782 case kDexAnnotationNull:
1783 if (result_style == kAllRaw) {
1784 annotation_value->value_.SetI(0);
1785 } else {
1786 CHECK(element_object == nullptr);
1787 set_object = true;
1788 }
1789 width = 0;
1790 break;
1791 default:
1792 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1793 return false;
1794 }
1795
1796 annotation += width;
1797 *annotation_ptr = annotation;
1798
1799 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1800 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1801 set_object = true;
1802 }
1803
1804 if (set_object) {
1805 annotation_value->value_.SetL(element_object);
1806 }
1807
1808 return true;
1809}
1810
1811mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1812 const uint8_t** annotation) const {
1813 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1814 uint32_t size = DecodeUnsignedLeb128(annotation);
1815
1816 Thread* self = Thread::Current();
1817 ScopedObjectAccessUnchecked soa(self);
1818 StackHandleScope<2> hs(self);
1819 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1820 Handle<mirror::Class> annotation_class(hs.NewHandle(
1821 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1822 if (annotation_class.Get() == nullptr) {
1823 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1824 << type_index;
1825 DCHECK(Thread::Current()->IsExceptionPending());
1826 Thread::Current()->ClearException();
1827 return nullptr;
1828 }
1829
1830 mirror::Class* annotation_member_class =
1831 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
1832 mirror::Class* annotation_member_array_class =
1833 class_linker->FindArrayClass(self, &annotation_member_class);
1834 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
1835
1836 if (size > 0) {
1837 element_array =
1838 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
1839 if (element_array == nullptr) {
1840 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
1841 return nullptr;
1842 }
1843 }
1844
1845 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
1846 for (uint32_t i = 0; i < size; ++i) {
1847 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
1848 if (new_member == nullptr) {
1849 return nullptr;
1850 }
1851 h_element_array->SetWithoutChecks<false>(i, new_member);
1852 }
1853
1854 JValue result;
1855 ArtMethod* create_annotation_method =
1856 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
1857 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
1858 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
1859 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
1860 if (self->IsExceptionPending()) {
1861 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
1862 return nullptr;
1863 }
1864
1865 return result.GetL();
1866}
1867
1868const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
1869 const char* descriptor, uint32_t visibility) const {
1870 const AnnotationItem* result = nullptr;
1871 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1872 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1873 if (annotation_item->visibility_ != visibility) {
1874 continue;
1875 }
1876 const uint8_t* annotation = annotation_item->annotation_;
1877 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1878
1879 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
1880 result = annotation_item;
1881 break;
1882 }
1883 }
1884 return result;
1885}
1886
1887const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
1888 DecodeUnsignedLeb128(&annotation); // unused type_index
1889 uint32_t size = DecodeUnsignedLeb128(&annotation);
1890
1891 while (size != 0) {
1892 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
1893 const char* element_name = GetStringData(GetStringId(element_name_index));
1894 if (strcmp(name, element_name) == 0) {
1895 return annotation;
1896 }
1897 SkipAnnotationValue(&annotation);
1898 size--;
1899 }
1900 return nullptr;
1901}
1902
1903bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
1904 const uint8_t* annotation = *annotation_ptr;
1905 uint8_t header_byte = *(annotation++);
1906 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1907 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1908 int32_t width = value_arg + 1;
1909
1910 switch (value_type) {
1911 case kDexAnnotationByte:
1912 case kDexAnnotationShort:
1913 case kDexAnnotationChar:
1914 case kDexAnnotationInt:
1915 case kDexAnnotationLong:
1916 case kDexAnnotationFloat:
1917 case kDexAnnotationDouble:
1918 case kDexAnnotationString:
1919 case kDexAnnotationType:
1920 case kDexAnnotationMethod:
1921 case kDexAnnotationField:
1922 case kDexAnnotationEnum:
1923 break;
1924 case kDexAnnotationArray:
1925 {
1926 uint32_t size = DecodeUnsignedLeb128(&annotation);
1927 while (size--) {
1928 if (!SkipAnnotationValue(&annotation)) {
1929 return false;
1930 }
1931 }
1932 width = 0;
1933 break;
1934 }
1935 case kDexAnnotationAnnotation:
1936 {
1937 DecodeUnsignedLeb128(&annotation); // unused type_index
1938 uint32_t size = DecodeUnsignedLeb128(&annotation);
1939 while (size--) {
1940 DecodeUnsignedLeb128(&annotation); // unused element_name_index
1941 if (!SkipAnnotationValue(&annotation)) {
1942 return false;
1943 }
1944 }
1945 width = 0;
1946 break;
1947 }
1948 case kDexAnnotationBoolean:
1949 case kDexAnnotationNull:
1950 width = 0;
1951 break;
1952 default:
1953 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
1954 return false;
1955 }
1956
1957 annotation += width;
1958 *annotation_ptr = annotation;
1959 return true;
1960}
1961
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001962std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
1963 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
1964 dex_file.GetLocation().c_str(),
1965 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
1966 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
1967 return os;
1968}
Calin Juravle4e1d5792014-07-15 23:56:47 +01001969
Ian Rogersd91d6d62013-09-25 20:26:14 -07001970std::string Signature::ToString() const {
1971 if (dex_file_ == nullptr) {
1972 CHECK(proto_id_ == nullptr);
1973 return "<no signature>";
1974 }
1975 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
1976 std::string result;
1977 if (params == nullptr) {
1978 result += "()";
1979 } else {
1980 result += "(";
1981 for (uint32_t i = 0; i < params->Size(); ++i) {
1982 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
1983 }
1984 result += ")";
1985 }
1986 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
1987 return result;
1988}
1989
Vladimir Markod9cffea2013-11-25 15:08:02 +00001990bool Signature::operator==(const StringPiece& rhs) const {
1991 if (dex_file_ == nullptr) {
1992 return false;
1993 }
1994 StringPiece tail(rhs);
1995 if (!tail.starts_with("(")) {
1996 return false; // Invalid signature
1997 }
1998 tail.remove_prefix(1); // "(";
1999 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2000 if (params != nullptr) {
2001 for (uint32_t i = 0; i < params->Size(); ++i) {
2002 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2003 if (!tail.starts_with(param)) {
2004 return false;
2005 }
2006 tail.remove_prefix(param.length());
2007 }
2008 }
2009 if (!tail.starts_with(")")) {
2010 return false;
2011 }
2012 tail.remove_prefix(1); // ")";
2013 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2014}
2015
Ian Rogersd91d6d62013-09-25 20:26:14 -07002016std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2017 return os << sig.ToString();
2018}
2019
Ian Rogers0571d352011-11-03 19:51:38 -07002020// Decodes the header section from the class data bytes.
2021void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002022 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002023 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2024 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2025 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2026 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2027}
2028
2029void ClassDataItemIterator::ReadClassDataField() {
2030 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2031 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002032 // The user of the iterator is responsible for checking if there
2033 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002034}
2035
2036void ClassDataItemIterator::ReadClassDataMethod() {
2037 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2038 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2039 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002040 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002041 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002042 }
Ian Rogers0571d352011-11-03 19:51:38 -07002043}
2044
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002045EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2046 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2047 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2048 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002049 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2050 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002051 DCHECK(dex_cache != nullptr);
2052 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002053 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002054 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002055 array_size_ = 0;
2056 } else {
2057 array_size_ = DecodeUnsignedLeb128(&ptr_);
2058 }
2059 if (array_size_ > 0) {
2060 Next();
2061 }
2062}
2063
2064void EncodedStaticFieldValueIterator::Next() {
2065 pos_++;
2066 if (pos_ >= array_size_) {
2067 return;
2068 }
Ian Rogers13735952014-10-08 12:43:28 -07002069 uint8_t value_type = *ptr_++;
2070 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002071 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002072 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002073 switch (type_) {
2074 case kBoolean:
2075 jval_.i = (value_arg != 0) ? 1 : 0;
2076 width = 0;
2077 break;
2078 case kByte:
2079 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002080 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002081 break;
2082 case kShort:
2083 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002084 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002085 break;
2086 case kChar:
2087 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002088 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002089 break;
2090 case kInt:
2091 jval_.i = ReadSignedInt(ptr_, value_arg);
2092 break;
2093 case kLong:
2094 jval_.j = ReadSignedLong(ptr_, value_arg);
2095 break;
2096 case kFloat:
2097 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2098 break;
2099 case kDouble:
2100 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2101 break;
2102 case kString:
2103 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002104 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2105 break;
2106 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002107 case kMethod:
2108 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002109 case kArray:
2110 case kAnnotation:
2111 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002112 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002113 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002114 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002115 width = 0;
2116 break;
2117 default:
2118 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002119 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002120 }
2121 ptr_ += width;
2122}
2123
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002124template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002125void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002126 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002127 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2128 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002129 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2130 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2131 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2132 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2133 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2134 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2135 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002136 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002137 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002138 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002139 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002140 break;
2141 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002142 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002143 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2144 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002145 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002146 break;
2147 }
Ian Rogers0571d352011-11-03 19:51:38 -07002148 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2149 }
2150}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002151template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2152template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002153
2154CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2155 handler_.address_ = -1;
2156 int32_t offset = -1;
2157
2158 // Short-circuit the overwhelmingly common cases.
2159 switch (code_item.tries_size_) {
2160 case 0:
2161 break;
2162 case 1: {
2163 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2164 uint32_t start = tries->start_addr_;
2165 if (address >= start) {
2166 uint32_t end = start + tries->insn_count_;
2167 if (address < end) {
2168 offset = tries->handler_off_;
2169 }
2170 }
2171 break;
2172 }
2173 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002174 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002175 }
Logan Chien736df022012-04-27 16:25:57 +08002176 Init(code_item, offset);
2177}
2178
2179CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2180 const DexFile::TryItem& try_item) {
2181 handler_.address_ = -1;
2182 Init(code_item, try_item.handler_off_);
2183}
2184
2185void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2186 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002187 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002188 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002189 } else {
2190 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002191 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002192 remaining_count_ = -1;
2193 catch_all_ = false;
2194 DCHECK(!HasNext());
2195 }
2196}
2197
Ian Rogers13735952014-10-08 12:43:28 -07002198void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002199 current_data_ = handler_data;
2200 remaining_count_ = DecodeSignedLeb128(&current_data_);
2201
2202 // If remaining_count_ is non-positive, then it is the negative of
2203 // the number of catch types, and the catches are followed by a
2204 // catch-all handler.
2205 if (remaining_count_ <= 0) {
2206 catch_all_ = true;
2207 remaining_count_ = -remaining_count_;
2208 } else {
2209 catch_all_ = false;
2210 }
2211 Next();
2212}
2213
2214void CatchHandlerIterator::Next() {
2215 if (remaining_count_ > 0) {
2216 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2217 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2218 remaining_count_--;
2219 return;
2220 }
2221
2222 if (catch_all_) {
2223 handler_.type_idx_ = DexFile::kDexNoIndex16;
2224 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2225 catch_all_ = false;
2226 return;
2227 }
2228
2229 // no more handler
2230 remaining_count_ = -1;
2231}
2232
Carl Shapiro1fb86202011-06-27 17:43:13 -07002233} // namespace art