blob: 24d73eff27fae95ac325e29b09bb05ac1444d19a [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);
231 if (verify && !DexFileVerifier::Verify(dex_file.get(),
232 dex_file->Begin(),
233 dex_file->Size(),
234 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700235 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800236 error_msg)) {
237 return nullptr;
238 }
239
240 return dex_file;
241}
242
Aart Bik37d6a3b2016-06-21 18:30:10 -0700243std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
244 const char* location,
245 bool verify,
246 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800247 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800248 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700249 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700250 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000251 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700252 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000253 struct stat sbuf;
254 memset(&sbuf, 0, sizeof(sbuf));
255 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800256 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000257 return nullptr;
258 }
259 if (S_ISDIR(sbuf.st_mode)) {
260 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
261 return nullptr;
262 }
263 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800264 map.reset(MemMap::MapFile(length,
265 PROT_READ,
266 MAP_PRIVATE,
267 fd,
268 0,
269 /*low_4gb*/false,
270 location,
271 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000272 if (map.get() == nullptr) {
273 DCHECK(!error_msg->empty());
274 return nullptr;
275 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700276 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800277
278 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700279 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800280 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700281 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800282 }
283
284 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
285
Andreas Gampe928f72b2014-09-09 19:53:48 -0700286 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
287 error_msg));
288 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700289 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
290 error_msg->c_str());
291 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800292 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800293
Andreas Gampe928f72b2014-09-09 19:53:48 -0700294 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700295 location,
296 verify_checksum,
297 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700298 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800299 }
300
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800301 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700302}
303
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700304const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700305
Aart Bik37d6a3b2016-06-21 18:30:10 -0700306bool DexFile::OpenZip(int fd,
307 const std::string& location,
308 bool verify_checksum,
309 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800310 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800311 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700312 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700313 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700314 if (zip_archive.get() == nullptr) {
315 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700316 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700317 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700318 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800319}
320
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800321std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
322 uint32_t location_checksum,
323 MemMap* mem_map,
324 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800325 return OpenMemory(mem_map->Begin(),
326 mem_map->Size(),
327 location,
328 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700329 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800330 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700331 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800332}
333
Aart Bik37d6a3b2016-06-21 18:30:10 -0700334std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
335 const char* entry_name,
336 const std::string& location,
337 bool verify_checksum,
338 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800339 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800340 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800341 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700342 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700343 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700344 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700345 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700346 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800347 if (zip_entry->GetUncompressedLength() == 0) {
348 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
349 *error_code = ZipOpenErrorCode::kDexFileError;
350 return nullptr;
351 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700352 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700353 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700354 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700355 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700356 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700357 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700358 }
Ian Rogers700a4022014-05-19 16:49:03 -0700359 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 error_msg));
361 if (dex_file.get() == nullptr) {
362 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
363 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700365 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800366 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700367 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700370 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700371 }
372 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700373 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700374 location.c_str(),
375 verify_checksum,
376 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700377 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700378 return nullptr;
379 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700380 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800381 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700382}
383
Andreas Gampe90e34042015-04-27 20:01:52 -0700384// Technically we do not have a limitation with respect to the number of dex files that can be in a
385// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
386// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
387// seems an excessive number.
388static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
389
Aart Bik37d6a3b2016-06-21 18:30:10 -0700390bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
391 const std::string& location,
392 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800393 std::string* error_msg,
394 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800395 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700396 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700397 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700398 std::unique_ptr<const DexFile> dex_file(
399 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700400 if (dex_file.get() == nullptr) {
401 return false;
402 } else {
403 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800404 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700405
406 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700407
408 // We could try to avoid std::string allocations by working on a char array directly. As we
409 // do not expect a lot of iterations, this seems too involved and brittle.
410
Andreas Gampe90e34042015-04-27 20:01:52 -0700411 for (size_t i = 1; ; ++i) {
412 std::string name = GetMultiDexClassesDexName(i);
413 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700414 std::unique_ptr<const DexFile> next_dex_file(
415 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700416 if (next_dex_file.get() == nullptr) {
417 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
418 LOG(WARNING) << error_msg;
419 }
420 break;
421 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800422 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700423 }
424
Andreas Gampe90e34042015-04-27 20:01:52 -0700425 if (i == kWarnOnManyDexFilesThreshold) {
426 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
427 << " dex files. Please consider coalescing and shrinking the number to "
428 " avoid runtime overhead.";
429 }
430
431 if (i == std::numeric_limits<size_t>::max()) {
432 LOG(ERROR) << "Overflow in number of dex files!";
433 break;
434 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700435 }
436
437 return true;
438 }
439}
440
441
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800442std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
443 size_t size,
444 const std::string& location,
445 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800446 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700447 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800448 std::string* error_msg) {
ganxiaolincd16d0a2016-07-18 11:21:44 +0800449 DCHECK(base != nullptr);
David Sehrd81c0f82016-08-03 09:05:20 -0700450 DCHECK_NE(size, 0U);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700451 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800452 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700453 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700454 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800455 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700456 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800457 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700458}
459
Ian Rogers13735952014-10-08 12:43:28 -0700460DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800461 const std::string& location,
462 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800463 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700464 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800465 : begin_(base),
466 size_(size),
467 location_(location),
468 location_checksum_(location_checksum),
469 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800470 header_(reinterpret_cast<const Header*>(base)),
471 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
472 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
473 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
474 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
475 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700476 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700477 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700478 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800479 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300480 const uint8_t* lookup_data = (oat_dex_file != nullptr)
481 ? oat_dex_file->GetLookupTableData()
482 : nullptr;
483 if (lookup_data != nullptr) {
484 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
485 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
486 } else {
487 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
488 }
489 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800490}
491
Jesse Wilson6bf19152011-09-29 13:12:33 -0400492DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700493 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
494 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
495 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
496 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400497}
498
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700499bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700500 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700501 return false;
502 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700503 return true;
504}
505
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700506bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800507 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 std::ostringstream oss;
509 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800510 << " " << header_->magic_[0]
511 << " " << header_->magic_[1]
512 << " " << header_->magic_[2]
513 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700514 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700515 return false;
516 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800517 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700518 std::ostringstream oss;
519 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800520 << " " << header_->magic_[4]
521 << " " << header_->magic_[5]
522 << " " << header_->magic_[6]
523 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700524 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700525 return false;
526 }
527 return true;
528}
529
Ian Rogers13735952014-10-08 12:43:28 -0700530bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800531 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
532}
533
Ian Rogers13735952014-10-08 12:43:28 -0700534bool DexFile::IsVersionValid(const uint8_t* magic) {
535 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700536 for (uint32_t i = 0; i < kNumDexVersions; i++) {
537 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
538 return true;
539 }
540 }
541 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800542}
543
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700544uint32_t DexFile::Header::GetVersion() const {
545 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700546 return atoi(version);
547}
548
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800549const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
550 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300551 if (LIKELY(lookup_table_ != nullptr)) {
552 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
553 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700554 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300555
Roland Levillainab880f42016-05-12 16:24:36 +0100556 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300557 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700558 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700559 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700560 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300561 const TypeId* type_id = FindTypeId(descriptor);
562 if (type_id != nullptr) {
563 uint16_t type_idx = GetIndexForTypeId(*type_id);
564 for (size_t i = 0; i < num_class_defs; ++i) {
565 const ClassDef& class_def = GetClassDef(i);
566 if (class_def.class_idx_ == type_idx) {
567 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700568 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700569 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700570 }
Ian Rogers68b56852014-08-29 20:19:11 -0700571 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700572}
573
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700574const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
575 size_t num_class_defs = NumClassDefs();
576 for (size_t i = 0; i < num_class_defs; ++i) {
577 const ClassDef& class_def = GetClassDef(i);
578 if (class_def.class_idx_ == type_idx) {
579 return &class_def;
580 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700581 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700582 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700583}
584
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800585const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100586 const DexFile::StringId& name,
587 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800588 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
589 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
590 const uint32_t name_idx = GetIndexForStringId(name);
591 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t lo = 0;
593 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800594 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700595 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800596 const DexFile::FieldId& field = GetFieldId(mid);
597 if (class_idx > field.class_idx_) {
598 lo = mid + 1;
599 } else if (class_idx < field.class_idx_) {
600 hi = mid - 1;
601 } else {
602 if (name_idx > field.name_idx_) {
603 lo = mid + 1;
604 } else if (name_idx < field.name_idx_) {
605 hi = mid - 1;
606 } else {
607 if (type_idx > field.type_idx_) {
608 lo = mid + 1;
609 } else if (type_idx < field.type_idx_) {
610 hi = mid - 1;
611 } else {
612 return &field;
613 }
614 }
615 }
616 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700617 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800618}
619
620const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700621 const DexFile::StringId& name,
622 const DexFile::ProtoId& signature) const {
623 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800624 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700625 const uint32_t name_idx = GetIndexForStringId(name);
626 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700627 int32_t lo = 0;
628 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700629 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700630 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700631 const DexFile::MethodId& method = GetMethodId(mid);
632 if (class_idx > method.class_idx_) {
633 lo = mid + 1;
634 } else if (class_idx < method.class_idx_) {
635 hi = mid - 1;
636 } else {
637 if (name_idx > method.name_idx_) {
638 lo = mid + 1;
639 } else if (name_idx < method.name_idx_) {
640 hi = mid - 1;
641 } else {
642 if (proto_idx > method.proto_idx_) {
643 lo = mid + 1;
644 } else if (proto_idx < method.proto_idx_) {
645 hi = mid - 1;
646 } else {
647 return &method;
648 }
649 }
650 }
651 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700652 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700653}
654
Ian Rogers637c65b2013-05-31 11:46:00 -0700655const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700656 int32_t lo = 0;
657 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700658 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700659 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700660 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700661 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700662 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
663 if (compare > 0) {
664 lo = mid + 1;
665 } else if (compare < 0) {
666 hi = mid - 1;
667 } else {
668 return &str_id;
669 }
670 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700671 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700672}
673
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300674const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
675 int32_t lo = 0;
676 int32_t hi = NumTypeIds() - 1;
677 while (hi >= lo) {
678 int32_t mid = (hi + lo) / 2;
679 const TypeId& type_id = GetTypeId(mid);
680 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
681 const char* str = GetStringData(str_id);
682 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
683 if (compare > 0) {
684 lo = mid + 1;
685 } else if (compare < 0) {
686 hi = mid - 1;
687 } else {
688 return &type_id;
689 }
690 }
691 return nullptr;
692}
693
Vladimir Markoa48aef42014-12-03 17:53:53 +0000694const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700695 int32_t lo = 0;
696 int32_t hi = NumStringIds() - 1;
697 while (hi >= lo) {
698 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700699 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700700 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000701 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700702 if (compare > 0) {
703 lo = mid + 1;
704 } else if (compare < 0) {
705 hi = mid - 1;
706 } else {
707 return &str_id;
708 }
709 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700710 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700711}
712
713const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700714 int32_t lo = 0;
715 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700716 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700717 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700718 const TypeId& type_id = GetTypeId(mid);
719 if (string_idx > type_id.descriptor_idx_) {
720 lo = mid + 1;
721 } else if (string_idx < type_id.descriptor_idx_) {
722 hi = mid - 1;
723 } else {
724 return &type_id;
725 }
726 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700727 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700728}
729
730const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000731 const uint16_t* signature_type_idxs,
732 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700733 int32_t lo = 0;
734 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700735 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700736 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700737 const DexFile::ProtoId& proto = GetProtoId(mid);
738 int compare = return_type_idx - proto.return_type_idx_;
739 if (compare == 0) {
740 DexFileParameterIterator it(*this, proto);
741 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000742 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800743 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700744 it.Next();
745 i++;
746 }
747 if (compare == 0) {
748 if (it.HasNext()) {
749 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000750 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700751 compare = 1;
752 }
753 }
754 }
755 if (compare > 0) {
756 lo = mid + 1;
757 } else if (compare < 0) {
758 hi = mid - 1;
759 } else {
760 return &proto;
761 }
762 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700763 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700764}
765
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000766void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
767 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300768}
769
Ian Rogers0571d352011-11-03 19:51:38 -0700770// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700771bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
772 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700773 if (signature[0] != '(') {
774 return false;
775 }
776 size_t offset = 1;
777 size_t end = signature.size();
778 bool process_return = false;
779 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000780 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700781 char c = signature[offset];
782 offset++;
783 if (c == ')') {
784 process_return = true;
785 continue;
786 }
Ian Rogers0571d352011-11-03 19:51:38 -0700787 while (c == '[') { // process array prefix
788 if (offset >= end) { // expect some descriptor following [
789 return false;
790 }
791 c = signature[offset];
792 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700793 }
794 if (c == 'L') { // process type descriptors
795 do {
796 if (offset >= end) { // unexpected early termination of descriptor
797 return false;
798 }
799 c = signature[offset];
800 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700801 } while (c != ';');
802 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000803 // TODO: avoid creating a std::string just to get a 0-terminated char array
804 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700805 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700806 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700807 return false;
808 }
809 uint16_t type_idx = GetIndexForTypeId(*type_id);
810 if (!process_return) {
811 param_type_idxs->push_back(type_idx);
812 } else {
813 *return_type_idx = type_idx;
814 return offset == end; // return true if the signature had reached a sensible end
815 }
816 }
817 return false; // failed to correctly parse return type
818}
819
Ian Rogersd91d6d62013-09-25 20:26:14 -0700820const Signature DexFile::CreateSignature(const StringPiece& signature) const {
821 uint16_t return_type_idx;
822 std::vector<uint16_t> param_type_indices;
823 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
824 if (!success) {
825 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700826 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700827 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700828 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700829 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700830 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700831 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700832}
833
Mathieu Chartiere401d142015-04-22 13:56:20 -0700834int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700835 // For native method, lineno should be -2 to indicate it is native. Note that
836 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700837 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700838 return -2;
839 }
840
TDYa127c8dc1012012-04-19 07:03:33 -0700841 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700842 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700843
844 // A method with no line number info should return -1
845 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000846 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700847 return context.line_num_;
848}
849
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700850int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700851 // Note: Signed type is important for max and min.
852 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700853 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700854
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700855 while (min <= max) {
856 int32_t mid = min + ((max - min) / 2);
857
858 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
859 uint32_t start = ti->start_addr_;
860 uint32_t end = start + ti->insn_count_;
861
Ian Rogers0571d352011-11-03 19:51:38 -0700862 if (address < start) {
863 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700864 } else if (address >= end) {
865 min = mid + 1;
866 } else { // We have a winner!
867 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700868 }
869 }
870 // No match.
871 return -1;
872}
873
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700874int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
875 int32_t try_item = FindTryItem(code_item, address);
876 if (try_item == -1) {
877 return -1;
878 } else {
879 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
880 }
881}
882
David Srbeckyb06e28e2015-12-10 13:15:00 +0000883bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
884 DexDebugNewLocalCb local_cb, void* context) const {
885 DCHECK(local_cb != nullptr);
886 if (code_item == nullptr) {
887 return false;
888 }
889 const uint8_t* stream = GetDebugInfoStream(code_item);
890 if (stream == nullptr) {
891 return false;
892 }
893 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700894
David Srbeckyb06e28e2015-12-10 13:15:00 +0000895 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800896 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000897 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
898 local_in_reg[arg_reg].name_ = "this";
899 local_in_reg[arg_reg].descriptor_ = descriptor;
900 local_in_reg[arg_reg].signature_ = nullptr;
901 local_in_reg[arg_reg].start_address_ = 0;
902 local_in_reg[arg_reg].reg_ = arg_reg;
903 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 arg_reg++;
905 }
906
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800907 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000908 DecodeUnsignedLeb128(&stream); // Line.
909 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
910 uint32_t i;
911 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700912 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700913 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800914 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000915 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700916 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000917 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700918 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000919 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
920 local_in_reg[arg_reg].descriptor_ = descriptor;
921 local_in_reg[arg_reg].signature_ = nullptr;
922 local_in_reg[arg_reg].start_address_ = 0;
923 local_in_reg[arg_reg].reg_ = arg_reg;
924 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700925 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 case 'D':
927 case 'J':
928 arg_reg += 2;
929 break;
930 default:
931 arg_reg += 1;
932 break;
933 }
934 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000935 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800936 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
937 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000938 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700939 }
940
David Srbeckyb06e28e2015-12-10 13:15:00 +0000941 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 for (;;) {
943 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944 switch (opcode) {
945 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000946 // Emit all variables which are still alive at the end of the method.
947 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
948 if (local_in_reg[reg].is_live_) {
949 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
950 local_cb(context, local_in_reg[reg]);
951 }
952 }
953 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700954 case DBG_ADVANCE_PC:
955 address += DecodeUnsignedLeb128(&stream);
956 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700957 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000958 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700959 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700960 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000961 case DBG_START_LOCAL_EXTENDED: {
962 uint16_t reg = DecodeUnsignedLeb128(&stream);
963 if (reg >= code_item->registers_size_) {
964 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800965 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000966 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700967 }
968
David Srbeckyb06e28e2015-12-10 13:15:00 +0000969 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
970 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
971 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700972 if (opcode == DBG_START_LOCAL_EXTENDED) {
973 signature_idx = DecodeUnsignedLeb128P1(&stream);
974 }
975
Shih-wei Liao195487c2011-08-20 13:29:04 -0700976 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000977 if (local_in_reg[reg].is_live_) {
978 local_in_reg[reg].end_address_ = address;
979 local_cb(context, local_in_reg[reg]);
980 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981
David Srbeckyb06e28e2015-12-10 13:15:00 +0000982 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
983 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
984 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
985 local_in_reg[reg].start_address_ = address;
986 local_in_reg[reg].reg_ = reg;
987 local_in_reg[reg].is_live_ = true;
988 break;
989 }
990 case DBG_END_LOCAL: {
991 uint16_t reg = DecodeUnsignedLeb128(&stream);
992 if (reg >= code_item->registers_size_) {
993 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
994 << code_item->registers_size_ << ") in " << GetLocation();
995 return false;
996 }
997 if (!local_in_reg[reg].is_live_) {
998 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
999 return false;
1000 }
1001 local_in_reg[reg].end_address_ = address;
1002 local_cb(context, local_in_reg[reg]);
1003 local_in_reg[reg].is_live_ = false;
1004 break;
1005 }
1006 case DBG_RESTART_LOCAL: {
1007 uint16_t reg = DecodeUnsignedLeb128(&stream);
1008 if (reg >= code_item->registers_size_) {
1009 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1010 << code_item->registers_size_ << ") in " << GetLocation();
1011 return false;
1012 }
1013 // If the register is live, the "restart" is superfluous,
1014 // and we don't want to mess with the existing start address.
1015 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001016 local_in_reg[reg].start_address_ = address;
1017 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001019 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001020 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001021 case DBG_SET_PROLOGUE_END:
1022 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001023 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001024 case DBG_SET_FILE:
1025 DecodeUnsignedLeb128P1(&stream); // name.
1026 break;
1027 default:
1028 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1029 break;
1030 }
1031 }
1032}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001033
David Srbeckyb06e28e2015-12-10 13:15:00 +00001034bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1035 void* context) const {
1036 DCHECK(position_cb != nullptr);
1037 if (code_item == nullptr) {
1038 return false;
1039 }
1040 const uint8_t* stream = GetDebugInfoStream(code_item);
1041 if (stream == nullptr) {
1042 return false;
1043 }
1044
1045 PositionInfo entry = PositionInfo();
1046 entry.line_ = DecodeUnsignedLeb128(&stream);
1047 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1048 for (uint32_t i = 0; i < parameters_size; ++i) {
1049 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1050 }
1051
1052 for (;;) {
1053 uint8_t opcode = *stream++;
1054 switch (opcode) {
1055 case DBG_END_SEQUENCE:
1056 return true; // end of stream.
1057 case DBG_ADVANCE_PC:
1058 entry.address_ += DecodeUnsignedLeb128(&stream);
1059 break;
1060 case DBG_ADVANCE_LINE:
1061 entry.line_ += DecodeSignedLeb128(&stream);
1062 break;
1063 case DBG_START_LOCAL:
1064 DecodeUnsignedLeb128(&stream); // reg.
1065 DecodeUnsignedLeb128P1(&stream); // name.
1066 DecodeUnsignedLeb128P1(&stream); // descriptor.
1067 break;
1068 case DBG_START_LOCAL_EXTENDED:
1069 DecodeUnsignedLeb128(&stream); // reg.
1070 DecodeUnsignedLeb128P1(&stream); // name.
1071 DecodeUnsignedLeb128P1(&stream); // descriptor.
1072 DecodeUnsignedLeb128P1(&stream); // signature.
1073 break;
1074 case DBG_END_LOCAL:
1075 case DBG_RESTART_LOCAL:
1076 DecodeUnsignedLeb128(&stream); // reg.
1077 break;
1078 case DBG_SET_PROLOGUE_END:
1079 entry.prologue_end_ = true;
1080 break;
1081 case DBG_SET_EPILOGUE_BEGIN:
1082 entry.epilogue_begin_ = true;
1083 break;
1084 case DBG_SET_FILE: {
1085 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1086 entry.source_file_ = StringDataByIdx(name_idx);
1087 break;
1088 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001089 default: {
1090 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001091 entry.address_ += adjopcode / DBG_LINE_RANGE;
1092 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1093 if (position_cb(context, entry)) {
1094 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001095 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001096 entry.prologue_end_ = false;
1097 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001098 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001099 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001100 }
1101 }
1102}
1103
David Srbeckyb06e28e2015-12-10 13:15:00 +00001104bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001105 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001106
1107 // We know that this callback will be called in
1108 // ascending address order, so keep going until we find
1109 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001110 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001111 // The line number from the previous positions callback
1112 // wil be the final result.
1113 return true;
1114 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001115 context->line_num_ = entry.line_;
1116 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001117 }
1118}
1119
Andreas Gampe833a4852014-05-21 18:46:59 -07001120bool DexFile::IsMultiDexLocation(const char* location) {
1121 return strrchr(location, kMultiDexSeparator) != nullptr;
1122}
1123
Andreas Gampe90e34042015-04-27 20:01:52 -07001124std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1125 if (index == 0) {
1126 return "classes.dex";
1127 } else {
1128 return StringPrintf("classes%zu.dex", index + 1);
1129 }
1130}
1131
1132std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1133 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001134 return dex_location;
1135 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001136 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001137 }
1138}
1139
1140std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1141 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001142 std::string base_location = GetBaseLocation(dex_location);
1143 const char* suffix = dex_location + base_location.size();
1144 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1145 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1146 if (path != nullptr && path.get() != base_location) {
1147 return std::string(path.get()) + suffix;
1148 } else if (suffix[0] == 0) {
1149 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001150 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001151 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001152 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001153}
1154
Jeff Hao13e748b2015-08-25 20:44:19 +00001155// Read a signed integer. "zwidth" is the zero-based byte count.
1156static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1157 int32_t val = 0;
1158 for (int i = zwidth; i >= 0; --i) {
1159 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1160 }
1161 val >>= (3 - zwidth) * 8;
1162 return val;
1163}
1164
1165// Read an unsigned integer. "zwidth" is the zero-based byte count,
1166// "fill_on_right" indicates which side we want to zero-fill from.
1167static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1168 uint32_t val = 0;
1169 for (int i = zwidth; i >= 0; --i) {
1170 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1171 }
1172 if (!fill_on_right) {
1173 val >>= (3 - zwidth) * 8;
1174 }
1175 return val;
1176}
1177
1178// Read a signed long. "zwidth" is the zero-based byte count.
1179static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1180 int64_t val = 0;
1181 for (int i = zwidth; i >= 0; --i) {
1182 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1183 }
1184 val >>= (7 - zwidth) * 8;
1185 return val;
1186}
1187
1188// Read an unsigned long. "zwidth" is the zero-based byte count,
1189// "fill_on_right" indicates which side we want to zero-fill from.
1190static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1191 uint64_t val = 0;
1192 for (int i = zwidth; i >= 0; --i) {
1193 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1194 }
1195 if (!fill_on_right) {
1196 val >>= (7 - zwidth) * 8;
1197 }
1198 return val;
1199}
1200
Jeff Hao3d080862016-05-26 18:39:17 -07001201// Checks that visibility is as expected. Includes special behavior for M and
1202// before to allow runtime and build visibility when expecting runtime.
1203static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1204 if (expected == DexFile::kDexVisibilityRuntime) {
1205 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1206 if (sdk_version > 0 && sdk_version <= 23) {
1207 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1208 }
1209 }
1210 return actual == expected;
1211}
1212
Jeff Hao13e748b2015-08-25 20:44:19 +00001213const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1214 mirror::Class* klass = field->GetDeclaringClass();
1215 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1216 if (annotations_dir == nullptr) {
1217 return nullptr;
1218 }
1219 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1220 if (field_annotations == nullptr) {
1221 return nullptr;
1222 }
1223 uint32_t field_index = field->GetDexFieldIndex();
1224 uint32_t field_count = annotations_dir->fields_size_;
1225 for (uint32_t i = 0; i < field_count; ++i) {
1226 if (field_annotations[i].field_idx_ == field_index) {
1227 return GetFieldAnnotationSetItem(field_annotations[i]);
1228 }
1229 }
1230 return nullptr;
1231}
1232
1233mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1234 Handle<mirror::Class> annotation_class) const {
1235 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1236 if (annotation_set == nullptr) {
1237 return nullptr;
1238 }
1239 StackHandleScope<1> hs(Thread::Current());
1240 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1241 return GetAnnotationObjectFromAnnotationSet(
1242 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1243}
1244
1245mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1246 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1247 StackHandleScope<1> hs(Thread::Current());
1248 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1249 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1250}
1251
Jeff Hao2a5892f2015-08-31 15:00:40 -07001252mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001253 const {
1254 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1255 if (annotation_set == nullptr) {
1256 return nullptr;
1257 }
1258 StackHandleScope<1> hs(Thread::Current());
1259 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1260 return GetSignatureValue(field_class, annotation_set);
1261}
1262
1263bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1264 const {
1265 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1266 if (annotation_set == nullptr) {
1267 return false;
1268 }
1269 StackHandleScope<1> hs(Thread::Current());
1270 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1271 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1272 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1273 return annotation_item != nullptr;
1274}
1275
1276const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1277 mirror::Class* klass = method->GetDeclaringClass();
1278 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1279 if (annotations_dir == nullptr) {
1280 return nullptr;
1281 }
1282 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1283 if (method_annotations == nullptr) {
1284 return nullptr;
1285 }
1286 uint32_t method_index = method->GetDexMethodIndex();
1287 uint32_t method_count = annotations_dir->methods_size_;
1288 for (uint32_t i = 0; i < method_count; ++i) {
1289 if (method_annotations[i].method_idx_ == method_index) {
1290 return GetMethodAnnotationSetItem(method_annotations[i]);
1291 }
1292 }
1293 return nullptr;
1294}
1295
1296const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1297 const {
1298 mirror::Class* klass = method->GetDeclaringClass();
1299 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1300 if (annotations_dir == nullptr) {
1301 return nullptr;
1302 }
1303 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1304 if (parameter_annotations == nullptr) {
1305 return nullptr;
1306 }
1307 uint32_t method_index = method->GetDexMethodIndex();
1308 uint32_t parameter_count = annotations_dir->parameters_size_;
1309 for (uint32_t i = 0; i < parameter_count; ++i) {
1310 if (parameter_annotations[i].method_idx_ == method_index) {
1311 return &parameter_annotations[i];
1312 }
1313 }
1314 return nullptr;
1315}
1316
1317mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1318 mirror::Class* klass = method->GetDeclaringClass();
1319 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1320 if (annotations_dir == nullptr) {
1321 return nullptr;
1322 }
1323 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1324 if (annotation_set == nullptr) {
1325 return nullptr;
1326 }
1327 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1328 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1329 if (annotation_item == nullptr) {
1330 return nullptr;
1331 }
1332 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1333 if (annotation == nullptr) {
1334 return nullptr;
1335 }
1336 uint8_t header_byte = *(annotation++);
1337 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1338 return nullptr;
1339 }
1340 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1341 if (annotation == nullptr) {
1342 return nullptr;
1343 }
1344 AnnotationValue annotation_value;
1345 StackHandleScope<2> hs(Thread::Current());
1346 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe542451c2016-07-26 09:02:02 -07001347 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Vladimir Marko05792b92015-08-03 11:56:49 +01001348 Handle<mirror::Class> return_type(hs.NewHandle(
1349 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001350 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1351 return nullptr;
1352 }
1353 return annotation_value.value_.GetL();
1354}
1355
1356mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1357 Handle<mirror::Class> annotation_class) const {
1358 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1359 if (annotation_set == nullptr) {
1360 return nullptr;
1361 }
1362 StackHandleScope<1> hs(Thread::Current());
1363 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1364 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1365 kDexVisibilityRuntime, annotation_class);
1366}
1367
1368mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1369 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1370 StackHandleScope<1> hs(Thread::Current());
1371 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1372 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1373}
1374
Jeff Hao2a5892f2015-08-31 15:00:40 -07001375mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001376 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1377 if (annotation_set == nullptr) {
1378 return nullptr;
1379 }
1380 StackHandleScope<1> hs(Thread::Current());
1381 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1382 return GetThrowsValue(method_class, annotation_set);
1383}
1384
1385mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1386 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1387 if (parameter_annotations == nullptr) {
1388 return nullptr;
1389 }
1390 const AnnotationSetRefList* set_ref_list =
1391 GetParameterAnnotationSetRefList(parameter_annotations);
1392 if (set_ref_list == nullptr) {
1393 return nullptr;
1394 }
1395 uint32_t size = set_ref_list->size_;
1396 StackHandleScope<1> hs(Thread::Current());
1397 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1398 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1399}
1400
Jeff Hao1133db72016-04-04 19:50:14 -07001401mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1402 const {
1403 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1404 if (annotation_set == nullptr) {
1405 return nullptr;
1406 }
1407 StackHandleScope<1> hs(Thread::Current());
1408 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1409 return GetSignatureValue(method_class, annotation_set);
1410}
1411
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001412bool DexFile::IsMethodAnnotationPresent(ArtMethod* method,
1413 Handle<mirror::Class> annotation_class,
1414 uint32_t visibility /* = kDexVisibilityRuntime */)
Jeff Hao13e748b2015-08-25 20:44:19 +00001415 const {
1416 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1417 if (annotation_set == nullptr) {
1418 return false;
1419 }
1420 StackHandleScope<1> hs(Thread::Current());
1421 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07001422 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(method_class,
1423 annotation_set,
1424 visibility,
1425 annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001426 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001427}
1428
1429const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1430 const {
1431 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1432 if (annotations_dir == nullptr) {
1433 return nullptr;
1434 }
1435 return GetClassAnnotationSet(annotations_dir);
1436}
1437
1438mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1439 Handle<mirror::Class> annotation_class) const {
1440 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1441 if (annotation_set == nullptr) {
1442 return nullptr;
1443 }
1444 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1445 annotation_class);
1446}
1447
1448mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1449 const {
1450 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1451 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1452}
1453
Jeff Hao2a5892f2015-08-31 15:00:40 -07001454mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1455 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1456 if (annotation_set == nullptr) {
1457 return nullptr;
1458 }
1459 const AnnotationItem* annotation_item = SearchAnnotationSet(
1460 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1461 if (annotation_item == nullptr) {
1462 return nullptr;
1463 }
1464 StackHandleScope<1> hs(Thread::Current());
1465 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1466 Handle<mirror::Class> class_array_class(hs.NewHandle(
1467 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1468 if (class_array_class.Get() == nullptr) {
1469 return nullptr;
1470 }
1471 mirror::Object* obj = GetAnnotationValue(
1472 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1473 if (obj == nullptr) {
1474 return nullptr;
1475 }
1476 return obj->AsObjectArray<mirror::Class>();
1477}
1478
1479mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1480 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1481 if (annotation_set == nullptr) {
1482 return nullptr;
1483 }
1484 const AnnotationItem* annotation_item = SearchAnnotationSet(
1485 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1486 if (annotation_item == nullptr) {
1487 return nullptr;
1488 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001489 mirror::Object* obj = GetAnnotationValue(klass,
1490 annotation_item,
1491 "value",
1492 ScopedNullHandle<mirror::Class>(),
1493 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001494 if (obj == nullptr) {
1495 return nullptr;
1496 }
1497 return obj->AsClass();
1498}
1499
1500mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1501 mirror::Class* declaring_class = GetDeclaringClass(klass);
1502 if (declaring_class != nullptr) {
1503 return declaring_class;
1504 }
1505 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1506 if (annotation_set == nullptr) {
1507 return nullptr;
1508 }
1509 const AnnotationItem* annotation_item = SearchAnnotationSet(
1510 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1511 if (annotation_item == nullptr) {
1512 return nullptr;
1513 }
1514 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1515 if (annotation == nullptr) {
1516 return nullptr;
1517 }
1518 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001519 if (!ProcessAnnotationValue(klass,
1520 &annotation,
1521 &annotation_value,
1522 ScopedNullHandle<mirror::Class>(),
1523 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001524 return nullptr;
1525 }
1526 if (annotation_value.type_ != kDexAnnotationMethod) {
1527 return nullptr;
1528 }
1529 StackHandleScope<2> hs(Thread::Current());
1530 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1531 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1532 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1533 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1534 if (method == nullptr) {
1535 return nullptr;
1536 }
1537 return method->GetDeclaringClass();
1538}
1539
1540mirror::Object* DexFile::GetEnclosingMethod(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/EnclosingMethod;", kDexVisibilitySystem);
1547 if (annotation_item == nullptr) {
1548 return nullptr;
1549 }
1550 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001551 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001552}
1553
1554bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1555 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1556 if (annotation_set == nullptr) {
1557 return false;
1558 }
1559 const AnnotationItem* annotation_item = SearchAnnotationSet(
1560 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1561 if (annotation_item == nullptr) {
1562 return false;
1563 }
1564 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1565 if (annotation == nullptr) {
1566 return false;
1567 }
1568 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001569 if (!ProcessAnnotationValue(klass,
1570 &annotation,
1571 &annotation_value,
1572 ScopedNullHandle<mirror::Class>(),
1573 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001574 return false;
1575 }
1576 if (annotation_value.type_ != kDexAnnotationNull &&
1577 annotation_value.type_ != kDexAnnotationString) {
1578 return false;
1579 }
1580 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1581 return true;
1582}
1583
1584bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1585 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1586 if (annotation_set == nullptr) {
1587 return false;
1588 }
1589 const AnnotationItem* annotation_item = SearchAnnotationSet(
1590 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1591 if (annotation_item == nullptr) {
1592 return false;
1593 }
1594 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1595 if (annotation == nullptr) {
1596 return false;
1597 }
1598 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001599 if (!ProcessAnnotationValue(klass,
1600 &annotation,
1601 &annotation_value,
1602 ScopedNullHandle<mirror::Class>(),
1603 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001604 return false;
1605 }
1606 if (annotation_value.type_ != kDexAnnotationInt) {
1607 return false;
1608 }
1609 *flags = annotation_value.value_.GetI();
1610 return true;
1611}
1612
Jeff Hao1133db72016-04-04 19:50:14 -07001613mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1614 Handle<mirror::Class> klass) const {
1615 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1616 if (annotation_set == nullptr) {
1617 return nullptr;
1618 }
1619 return GetSignatureValue(klass, annotation_set);
1620}
1621
Jeff Hao13e748b2015-08-25 20:44:19 +00001622bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1623 Handle<mirror::Class> annotation_class) const {
1624 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1625 if (annotation_set == nullptr) {
1626 return false;
1627 }
1628 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1629 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001630 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001631}
1632
1633mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1634 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1635 Thread* self = Thread::Current();
1636 ScopedObjectAccessUnchecked soa(self);
1637 StackHandleScope<5> hs(self);
1638 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1639 const char* name = StringDataByIdx(element_name_index);
1640 Handle<mirror::String> string_name(
1641 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1642
Andreas Gampe542451c2016-07-26 09:02:02 -07001643 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001644 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001645 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001646 if (annotation_method == nullptr) {
1647 return nullptr;
1648 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001649 Handle<mirror::Class> method_return(hs.NewHandle(
1650 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001651
1652 AnnotationValue annotation_value;
1653 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1654 return nullptr;
1655 }
1656 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1657
1658 mirror::Class* annotation_member_class =
1659 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1660 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001661 mirror::Method* method_obj_ptr;
1662 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001663 if (pointer_size == PointerSize::k64) {
1664 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1665 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001666 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001667 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1668 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001669 }
1670 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001671
1672 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1673 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1674 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1675 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1676 return nullptr;
1677 }
1678
1679 JValue result;
1680 ArtMethod* annotation_member_init =
1681 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1682 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1683 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1684 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1685 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1686 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1687 };
1688 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1689 if (self->IsExceptionPending()) {
1690 LOG(INFO) << "Exception in AnnotationMember.<init>";
1691 return nullptr;
1692 }
1693
1694 return new_member.Get();
1695}
1696
1697const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1698 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1699 Handle<mirror::Class> annotation_class) const {
1700 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1701 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001702 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001703 continue;
1704 }
1705 const uint8_t* annotation = annotation_item->annotation_;
1706 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1707 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1708 klass->GetDexFile(), type_index, klass.Get());
1709 if (resolved_class == nullptr) {
1710 std::string temp;
1711 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1712 klass->GetDescriptor(&temp), type_index);
1713 CHECK(Thread::Current()->IsExceptionPending());
1714 Thread::Current()->ClearException();
1715 continue;
1716 }
1717 if (resolved_class == annotation_class.Get()) {
1718 return annotation_item;
1719 }
1720 }
1721
1722 return nullptr;
1723}
1724
1725mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1726 const AnnotationSetItem* annotation_set, uint32_t visibility,
1727 Handle<mirror::Class> annotation_class) const {
1728 const AnnotationItem* annotation_item =
1729 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1730 if (annotation_item == nullptr) {
1731 return nullptr;
1732 }
1733 const uint8_t* annotation = annotation_item->annotation_;
1734 return ProcessEncodedAnnotation(klass, &annotation);
1735}
1736
1737mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1738 const AnnotationItem* annotation_item, const char* annotation_name,
1739 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1740 const uint8_t* annotation =
1741 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1742 if (annotation == nullptr) {
1743 return nullptr;
1744 }
1745 AnnotationValue annotation_value;
1746 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1747 return nullptr;
1748 }
1749 if (annotation_value.type_ != expected_type) {
1750 return nullptr;
1751 }
1752 return annotation_value.value_.GetL();
1753}
1754
Jeff Hao2a5892f2015-08-31 15:00:40 -07001755mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001756 const AnnotationSetItem* annotation_set) const {
1757 StackHandleScope<1> hs(Thread::Current());
1758 const AnnotationItem* annotation_item =
1759 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1760 if (annotation_item == nullptr) {
1761 return nullptr;
1762 }
1763 mirror::Class* string_class = mirror::String::GetJavaLangString();
1764 Handle<mirror::Class> string_array_class(hs.NewHandle(
1765 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001766 if (string_array_class.Get() == nullptr) {
1767 return nullptr;
1768 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001769 mirror::Object* obj =
1770 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1771 if (obj == nullptr) {
1772 return nullptr;
1773 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001774 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001775}
1776
Jeff Hao2a5892f2015-08-31 15:00:40 -07001777mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001778 const AnnotationSetItem* annotation_set) const {
1779 StackHandleScope<1> hs(Thread::Current());
1780 const AnnotationItem* annotation_item =
1781 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1782 if (annotation_item == nullptr) {
1783 return nullptr;
1784 }
1785 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1786 Handle<mirror::Class> class_array_class(hs.NewHandle(
1787 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001788 if (class_array_class.Get() == nullptr) {
1789 return nullptr;
1790 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001791 mirror::Object* obj =
1792 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1793 if (obj == nullptr) {
1794 return nullptr;
1795 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001796 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001797}
1798
1799mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1800 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1801 Thread* self = Thread::Current();
1802 ScopedObjectAccessUnchecked soa(self);
1803 StackHandleScope<2> hs(self);
1804 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1805 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1806 if (annotation_set == nullptr) {
1807 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1808 }
1809
1810 uint32_t size = annotation_set->size_;
1811 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1812 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1813 if (result.Get() == nullptr) {
1814 return nullptr;
1815 }
1816
1817 uint32_t dest_index = 0;
1818 for (uint32_t i = 0; i < size; ++i) {
1819 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001820 // Note that we do not use IsVisibilityCompatible here because older code
1821 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001822 if (annotation_item->visibility_ != visibility) {
1823 continue;
1824 }
1825 const uint8_t* annotation = annotation_item->annotation_;
1826 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1827 if (annotation_obj != nullptr) {
1828 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1829 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001830 } else if (self->IsExceptionPending()) {
1831 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001832 }
1833 }
1834
1835 if (dest_index == size) {
1836 return result.Get();
1837 }
1838
1839 mirror::ObjectArray<mirror::Object>* trimmed_result =
1840 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001841 if (trimmed_result == nullptr) {
1842 return nullptr;
1843 }
1844
Jeff Hao13e748b2015-08-25 20:44:19 +00001845 for (uint32_t i = 0; i < dest_index; ++i) {
1846 mirror::Object* obj = result->GetWithoutChecks(i);
1847 trimmed_result->SetWithoutChecks<false>(i, obj);
1848 }
1849
1850 return trimmed_result;
1851}
1852
1853mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1854 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1855 Thread* self = Thread::Current();
1856 ScopedObjectAccessUnchecked soa(self);
1857 StackHandleScope<1> hs(self);
1858 mirror::Class* annotation_array_class =
1859 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1860 mirror::Class* annotation_array_array_class =
1861 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001862 if (annotation_array_array_class == nullptr) {
1863 return nullptr;
1864 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001865 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1866 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1867 if (annotation_array_array.Get() == nullptr) {
1868 LOG(ERROR) << "Annotation set ref array allocation failed";
1869 return nullptr;
1870 }
1871 for (uint32_t index = 0; index < size; ++index) {
1872 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1873 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1874 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1875 if (annotation_set == nullptr) {
1876 return nullptr;
1877 }
1878 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1879 }
1880 return annotation_array_array.Get();
1881}
1882
1883bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1884 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1885 DexFile::AnnotationResultStyle result_style) const {
1886 Thread* self = Thread::Current();
1887 mirror::Object* element_object = nullptr;
1888 bool set_object = false;
1889 Primitive::Type primitive_type = Primitive::kPrimVoid;
1890 const uint8_t* annotation = *annotation_ptr;
1891 uint8_t header_byte = *(annotation++);
1892 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1893 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1894 int32_t width = value_arg + 1;
1895 annotation_value->type_ = value_type;
1896
1897 switch (value_type) {
1898 case kDexAnnotationByte:
1899 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1900 primitive_type = Primitive::kPrimByte;
1901 break;
1902 case kDexAnnotationShort:
1903 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1904 primitive_type = Primitive::kPrimShort;
1905 break;
1906 case kDexAnnotationChar:
1907 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1908 false)));
1909 primitive_type = Primitive::kPrimChar;
1910 break;
1911 case kDexAnnotationInt:
1912 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1913 primitive_type = Primitive::kPrimInt;
1914 break;
1915 case kDexAnnotationLong:
1916 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1917 primitive_type = Primitive::kPrimLong;
1918 break;
1919 case kDexAnnotationFloat:
1920 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1921 primitive_type = Primitive::kPrimFloat;
1922 break;
1923 case kDexAnnotationDouble:
1924 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1925 primitive_type = Primitive::kPrimDouble;
1926 break;
1927 case kDexAnnotationBoolean:
1928 annotation_value->value_.SetZ(value_arg != 0);
1929 primitive_type = Primitive::kPrimBoolean;
1930 width = 0;
1931 break;
1932 case kDexAnnotationString: {
1933 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1934 if (result_style == kAllRaw) {
1935 annotation_value->value_.SetI(index);
1936 } else {
1937 StackHandleScope<1> hs(self);
1938 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1939 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1940 klass->GetDexFile(), index, dex_cache);
1941 set_object = true;
1942 if (element_object == nullptr) {
1943 return false;
1944 }
1945 }
1946 break;
1947 }
1948 case kDexAnnotationType: {
1949 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1950 if (result_style == kAllRaw) {
1951 annotation_value->value_.SetI(index);
1952 } else {
1953 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1954 klass->GetDexFile(), index, klass.Get());
1955 set_object = true;
1956 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001957 CHECK(self->IsExceptionPending());
1958 if (result_style == kAllObjects) {
1959 const char* msg = StringByTypeIdx(index);
1960 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1961 element_object = self->GetException();
1962 self->ClearException();
1963 } else {
1964 return false;
1965 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001966 }
1967 }
1968 break;
1969 }
1970 case kDexAnnotationMethod: {
1971 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1972 if (result_style == kAllRaw) {
1973 annotation_value->value_.SetI(index);
1974 } else {
1975 StackHandleScope<2> hs(self);
1976 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1977 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07001978 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1979 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00001980 klass->GetDexFile(), index, dex_cache, class_loader);
1981 if (method == nullptr) {
1982 return false;
1983 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001984 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001985 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07001986 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00001987 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001988 if (pointer_size == PointerSize::k64) {
1989 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
1990 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001991 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001992 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
1993 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001994 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001995 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001996 if (pointer_size == PointerSize::k64) {
1997 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
1998 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001999 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002000 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
2001 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07002002 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002003 }
2004 if (element_object == nullptr) {
2005 return false;
2006 }
2007 }
2008 break;
2009 }
2010 case kDexAnnotationField: {
2011 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2012 if (result_style == kAllRaw) {
2013 annotation_value->value_.SetI(index);
2014 } else {
2015 StackHandleScope<2> hs(self);
2016 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2017 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2018 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2019 klass->GetDexFile(), index, dex_cache, class_loader);
2020 if (field == nullptr) {
2021 return false;
2022 }
2023 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002024 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2025 if (pointer_size == PointerSize::k64) {
2026 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002027 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002028 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002029 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002030 if (element_object == nullptr) {
2031 return false;
2032 }
2033 }
2034 break;
2035 }
2036 case kDexAnnotationEnum: {
2037 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2038 if (result_style == kAllRaw) {
2039 annotation_value->value_.SetI(index);
2040 } else {
2041 StackHandleScope<3> hs(self);
2042 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2043 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2044 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2045 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002046 if (enum_field == nullptr) {
2047 return false;
2048 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002049 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002050 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2051 element_object = enum_field->GetObject(field_class.Get());
2052 set_object = true;
2053 }
2054 }
2055 break;
2056 }
2057 case kDexAnnotationArray:
2058 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2059 return false;
2060 } else {
2061 ScopedObjectAccessUnchecked soa(self);
2062 StackHandleScope<2> hs(self);
2063 uint32_t size = DecodeUnsignedLeb128(&annotation);
2064 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2065 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2066 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2067 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2068 if (new_array.Get() == nullptr) {
2069 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2070 return false;
2071 }
2072 AnnotationValue new_annotation_value;
2073 for (uint32_t i = 0; i < size; ++i) {
2074 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2075 kPrimitivesOrObjects)) {
2076 return false;
2077 }
2078 if (!component_type->IsPrimitive()) {
2079 mirror::Object* obj = new_annotation_value.value_.GetL();
2080 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2081 } else {
2082 switch (new_annotation_value.type_) {
2083 case kDexAnnotationByte:
2084 new_array->AsByteArray()->SetWithoutChecks<false>(
2085 i, new_annotation_value.value_.GetB());
2086 break;
2087 case kDexAnnotationShort:
2088 new_array->AsShortArray()->SetWithoutChecks<false>(
2089 i, new_annotation_value.value_.GetS());
2090 break;
2091 case kDexAnnotationChar:
2092 new_array->AsCharArray()->SetWithoutChecks<false>(
2093 i, new_annotation_value.value_.GetC());
2094 break;
2095 case kDexAnnotationInt:
2096 new_array->AsIntArray()->SetWithoutChecks<false>(
2097 i, new_annotation_value.value_.GetI());
2098 break;
2099 case kDexAnnotationLong:
2100 new_array->AsLongArray()->SetWithoutChecks<false>(
2101 i, new_annotation_value.value_.GetJ());
2102 break;
2103 case kDexAnnotationFloat:
2104 new_array->AsFloatArray()->SetWithoutChecks<false>(
2105 i, new_annotation_value.value_.GetF());
2106 break;
2107 case kDexAnnotationDouble:
2108 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2109 i, new_annotation_value.value_.GetD());
2110 break;
2111 case kDexAnnotationBoolean:
2112 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2113 i, new_annotation_value.value_.GetZ());
2114 break;
2115 default:
2116 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2117 return false;
2118 }
2119 }
2120 }
2121 element_object = new_array.Get();
2122 set_object = true;
2123 width = 0;
2124 }
2125 break;
2126 case kDexAnnotationAnnotation:
2127 if (result_style == kAllRaw) {
2128 return false;
2129 }
2130 element_object = ProcessEncodedAnnotation(klass, &annotation);
2131 if (element_object == nullptr) {
2132 return false;
2133 }
2134 set_object = true;
2135 width = 0;
2136 break;
2137 case kDexAnnotationNull:
2138 if (result_style == kAllRaw) {
2139 annotation_value->value_.SetI(0);
2140 } else {
2141 CHECK(element_object == nullptr);
2142 set_object = true;
2143 }
2144 width = 0;
2145 break;
2146 default:
2147 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2148 return false;
2149 }
2150
2151 annotation += width;
2152 *annotation_ptr = annotation;
2153
2154 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2155 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2156 set_object = true;
2157 }
2158
2159 if (set_object) {
2160 annotation_value->value_.SetL(element_object);
2161 }
2162
2163 return true;
2164}
2165
2166mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2167 const uint8_t** annotation) const {
2168 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2169 uint32_t size = DecodeUnsignedLeb128(annotation);
2170
2171 Thread* self = Thread::Current();
2172 ScopedObjectAccessUnchecked soa(self);
2173 StackHandleScope<2> hs(self);
2174 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2175 Handle<mirror::Class> annotation_class(hs.NewHandle(
2176 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2177 if (annotation_class.Get() == nullptr) {
2178 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2179 << type_index;
2180 DCHECK(Thread::Current()->IsExceptionPending());
2181 Thread::Current()->ClearException();
2182 return nullptr;
2183 }
2184
2185 mirror::Class* annotation_member_class =
2186 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2187 mirror::Class* annotation_member_array_class =
2188 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002189 if (annotation_member_array_class == nullptr) {
2190 return nullptr;
2191 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002192 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002193 if (size > 0) {
2194 element_array =
2195 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2196 if (element_array == nullptr) {
2197 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2198 return nullptr;
2199 }
2200 }
2201
2202 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2203 for (uint32_t i = 0; i < size; ++i) {
2204 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2205 if (new_member == nullptr) {
2206 return nullptr;
2207 }
2208 h_element_array->SetWithoutChecks<false>(i, new_member);
2209 }
2210
2211 JValue result;
2212 ArtMethod* create_annotation_method =
2213 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2214 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2215 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2216 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2217 if (self->IsExceptionPending()) {
2218 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2219 return nullptr;
2220 }
2221
2222 return result.GetL();
2223}
2224
2225const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2226 const char* descriptor, uint32_t visibility) const {
2227 const AnnotationItem* result = nullptr;
2228 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2229 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002230 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002231 continue;
2232 }
2233 const uint8_t* annotation = annotation_item->annotation_;
2234 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2235
2236 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2237 result = annotation_item;
2238 break;
2239 }
2240 }
2241 return result;
2242}
2243
2244const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2245 DecodeUnsignedLeb128(&annotation); // unused type_index
2246 uint32_t size = DecodeUnsignedLeb128(&annotation);
2247
2248 while (size != 0) {
2249 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2250 const char* element_name = GetStringData(GetStringId(element_name_index));
2251 if (strcmp(name, element_name) == 0) {
2252 return annotation;
2253 }
2254 SkipAnnotationValue(&annotation);
2255 size--;
2256 }
2257 return nullptr;
2258}
2259
2260bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2261 const uint8_t* annotation = *annotation_ptr;
2262 uint8_t header_byte = *(annotation++);
2263 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2264 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2265 int32_t width = value_arg + 1;
2266
2267 switch (value_type) {
2268 case kDexAnnotationByte:
2269 case kDexAnnotationShort:
2270 case kDexAnnotationChar:
2271 case kDexAnnotationInt:
2272 case kDexAnnotationLong:
2273 case kDexAnnotationFloat:
2274 case kDexAnnotationDouble:
2275 case kDexAnnotationString:
2276 case kDexAnnotationType:
2277 case kDexAnnotationMethod:
2278 case kDexAnnotationField:
2279 case kDexAnnotationEnum:
2280 break;
2281 case kDexAnnotationArray:
2282 {
2283 uint32_t size = DecodeUnsignedLeb128(&annotation);
2284 while (size--) {
2285 if (!SkipAnnotationValue(&annotation)) {
2286 return false;
2287 }
2288 }
2289 width = 0;
2290 break;
2291 }
2292 case kDexAnnotationAnnotation:
2293 {
2294 DecodeUnsignedLeb128(&annotation); // unused type_index
2295 uint32_t size = DecodeUnsignedLeb128(&annotation);
2296 while (size--) {
2297 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2298 if (!SkipAnnotationValue(&annotation)) {
2299 return false;
2300 }
2301 }
2302 width = 0;
2303 break;
2304 }
2305 case kDexAnnotationBoolean:
2306 case kDexAnnotationNull:
2307 width = 0;
2308 break;
2309 default:
2310 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2311 return false;
2312 }
2313
2314 annotation += width;
2315 *annotation_ptr = annotation;
2316 return true;
2317}
2318
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002319std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2320 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2321 dex_file.GetLocation().c_str(),
2322 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2323 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2324 return os;
2325}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002326
Ian Rogersd91d6d62013-09-25 20:26:14 -07002327std::string Signature::ToString() const {
2328 if (dex_file_ == nullptr) {
2329 CHECK(proto_id_ == nullptr);
2330 return "<no signature>";
2331 }
2332 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2333 std::string result;
2334 if (params == nullptr) {
2335 result += "()";
2336 } else {
2337 result += "(";
2338 for (uint32_t i = 0; i < params->Size(); ++i) {
2339 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2340 }
2341 result += ")";
2342 }
2343 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2344 return result;
2345}
2346
Vladimir Markod9cffea2013-11-25 15:08:02 +00002347bool Signature::operator==(const StringPiece& rhs) const {
2348 if (dex_file_ == nullptr) {
2349 return false;
2350 }
2351 StringPiece tail(rhs);
2352 if (!tail.starts_with("(")) {
2353 return false; // Invalid signature
2354 }
2355 tail.remove_prefix(1); // "(";
2356 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2357 if (params != nullptr) {
2358 for (uint32_t i = 0; i < params->Size(); ++i) {
2359 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2360 if (!tail.starts_with(param)) {
2361 return false;
2362 }
2363 tail.remove_prefix(param.length());
2364 }
2365 }
2366 if (!tail.starts_with(")")) {
2367 return false;
2368 }
2369 tail.remove_prefix(1); // ")";
2370 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2371}
2372
Ian Rogersd91d6d62013-09-25 20:26:14 -07002373std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2374 return os << sig.ToString();
2375}
2376
Ian Rogers0571d352011-11-03 19:51:38 -07002377// Decodes the header section from the class data bytes.
2378void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002379 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002380 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2381 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2382 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2383 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2384}
2385
2386void ClassDataItemIterator::ReadClassDataField() {
2387 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2388 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002389 // The user of the iterator is responsible for checking if there
2390 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002391}
2392
2393void ClassDataItemIterator::ReadClassDataMethod() {
2394 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2395 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2396 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002397 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002398 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002399 }
Ian Rogers0571d352011-11-03 19:51:38 -07002400}
2401
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002402EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002403 const DexFile& dex_file,
2404 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002405 : EncodedStaticFieldValueIterator(dex_file,
2406 nullptr,
2407 nullptr,
2408 nullptr,
2409 class_def,
2410 -1,
2411 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002412}
2413
2414EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002415 const DexFile& dex_file,
2416 Handle<mirror::DexCache>* dex_cache,
2417 Handle<mirror::ClassLoader>* class_loader,
2418 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002419 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002420 : EncodedStaticFieldValueIterator(dex_file,
2421 dex_cache, class_loader,
2422 linker,
2423 class_def,
2424 -1,
2425 kByte) {
2426 DCHECK(dex_cache_ != nullptr);
2427 DCHECK(class_loader_ != nullptr);
2428}
2429
2430EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2431 const DexFile& dex_file,
2432 Handle<mirror::DexCache>* dex_cache,
2433 Handle<mirror::ClassLoader>* class_loader,
2434 ClassLinker* linker,
2435 const DexFile::ClassDef& class_def,
2436 size_t pos,
2437 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002438 : dex_file_(dex_file),
2439 dex_cache_(dex_cache),
2440 class_loader_(class_loader),
2441 linker_(linker),
2442 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002443 pos_(pos),
2444 type_(type) {
2445 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002446 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002447 array_size_ = 0;
2448 } else {
2449 array_size_ = DecodeUnsignedLeb128(&ptr_);
2450 }
2451 if (array_size_ > 0) {
2452 Next();
2453 }
2454}
2455
2456void EncodedStaticFieldValueIterator::Next() {
2457 pos_++;
2458 if (pos_ >= array_size_) {
2459 return;
2460 }
Ian Rogers13735952014-10-08 12:43:28 -07002461 uint8_t value_type = *ptr_++;
2462 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002463 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002464 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002465 switch (type_) {
2466 case kBoolean:
2467 jval_.i = (value_arg != 0) ? 1 : 0;
2468 width = 0;
2469 break;
2470 case kByte:
2471 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002472 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002473 break;
2474 case kShort:
2475 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002476 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002477 break;
2478 case kChar:
2479 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002480 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002481 break;
2482 case kInt:
2483 jval_.i = ReadSignedInt(ptr_, value_arg);
2484 break;
2485 case kLong:
2486 jval_.j = ReadSignedLong(ptr_, value_arg);
2487 break;
2488 case kFloat:
2489 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2490 break;
2491 case kDouble:
2492 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2493 break;
2494 case kString:
2495 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002496 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2497 break;
2498 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002499 case kMethod:
2500 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002501 case kArray:
2502 case kAnnotation:
2503 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002504 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002505 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002506 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002507 width = 0;
2508 break;
2509 default:
2510 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002511 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002512 }
2513 ptr_ += width;
2514}
2515
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002516template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002517void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002518 DCHECK(dex_cache_ != nullptr);
2519 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002520 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002521 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2522 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002523 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2524 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2525 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2526 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2527 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2528 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2529 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002530 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002531 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002532 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002533 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002534 break;
2535 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002536 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002537 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2538 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002539 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002540 break;
2541 }
Ian Rogers0571d352011-11-03 19:51:38 -07002542 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2543 }
2544}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002545template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2546template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002547
2548CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2549 handler_.address_ = -1;
2550 int32_t offset = -1;
2551
2552 // Short-circuit the overwhelmingly common cases.
2553 switch (code_item.tries_size_) {
2554 case 0:
2555 break;
2556 case 1: {
2557 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2558 uint32_t start = tries->start_addr_;
2559 if (address >= start) {
2560 uint32_t end = start + tries->insn_count_;
2561 if (address < end) {
2562 offset = tries->handler_off_;
2563 }
2564 }
2565 break;
2566 }
2567 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002568 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002569 }
Logan Chien736df022012-04-27 16:25:57 +08002570 Init(code_item, offset);
2571}
2572
2573CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2574 const DexFile::TryItem& try_item) {
2575 handler_.address_ = -1;
2576 Init(code_item, try_item.handler_off_);
2577}
2578
2579void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2580 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002581 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002582 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002583 } else {
2584 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002585 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002586 remaining_count_ = -1;
2587 catch_all_ = false;
2588 DCHECK(!HasNext());
2589 }
2590}
2591
Ian Rogers13735952014-10-08 12:43:28 -07002592void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002593 current_data_ = handler_data;
2594 remaining_count_ = DecodeSignedLeb128(&current_data_);
2595
2596 // If remaining_count_ is non-positive, then it is the negative of
2597 // the number of catch types, and the catches are followed by a
2598 // catch-all handler.
2599 if (remaining_count_ <= 0) {
2600 catch_all_ = true;
2601 remaining_count_ = -remaining_count_;
2602 } else {
2603 catch_all_ = false;
2604 }
2605 Next();
2606}
2607
2608void CatchHandlerIterator::Next() {
2609 if (remaining_count_ > 0) {
2610 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2611 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2612 remaining_count_--;
2613 return;
2614 }
2615
2616 if (catch_all_) {
2617 handler_.type_idx_ = DexFile::kDexNoIndex16;
2618 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2619 catch_all_ = false;
2620 return;
2621 }
2622
2623 // no more handler
2624 remaining_count_ = -1;
2625}
2626
Carl Shapiro1fb86202011-06-27 17:43:13 -07002627} // namespace art