blob: 76cd348d8e0670e1eb62f75332809ee9fc95a158 [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
Neil Fuller60458a02016-09-01 15:32:44 +01001434mirror::Object* DexFile::GetAnnotationForMethodParameter(ArtMethod* method,
1435 uint32_t parameter_idx,
1436 Handle<mirror::Class> annotation_class)
1437 const {
1438 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1439 if (parameter_annotations == nullptr) {
1440 return nullptr;
1441 }
1442 const AnnotationSetRefList* set_ref_list =
1443 GetParameterAnnotationSetRefList(parameter_annotations);
1444 if (set_ref_list == nullptr) {
1445 return nullptr;
1446 }
1447
1448 if (parameter_idx >= set_ref_list->size_) {
1449 return nullptr;
1450 }
1451 const AnnotationSetRefItem* annotation_set_ref = &set_ref_list->list_[parameter_idx];
1452 const AnnotationSetItem* annotation_set = GetSetRefItemItem(annotation_set_ref);
1453
1454 StackHandleScope<1> hs(Thread::Current());
1455 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1456 return GetAnnotationObjectFromAnnotationSet(method_class,
1457 annotation_set,
1458 kDexVisibilityRuntime,
1459 annotation_class);
1460}
1461
Jeff Hao1133db72016-04-04 19:50:14 -07001462mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1463 const {
1464 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1465 if (annotation_set == nullptr) {
1466 return nullptr;
1467 }
1468 StackHandleScope<1> hs(Thread::Current());
1469 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1470 return GetSignatureValue(method_class, annotation_set);
1471}
1472
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001473bool DexFile::IsMethodAnnotationPresent(ArtMethod* method,
1474 Handle<mirror::Class> annotation_class,
1475 uint32_t visibility /* = kDexVisibilityRuntime */)
Jeff Hao13e748b2015-08-25 20:44:19 +00001476 const {
1477 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1478 if (annotation_set == nullptr) {
1479 return false;
1480 }
1481 StackHandleScope<1> hs(Thread::Current());
1482 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001483 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(method_class,
1484 annotation_set,
1485 visibility,
1486 annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001487 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001488}
1489
1490const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1491 const {
1492 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1493 if (annotations_dir == nullptr) {
1494 return nullptr;
1495 }
1496 return GetClassAnnotationSet(annotations_dir);
1497}
1498
1499mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1500 Handle<mirror::Class> annotation_class) const {
1501 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1502 if (annotation_set == nullptr) {
1503 return nullptr;
1504 }
1505 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1506 annotation_class);
1507}
1508
1509mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1510 const {
1511 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1512 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1513}
1514
Jeff Hao2a5892f2015-08-31 15:00:40 -07001515mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1516 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1517 if (annotation_set == nullptr) {
1518 return nullptr;
1519 }
1520 const AnnotationItem* annotation_item = SearchAnnotationSet(
1521 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1522 if (annotation_item == nullptr) {
1523 return nullptr;
1524 }
1525 StackHandleScope<1> hs(Thread::Current());
1526 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1527 Handle<mirror::Class> class_array_class(hs.NewHandle(
1528 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1529 if (class_array_class.Get() == nullptr) {
1530 return nullptr;
1531 }
1532 mirror::Object* obj = GetAnnotationValue(
1533 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1534 if (obj == nullptr) {
1535 return nullptr;
1536 }
1537 return obj->AsObjectArray<mirror::Class>();
1538}
1539
1540mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1541 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1542 if (annotation_set == nullptr) {
1543 return nullptr;
1544 }
1545 const AnnotationItem* annotation_item = SearchAnnotationSet(
1546 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1547 if (annotation_item == nullptr) {
1548 return nullptr;
1549 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001550 mirror::Object* obj = GetAnnotationValue(klass,
1551 annotation_item,
1552 "value",
1553 ScopedNullHandle<mirror::Class>(),
1554 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001555 if (obj == nullptr) {
1556 return nullptr;
1557 }
1558 return obj->AsClass();
1559}
1560
1561mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1562 mirror::Class* declaring_class = GetDeclaringClass(klass);
1563 if (declaring_class != nullptr) {
1564 return declaring_class;
1565 }
1566 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1567 if (annotation_set == nullptr) {
1568 return nullptr;
1569 }
1570 const AnnotationItem* annotation_item = SearchAnnotationSet(
1571 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1572 if (annotation_item == nullptr) {
1573 return nullptr;
1574 }
1575 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1576 if (annotation == nullptr) {
1577 return nullptr;
1578 }
1579 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001580 if (!ProcessAnnotationValue(klass,
1581 &annotation,
1582 &annotation_value,
1583 ScopedNullHandle<mirror::Class>(),
1584 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001585 return nullptr;
1586 }
1587 if (annotation_value.type_ != kDexAnnotationMethod) {
1588 return nullptr;
1589 }
1590 StackHandleScope<2> hs(Thread::Current());
1591 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1592 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1593 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1594 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1595 if (method == nullptr) {
1596 return nullptr;
1597 }
1598 return method->GetDeclaringClass();
1599}
1600
1601mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1602 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1603 if (annotation_set == nullptr) {
1604 return nullptr;
1605 }
1606 const AnnotationItem* annotation_item = SearchAnnotationSet(
1607 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1608 if (annotation_item == nullptr) {
1609 return nullptr;
1610 }
1611 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001612 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001613}
1614
1615bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1616 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1617 if (annotation_set == nullptr) {
1618 return false;
1619 }
1620 const AnnotationItem* annotation_item = SearchAnnotationSet(
1621 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1622 if (annotation_item == nullptr) {
1623 return false;
1624 }
1625 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1626 if (annotation == nullptr) {
1627 return false;
1628 }
1629 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001630 if (!ProcessAnnotationValue(klass,
1631 &annotation,
1632 &annotation_value,
1633 ScopedNullHandle<mirror::Class>(),
1634 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001635 return false;
1636 }
1637 if (annotation_value.type_ != kDexAnnotationNull &&
1638 annotation_value.type_ != kDexAnnotationString) {
1639 return false;
1640 }
1641 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1642 return true;
1643}
1644
1645bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1646 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1647 if (annotation_set == nullptr) {
1648 return false;
1649 }
1650 const AnnotationItem* annotation_item = SearchAnnotationSet(
1651 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1652 if (annotation_item == nullptr) {
1653 return false;
1654 }
1655 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1656 if (annotation == nullptr) {
1657 return false;
1658 }
1659 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001660 if (!ProcessAnnotationValue(klass,
1661 &annotation,
1662 &annotation_value,
1663 ScopedNullHandle<mirror::Class>(),
1664 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001665 return false;
1666 }
1667 if (annotation_value.type_ != kDexAnnotationInt) {
1668 return false;
1669 }
1670 *flags = annotation_value.value_.GetI();
1671 return true;
1672}
1673
Jeff Hao1133db72016-04-04 19:50:14 -07001674mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1675 Handle<mirror::Class> klass) const {
1676 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1677 if (annotation_set == nullptr) {
1678 return nullptr;
1679 }
1680 return GetSignatureValue(klass, annotation_set);
1681}
1682
Jeff Hao13e748b2015-08-25 20:44:19 +00001683bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1684 Handle<mirror::Class> annotation_class) const {
1685 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1686 if (annotation_set == nullptr) {
1687 return false;
1688 }
1689 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1690 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001691 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001692}
1693
1694mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1695 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1696 Thread* self = Thread::Current();
1697 ScopedObjectAccessUnchecked soa(self);
1698 StackHandleScope<5> hs(self);
1699 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1700 const char* name = StringDataByIdx(element_name_index);
1701 Handle<mirror::String> string_name(
1702 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1703
Andreas Gampe542451c2016-07-26 09:02:02 -07001704 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001705 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001706 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001707 if (annotation_method == nullptr) {
1708 return nullptr;
1709 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001710 Handle<mirror::Class> method_return(hs.NewHandle(
1711 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001712
1713 AnnotationValue annotation_value;
1714 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1715 return nullptr;
1716 }
1717 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1718
1719 mirror::Class* annotation_member_class =
1720 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1721 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001722 mirror::Method* method_obj_ptr;
1723 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001724 if (pointer_size == PointerSize::k64) {
1725 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1726 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001727 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001728 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1729 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001730 }
1731 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001732
1733 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1734 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1735 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1736 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1737 return nullptr;
1738 }
1739
1740 JValue result;
1741 ArtMethod* annotation_member_init =
1742 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1743 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1744 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1745 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1746 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1747 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1748 };
1749 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1750 if (self->IsExceptionPending()) {
1751 LOG(INFO) << "Exception in AnnotationMember.<init>";
1752 return nullptr;
1753 }
1754
1755 return new_member.Get();
1756}
1757
1758const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1759 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1760 Handle<mirror::Class> annotation_class) const {
1761 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1762 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001763 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001764 continue;
1765 }
1766 const uint8_t* annotation = annotation_item->annotation_;
1767 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1768 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1769 klass->GetDexFile(), type_index, klass.Get());
1770 if (resolved_class == nullptr) {
1771 std::string temp;
1772 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1773 klass->GetDescriptor(&temp), type_index);
1774 CHECK(Thread::Current()->IsExceptionPending());
1775 Thread::Current()->ClearException();
1776 continue;
1777 }
1778 if (resolved_class == annotation_class.Get()) {
1779 return annotation_item;
1780 }
1781 }
1782
1783 return nullptr;
1784}
1785
1786mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1787 const AnnotationSetItem* annotation_set, uint32_t visibility,
1788 Handle<mirror::Class> annotation_class) const {
1789 const AnnotationItem* annotation_item =
1790 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1791 if (annotation_item == nullptr) {
1792 return nullptr;
1793 }
1794 const uint8_t* annotation = annotation_item->annotation_;
1795 return ProcessEncodedAnnotation(klass, &annotation);
1796}
1797
1798mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1799 const AnnotationItem* annotation_item, const char* annotation_name,
1800 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1801 const uint8_t* annotation =
1802 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1803 if (annotation == nullptr) {
1804 return nullptr;
1805 }
1806 AnnotationValue annotation_value;
1807 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1808 return nullptr;
1809 }
1810 if (annotation_value.type_ != expected_type) {
1811 return nullptr;
1812 }
1813 return annotation_value.value_.GetL();
1814}
1815
Jeff Hao2a5892f2015-08-31 15:00:40 -07001816mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001817 const AnnotationSetItem* annotation_set) const {
1818 StackHandleScope<1> hs(Thread::Current());
1819 const AnnotationItem* annotation_item =
1820 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1821 if (annotation_item == nullptr) {
1822 return nullptr;
1823 }
1824 mirror::Class* string_class = mirror::String::GetJavaLangString();
1825 Handle<mirror::Class> string_array_class(hs.NewHandle(
1826 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001827 if (string_array_class.Get() == nullptr) {
1828 return nullptr;
1829 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001830 mirror::Object* obj =
1831 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1832 if (obj == nullptr) {
1833 return nullptr;
1834 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001835 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001836}
1837
Jeff Hao2a5892f2015-08-31 15:00:40 -07001838mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001839 const AnnotationSetItem* annotation_set) const {
1840 StackHandleScope<1> hs(Thread::Current());
1841 const AnnotationItem* annotation_item =
1842 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1843 if (annotation_item == nullptr) {
1844 return nullptr;
1845 }
1846 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1847 Handle<mirror::Class> class_array_class(hs.NewHandle(
1848 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001849 if (class_array_class.Get() == nullptr) {
1850 return nullptr;
1851 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001852 mirror::Object* obj =
1853 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1854 if (obj == nullptr) {
1855 return nullptr;
1856 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001857 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001858}
1859
1860mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1861 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1862 Thread* self = Thread::Current();
1863 ScopedObjectAccessUnchecked soa(self);
1864 StackHandleScope<2> hs(self);
1865 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1866 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1867 if (annotation_set == nullptr) {
1868 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1869 }
1870
1871 uint32_t size = annotation_set->size_;
1872 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1873 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1874 if (result.Get() == nullptr) {
1875 return nullptr;
1876 }
1877
1878 uint32_t dest_index = 0;
1879 for (uint32_t i = 0; i < size; ++i) {
1880 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001881 // Note that we do not use IsVisibilityCompatible here because older code
1882 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001883 if (annotation_item->visibility_ != visibility) {
1884 continue;
1885 }
1886 const uint8_t* annotation = annotation_item->annotation_;
1887 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1888 if (annotation_obj != nullptr) {
1889 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1890 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001891 } else if (self->IsExceptionPending()) {
1892 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001893 }
1894 }
1895
1896 if (dest_index == size) {
1897 return result.Get();
1898 }
1899
1900 mirror::ObjectArray<mirror::Object>* trimmed_result =
1901 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001902 if (trimmed_result == nullptr) {
1903 return nullptr;
1904 }
1905
Jeff Hao13e748b2015-08-25 20:44:19 +00001906 for (uint32_t i = 0; i < dest_index; ++i) {
1907 mirror::Object* obj = result->GetWithoutChecks(i);
1908 trimmed_result->SetWithoutChecks<false>(i, obj);
1909 }
1910
1911 return trimmed_result;
1912}
1913
1914mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1915 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1916 Thread* self = Thread::Current();
1917 ScopedObjectAccessUnchecked soa(self);
1918 StackHandleScope<1> hs(self);
1919 mirror::Class* annotation_array_class =
1920 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1921 mirror::Class* annotation_array_array_class =
1922 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001923 if (annotation_array_array_class == nullptr) {
1924 return nullptr;
1925 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001926 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1927 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1928 if (annotation_array_array.Get() == nullptr) {
1929 LOG(ERROR) << "Annotation set ref array allocation failed";
1930 return nullptr;
1931 }
1932 for (uint32_t index = 0; index < size; ++index) {
1933 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1934 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1935 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1936 if (annotation_set == nullptr) {
1937 return nullptr;
1938 }
1939 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1940 }
1941 return annotation_array_array.Get();
1942}
1943
1944bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1945 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1946 DexFile::AnnotationResultStyle result_style) const {
1947 Thread* self = Thread::Current();
1948 mirror::Object* element_object = nullptr;
1949 bool set_object = false;
1950 Primitive::Type primitive_type = Primitive::kPrimVoid;
1951 const uint8_t* annotation = *annotation_ptr;
1952 uint8_t header_byte = *(annotation++);
1953 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1954 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1955 int32_t width = value_arg + 1;
1956 annotation_value->type_ = value_type;
1957
1958 switch (value_type) {
1959 case kDexAnnotationByte:
1960 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1961 primitive_type = Primitive::kPrimByte;
1962 break;
1963 case kDexAnnotationShort:
1964 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1965 primitive_type = Primitive::kPrimShort;
1966 break;
1967 case kDexAnnotationChar:
1968 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1969 false)));
1970 primitive_type = Primitive::kPrimChar;
1971 break;
1972 case kDexAnnotationInt:
1973 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1974 primitive_type = Primitive::kPrimInt;
1975 break;
1976 case kDexAnnotationLong:
1977 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1978 primitive_type = Primitive::kPrimLong;
1979 break;
1980 case kDexAnnotationFloat:
1981 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1982 primitive_type = Primitive::kPrimFloat;
1983 break;
1984 case kDexAnnotationDouble:
1985 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1986 primitive_type = Primitive::kPrimDouble;
1987 break;
1988 case kDexAnnotationBoolean:
1989 annotation_value->value_.SetZ(value_arg != 0);
1990 primitive_type = Primitive::kPrimBoolean;
1991 width = 0;
1992 break;
1993 case kDexAnnotationString: {
1994 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1995 if (result_style == kAllRaw) {
1996 annotation_value->value_.SetI(index);
1997 } else {
1998 StackHandleScope<1> hs(self);
1999 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2000 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
2001 klass->GetDexFile(), index, dex_cache);
2002 set_object = true;
2003 if (element_object == nullptr) {
2004 return false;
2005 }
2006 }
2007 break;
2008 }
2009 case kDexAnnotationType: {
2010 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2011 if (result_style == kAllRaw) {
2012 annotation_value->value_.SetI(index);
2013 } else {
2014 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
2015 klass->GetDexFile(), index, klass.Get());
2016 set_object = true;
2017 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07002018 CHECK(self->IsExceptionPending());
2019 if (result_style == kAllObjects) {
2020 const char* msg = StringByTypeIdx(index);
2021 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
2022 element_object = self->GetException();
2023 self->ClearException();
2024 } else {
2025 return false;
2026 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002027 }
2028 }
2029 break;
2030 }
2031 case kDexAnnotationMethod: {
2032 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2033 if (result_style == kAllRaw) {
2034 annotation_value->value_.SetI(index);
2035 } else {
2036 StackHandleScope<2> hs(self);
2037 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2038 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07002039 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2040 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00002041 klass->GetDexFile(), index, dex_cache, class_loader);
2042 if (method == nullptr) {
2043 return false;
2044 }
Andreas Gampe542451c2016-07-26 09:02:02 -07002045 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00002046 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07002047 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00002048 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002049 if (pointer_size == PointerSize::k64) {
2050 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
2051 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002052 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002053 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
2054 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002055 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002056 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002057 if (pointer_size == PointerSize::k64) {
2058 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
2059 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002060 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002061 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
2062 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002063 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002064 }
2065 if (element_object == nullptr) {
2066 return false;
2067 }
2068 }
2069 break;
2070 }
2071 case kDexAnnotationField: {
2072 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2073 if (result_style == kAllRaw) {
2074 annotation_value->value_.SetI(index);
2075 } else {
2076 StackHandleScope<2> hs(self);
2077 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2078 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2079 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2080 klass->GetDexFile(), index, dex_cache, class_loader);
2081 if (field == nullptr) {
2082 return false;
2083 }
2084 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002085 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2086 if (pointer_size == PointerSize::k64) {
2087 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002088 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002089 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002090 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002091 if (element_object == nullptr) {
2092 return false;
2093 }
2094 }
2095 break;
2096 }
2097 case kDexAnnotationEnum: {
2098 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2099 if (result_style == kAllRaw) {
2100 annotation_value->value_.SetI(index);
2101 } else {
2102 StackHandleScope<3> hs(self);
2103 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2104 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2105 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2106 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002107 if (enum_field == nullptr) {
2108 return false;
2109 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002110 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002111 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2112 element_object = enum_field->GetObject(field_class.Get());
2113 set_object = true;
2114 }
2115 }
2116 break;
2117 }
2118 case kDexAnnotationArray:
2119 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2120 return false;
2121 } else {
2122 ScopedObjectAccessUnchecked soa(self);
2123 StackHandleScope<2> hs(self);
2124 uint32_t size = DecodeUnsignedLeb128(&annotation);
2125 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2126 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2127 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2128 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2129 if (new_array.Get() == nullptr) {
2130 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2131 return false;
2132 }
2133 AnnotationValue new_annotation_value;
2134 for (uint32_t i = 0; i < size; ++i) {
2135 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2136 kPrimitivesOrObjects)) {
2137 return false;
2138 }
2139 if (!component_type->IsPrimitive()) {
2140 mirror::Object* obj = new_annotation_value.value_.GetL();
2141 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2142 } else {
2143 switch (new_annotation_value.type_) {
2144 case kDexAnnotationByte:
2145 new_array->AsByteArray()->SetWithoutChecks<false>(
2146 i, new_annotation_value.value_.GetB());
2147 break;
2148 case kDexAnnotationShort:
2149 new_array->AsShortArray()->SetWithoutChecks<false>(
2150 i, new_annotation_value.value_.GetS());
2151 break;
2152 case kDexAnnotationChar:
2153 new_array->AsCharArray()->SetWithoutChecks<false>(
2154 i, new_annotation_value.value_.GetC());
2155 break;
2156 case kDexAnnotationInt:
2157 new_array->AsIntArray()->SetWithoutChecks<false>(
2158 i, new_annotation_value.value_.GetI());
2159 break;
2160 case kDexAnnotationLong:
2161 new_array->AsLongArray()->SetWithoutChecks<false>(
2162 i, new_annotation_value.value_.GetJ());
2163 break;
2164 case kDexAnnotationFloat:
2165 new_array->AsFloatArray()->SetWithoutChecks<false>(
2166 i, new_annotation_value.value_.GetF());
2167 break;
2168 case kDexAnnotationDouble:
2169 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2170 i, new_annotation_value.value_.GetD());
2171 break;
2172 case kDexAnnotationBoolean:
2173 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2174 i, new_annotation_value.value_.GetZ());
2175 break;
2176 default:
2177 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2178 return false;
2179 }
2180 }
2181 }
2182 element_object = new_array.Get();
2183 set_object = true;
2184 width = 0;
2185 }
2186 break;
2187 case kDexAnnotationAnnotation:
2188 if (result_style == kAllRaw) {
2189 return false;
2190 }
2191 element_object = ProcessEncodedAnnotation(klass, &annotation);
2192 if (element_object == nullptr) {
2193 return false;
2194 }
2195 set_object = true;
2196 width = 0;
2197 break;
2198 case kDexAnnotationNull:
2199 if (result_style == kAllRaw) {
2200 annotation_value->value_.SetI(0);
2201 } else {
2202 CHECK(element_object == nullptr);
2203 set_object = true;
2204 }
2205 width = 0;
2206 break;
2207 default:
2208 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2209 return false;
2210 }
2211
2212 annotation += width;
2213 *annotation_ptr = annotation;
2214
2215 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2216 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2217 set_object = true;
2218 }
2219
2220 if (set_object) {
2221 annotation_value->value_.SetL(element_object);
2222 }
2223
2224 return true;
2225}
2226
2227mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2228 const uint8_t** annotation) const {
2229 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2230 uint32_t size = DecodeUnsignedLeb128(annotation);
2231
2232 Thread* self = Thread::Current();
2233 ScopedObjectAccessUnchecked soa(self);
2234 StackHandleScope<2> hs(self);
2235 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2236 Handle<mirror::Class> annotation_class(hs.NewHandle(
2237 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2238 if (annotation_class.Get() == nullptr) {
2239 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2240 << type_index;
2241 DCHECK(Thread::Current()->IsExceptionPending());
2242 Thread::Current()->ClearException();
2243 return nullptr;
2244 }
2245
2246 mirror::Class* annotation_member_class =
2247 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2248 mirror::Class* annotation_member_array_class =
2249 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002250 if (annotation_member_array_class == nullptr) {
2251 return nullptr;
2252 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002253 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002254 if (size > 0) {
2255 element_array =
2256 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2257 if (element_array == nullptr) {
2258 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2259 return nullptr;
2260 }
2261 }
2262
2263 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2264 for (uint32_t i = 0; i < size; ++i) {
2265 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2266 if (new_member == nullptr) {
2267 return nullptr;
2268 }
2269 h_element_array->SetWithoutChecks<false>(i, new_member);
2270 }
2271
2272 JValue result;
2273 ArtMethod* create_annotation_method =
2274 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2275 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2276 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2277 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2278 if (self->IsExceptionPending()) {
2279 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2280 return nullptr;
2281 }
2282
2283 return result.GetL();
2284}
2285
2286const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2287 const char* descriptor, uint32_t visibility) const {
2288 const AnnotationItem* result = nullptr;
2289 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2290 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002291 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002292 continue;
2293 }
2294 const uint8_t* annotation = annotation_item->annotation_;
2295 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2296
2297 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2298 result = annotation_item;
2299 break;
2300 }
2301 }
2302 return result;
2303}
2304
2305const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2306 DecodeUnsignedLeb128(&annotation); // unused type_index
2307 uint32_t size = DecodeUnsignedLeb128(&annotation);
2308
2309 while (size != 0) {
2310 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2311 const char* element_name = GetStringData(GetStringId(element_name_index));
2312 if (strcmp(name, element_name) == 0) {
2313 return annotation;
2314 }
2315 SkipAnnotationValue(&annotation);
2316 size--;
2317 }
2318 return nullptr;
2319}
2320
2321bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2322 const uint8_t* annotation = *annotation_ptr;
2323 uint8_t header_byte = *(annotation++);
2324 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2325 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2326 int32_t width = value_arg + 1;
2327
2328 switch (value_type) {
2329 case kDexAnnotationByte:
2330 case kDexAnnotationShort:
2331 case kDexAnnotationChar:
2332 case kDexAnnotationInt:
2333 case kDexAnnotationLong:
2334 case kDexAnnotationFloat:
2335 case kDexAnnotationDouble:
2336 case kDexAnnotationString:
2337 case kDexAnnotationType:
2338 case kDexAnnotationMethod:
2339 case kDexAnnotationField:
2340 case kDexAnnotationEnum:
2341 break;
2342 case kDexAnnotationArray:
2343 {
2344 uint32_t size = DecodeUnsignedLeb128(&annotation);
2345 while (size--) {
2346 if (!SkipAnnotationValue(&annotation)) {
2347 return false;
2348 }
2349 }
2350 width = 0;
2351 break;
2352 }
2353 case kDexAnnotationAnnotation:
2354 {
2355 DecodeUnsignedLeb128(&annotation); // unused type_index
2356 uint32_t size = DecodeUnsignedLeb128(&annotation);
2357 while (size--) {
2358 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2359 if (!SkipAnnotationValue(&annotation)) {
2360 return false;
2361 }
2362 }
2363 width = 0;
2364 break;
2365 }
2366 case kDexAnnotationBoolean:
2367 case kDexAnnotationNull:
2368 width = 0;
2369 break;
2370 default:
2371 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2372 return false;
2373 }
2374
2375 annotation += width;
2376 *annotation_ptr = annotation;
2377 return true;
2378}
2379
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002380std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2381 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2382 dex_file.GetLocation().c_str(),
2383 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2384 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2385 return os;
2386}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002387
Ian Rogersd91d6d62013-09-25 20:26:14 -07002388std::string Signature::ToString() const {
2389 if (dex_file_ == nullptr) {
2390 CHECK(proto_id_ == nullptr);
2391 return "<no signature>";
2392 }
2393 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2394 std::string result;
2395 if (params == nullptr) {
2396 result += "()";
2397 } else {
2398 result += "(";
2399 for (uint32_t i = 0; i < params->Size(); ++i) {
2400 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2401 }
2402 result += ")";
2403 }
2404 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2405 return result;
2406}
2407
Vladimir Markod9cffea2013-11-25 15:08:02 +00002408bool Signature::operator==(const StringPiece& rhs) const {
2409 if (dex_file_ == nullptr) {
2410 return false;
2411 }
2412 StringPiece tail(rhs);
2413 if (!tail.starts_with("(")) {
2414 return false; // Invalid signature
2415 }
2416 tail.remove_prefix(1); // "(";
2417 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2418 if (params != nullptr) {
2419 for (uint32_t i = 0; i < params->Size(); ++i) {
2420 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2421 if (!tail.starts_with(param)) {
2422 return false;
2423 }
2424 tail.remove_prefix(param.length());
2425 }
2426 }
2427 if (!tail.starts_with(")")) {
2428 return false;
2429 }
2430 tail.remove_prefix(1); // ")";
2431 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2432}
2433
Ian Rogersd91d6d62013-09-25 20:26:14 -07002434std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2435 return os << sig.ToString();
2436}
2437
Ian Rogers0571d352011-11-03 19:51:38 -07002438// Decodes the header section from the class data bytes.
2439void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002440 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002441 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2442 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2443 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2444 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2445}
2446
2447void ClassDataItemIterator::ReadClassDataField() {
2448 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2449 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002450 // The user of the iterator is responsible for checking if there
2451 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002452}
2453
2454void ClassDataItemIterator::ReadClassDataMethod() {
2455 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2456 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2457 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002458 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002459 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002460 }
Ian Rogers0571d352011-11-03 19:51:38 -07002461}
2462
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002463EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002464 const DexFile& dex_file,
2465 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002466 : EncodedStaticFieldValueIterator(dex_file,
2467 nullptr,
2468 nullptr,
2469 nullptr,
2470 class_def,
2471 -1,
2472 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002473}
2474
2475EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002476 const DexFile& dex_file,
2477 Handle<mirror::DexCache>* dex_cache,
2478 Handle<mirror::ClassLoader>* class_loader,
2479 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002480 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002481 : EncodedStaticFieldValueIterator(dex_file,
2482 dex_cache, class_loader,
2483 linker,
2484 class_def,
2485 -1,
2486 kByte) {
2487 DCHECK(dex_cache_ != nullptr);
2488 DCHECK(class_loader_ != nullptr);
2489}
2490
2491EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2492 const DexFile& dex_file,
2493 Handle<mirror::DexCache>* dex_cache,
2494 Handle<mirror::ClassLoader>* class_loader,
2495 ClassLinker* linker,
2496 const DexFile::ClassDef& class_def,
2497 size_t pos,
2498 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002499 : dex_file_(dex_file),
2500 dex_cache_(dex_cache),
2501 class_loader_(class_loader),
2502 linker_(linker),
2503 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002504 pos_(pos),
2505 type_(type) {
2506 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002507 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002508 array_size_ = 0;
2509 } else {
2510 array_size_ = DecodeUnsignedLeb128(&ptr_);
2511 }
2512 if (array_size_ > 0) {
2513 Next();
2514 }
2515}
2516
2517void EncodedStaticFieldValueIterator::Next() {
2518 pos_++;
2519 if (pos_ >= array_size_) {
2520 return;
2521 }
Ian Rogers13735952014-10-08 12:43:28 -07002522 uint8_t value_type = *ptr_++;
2523 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002524 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002525 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002526 switch (type_) {
2527 case kBoolean:
2528 jval_.i = (value_arg != 0) ? 1 : 0;
2529 width = 0;
2530 break;
2531 case kByte:
2532 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002533 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002534 break;
2535 case kShort:
2536 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002537 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002538 break;
2539 case kChar:
2540 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002541 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002542 break;
2543 case kInt:
2544 jval_.i = ReadSignedInt(ptr_, value_arg);
2545 break;
2546 case kLong:
2547 jval_.j = ReadSignedLong(ptr_, value_arg);
2548 break;
2549 case kFloat:
2550 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2551 break;
2552 case kDouble:
2553 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2554 break;
2555 case kString:
2556 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002557 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2558 break;
2559 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002560 case kMethod:
2561 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002562 case kArray:
2563 case kAnnotation:
2564 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002565 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002566 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002567 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002568 width = 0;
2569 break;
2570 default:
2571 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002572 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002573 }
2574 ptr_ += width;
2575}
2576
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002577template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002578void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002579 DCHECK(dex_cache_ != nullptr);
2580 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002581 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002582 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2583 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002584 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2585 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2586 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2587 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2588 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2589 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2590 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002591 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002592 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002593 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002594 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002595 break;
2596 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002597 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002598 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2599 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002600 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002601 break;
2602 }
Ian Rogers0571d352011-11-03 19:51:38 -07002603 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2604 }
2605}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002606template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2607template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002608
2609CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2610 handler_.address_ = -1;
2611 int32_t offset = -1;
2612
2613 // Short-circuit the overwhelmingly common cases.
2614 switch (code_item.tries_size_) {
2615 case 0:
2616 break;
2617 case 1: {
2618 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2619 uint32_t start = tries->start_addr_;
2620 if (address >= start) {
2621 uint32_t end = start + tries->insn_count_;
2622 if (address < end) {
2623 offset = tries->handler_off_;
2624 }
2625 }
2626 break;
2627 }
2628 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002629 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002630 }
Logan Chien736df022012-04-27 16:25:57 +08002631 Init(code_item, offset);
2632}
2633
2634CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2635 const DexFile::TryItem& try_item) {
2636 handler_.address_ = -1;
2637 Init(code_item, try_item.handler_off_);
2638}
2639
2640void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2641 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002642 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002643 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002644 } else {
2645 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002646 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002647 remaining_count_ = -1;
2648 catch_all_ = false;
2649 DCHECK(!HasNext());
2650 }
2651}
2652
Ian Rogers13735952014-10-08 12:43:28 -07002653void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002654 current_data_ = handler_data;
2655 remaining_count_ = DecodeSignedLeb128(&current_data_);
2656
2657 // If remaining_count_ is non-positive, then it is the negative of
2658 // the number of catch types, and the catches are followed by a
2659 // catch-all handler.
2660 if (remaining_count_ <= 0) {
2661 catch_all_ = true;
2662 remaining_count_ = -remaining_count_;
2663 } else {
2664 catch_all_ = false;
2665 }
2666 Next();
2667}
2668
2669void CatchHandlerIterator::Next() {
2670 if (remaining_count_ > 0) {
2671 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2672 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2673 remaining_count_--;
2674 return;
2675 }
2676
2677 if (catch_all_) {
2678 handler_.type_idx_ = DexFile::kDexNoIndex16;
2679 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2680 catch_all_ = false;
2681 return;
2682 }
2683
2684 // no more handler
2685 remaining_count_ = -1;
2686}
2687
Carl Shapiro1fb86202011-06-27 17:43:13 -07002688} // namespace art