blob: ebadd7951cd2eeba569b3de210f4211852bccc15 [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 Gampe542451c2016-07-26 09:02:02 -070032#include "base/enums.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000033#include "base/file_magic.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070034#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080035#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010036#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080037#include "base/stringprintf.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080038#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070039#include "base/unix_file/fd_file.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000040#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070041#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080042#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070043#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030044#include "handle_scope-inl.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010045#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070046#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000047#include "mirror/field.h"
48#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070050#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000051#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070052#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070053#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030054#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070055#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070056#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070057#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070058#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070059
60namespace art {
61
Ian Rogers13735952014-10-08 12:43:28 -070062const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070063const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
64 {'0', '3', '5', '\0'},
65 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
66 // files with that version number would erroneously be accepted and run.
Narayan Kamath52e66502016-08-01 14:20:31 +010067 {'0', '3', '7', '\0'},
68 // Dex version 038: Android "O" and beyond.
69 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070070};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070071
Vladimir Marko3a21e382016-09-02 12:38:38 +010072struct DexFile::AnnotationValue {
73 JValue value_;
74 uint8_t type_;
75};
76
Ian Rogers8d31bbd2013-10-13 10:44:14 -070077bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070078 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070079 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070080
81 // Strip ":...", which is the location
82 const char* zip_entry_name = kClassesDex;
83 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010084 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070085
Vladimir Markoaa4497d2014-09-05 14:01:17 +010086 if (DexFile::IsMultiDexLocation(filename)) {
87 file_part_storage = GetBaseLocation(filename);
88 file_part = file_part_storage.c_str();
89 zip_entry_name = filename + file_part_storage.size() + 1;
90 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070091 }
92
Andreas Gampe43e10b02016-07-15 17:17:34 -070093 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
94 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070095 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070096 return false;
97 }
98 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070099 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700100 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700101 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800102 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
103 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800104 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700105 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700106 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700107 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700108 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
109 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return false;
111 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700112 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700114 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700115 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700116 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700117 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return false;
120 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700121 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800122 return true;
123 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700124 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800125 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700126}
127
Aart Bik37d6a3b2016-06-21 18:30:10 -0700128bool DexFile::Open(const char* filename,
129 const char* location,
130 bool verify_checksum,
131 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800132 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800133 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700134 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700135 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700136 File fd = OpenAndReadMagic(filename, &magic, error_msg);
137 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700138 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700139 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700140 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700141 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700142 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700143 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700144 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700145 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700146 location,
147 /* verify */ true,
148 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700149 error_msg));
150 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800151 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700152 return true;
153 } else {
154 return false;
155 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700156 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700157 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400158 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700159}
160
Andreas Gampe0cba0042015-04-29 20:47:16 -0700161static bool ContainsClassesDex(int fd, const char* filename) {
162 std::string error_msg;
163 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
164 if (zip_archive.get() == nullptr) {
165 return false;
166 }
167 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
168 return (zip_entry.get() != nullptr);
169}
170
171bool DexFile::MaybeDex(const char* filename) {
172 uint32_t magic;
173 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700174 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
175 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700176 return false;
177 }
178 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700179 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700180 } else if (IsDexMagic(magic)) {
181 return true;
182 }
183 return false;
184}
185
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800186int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800188 return 0;
189 } else {
190 return mem_map_->GetProtect();
191 }
192}
193
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194bool DexFile::IsReadOnly() const {
195 return GetPermissions() == PROT_READ;
196}
197
Brian Carlstrome0948e12013-08-29 09:36:15 -0700198bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700200 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200201 return false;
202 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700203 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200204 }
205}
206
Brian Carlstrome0948e12013-08-29 09:36:15 -0700207bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200208 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700209 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200210 return false;
211 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700212 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200213 }
214}
215
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800216std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
217 const std::string& location,
218 uint32_t location_checksum,
219 const OatDexFile* oat_dex_file,
220 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700221 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800222 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800223 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800224 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
225 size,
226 location,
227 location_checksum,
228 nullptr,
229 oat_dex_file,
230 error_msg);
Orion Hodsona4c2a052016-08-17 10:51:42 +0100231 if (dex_file == nullptr) {
232 return nullptr;
233 }
234
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800235 if (verify && !DexFileVerifier::Verify(dex_file.get(),
236 dex_file->Begin(),
237 dex_file->Size(),
238 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700239 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800240 error_msg)) {
241 return nullptr;
242 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100243 return dex_file;
244}
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800245
Orion Hodsona4c2a052016-08-17 10:51:42 +0100246std::unique_ptr<const DexFile> DexFile::Open(const std::string& location,
247 uint32_t location_checksum,
248 std::unique_ptr<MemMap> mem_map,
249 bool verify,
250 bool verify_checksum,
251 std::string* error_msg) {
252 ScopedTrace trace(std::string("Open dex file from mapped-memory ") + location);
253 std::unique_ptr<const DexFile> dex_file = OpenMemory(location,
254 location_checksum,
255 std::move(mem_map),
256 error_msg);
257 if (dex_file == nullptr) {
258 return nullptr;
259 }
260
261 if (verify && !DexFileVerifier::Verify(dex_file.get(),
262 dex_file->Begin(),
263 dex_file->Size(),
264 location.c_str(),
265 verify_checksum,
266 error_msg)) {
267 return nullptr;
268 }
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800269 return dex_file;
270}
271
Aart Bik37d6a3b2016-06-21 18:30:10 -0700272std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
273 const char* location,
274 bool verify,
275 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800276 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800277 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700278 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700279 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000280 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700281 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000282 struct stat sbuf;
283 memset(&sbuf, 0, sizeof(sbuf));
284 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800285 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000286 return nullptr;
287 }
288 if (S_ISDIR(sbuf.st_mode)) {
289 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
290 return nullptr;
291 }
292 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800293 map.reset(MemMap::MapFile(length,
294 PROT_READ,
295 MAP_PRIVATE,
296 fd,
297 0,
298 /*low_4gb*/false,
299 location,
300 error_msg));
Orion Hodsona4c2a052016-08-17 10:51:42 +0100301 if (map == nullptr) {
Vladimir Markofd995762013-11-06 16:36:36 +0000302 DCHECK(!error_msg->empty());
303 return nullptr;
304 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700305 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800306
307 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800309 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800311 }
312
313 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
314
Orion Hodsona4c2a052016-08-17 10:51:42 +0100315 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
316 dex_header->checksum_,
317 std::move(map),
Andreas Gampe928f72b2014-09-09 19:53:48 -0700318 error_msg));
319 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
321 error_msg->c_str());
322 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800323 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800324
Andreas Gampe928f72b2014-09-09 19:53:48 -0700325 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700326 location,
327 verify_checksum,
328 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700329 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800330 }
331
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800332 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700333}
334
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700335const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700336
Aart Bik37d6a3b2016-06-21 18:30:10 -0700337bool DexFile::OpenZip(int fd,
338 const std::string& location,
339 bool verify_checksum,
340 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800341 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800342 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700343 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700344 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700345 if (zip_archive.get() == nullptr) {
346 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700347 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700348 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700349 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800350}
351
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800352std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
353 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100354 std::unique_ptr<MemMap> mem_map,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800355 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800356 return OpenMemory(mem_map->Begin(),
357 mem_map->Size(),
358 location,
359 location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100360 std::move(mem_map),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800361 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800363}
364
Aart Bik37d6a3b2016-06-21 18:30:10 -0700365std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
366 const char* entry_name,
367 const std::string& location,
368 bool verify_checksum,
369 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800370 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800371 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800372 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700373 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700374 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700375 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700376 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700377 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800378 if (zip_entry->GetUncompressedLength() == 0) {
379 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
380 *error_code = ZipOpenErrorCode::kDexFileError;
381 return nullptr;
382 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700383 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700384 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700385 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700386 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700387 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700389 }
Orion Hodsona4c2a052016-08-17 10:51:42 +0100390 std::unique_ptr<const DexFile> dex_file(OpenMemory(location,
391 zip_entry->GetCrc32(),
392 std::move(map),
393 error_msg));
394 if (dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
396 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700397 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700398 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800399 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700400 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700401 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700402 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700403 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700404 }
405 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700406 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700407 location.c_str(),
408 verify_checksum,
409 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700410 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700411 return nullptr;
412 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700413 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800414 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700415}
416
Andreas Gampe90e34042015-04-27 20:01:52 -0700417// Technically we do not have a limitation with respect to the number of dex files that can be in a
418// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
419// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
420// seems an excessive number.
421static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
422
Aart Bik37d6a3b2016-06-21 18:30:10 -0700423bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
424 const std::string& location,
425 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800426 std::string* error_msg,
427 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800428 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700429 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700430 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700431 std::unique_ptr<const DexFile> dex_file(
432 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700433 if (dex_file.get() == nullptr) {
434 return false;
435 } else {
436 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800437 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700438
439 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700440
441 // We could try to avoid std::string allocations by working on a char array directly. As we
442 // do not expect a lot of iterations, this seems too involved and brittle.
443
Andreas Gampe90e34042015-04-27 20:01:52 -0700444 for (size_t i = 1; ; ++i) {
445 std::string name = GetMultiDexClassesDexName(i);
446 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700447 std::unique_ptr<const DexFile> next_dex_file(
448 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700449 if (next_dex_file.get() == nullptr) {
450 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
451 LOG(WARNING) << error_msg;
452 }
453 break;
454 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800455 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700456 }
457
Andreas Gampe90e34042015-04-27 20:01:52 -0700458 if (i == kWarnOnManyDexFilesThreshold) {
459 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
460 << " dex files. Please consider coalescing and shrinking the number to "
461 " avoid runtime overhead.";
462 }
463
464 if (i == std::numeric_limits<size_t>::max()) {
465 LOG(ERROR) << "Overflow in number of dex files!";
466 break;
467 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700468 }
469
470 return true;
471 }
472}
473
474
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800475std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
476 size_t size,
477 const std::string& location,
478 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100479 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700480 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800481 std::string* error_msg) {
ganxiaolincd16d0a2016-07-18 11:21:44 +0800482 DCHECK(base != nullptr);
David Sehrd81c0f82016-08-03 09:05:20 -0700483 DCHECK_NE(size, 0U);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700484 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800485 std::unique_ptr<DexFile> dex_file(
Orion Hodsona4c2a052016-08-17 10:51:42 +0100486 new DexFile(base, size, location, location_checksum, std::move(mem_map), oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800488 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700489 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800490 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700491}
492
Ian Rogers13735952014-10-08 12:43:28 -0700493DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800494 const std::string& location,
495 uint32_t location_checksum,
Orion Hodsona4c2a052016-08-17 10:51:42 +0100496 std::unique_ptr<MemMap> mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700497 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800498 : begin_(base),
499 size_(size),
500 location_(location),
501 location_checksum_(location_checksum),
Orion Hodsona4c2a052016-08-17 10:51:42 +0100502 mem_map_(std::move(mem_map)),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800503 header_(reinterpret_cast<const Header*>(base)),
504 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
505 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
506 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
507 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
508 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700509 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700510 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700511 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800512 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300513 const uint8_t* lookup_data = (oat_dex_file != nullptr)
514 ? oat_dex_file->GetLookupTableData()
515 : nullptr;
516 if (lookup_data != nullptr) {
517 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
518 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
519 } else {
520 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
521 }
522 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800523}
524
Jesse Wilson6bf19152011-09-29 13:12:33 -0400525DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700526 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
527 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
528 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
529 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400530}
531
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700532bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700533 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700534 return false;
535 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700536 return true;
537}
538
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700539bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800540 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700541 std::ostringstream oss;
542 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800543 << " " << header_->magic_[0]
544 << " " << header_->magic_[1]
545 << " " << header_->magic_[2]
546 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700547 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700548 return false;
549 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800550 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700551 std::ostringstream oss;
552 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800553 << " " << header_->magic_[4]
554 << " " << header_->magic_[5]
555 << " " << header_->magic_[6]
556 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700557 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700558 return false;
559 }
560 return true;
561}
562
Ian Rogers13735952014-10-08 12:43:28 -0700563bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800564 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
565}
566
Ian Rogers13735952014-10-08 12:43:28 -0700567bool DexFile::IsVersionValid(const uint8_t* magic) {
568 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700569 for (uint32_t i = 0; i < kNumDexVersions; i++) {
570 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
571 return true;
572 }
573 }
574 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800575}
576
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700577uint32_t DexFile::Header::GetVersion() const {
578 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700579 return atoi(version);
580}
581
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800582const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
583 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300584 if (LIKELY(lookup_table_ != nullptr)) {
585 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
586 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700587 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300588
Roland Levillainab880f42016-05-12 16:24:36 +0100589 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300590 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700591 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700592 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700593 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300594 const TypeId* type_id = FindTypeId(descriptor);
595 if (type_id != nullptr) {
596 uint16_t type_idx = GetIndexForTypeId(*type_id);
597 for (size_t i = 0; i < num_class_defs; ++i) {
598 const ClassDef& class_def = GetClassDef(i);
599 if (class_def.class_idx_ == type_idx) {
600 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700601 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700602 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700603 }
Ian Rogers68b56852014-08-29 20:19:11 -0700604 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700605}
606
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700607const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
608 size_t num_class_defs = NumClassDefs();
609 for (size_t i = 0; i < num_class_defs; ++i) {
610 const ClassDef& class_def = GetClassDef(i);
611 if (class_def.class_idx_ == type_idx) {
612 return &class_def;
613 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700614 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700615 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700616}
617
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800618const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100619 const DexFile::StringId& name,
620 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800621 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
622 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
623 const uint32_t name_idx = GetIndexForStringId(name);
624 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700625 int32_t lo = 0;
626 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800627 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700628 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800629 const DexFile::FieldId& field = GetFieldId(mid);
630 if (class_idx > field.class_idx_) {
631 lo = mid + 1;
632 } else if (class_idx < field.class_idx_) {
633 hi = mid - 1;
634 } else {
635 if (name_idx > field.name_idx_) {
636 lo = mid + 1;
637 } else if (name_idx < field.name_idx_) {
638 hi = mid - 1;
639 } else {
640 if (type_idx > field.type_idx_) {
641 lo = mid + 1;
642 } else if (type_idx < field.type_idx_) {
643 hi = mid - 1;
644 } else {
645 return &field;
646 }
647 }
648 }
649 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700650 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800651}
652
653const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700654 const DexFile::StringId& name,
655 const DexFile::ProtoId& signature) const {
656 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800657 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700658 const uint32_t name_idx = GetIndexForStringId(name);
659 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700660 int32_t lo = 0;
661 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700662 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700663 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700664 const DexFile::MethodId& method = GetMethodId(mid);
665 if (class_idx > method.class_idx_) {
666 lo = mid + 1;
667 } else if (class_idx < method.class_idx_) {
668 hi = mid - 1;
669 } else {
670 if (name_idx > method.name_idx_) {
671 lo = mid + 1;
672 } else if (name_idx < method.name_idx_) {
673 hi = mid - 1;
674 } else {
675 if (proto_idx > method.proto_idx_) {
676 lo = mid + 1;
677 } else if (proto_idx < method.proto_idx_) {
678 hi = mid - 1;
679 } else {
680 return &method;
681 }
682 }
683 }
684 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700685 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700686}
687
Ian Rogers637c65b2013-05-31 11:46:00 -0700688const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700689 int32_t lo = 0;
690 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700691 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700692 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700693 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700694 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700695 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
696 if (compare > 0) {
697 lo = mid + 1;
698 } else if (compare < 0) {
699 hi = mid - 1;
700 } else {
701 return &str_id;
702 }
703 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700704 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700705}
706
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300707const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
708 int32_t lo = 0;
709 int32_t hi = NumTypeIds() - 1;
710 while (hi >= lo) {
711 int32_t mid = (hi + lo) / 2;
712 const TypeId& type_id = GetTypeId(mid);
713 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
714 const char* str = GetStringData(str_id);
715 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
716 if (compare > 0) {
717 lo = mid + 1;
718 } else if (compare < 0) {
719 hi = mid - 1;
720 } else {
721 return &type_id;
722 }
723 }
724 return nullptr;
725}
726
Vladimir Markoa48aef42014-12-03 17:53:53 +0000727const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700728 int32_t lo = 0;
729 int32_t hi = NumStringIds() - 1;
730 while (hi >= lo) {
731 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700732 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700733 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000734 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700735 if (compare > 0) {
736 lo = mid + 1;
737 } else if (compare < 0) {
738 hi = mid - 1;
739 } else {
740 return &str_id;
741 }
742 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700743 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700744}
745
746const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700747 int32_t lo = 0;
748 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700749 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700750 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700751 const TypeId& type_id = GetTypeId(mid);
752 if (string_idx > type_id.descriptor_idx_) {
753 lo = mid + 1;
754 } else if (string_idx < type_id.descriptor_idx_) {
755 hi = mid - 1;
756 } else {
757 return &type_id;
758 }
759 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700760 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700761}
762
763const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000764 const uint16_t* signature_type_idxs,
765 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700766 int32_t lo = 0;
767 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700768 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700769 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700770 const DexFile::ProtoId& proto = GetProtoId(mid);
771 int compare = return_type_idx - proto.return_type_idx_;
772 if (compare == 0) {
773 DexFileParameterIterator it(*this, proto);
774 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000775 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800776 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700777 it.Next();
778 i++;
779 }
780 if (compare == 0) {
781 if (it.HasNext()) {
782 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000783 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700784 compare = 1;
785 }
786 }
787 }
788 if (compare > 0) {
789 lo = mid + 1;
790 } else if (compare < 0) {
791 hi = mid - 1;
792 } else {
793 return &proto;
794 }
795 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700796 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700797}
798
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000799void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
800 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300801}
802
Ian Rogers0571d352011-11-03 19:51:38 -0700803// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700804bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
805 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700806 if (signature[0] != '(') {
807 return false;
808 }
809 size_t offset = 1;
810 size_t end = signature.size();
811 bool process_return = false;
812 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000813 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700814 char c = signature[offset];
815 offset++;
816 if (c == ')') {
817 process_return = true;
818 continue;
819 }
Ian Rogers0571d352011-11-03 19:51:38 -0700820 while (c == '[') { // process array prefix
821 if (offset >= end) { // expect some descriptor following [
822 return false;
823 }
824 c = signature[offset];
825 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700826 }
827 if (c == 'L') { // process type descriptors
828 do {
829 if (offset >= end) { // unexpected early termination of descriptor
830 return false;
831 }
832 c = signature[offset];
833 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700834 } while (c != ';');
835 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000836 // TODO: avoid creating a std::string just to get a 0-terminated char array
837 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700838 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700840 return false;
841 }
842 uint16_t type_idx = GetIndexForTypeId(*type_id);
843 if (!process_return) {
844 param_type_idxs->push_back(type_idx);
845 } else {
846 *return_type_idx = type_idx;
847 return offset == end; // return true if the signature had reached a sensible end
848 }
849 }
850 return false; // failed to correctly parse return type
851}
852
Ian Rogersd91d6d62013-09-25 20:26:14 -0700853const Signature DexFile::CreateSignature(const StringPiece& signature) const {
854 uint16_t return_type_idx;
855 std::vector<uint16_t> param_type_indices;
856 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
857 if (!success) {
858 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700859 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700860 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700861 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700862 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700863 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700864 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700865}
866
Mathieu Chartiere401d142015-04-22 13:56:20 -0700867int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700868 // For native method, lineno should be -2 to indicate it is native. Note that
869 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700870 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700871 return -2;
872 }
873
TDYa127c8dc1012012-04-19 07:03:33 -0700874 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700875 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700876
877 // A method with no line number info should return -1
878 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000879 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 return context.line_num_;
881}
882
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700883int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700884 // Note: Signed type is important for max and min.
885 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700886 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700887
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700888 while (min <= max) {
889 int32_t mid = min + ((max - min) / 2);
890
891 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
892 uint32_t start = ti->start_addr_;
893 uint32_t end = start + ti->insn_count_;
894
Ian Rogers0571d352011-11-03 19:51:38 -0700895 if (address < start) {
896 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700897 } else if (address >= end) {
898 min = mid + 1;
899 } else { // We have a winner!
900 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700901 }
902 }
903 // No match.
904 return -1;
905}
906
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700907int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
908 int32_t try_item = FindTryItem(code_item, address);
909 if (try_item == -1) {
910 return -1;
911 } else {
912 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
913 }
914}
915
David Srbeckyb06e28e2015-12-10 13:15:00 +0000916bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
917 DexDebugNewLocalCb local_cb, void* context) const {
918 DCHECK(local_cb != nullptr);
919 if (code_item == nullptr) {
920 return false;
921 }
922 const uint8_t* stream = GetDebugInfoStream(code_item);
923 if (stream == nullptr) {
924 return false;
925 }
926 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700927
David Srbeckyb06e28e2015-12-10 13:15:00 +0000928 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800929 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000930 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
931 local_in_reg[arg_reg].name_ = "this";
932 local_in_reg[arg_reg].descriptor_ = descriptor;
933 local_in_reg[arg_reg].signature_ = nullptr;
934 local_in_reg[arg_reg].start_address_ = 0;
935 local_in_reg[arg_reg].reg_ = arg_reg;
936 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700937 arg_reg++;
938 }
939
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800940 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000941 DecodeUnsignedLeb128(&stream); // Line.
942 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
943 uint32_t i;
944 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700946 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800947 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000948 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700949 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000950 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700951 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000952 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
953 local_in_reg[arg_reg].descriptor_ = descriptor;
954 local_in_reg[arg_reg].signature_ = nullptr;
955 local_in_reg[arg_reg].start_address_ = 0;
956 local_in_reg[arg_reg].reg_ = arg_reg;
957 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700958 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700959 case 'D':
960 case 'J':
961 arg_reg += 2;
962 break;
963 default:
964 arg_reg += 1;
965 break;
966 }
967 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000968 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800969 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
970 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000971 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700972 }
973
David Srbeckyb06e28e2015-12-10 13:15:00 +0000974 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700975 for (;;) {
976 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700977 switch (opcode) {
978 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000979 // Emit all variables which are still alive at the end of the method.
980 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
981 if (local_in_reg[reg].is_live_) {
982 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
983 local_cb(context, local_in_reg[reg]);
984 }
985 }
986 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700987 case DBG_ADVANCE_PC:
988 address += DecodeUnsignedLeb128(&stream);
989 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700990 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000991 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700992 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700993 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000994 case DBG_START_LOCAL_EXTENDED: {
995 uint16_t reg = DecodeUnsignedLeb128(&stream);
996 if (reg >= code_item->registers_size_) {
997 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800998 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000999 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001000 }
1001
David Srbeckyb06e28e2015-12-10 13:15:00 +00001002 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1003 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
1004 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -07001005 if (opcode == DBG_START_LOCAL_EXTENDED) {
1006 signature_idx = DecodeUnsignedLeb128P1(&stream);
1007 }
1008
Shih-wei Liao195487c2011-08-20 13:29:04 -07001009 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +00001010 if (local_in_reg[reg].is_live_) {
1011 local_in_reg[reg].end_address_ = address;
1012 local_cb(context, local_in_reg[reg]);
1013 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001014
David Srbeckyb06e28e2015-12-10 13:15:00 +00001015 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
1016 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
1017 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
1018 local_in_reg[reg].start_address_ = address;
1019 local_in_reg[reg].reg_ = reg;
1020 local_in_reg[reg].is_live_ = true;
1021 break;
1022 }
1023 case DBG_END_LOCAL: {
1024 uint16_t reg = DecodeUnsignedLeb128(&stream);
1025 if (reg >= code_item->registers_size_) {
1026 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1027 << code_item->registers_size_ << ") in " << GetLocation();
1028 return false;
1029 }
1030 if (!local_in_reg[reg].is_live_) {
1031 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
1032 return false;
1033 }
1034 local_in_reg[reg].end_address_ = address;
1035 local_cb(context, local_in_reg[reg]);
1036 local_in_reg[reg].is_live_ = false;
1037 break;
1038 }
1039 case DBG_RESTART_LOCAL: {
1040 uint16_t reg = DecodeUnsignedLeb128(&stream);
1041 if (reg >= code_item->registers_size_) {
1042 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1043 << code_item->registers_size_ << ") in " << GetLocation();
1044 return false;
1045 }
1046 // If the register is live, the "restart" is superfluous,
1047 // and we don't want to mess with the existing start address.
1048 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001049 local_in_reg[reg].start_address_ = address;
1050 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001051 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001052 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001053 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001054 case DBG_SET_PROLOGUE_END:
1055 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001056 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001057 case DBG_SET_FILE:
1058 DecodeUnsignedLeb128P1(&stream); // name.
1059 break;
1060 default:
1061 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1062 break;
1063 }
1064 }
1065}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001066
David Srbeckyb06e28e2015-12-10 13:15:00 +00001067bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1068 void* context) const {
1069 DCHECK(position_cb != nullptr);
1070 if (code_item == nullptr) {
1071 return false;
1072 }
1073 const uint8_t* stream = GetDebugInfoStream(code_item);
1074 if (stream == nullptr) {
1075 return false;
1076 }
1077
1078 PositionInfo entry = PositionInfo();
1079 entry.line_ = DecodeUnsignedLeb128(&stream);
1080 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1081 for (uint32_t i = 0; i < parameters_size; ++i) {
1082 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1083 }
1084
1085 for (;;) {
1086 uint8_t opcode = *stream++;
1087 switch (opcode) {
1088 case DBG_END_SEQUENCE:
1089 return true; // end of stream.
1090 case DBG_ADVANCE_PC:
1091 entry.address_ += DecodeUnsignedLeb128(&stream);
1092 break;
1093 case DBG_ADVANCE_LINE:
1094 entry.line_ += DecodeSignedLeb128(&stream);
1095 break;
1096 case DBG_START_LOCAL:
1097 DecodeUnsignedLeb128(&stream); // reg.
1098 DecodeUnsignedLeb128P1(&stream); // name.
1099 DecodeUnsignedLeb128P1(&stream); // descriptor.
1100 break;
1101 case DBG_START_LOCAL_EXTENDED:
1102 DecodeUnsignedLeb128(&stream); // reg.
1103 DecodeUnsignedLeb128P1(&stream); // name.
1104 DecodeUnsignedLeb128P1(&stream); // descriptor.
1105 DecodeUnsignedLeb128P1(&stream); // signature.
1106 break;
1107 case DBG_END_LOCAL:
1108 case DBG_RESTART_LOCAL:
1109 DecodeUnsignedLeb128(&stream); // reg.
1110 break;
1111 case DBG_SET_PROLOGUE_END:
1112 entry.prologue_end_ = true;
1113 break;
1114 case DBG_SET_EPILOGUE_BEGIN:
1115 entry.epilogue_begin_ = true;
1116 break;
1117 case DBG_SET_FILE: {
1118 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1119 entry.source_file_ = StringDataByIdx(name_idx);
1120 break;
1121 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001122 default: {
1123 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001124 entry.address_ += adjopcode / DBG_LINE_RANGE;
1125 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1126 if (position_cb(context, entry)) {
1127 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001128 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001129 entry.prologue_end_ = false;
1130 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001131 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001132 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001133 }
1134 }
1135}
1136
David Srbeckyb06e28e2015-12-10 13:15:00 +00001137bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001138 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001139
1140 // We know that this callback will be called in
1141 // ascending address order, so keep going until we find
1142 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001143 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001144 // The line number from the previous positions callback
1145 // wil be the final result.
1146 return true;
1147 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001148 context->line_num_ = entry.line_;
1149 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001150 }
1151}
1152
Andreas Gampe833a4852014-05-21 18:46:59 -07001153bool DexFile::IsMultiDexLocation(const char* location) {
1154 return strrchr(location, kMultiDexSeparator) != nullptr;
1155}
1156
Andreas Gampe90e34042015-04-27 20:01:52 -07001157std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1158 if (index == 0) {
1159 return "classes.dex";
1160 } else {
1161 return StringPrintf("classes%zu.dex", index + 1);
1162 }
1163}
1164
1165std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1166 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001167 return dex_location;
1168 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001169 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001170 }
1171}
1172
1173std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1174 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001175 std::string base_location = GetBaseLocation(dex_location);
1176 const char* suffix = dex_location + base_location.size();
1177 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1178 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1179 if (path != nullptr && path.get() != base_location) {
1180 return std::string(path.get()) + suffix;
1181 } else if (suffix[0] == 0) {
1182 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001183 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001184 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001185 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001186}
1187
Jeff Hao13e748b2015-08-25 20:44:19 +00001188// Read a signed integer. "zwidth" is the zero-based byte count.
1189static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1190 int32_t val = 0;
1191 for (int i = zwidth; i >= 0; --i) {
1192 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1193 }
1194 val >>= (3 - zwidth) * 8;
1195 return val;
1196}
1197
1198// Read an unsigned integer. "zwidth" is the zero-based byte count,
1199// "fill_on_right" indicates which side we want to zero-fill from.
1200static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1201 uint32_t val = 0;
1202 for (int i = zwidth; i >= 0; --i) {
1203 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1204 }
1205 if (!fill_on_right) {
1206 val >>= (3 - zwidth) * 8;
1207 }
1208 return val;
1209}
1210
1211// Read a signed long. "zwidth" is the zero-based byte count.
1212static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1213 int64_t val = 0;
1214 for (int i = zwidth; i >= 0; --i) {
1215 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1216 }
1217 val >>= (7 - zwidth) * 8;
1218 return val;
1219}
1220
1221// Read an unsigned long. "zwidth" is the zero-based byte count,
1222// "fill_on_right" indicates which side we want to zero-fill from.
1223static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1224 uint64_t val = 0;
1225 for (int i = zwidth; i >= 0; --i) {
1226 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1227 }
1228 if (!fill_on_right) {
1229 val >>= (7 - zwidth) * 8;
1230 }
1231 return val;
1232}
1233
Jeff Hao3d080862016-05-26 18:39:17 -07001234// Checks that visibility is as expected. Includes special behavior for M and
1235// before to allow runtime and build visibility when expecting runtime.
1236static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1237 if (expected == DexFile::kDexVisibilityRuntime) {
1238 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1239 if (sdk_version > 0 && sdk_version <= 23) {
1240 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1241 }
1242 }
1243 return actual == expected;
1244}
1245
Jeff Hao13e748b2015-08-25 20:44:19 +00001246const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1247 mirror::Class* klass = field->GetDeclaringClass();
1248 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1249 if (annotations_dir == nullptr) {
1250 return nullptr;
1251 }
1252 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1253 if (field_annotations == nullptr) {
1254 return nullptr;
1255 }
1256 uint32_t field_index = field->GetDexFieldIndex();
1257 uint32_t field_count = annotations_dir->fields_size_;
1258 for (uint32_t i = 0; i < field_count; ++i) {
1259 if (field_annotations[i].field_idx_ == field_index) {
1260 return GetFieldAnnotationSetItem(field_annotations[i]);
1261 }
1262 }
1263 return nullptr;
1264}
1265
1266mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1267 Handle<mirror::Class> annotation_class) const {
1268 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1269 if (annotation_set == nullptr) {
1270 return nullptr;
1271 }
1272 StackHandleScope<1> hs(Thread::Current());
1273 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1274 return GetAnnotationObjectFromAnnotationSet(
1275 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1276}
1277
1278mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1279 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1280 StackHandleScope<1> hs(Thread::Current());
1281 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1282 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1283}
1284
Jeff Hao2a5892f2015-08-31 15:00:40 -07001285mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001286 const {
1287 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1288 if (annotation_set == nullptr) {
1289 return nullptr;
1290 }
1291 StackHandleScope<1> hs(Thread::Current());
1292 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1293 return GetSignatureValue(field_class, annotation_set);
1294}
1295
1296bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1297 const {
1298 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1299 if (annotation_set == nullptr) {
1300 return false;
1301 }
1302 StackHandleScope<1> hs(Thread::Current());
1303 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1304 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1305 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1306 return annotation_item != nullptr;
1307}
1308
1309const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1310 mirror::Class* klass = method->GetDeclaringClass();
1311 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1312 if (annotations_dir == nullptr) {
1313 return nullptr;
1314 }
1315 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1316 if (method_annotations == nullptr) {
1317 return nullptr;
1318 }
1319 uint32_t method_index = method->GetDexMethodIndex();
1320 uint32_t method_count = annotations_dir->methods_size_;
1321 for (uint32_t i = 0; i < method_count; ++i) {
1322 if (method_annotations[i].method_idx_ == method_index) {
1323 return GetMethodAnnotationSetItem(method_annotations[i]);
1324 }
1325 }
1326 return nullptr;
1327}
1328
1329const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1330 const {
1331 mirror::Class* klass = method->GetDeclaringClass();
1332 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1333 if (annotations_dir == nullptr) {
1334 return nullptr;
1335 }
1336 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1337 if (parameter_annotations == nullptr) {
1338 return nullptr;
1339 }
1340 uint32_t method_index = method->GetDexMethodIndex();
1341 uint32_t parameter_count = annotations_dir->parameters_size_;
1342 for (uint32_t i = 0; i < parameter_count; ++i) {
1343 if (parameter_annotations[i].method_idx_ == method_index) {
1344 return &parameter_annotations[i];
1345 }
1346 }
1347 return nullptr;
1348}
1349
1350mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1351 mirror::Class* klass = method->GetDeclaringClass();
1352 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1353 if (annotations_dir == nullptr) {
1354 return nullptr;
1355 }
1356 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1357 if (annotation_set == nullptr) {
1358 return nullptr;
1359 }
1360 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1361 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1362 if (annotation_item == nullptr) {
1363 return nullptr;
1364 }
1365 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1366 if (annotation == nullptr) {
1367 return nullptr;
1368 }
1369 uint8_t header_byte = *(annotation++);
1370 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1371 return nullptr;
1372 }
1373 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1374 if (annotation == nullptr) {
1375 return nullptr;
1376 }
1377 AnnotationValue annotation_value;
1378 StackHandleScope<2> hs(Thread::Current());
1379 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe542451c2016-07-26 09:02:02 -07001380 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Vladimir Marko05792b92015-08-03 11:56:49 +01001381 Handle<mirror::Class> return_type(hs.NewHandle(
1382 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001383 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1384 return nullptr;
1385 }
1386 return annotation_value.value_.GetL();
1387}
1388
1389mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1390 Handle<mirror::Class> annotation_class) const {
1391 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1392 if (annotation_set == nullptr) {
1393 return nullptr;
1394 }
1395 StackHandleScope<1> hs(Thread::Current());
1396 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1397 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1398 kDexVisibilityRuntime, annotation_class);
1399}
1400
1401mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1402 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1403 StackHandleScope<1> hs(Thread::Current());
1404 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1405 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1406}
1407
Jeff Hao2a5892f2015-08-31 15:00:40 -07001408mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001409 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1410 if (annotation_set == nullptr) {
1411 return nullptr;
1412 }
1413 StackHandleScope<1> hs(Thread::Current());
1414 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1415 return GetThrowsValue(method_class, annotation_set);
1416}
1417
1418mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1419 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1420 if (parameter_annotations == nullptr) {
1421 return nullptr;
1422 }
1423 const AnnotationSetRefList* set_ref_list =
1424 GetParameterAnnotationSetRefList(parameter_annotations);
1425 if (set_ref_list == nullptr) {
1426 return nullptr;
1427 }
1428 uint32_t size = set_ref_list->size_;
1429 StackHandleScope<1> hs(Thread::Current());
1430 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1431 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1432}
1433
Jeff Hao1133db72016-04-04 19:50:14 -07001434mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1435 const {
1436 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1437 if (annotation_set == nullptr) {
1438 return nullptr;
1439 }
1440 StackHandleScope<1> hs(Thread::Current());
1441 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1442 return GetSignatureValue(method_class, annotation_set);
1443}
1444
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001445bool DexFile::IsMethodAnnotationPresent(ArtMethod* method,
1446 Handle<mirror::Class> annotation_class,
1447 uint32_t visibility /* = kDexVisibilityRuntime */)
Jeff Hao13e748b2015-08-25 20:44:19 +00001448 const {
1449 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1450 if (annotation_set == nullptr) {
1451 return false;
1452 }
1453 StackHandleScope<1> hs(Thread::Current());
1454 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001455 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(method_class,
1456 annotation_set,
1457 visibility,
1458 annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001459 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001460}
1461
1462const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1463 const {
1464 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1465 if (annotations_dir == nullptr) {
1466 return nullptr;
1467 }
1468 return GetClassAnnotationSet(annotations_dir);
1469}
1470
1471mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1472 Handle<mirror::Class> annotation_class) const {
1473 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1474 if (annotation_set == nullptr) {
1475 return nullptr;
1476 }
1477 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1478 annotation_class);
1479}
1480
1481mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1482 const {
1483 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1484 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1485}
1486
Jeff Hao2a5892f2015-08-31 15:00:40 -07001487mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1488 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1489 if (annotation_set == nullptr) {
1490 return nullptr;
1491 }
1492 const AnnotationItem* annotation_item = SearchAnnotationSet(
1493 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1494 if (annotation_item == nullptr) {
1495 return nullptr;
1496 }
1497 StackHandleScope<1> hs(Thread::Current());
1498 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1499 Handle<mirror::Class> class_array_class(hs.NewHandle(
1500 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1501 if (class_array_class.Get() == nullptr) {
1502 return nullptr;
1503 }
1504 mirror::Object* obj = GetAnnotationValue(
1505 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1506 if (obj == nullptr) {
1507 return nullptr;
1508 }
1509 return obj->AsObjectArray<mirror::Class>();
1510}
1511
1512mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1513 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1514 if (annotation_set == nullptr) {
1515 return nullptr;
1516 }
1517 const AnnotationItem* annotation_item = SearchAnnotationSet(
1518 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1519 if (annotation_item == nullptr) {
1520 return nullptr;
1521 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001522 mirror::Object* obj = GetAnnotationValue(klass,
1523 annotation_item,
1524 "value",
1525 ScopedNullHandle<mirror::Class>(),
1526 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001527 if (obj == nullptr) {
1528 return nullptr;
1529 }
1530 return obj->AsClass();
1531}
1532
1533mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1534 mirror::Class* declaring_class = GetDeclaringClass(klass);
1535 if (declaring_class != nullptr) {
1536 return declaring_class;
1537 }
1538 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1539 if (annotation_set == nullptr) {
1540 return nullptr;
1541 }
1542 const AnnotationItem* annotation_item = SearchAnnotationSet(
1543 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1544 if (annotation_item == nullptr) {
1545 return nullptr;
1546 }
1547 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1548 if (annotation == nullptr) {
1549 return nullptr;
1550 }
1551 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001552 if (!ProcessAnnotationValue(klass,
1553 &annotation,
1554 &annotation_value,
1555 ScopedNullHandle<mirror::Class>(),
1556 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001557 return nullptr;
1558 }
1559 if (annotation_value.type_ != kDexAnnotationMethod) {
1560 return nullptr;
1561 }
1562 StackHandleScope<2> hs(Thread::Current());
1563 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1564 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1565 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1566 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1567 if (method == nullptr) {
1568 return nullptr;
1569 }
1570 return method->GetDeclaringClass();
1571}
1572
1573mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1574 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1575 if (annotation_set == nullptr) {
1576 return nullptr;
1577 }
1578 const AnnotationItem* annotation_item = SearchAnnotationSet(
1579 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1580 if (annotation_item == nullptr) {
1581 return nullptr;
1582 }
1583 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001584 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001585}
1586
1587bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1588 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1589 if (annotation_set == nullptr) {
1590 return false;
1591 }
1592 const AnnotationItem* annotation_item = SearchAnnotationSet(
1593 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1594 if (annotation_item == nullptr) {
1595 return false;
1596 }
1597 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1598 if (annotation == nullptr) {
1599 return false;
1600 }
1601 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001602 if (!ProcessAnnotationValue(klass,
1603 &annotation,
1604 &annotation_value,
1605 ScopedNullHandle<mirror::Class>(),
1606 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001607 return false;
1608 }
1609 if (annotation_value.type_ != kDexAnnotationNull &&
1610 annotation_value.type_ != kDexAnnotationString) {
1611 return false;
1612 }
1613 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1614 return true;
1615}
1616
1617bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1618 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1619 if (annotation_set == nullptr) {
1620 return false;
1621 }
1622 const AnnotationItem* annotation_item = SearchAnnotationSet(
1623 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1624 if (annotation_item == nullptr) {
1625 return false;
1626 }
1627 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1628 if (annotation == nullptr) {
1629 return false;
1630 }
1631 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001632 if (!ProcessAnnotationValue(klass,
1633 &annotation,
1634 &annotation_value,
1635 ScopedNullHandle<mirror::Class>(),
1636 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001637 return false;
1638 }
1639 if (annotation_value.type_ != kDexAnnotationInt) {
1640 return false;
1641 }
1642 *flags = annotation_value.value_.GetI();
1643 return true;
1644}
1645
Jeff Hao1133db72016-04-04 19:50:14 -07001646mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1647 Handle<mirror::Class> klass) const {
1648 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1649 if (annotation_set == nullptr) {
1650 return nullptr;
1651 }
1652 return GetSignatureValue(klass, annotation_set);
1653}
1654
Jeff Hao13e748b2015-08-25 20:44:19 +00001655bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1656 Handle<mirror::Class> annotation_class) const {
1657 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1658 if (annotation_set == nullptr) {
1659 return false;
1660 }
1661 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1662 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001663 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001664}
1665
1666mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1667 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1668 Thread* self = Thread::Current();
1669 ScopedObjectAccessUnchecked soa(self);
1670 StackHandleScope<5> hs(self);
1671 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1672 const char* name = StringDataByIdx(element_name_index);
1673 Handle<mirror::String> string_name(
1674 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1675
Andreas Gampe542451c2016-07-26 09:02:02 -07001676 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001677 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001678 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001679 if (annotation_method == nullptr) {
1680 return nullptr;
1681 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001682 Handle<mirror::Class> method_return(hs.NewHandle(
1683 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001684
1685 AnnotationValue annotation_value;
1686 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1687 return nullptr;
1688 }
1689 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1690
1691 mirror::Class* annotation_member_class =
1692 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1693 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001694 mirror::Method* method_obj_ptr;
1695 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001696 if (pointer_size == PointerSize::k64) {
1697 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1698 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001699 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001700 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1701 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001702 }
1703 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001704
1705 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1706 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1707 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1708 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1709 return nullptr;
1710 }
1711
1712 JValue result;
1713 ArtMethod* annotation_member_init =
1714 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1715 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1716 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1717 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1718 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1719 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1720 };
1721 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1722 if (self->IsExceptionPending()) {
1723 LOG(INFO) << "Exception in AnnotationMember.<init>";
1724 return nullptr;
1725 }
1726
1727 return new_member.Get();
1728}
1729
1730const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1731 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1732 Handle<mirror::Class> annotation_class) const {
1733 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1734 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001735 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001736 continue;
1737 }
1738 const uint8_t* annotation = annotation_item->annotation_;
1739 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1740 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1741 klass->GetDexFile(), type_index, klass.Get());
1742 if (resolved_class == nullptr) {
1743 std::string temp;
1744 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1745 klass->GetDescriptor(&temp), type_index);
1746 CHECK(Thread::Current()->IsExceptionPending());
1747 Thread::Current()->ClearException();
1748 continue;
1749 }
1750 if (resolved_class == annotation_class.Get()) {
1751 return annotation_item;
1752 }
1753 }
1754
1755 return nullptr;
1756}
1757
1758mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1759 const AnnotationSetItem* annotation_set, uint32_t visibility,
1760 Handle<mirror::Class> annotation_class) const {
1761 const AnnotationItem* annotation_item =
1762 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1763 if (annotation_item == nullptr) {
1764 return nullptr;
1765 }
1766 const uint8_t* annotation = annotation_item->annotation_;
1767 return ProcessEncodedAnnotation(klass, &annotation);
1768}
1769
1770mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1771 const AnnotationItem* annotation_item, const char* annotation_name,
1772 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1773 const uint8_t* annotation =
1774 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1775 if (annotation == nullptr) {
1776 return nullptr;
1777 }
1778 AnnotationValue annotation_value;
1779 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1780 return nullptr;
1781 }
1782 if (annotation_value.type_ != expected_type) {
1783 return nullptr;
1784 }
1785 return annotation_value.value_.GetL();
1786}
1787
Jeff Hao2a5892f2015-08-31 15:00:40 -07001788mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001789 const AnnotationSetItem* annotation_set) const {
1790 StackHandleScope<1> hs(Thread::Current());
1791 const AnnotationItem* annotation_item =
1792 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1793 if (annotation_item == nullptr) {
1794 return nullptr;
1795 }
1796 mirror::Class* string_class = mirror::String::GetJavaLangString();
1797 Handle<mirror::Class> string_array_class(hs.NewHandle(
1798 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001799 if (string_array_class.Get() == nullptr) {
1800 return nullptr;
1801 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001802 mirror::Object* obj =
1803 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1804 if (obj == nullptr) {
1805 return nullptr;
1806 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001807 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001808}
1809
Jeff Hao2a5892f2015-08-31 15:00:40 -07001810mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001811 const AnnotationSetItem* annotation_set) const {
1812 StackHandleScope<1> hs(Thread::Current());
1813 const AnnotationItem* annotation_item =
1814 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1815 if (annotation_item == nullptr) {
1816 return nullptr;
1817 }
1818 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1819 Handle<mirror::Class> class_array_class(hs.NewHandle(
1820 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001821 if (class_array_class.Get() == nullptr) {
1822 return nullptr;
1823 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001824 mirror::Object* obj =
1825 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1826 if (obj == nullptr) {
1827 return nullptr;
1828 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001829 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001830}
1831
1832mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1833 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1834 Thread* self = Thread::Current();
1835 ScopedObjectAccessUnchecked soa(self);
1836 StackHandleScope<2> hs(self);
1837 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1838 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1839 if (annotation_set == nullptr) {
1840 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1841 }
1842
1843 uint32_t size = annotation_set->size_;
1844 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1845 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1846 if (result.Get() == nullptr) {
1847 return nullptr;
1848 }
1849
1850 uint32_t dest_index = 0;
1851 for (uint32_t i = 0; i < size; ++i) {
1852 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001853 // Note that we do not use IsVisibilityCompatible here because older code
1854 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001855 if (annotation_item->visibility_ != visibility) {
1856 continue;
1857 }
1858 const uint8_t* annotation = annotation_item->annotation_;
1859 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1860 if (annotation_obj != nullptr) {
1861 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1862 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001863 } else if (self->IsExceptionPending()) {
1864 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001865 }
1866 }
1867
1868 if (dest_index == size) {
1869 return result.Get();
1870 }
1871
1872 mirror::ObjectArray<mirror::Object>* trimmed_result =
1873 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001874 if (trimmed_result == nullptr) {
1875 return nullptr;
1876 }
1877
Jeff Hao13e748b2015-08-25 20:44:19 +00001878 for (uint32_t i = 0; i < dest_index; ++i) {
1879 mirror::Object* obj = result->GetWithoutChecks(i);
1880 trimmed_result->SetWithoutChecks<false>(i, obj);
1881 }
1882
1883 return trimmed_result;
1884}
1885
1886mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1887 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1888 Thread* self = Thread::Current();
1889 ScopedObjectAccessUnchecked soa(self);
1890 StackHandleScope<1> hs(self);
1891 mirror::Class* annotation_array_class =
1892 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1893 mirror::Class* annotation_array_array_class =
1894 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001895 if (annotation_array_array_class == nullptr) {
1896 return nullptr;
1897 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001898 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1899 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1900 if (annotation_array_array.Get() == nullptr) {
1901 LOG(ERROR) << "Annotation set ref array allocation failed";
1902 return nullptr;
1903 }
1904 for (uint32_t index = 0; index < size; ++index) {
1905 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1906 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1907 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1908 if (annotation_set == nullptr) {
1909 return nullptr;
1910 }
1911 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1912 }
1913 return annotation_array_array.Get();
1914}
1915
1916bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1917 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1918 DexFile::AnnotationResultStyle result_style) const {
1919 Thread* self = Thread::Current();
1920 mirror::Object* element_object = nullptr;
1921 bool set_object = false;
1922 Primitive::Type primitive_type = Primitive::kPrimVoid;
1923 const uint8_t* annotation = *annotation_ptr;
1924 uint8_t header_byte = *(annotation++);
1925 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1926 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1927 int32_t width = value_arg + 1;
1928 annotation_value->type_ = value_type;
1929
1930 switch (value_type) {
1931 case kDexAnnotationByte:
1932 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1933 primitive_type = Primitive::kPrimByte;
1934 break;
1935 case kDexAnnotationShort:
1936 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1937 primitive_type = Primitive::kPrimShort;
1938 break;
1939 case kDexAnnotationChar:
1940 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1941 false)));
1942 primitive_type = Primitive::kPrimChar;
1943 break;
1944 case kDexAnnotationInt:
1945 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1946 primitive_type = Primitive::kPrimInt;
1947 break;
1948 case kDexAnnotationLong:
1949 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1950 primitive_type = Primitive::kPrimLong;
1951 break;
1952 case kDexAnnotationFloat:
1953 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1954 primitive_type = Primitive::kPrimFloat;
1955 break;
1956 case kDexAnnotationDouble:
1957 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1958 primitive_type = Primitive::kPrimDouble;
1959 break;
1960 case kDexAnnotationBoolean:
1961 annotation_value->value_.SetZ(value_arg != 0);
1962 primitive_type = Primitive::kPrimBoolean;
1963 width = 0;
1964 break;
1965 case kDexAnnotationString: {
1966 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1967 if (result_style == kAllRaw) {
1968 annotation_value->value_.SetI(index);
1969 } else {
1970 StackHandleScope<1> hs(self);
1971 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1972 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1973 klass->GetDexFile(), index, dex_cache);
1974 set_object = true;
1975 if (element_object == nullptr) {
1976 return false;
1977 }
1978 }
1979 break;
1980 }
1981 case kDexAnnotationType: {
1982 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1983 if (result_style == kAllRaw) {
1984 annotation_value->value_.SetI(index);
1985 } else {
1986 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1987 klass->GetDexFile(), index, klass.Get());
1988 set_object = true;
1989 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001990 CHECK(self->IsExceptionPending());
1991 if (result_style == kAllObjects) {
1992 const char* msg = StringByTypeIdx(index);
1993 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1994 element_object = self->GetException();
1995 self->ClearException();
1996 } else {
1997 return false;
1998 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001999 }
2000 }
2001 break;
2002 }
2003 case kDexAnnotationMethod: {
2004 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2005 if (result_style == kAllRaw) {
2006 annotation_value->value_.SetI(index);
2007 } else {
2008 StackHandleScope<2> hs(self);
2009 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2010 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07002011 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2012 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00002013 klass->GetDexFile(), index, dex_cache, class_loader);
2014 if (method == nullptr) {
2015 return false;
2016 }
Andreas Gampe542451c2016-07-26 09:02:02 -07002017 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00002018 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07002019 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00002020 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002021 if (pointer_size == PointerSize::k64) {
2022 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
2023 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002024 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002025 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
2026 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002027 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002028 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002029 if (pointer_size == PointerSize::k64) {
2030 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
2031 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002032 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002033 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
2034 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002035 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002036 }
2037 if (element_object == nullptr) {
2038 return false;
2039 }
2040 }
2041 break;
2042 }
2043 case kDexAnnotationField: {
2044 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2045 if (result_style == kAllRaw) {
2046 annotation_value->value_.SetI(index);
2047 } else {
2048 StackHandleScope<2> hs(self);
2049 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2050 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2051 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2052 klass->GetDexFile(), index, dex_cache, class_loader);
2053 if (field == nullptr) {
2054 return false;
2055 }
2056 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002057 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2058 if (pointer_size == PointerSize::k64) {
2059 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002060 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002061 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002062 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002063 if (element_object == nullptr) {
2064 return false;
2065 }
2066 }
2067 break;
2068 }
2069 case kDexAnnotationEnum: {
2070 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2071 if (result_style == kAllRaw) {
2072 annotation_value->value_.SetI(index);
2073 } else {
2074 StackHandleScope<3> hs(self);
2075 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2076 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2077 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2078 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002079 if (enum_field == nullptr) {
2080 return false;
2081 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002082 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002083 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2084 element_object = enum_field->GetObject(field_class.Get());
2085 set_object = true;
2086 }
2087 }
2088 break;
2089 }
2090 case kDexAnnotationArray:
2091 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2092 return false;
2093 } else {
2094 ScopedObjectAccessUnchecked soa(self);
2095 StackHandleScope<2> hs(self);
2096 uint32_t size = DecodeUnsignedLeb128(&annotation);
2097 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2098 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2099 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2100 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2101 if (new_array.Get() == nullptr) {
2102 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2103 return false;
2104 }
2105 AnnotationValue new_annotation_value;
2106 for (uint32_t i = 0; i < size; ++i) {
2107 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2108 kPrimitivesOrObjects)) {
2109 return false;
2110 }
2111 if (!component_type->IsPrimitive()) {
2112 mirror::Object* obj = new_annotation_value.value_.GetL();
2113 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2114 } else {
2115 switch (new_annotation_value.type_) {
2116 case kDexAnnotationByte:
2117 new_array->AsByteArray()->SetWithoutChecks<false>(
2118 i, new_annotation_value.value_.GetB());
2119 break;
2120 case kDexAnnotationShort:
2121 new_array->AsShortArray()->SetWithoutChecks<false>(
2122 i, new_annotation_value.value_.GetS());
2123 break;
2124 case kDexAnnotationChar:
2125 new_array->AsCharArray()->SetWithoutChecks<false>(
2126 i, new_annotation_value.value_.GetC());
2127 break;
2128 case kDexAnnotationInt:
2129 new_array->AsIntArray()->SetWithoutChecks<false>(
2130 i, new_annotation_value.value_.GetI());
2131 break;
2132 case kDexAnnotationLong:
2133 new_array->AsLongArray()->SetWithoutChecks<false>(
2134 i, new_annotation_value.value_.GetJ());
2135 break;
2136 case kDexAnnotationFloat:
2137 new_array->AsFloatArray()->SetWithoutChecks<false>(
2138 i, new_annotation_value.value_.GetF());
2139 break;
2140 case kDexAnnotationDouble:
2141 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2142 i, new_annotation_value.value_.GetD());
2143 break;
2144 case kDexAnnotationBoolean:
2145 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2146 i, new_annotation_value.value_.GetZ());
2147 break;
2148 default:
2149 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2150 return false;
2151 }
2152 }
2153 }
2154 element_object = new_array.Get();
2155 set_object = true;
2156 width = 0;
2157 }
2158 break;
2159 case kDexAnnotationAnnotation:
2160 if (result_style == kAllRaw) {
2161 return false;
2162 }
2163 element_object = ProcessEncodedAnnotation(klass, &annotation);
2164 if (element_object == nullptr) {
2165 return false;
2166 }
2167 set_object = true;
2168 width = 0;
2169 break;
2170 case kDexAnnotationNull:
2171 if (result_style == kAllRaw) {
2172 annotation_value->value_.SetI(0);
2173 } else {
2174 CHECK(element_object == nullptr);
2175 set_object = true;
2176 }
2177 width = 0;
2178 break;
2179 default:
2180 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2181 return false;
2182 }
2183
2184 annotation += width;
2185 *annotation_ptr = annotation;
2186
2187 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2188 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2189 set_object = true;
2190 }
2191
2192 if (set_object) {
2193 annotation_value->value_.SetL(element_object);
2194 }
2195
2196 return true;
2197}
2198
2199mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2200 const uint8_t** annotation) const {
2201 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2202 uint32_t size = DecodeUnsignedLeb128(annotation);
2203
2204 Thread* self = Thread::Current();
2205 ScopedObjectAccessUnchecked soa(self);
2206 StackHandleScope<2> hs(self);
2207 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2208 Handle<mirror::Class> annotation_class(hs.NewHandle(
2209 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2210 if (annotation_class.Get() == nullptr) {
2211 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2212 << type_index;
2213 DCHECK(Thread::Current()->IsExceptionPending());
2214 Thread::Current()->ClearException();
2215 return nullptr;
2216 }
2217
2218 mirror::Class* annotation_member_class =
2219 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2220 mirror::Class* annotation_member_array_class =
2221 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002222 if (annotation_member_array_class == nullptr) {
2223 return nullptr;
2224 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002225 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002226 if (size > 0) {
2227 element_array =
2228 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2229 if (element_array == nullptr) {
2230 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2231 return nullptr;
2232 }
2233 }
2234
2235 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2236 for (uint32_t i = 0; i < size; ++i) {
2237 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2238 if (new_member == nullptr) {
2239 return nullptr;
2240 }
2241 h_element_array->SetWithoutChecks<false>(i, new_member);
2242 }
2243
2244 JValue result;
2245 ArtMethod* create_annotation_method =
2246 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2247 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2248 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2249 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2250 if (self->IsExceptionPending()) {
2251 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2252 return nullptr;
2253 }
2254
2255 return result.GetL();
2256}
2257
2258const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2259 const char* descriptor, uint32_t visibility) const {
2260 const AnnotationItem* result = nullptr;
2261 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2262 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002263 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002264 continue;
2265 }
2266 const uint8_t* annotation = annotation_item->annotation_;
2267 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2268
2269 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2270 result = annotation_item;
2271 break;
2272 }
2273 }
2274 return result;
2275}
2276
2277const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2278 DecodeUnsignedLeb128(&annotation); // unused type_index
2279 uint32_t size = DecodeUnsignedLeb128(&annotation);
2280
2281 while (size != 0) {
2282 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2283 const char* element_name = GetStringData(GetStringId(element_name_index));
2284 if (strcmp(name, element_name) == 0) {
2285 return annotation;
2286 }
2287 SkipAnnotationValue(&annotation);
2288 size--;
2289 }
2290 return nullptr;
2291}
2292
2293bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2294 const uint8_t* annotation = *annotation_ptr;
2295 uint8_t header_byte = *(annotation++);
2296 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2297 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2298 int32_t width = value_arg + 1;
2299
2300 switch (value_type) {
2301 case kDexAnnotationByte:
2302 case kDexAnnotationShort:
2303 case kDexAnnotationChar:
2304 case kDexAnnotationInt:
2305 case kDexAnnotationLong:
2306 case kDexAnnotationFloat:
2307 case kDexAnnotationDouble:
2308 case kDexAnnotationString:
2309 case kDexAnnotationType:
2310 case kDexAnnotationMethod:
2311 case kDexAnnotationField:
2312 case kDexAnnotationEnum:
2313 break;
2314 case kDexAnnotationArray:
2315 {
2316 uint32_t size = DecodeUnsignedLeb128(&annotation);
2317 while (size--) {
2318 if (!SkipAnnotationValue(&annotation)) {
2319 return false;
2320 }
2321 }
2322 width = 0;
2323 break;
2324 }
2325 case kDexAnnotationAnnotation:
2326 {
2327 DecodeUnsignedLeb128(&annotation); // unused type_index
2328 uint32_t size = DecodeUnsignedLeb128(&annotation);
2329 while (size--) {
2330 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2331 if (!SkipAnnotationValue(&annotation)) {
2332 return false;
2333 }
2334 }
2335 width = 0;
2336 break;
2337 }
2338 case kDexAnnotationBoolean:
2339 case kDexAnnotationNull:
2340 width = 0;
2341 break;
2342 default:
2343 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2344 return false;
2345 }
2346
2347 annotation += width;
2348 *annotation_ptr = annotation;
2349 return true;
2350}
2351
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002352std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2353 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2354 dex_file.GetLocation().c_str(),
2355 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2356 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2357 return os;
2358}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002359
Ian Rogersd91d6d62013-09-25 20:26:14 -07002360std::string Signature::ToString() const {
2361 if (dex_file_ == nullptr) {
2362 CHECK(proto_id_ == nullptr);
2363 return "<no signature>";
2364 }
2365 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2366 std::string result;
2367 if (params == nullptr) {
2368 result += "()";
2369 } else {
2370 result += "(";
2371 for (uint32_t i = 0; i < params->Size(); ++i) {
2372 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2373 }
2374 result += ")";
2375 }
2376 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2377 return result;
2378}
2379
Vladimir Markod9cffea2013-11-25 15:08:02 +00002380bool Signature::operator==(const StringPiece& rhs) const {
2381 if (dex_file_ == nullptr) {
2382 return false;
2383 }
2384 StringPiece tail(rhs);
2385 if (!tail.starts_with("(")) {
2386 return false; // Invalid signature
2387 }
2388 tail.remove_prefix(1); // "(";
2389 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2390 if (params != nullptr) {
2391 for (uint32_t i = 0; i < params->Size(); ++i) {
2392 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2393 if (!tail.starts_with(param)) {
2394 return false;
2395 }
2396 tail.remove_prefix(param.length());
2397 }
2398 }
2399 if (!tail.starts_with(")")) {
2400 return false;
2401 }
2402 tail.remove_prefix(1); // ")";
2403 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2404}
2405
Ian Rogersd91d6d62013-09-25 20:26:14 -07002406std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2407 return os << sig.ToString();
2408}
2409
Ian Rogers0571d352011-11-03 19:51:38 -07002410// Decodes the header section from the class data bytes.
2411void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002412 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002413 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2414 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2415 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2416 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2417}
2418
2419void ClassDataItemIterator::ReadClassDataField() {
2420 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2421 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002422 // The user of the iterator is responsible for checking if there
2423 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002424}
2425
2426void ClassDataItemIterator::ReadClassDataMethod() {
2427 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2428 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2429 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002430 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002431 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002432 }
Ian Rogers0571d352011-11-03 19:51:38 -07002433}
2434
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002435EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002436 const DexFile& dex_file,
2437 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002438 : EncodedStaticFieldValueIterator(dex_file,
2439 nullptr,
2440 nullptr,
2441 nullptr,
2442 class_def,
2443 -1,
2444 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002445}
2446
2447EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002448 const DexFile& dex_file,
2449 Handle<mirror::DexCache>* dex_cache,
2450 Handle<mirror::ClassLoader>* class_loader,
2451 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002452 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002453 : EncodedStaticFieldValueIterator(dex_file,
2454 dex_cache, class_loader,
2455 linker,
2456 class_def,
2457 -1,
2458 kByte) {
2459 DCHECK(dex_cache_ != nullptr);
2460 DCHECK(class_loader_ != nullptr);
2461}
2462
2463EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2464 const DexFile& dex_file,
2465 Handle<mirror::DexCache>* dex_cache,
2466 Handle<mirror::ClassLoader>* class_loader,
2467 ClassLinker* linker,
2468 const DexFile::ClassDef& class_def,
2469 size_t pos,
2470 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002471 : dex_file_(dex_file),
2472 dex_cache_(dex_cache),
2473 class_loader_(class_loader),
2474 linker_(linker),
2475 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002476 pos_(pos),
2477 type_(type) {
2478 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002479 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002480 array_size_ = 0;
2481 } else {
2482 array_size_ = DecodeUnsignedLeb128(&ptr_);
2483 }
2484 if (array_size_ > 0) {
2485 Next();
2486 }
2487}
2488
2489void EncodedStaticFieldValueIterator::Next() {
2490 pos_++;
2491 if (pos_ >= array_size_) {
2492 return;
2493 }
Ian Rogers13735952014-10-08 12:43:28 -07002494 uint8_t value_type = *ptr_++;
2495 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002496 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002497 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002498 switch (type_) {
2499 case kBoolean:
2500 jval_.i = (value_arg != 0) ? 1 : 0;
2501 width = 0;
2502 break;
2503 case kByte:
2504 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002505 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002506 break;
2507 case kShort:
2508 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002509 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002510 break;
2511 case kChar:
2512 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002513 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002514 break;
2515 case kInt:
2516 jval_.i = ReadSignedInt(ptr_, value_arg);
2517 break;
2518 case kLong:
2519 jval_.j = ReadSignedLong(ptr_, value_arg);
2520 break;
2521 case kFloat:
2522 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2523 break;
2524 case kDouble:
2525 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2526 break;
2527 case kString:
2528 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002529 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2530 break;
2531 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002532 case kMethod:
2533 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002534 case kArray:
2535 case kAnnotation:
2536 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002537 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002538 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002539 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002540 width = 0;
2541 break;
2542 default:
2543 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002544 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002545 }
2546 ptr_ += width;
2547}
2548
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002549template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002550void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002551 DCHECK(dex_cache_ != nullptr);
2552 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002553 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002554 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2555 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002556 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2557 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2558 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2559 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2560 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2561 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2562 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002563 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002564 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002565 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002566 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002567 break;
2568 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002569 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002570 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2571 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002572 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002573 break;
2574 }
Ian Rogers0571d352011-11-03 19:51:38 -07002575 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2576 }
2577}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002578template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2579template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002580
2581CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2582 handler_.address_ = -1;
2583 int32_t offset = -1;
2584
2585 // Short-circuit the overwhelmingly common cases.
2586 switch (code_item.tries_size_) {
2587 case 0:
2588 break;
2589 case 1: {
2590 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2591 uint32_t start = tries->start_addr_;
2592 if (address >= start) {
2593 uint32_t end = start + tries->insn_count_;
2594 if (address < end) {
2595 offset = tries->handler_off_;
2596 }
2597 }
2598 break;
2599 }
2600 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002601 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002602 }
Logan Chien736df022012-04-27 16:25:57 +08002603 Init(code_item, offset);
2604}
2605
2606CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2607 const DexFile::TryItem& try_item) {
2608 handler_.address_ = -1;
2609 Init(code_item, try_item.handler_off_);
2610}
2611
2612void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2613 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002614 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002615 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002616 } else {
2617 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002618 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002619 remaining_count_ = -1;
2620 catch_all_ = false;
2621 DCHECK(!HasNext());
2622 }
2623}
2624
Ian Rogers13735952014-10-08 12:43:28 -07002625void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002626 current_data_ = handler_data;
2627 remaining_count_ = DecodeSignedLeb128(&current_data_);
2628
2629 // If remaining_count_ is non-positive, then it is the negative of
2630 // the number of catch types, and the catches are followed by a
2631 // catch-all handler.
2632 if (remaining_count_ <= 0) {
2633 catch_all_ = true;
2634 remaining_count_ = -remaining_count_;
2635 } else {
2636 catch_all_ = false;
2637 }
2638 Next();
2639}
2640
2641void CatchHandlerIterator::Next() {
2642 if (remaining_count_ > 0) {
2643 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2644 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2645 remaining_count_--;
2646 return;
2647 }
2648
2649 if (catch_all_) {
2650 handler_.type_idx_ = DexFile::kDexNoIndex16;
2651 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2652 catch_all_ = false;
2653 return;
2654 }
2655
2656 // no more handler
2657 remaining_count_ = -1;
2658}
2659
Carl Shapiro1fb86202011-06-27 17:43:13 -07002660} // namespace art