blob: 16087a572f1997f78081c35c252dcaa903889c7c [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"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000046#include "mirror/field.h"
47#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080048#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070049#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000050#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070051#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070052#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030053#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070054#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070055#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070057#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070058
59namespace art {
60
Ian Rogers13735952014-10-08 12:43:28 -070061const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070062const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
63 {'0', '3', '5', '\0'},
64 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
65 // files with that version number would erroneously be accepted and run.
66 {'0', '3', '7', '\0'}
67};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070068
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070070 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070071 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070072
73 // Strip ":...", which is the location
74 const char* zip_entry_name = kClassesDex;
75 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010076 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070077
Vladimir Markoaa4497d2014-09-05 14:01:17 +010078 if (DexFile::IsMultiDexLocation(filename)) {
79 file_part_storage = GetBaseLocation(filename);
80 file_part = file_part_storage.c_str();
81 zip_entry_name = filename + file_part_storage.size() + 1;
82 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070083 }
84
Andreas Gampe43e10b02016-07-15 17:17:34 -070085 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
86 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070087 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070088 return false;
89 }
90 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070091 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070092 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070093 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080094 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
95 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080096 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070097 }
Andreas Gampe833a4852014-05-21 18:46:59 -070098 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070099 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700100 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
101 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 return false;
103 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700106 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700108 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700109 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700110 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return false;
112 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700113 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return true;
115 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700116 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700118}
119
Aart Bik37d6a3b2016-06-21 18:30:10 -0700120bool DexFile::Open(const char* filename,
121 const char* location,
122 bool verify_checksum,
123 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800124 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800125 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700128 File fd = OpenAndReadMagic(filename, &magic, error_msg);
129 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700131 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700132 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700134 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700137 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700138 location,
139 /* verify */ true,
140 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 error_msg));
142 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800143 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 return true;
145 } else {
146 return false;
147 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700148 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700149 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400150 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151}
152
Andreas Gampe0cba0042015-04-29 20:47:16 -0700153static bool ContainsClassesDex(int fd, const char* filename) {
154 std::string error_msg;
155 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
156 if (zip_archive.get() == nullptr) {
157 return false;
158 }
159 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
160 return (zip_entry.get() != nullptr);
161}
162
163bool DexFile::MaybeDex(const char* filename) {
164 uint32_t magic;
165 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700166 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
167 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700168 return false;
169 }
170 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700171 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700172 } else if (IsDexMagic(magic)) {
173 return true;
174 }
175 return false;
176}
177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800178int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700179 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800180 return 0;
181 } else {
182 return mem_map_->GetProtect();
183 }
184}
185
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200186bool DexFile::IsReadOnly() const {
187 return GetPermissions() == PROT_READ;
188}
189
Brian Carlstrome0948e12013-08-29 09:36:15 -0700190bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200191 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700192 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193 return false;
194 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700195 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200196 }
197}
198
Brian Carlstrome0948e12013-08-29 09:36:15 -0700199bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 return false;
203 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700204 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 }
206}
207
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800208std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
209 const std::string& location,
210 uint32_t location_checksum,
211 const OatDexFile* oat_dex_file,
212 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700213 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800214 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800215 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800216 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
217 size,
218 location,
219 location_checksum,
220 nullptr,
221 oat_dex_file,
222 error_msg);
223 if (verify && !DexFileVerifier::Verify(dex_file.get(),
224 dex_file->Begin(),
225 dex_file->Size(),
226 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700227 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800228 error_msg)) {
229 return nullptr;
230 }
231
232 return dex_file;
233}
234
Aart Bik37d6a3b2016-06-21 18:30:10 -0700235std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
236 const char* location,
237 bool verify,
238 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800239 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800240 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700241 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700242 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000243 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700244 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000245 struct stat sbuf;
246 memset(&sbuf, 0, sizeof(sbuf));
247 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800248 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000249 return nullptr;
250 }
251 if (S_ISDIR(sbuf.st_mode)) {
252 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
253 return nullptr;
254 }
255 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800256 map.reset(MemMap::MapFile(length,
257 PROT_READ,
258 MAP_PRIVATE,
259 fd,
260 0,
261 /*low_4gb*/false,
262 location,
263 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000264 if (map.get() == nullptr) {
265 DCHECK(!error_msg->empty());
266 return nullptr;
267 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700268 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800269
270 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800272 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700273 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800274 }
275
276 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
277
Andreas Gampe928f72b2014-09-09 19:53:48 -0700278 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
279 error_msg));
280 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700281 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
282 error_msg->c_str());
283 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800284 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800285
Andreas Gampe928f72b2014-09-09 19:53:48 -0700286 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700287 location,
288 verify_checksum,
289 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700290 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800291 }
292
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800293 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700294}
295
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700296const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297
Aart Bik37d6a3b2016-06-21 18:30:10 -0700298bool DexFile::OpenZip(int fd,
299 const std::string& location,
300 bool verify_checksum,
301 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800302 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800303 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700304 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700305 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700306 if (zip_archive.get() == nullptr) {
307 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700308 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700309 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700310 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800311}
312
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800313std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
314 uint32_t location_checksum,
315 MemMap* mem_map,
316 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800317 return OpenMemory(mem_map->Begin(),
318 mem_map->Size(),
319 location,
320 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700321 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800322 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700323 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800324}
325
Aart Bik37d6a3b2016-06-21 18:30:10 -0700326std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
327 const char* entry_name,
328 const std::string& location,
329 bool verify_checksum,
330 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800331 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800332 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800333 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700334 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700335 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700336 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700337 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700338 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700339 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700340 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700341 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700342 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700343 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700344 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700345 }
Ian Rogers700a4022014-05-19 16:49:03 -0700346 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347 error_msg));
348 if (dex_file.get() == nullptr) {
349 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
350 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700351 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700352 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800353 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700354 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700355 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700356 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700357 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700358 }
359 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700360 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700361 location.c_str(),
362 verify_checksum,
363 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700365 return nullptr;
366 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700367 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800368 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700369}
370
Andreas Gampe90e34042015-04-27 20:01:52 -0700371// Technically we do not have a limitation with respect to the number of dex files that can be in a
372// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
373// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
374// seems an excessive number.
375static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
376
Aart Bik37d6a3b2016-06-21 18:30:10 -0700377bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
378 const std::string& location,
379 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800380 std::string* error_msg,
381 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800382 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700383 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700384 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700385 std::unique_ptr<const DexFile> dex_file(
386 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700387 if (dex_file.get() == nullptr) {
388 return false;
389 } else {
390 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800391 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700392
393 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700394
395 // We could try to avoid std::string allocations by working on a char array directly. As we
396 // do not expect a lot of iterations, this seems too involved and brittle.
397
Andreas Gampe90e34042015-04-27 20:01:52 -0700398 for (size_t i = 1; ; ++i) {
399 std::string name = GetMultiDexClassesDexName(i);
400 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700401 std::unique_ptr<const DexFile> next_dex_file(
402 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700403 if (next_dex_file.get() == nullptr) {
404 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
405 LOG(WARNING) << error_msg;
406 }
407 break;
408 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700410 }
411
Andreas Gampe90e34042015-04-27 20:01:52 -0700412 if (i == kWarnOnManyDexFilesThreshold) {
413 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
414 << " dex files. Please consider coalescing and shrinking the number to "
415 " avoid runtime overhead.";
416 }
417
418 if (i == std::numeric_limits<size_t>::max()) {
419 LOG(ERROR) << "Overflow in number of dex files!";
420 break;
421 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700422 }
423
424 return true;
425 }
426}
427
428
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800429std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
430 size_t size,
431 const std::string& location,
432 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800433 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700434 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800435 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700436 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800437 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700438 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800440 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700441 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800442 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700443}
444
Ian Rogers13735952014-10-08 12:43:28 -0700445DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800446 const std::string& location,
447 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800448 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700449 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800450 : begin_(base),
451 size_(size),
452 location_(location),
453 location_checksum_(location_checksum),
454 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800455 header_(reinterpret_cast<const Header*>(base)),
456 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
457 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
458 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
459 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
460 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700461 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700462 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700463 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800464 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300465 const uint8_t* lookup_data = (oat_dex_file != nullptr)
466 ? oat_dex_file->GetLookupTableData()
467 : nullptr;
468 if (lookup_data != nullptr) {
469 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
470 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
471 } else {
472 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
473 }
474 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800475}
476
Jesse Wilson6bf19152011-09-29 13:12:33 -0400477DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700478 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
479 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
480 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
481 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400482}
483
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700484bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700485 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700486 return false;
487 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700488 return true;
489}
490
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700491bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800492 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700493 std::ostringstream oss;
494 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800495 << " " << header_->magic_[0]
496 << " " << header_->magic_[1]
497 << " " << header_->magic_[2]
498 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700499 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700500 return false;
501 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800502 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700503 std::ostringstream oss;
504 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800505 << " " << header_->magic_[4]
506 << " " << header_->magic_[5]
507 << " " << header_->magic_[6]
508 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700510 return false;
511 }
512 return true;
513}
514
Ian Rogers13735952014-10-08 12:43:28 -0700515bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800516 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
517}
518
Ian Rogers13735952014-10-08 12:43:28 -0700519bool DexFile::IsVersionValid(const uint8_t* magic) {
520 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700521 for (uint32_t i = 0; i < kNumDexVersions; i++) {
522 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
523 return true;
524 }
525 }
526 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800527}
528
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700529uint32_t DexFile::Header::GetVersion() const {
530 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700531 return atoi(version);
532}
533
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800534const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
535 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300536 if (LIKELY(lookup_table_ != nullptr)) {
537 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
538 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700539 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300540
Roland Levillainab880f42016-05-12 16:24:36 +0100541 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300542 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700543 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700544 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700545 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300546 const TypeId* type_id = FindTypeId(descriptor);
547 if (type_id != nullptr) {
548 uint16_t type_idx = GetIndexForTypeId(*type_id);
549 for (size_t i = 0; i < num_class_defs; ++i) {
550 const ClassDef& class_def = GetClassDef(i);
551 if (class_def.class_idx_ == type_idx) {
552 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700553 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700554 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700555 }
Ian Rogers68b56852014-08-29 20:19:11 -0700556 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700557}
558
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700559const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
560 size_t num_class_defs = NumClassDefs();
561 for (size_t i = 0; i < num_class_defs; ++i) {
562 const ClassDef& class_def = GetClassDef(i);
563 if (class_def.class_idx_ == type_idx) {
564 return &class_def;
565 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700566 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700567 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700568}
569
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800570const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100571 const DexFile::StringId& name,
572 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800573 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
574 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
575 const uint32_t name_idx = GetIndexForStringId(name);
576 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700577 int32_t lo = 0;
578 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800579 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800581 const DexFile::FieldId& field = GetFieldId(mid);
582 if (class_idx > field.class_idx_) {
583 lo = mid + 1;
584 } else if (class_idx < field.class_idx_) {
585 hi = mid - 1;
586 } else {
587 if (name_idx > field.name_idx_) {
588 lo = mid + 1;
589 } else if (name_idx < field.name_idx_) {
590 hi = mid - 1;
591 } else {
592 if (type_idx > field.type_idx_) {
593 lo = mid + 1;
594 } else if (type_idx < field.type_idx_) {
595 hi = mid - 1;
596 } else {
597 return &field;
598 }
599 }
600 }
601 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700602 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800603}
604
605const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700606 const DexFile::StringId& name,
607 const DexFile::ProtoId& signature) const {
608 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800609 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700610 const uint32_t name_idx = GetIndexForStringId(name);
611 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700612 int32_t lo = 0;
613 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700614 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700615 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700616 const DexFile::MethodId& method = GetMethodId(mid);
617 if (class_idx > method.class_idx_) {
618 lo = mid + 1;
619 } else if (class_idx < method.class_idx_) {
620 hi = mid - 1;
621 } else {
622 if (name_idx > method.name_idx_) {
623 lo = mid + 1;
624 } else if (name_idx < method.name_idx_) {
625 hi = mid - 1;
626 } else {
627 if (proto_idx > method.proto_idx_) {
628 lo = mid + 1;
629 } else if (proto_idx < method.proto_idx_) {
630 hi = mid - 1;
631 } else {
632 return &method;
633 }
634 }
635 }
636 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700637 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700638}
639
Ian Rogers637c65b2013-05-31 11:46:00 -0700640const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700641 int32_t lo = 0;
642 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700643 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700644 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700645 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700646 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700647 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
648 if (compare > 0) {
649 lo = mid + 1;
650 } else if (compare < 0) {
651 hi = mid - 1;
652 } else {
653 return &str_id;
654 }
655 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700656 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700657}
658
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300659const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
660 int32_t lo = 0;
661 int32_t hi = NumTypeIds() - 1;
662 while (hi >= lo) {
663 int32_t mid = (hi + lo) / 2;
664 const TypeId& type_id = GetTypeId(mid);
665 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
666 const char* str = GetStringData(str_id);
667 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
668 if (compare > 0) {
669 lo = mid + 1;
670 } else if (compare < 0) {
671 hi = mid - 1;
672 } else {
673 return &type_id;
674 }
675 }
676 return nullptr;
677}
678
Vladimir Markoa48aef42014-12-03 17:53:53 +0000679const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700680 int32_t lo = 0;
681 int32_t hi = NumStringIds() - 1;
682 while (hi >= lo) {
683 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700684 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700685 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000686 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700687 if (compare > 0) {
688 lo = mid + 1;
689 } else if (compare < 0) {
690 hi = mid - 1;
691 } else {
692 return &str_id;
693 }
694 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700695 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700696}
697
698const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700699 int32_t lo = 0;
700 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700701 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700702 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700703 const TypeId& type_id = GetTypeId(mid);
704 if (string_idx > type_id.descriptor_idx_) {
705 lo = mid + 1;
706 } else if (string_idx < type_id.descriptor_idx_) {
707 hi = mid - 1;
708 } else {
709 return &type_id;
710 }
711 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700712 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700713}
714
715const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000716 const uint16_t* signature_type_idxs,
717 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700718 int32_t lo = 0;
719 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700720 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700721 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700722 const DexFile::ProtoId& proto = GetProtoId(mid);
723 int compare = return_type_idx - proto.return_type_idx_;
724 if (compare == 0) {
725 DexFileParameterIterator it(*this, proto);
726 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000727 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800728 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700729 it.Next();
730 i++;
731 }
732 if (compare == 0) {
733 if (it.HasNext()) {
734 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000735 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700736 compare = 1;
737 }
738 }
739 }
740 if (compare > 0) {
741 lo = mid + 1;
742 } else if (compare < 0) {
743 hi = mid - 1;
744 } else {
745 return &proto;
746 }
747 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700748 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700749}
750
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000751void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
752 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300753}
754
Ian Rogers0571d352011-11-03 19:51:38 -0700755// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700756bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
757 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700758 if (signature[0] != '(') {
759 return false;
760 }
761 size_t offset = 1;
762 size_t end = signature.size();
763 bool process_return = false;
764 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000765 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700766 char c = signature[offset];
767 offset++;
768 if (c == ')') {
769 process_return = true;
770 continue;
771 }
Ian Rogers0571d352011-11-03 19:51:38 -0700772 while (c == '[') { // process array prefix
773 if (offset >= end) { // expect some descriptor following [
774 return false;
775 }
776 c = signature[offset];
777 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700778 }
779 if (c == 'L') { // process type descriptors
780 do {
781 if (offset >= end) { // unexpected early termination of descriptor
782 return false;
783 }
784 c = signature[offset];
785 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700786 } while (c != ';');
787 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000788 // TODO: avoid creating a std::string just to get a 0-terminated char array
789 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700790 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700791 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700792 return false;
793 }
794 uint16_t type_idx = GetIndexForTypeId(*type_id);
795 if (!process_return) {
796 param_type_idxs->push_back(type_idx);
797 } else {
798 *return_type_idx = type_idx;
799 return offset == end; // return true if the signature had reached a sensible end
800 }
801 }
802 return false; // failed to correctly parse return type
803}
804
Ian Rogersd91d6d62013-09-25 20:26:14 -0700805const Signature DexFile::CreateSignature(const StringPiece& signature) const {
806 uint16_t return_type_idx;
807 std::vector<uint16_t> param_type_indices;
808 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
809 if (!success) {
810 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700811 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700812 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700813 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700814 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700815 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700816 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700817}
818
Mathieu Chartiere401d142015-04-22 13:56:20 -0700819int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700820 // For native method, lineno should be -2 to indicate it is native. Note that
821 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700822 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700823 return -2;
824 }
825
TDYa127c8dc1012012-04-19 07:03:33 -0700826 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700827 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700828
829 // A method with no line number info should return -1
830 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000831 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700832 return context.line_num_;
833}
834
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700835int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700836 // Note: Signed type is important for max and min.
837 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700838 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700839
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700840 while (min <= max) {
841 int32_t mid = min + ((max - min) / 2);
842
843 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
844 uint32_t start = ti->start_addr_;
845 uint32_t end = start + ti->insn_count_;
846
Ian Rogers0571d352011-11-03 19:51:38 -0700847 if (address < start) {
848 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700849 } else if (address >= end) {
850 min = mid + 1;
851 } else { // We have a winner!
852 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700853 }
854 }
855 // No match.
856 return -1;
857}
858
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700859int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
860 int32_t try_item = FindTryItem(code_item, address);
861 if (try_item == -1) {
862 return -1;
863 } else {
864 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
865 }
866}
867
David Srbeckyb06e28e2015-12-10 13:15:00 +0000868bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
869 DexDebugNewLocalCb local_cb, void* context) const {
870 DCHECK(local_cb != nullptr);
871 if (code_item == nullptr) {
872 return false;
873 }
874 const uint8_t* stream = GetDebugInfoStream(code_item);
875 if (stream == nullptr) {
876 return false;
877 }
878 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700879
David Srbeckyb06e28e2015-12-10 13:15:00 +0000880 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800881 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
883 local_in_reg[arg_reg].name_ = "this";
884 local_in_reg[arg_reg].descriptor_ = descriptor;
885 local_in_reg[arg_reg].signature_ = nullptr;
886 local_in_reg[arg_reg].start_address_ = 0;
887 local_in_reg[arg_reg].reg_ = arg_reg;
888 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700889 arg_reg++;
890 }
891
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800892 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000893 DecodeUnsignedLeb128(&stream); // Line.
894 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
895 uint32_t i;
896 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700897 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700898 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800899 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000900 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700901 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000902 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700903 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000904 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
905 local_in_reg[arg_reg].descriptor_ = descriptor;
906 local_in_reg[arg_reg].signature_ = nullptr;
907 local_in_reg[arg_reg].start_address_ = 0;
908 local_in_reg[arg_reg].reg_ = arg_reg;
909 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700910 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700911 case 'D':
912 case 'J':
913 arg_reg += 2;
914 break;
915 default:
916 arg_reg += 1;
917 break;
918 }
919 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000920 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800921 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
922 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000923 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 }
925
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700927 for (;;) {
928 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 switch (opcode) {
930 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000931 // Emit all variables which are still alive at the end of the method.
932 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
933 if (local_in_reg[reg].is_live_) {
934 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
935 local_cb(context, local_in_reg[reg]);
936 }
937 }
938 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700939 case DBG_ADVANCE_PC:
940 address += DecodeUnsignedLeb128(&stream);
941 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000943 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000946 case DBG_START_LOCAL_EXTENDED: {
947 uint16_t reg = DecodeUnsignedLeb128(&stream);
948 if (reg >= code_item->registers_size_) {
949 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800950 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000951 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700952 }
953
David Srbeckyb06e28e2015-12-10 13:15:00 +0000954 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
955 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
956 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700957 if (opcode == DBG_START_LOCAL_EXTENDED) {
958 signature_idx = DecodeUnsignedLeb128P1(&stream);
959 }
960
Shih-wei Liao195487c2011-08-20 13:29:04 -0700961 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000962 if (local_in_reg[reg].is_live_) {
963 local_in_reg[reg].end_address_ = address;
964 local_cb(context, local_in_reg[reg]);
965 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966
David Srbeckyb06e28e2015-12-10 13:15:00 +0000967 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
968 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
969 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
970 local_in_reg[reg].start_address_ = address;
971 local_in_reg[reg].reg_ = reg;
972 local_in_reg[reg].is_live_ = true;
973 break;
974 }
975 case DBG_END_LOCAL: {
976 uint16_t reg = DecodeUnsignedLeb128(&stream);
977 if (reg >= code_item->registers_size_) {
978 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
979 << code_item->registers_size_ << ") in " << GetLocation();
980 return false;
981 }
982 if (!local_in_reg[reg].is_live_) {
983 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
984 return false;
985 }
986 local_in_reg[reg].end_address_ = address;
987 local_cb(context, local_in_reg[reg]);
988 local_in_reg[reg].is_live_ = false;
989 break;
990 }
991 case DBG_RESTART_LOCAL: {
992 uint16_t reg = DecodeUnsignedLeb128(&stream);
993 if (reg >= code_item->registers_size_) {
994 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
995 << code_item->registers_size_ << ") in " << GetLocation();
996 return false;
997 }
998 // If the register is live, the "restart" is superfluous,
999 // and we don't want to mess with the existing start address.
1000 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001001 local_in_reg[reg].start_address_ = address;
1002 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001003 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001004 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001005 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001006 case DBG_SET_PROLOGUE_END:
1007 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001008 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001009 case DBG_SET_FILE:
1010 DecodeUnsignedLeb128P1(&stream); // name.
1011 break;
1012 default:
1013 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1014 break;
1015 }
1016 }
1017}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001018
David Srbeckyb06e28e2015-12-10 13:15:00 +00001019bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1020 void* context) const {
1021 DCHECK(position_cb != nullptr);
1022 if (code_item == nullptr) {
1023 return false;
1024 }
1025 const uint8_t* stream = GetDebugInfoStream(code_item);
1026 if (stream == nullptr) {
1027 return false;
1028 }
1029
1030 PositionInfo entry = PositionInfo();
1031 entry.line_ = DecodeUnsignedLeb128(&stream);
1032 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1033 for (uint32_t i = 0; i < parameters_size; ++i) {
1034 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1035 }
1036
1037 for (;;) {
1038 uint8_t opcode = *stream++;
1039 switch (opcode) {
1040 case DBG_END_SEQUENCE:
1041 return true; // end of stream.
1042 case DBG_ADVANCE_PC:
1043 entry.address_ += DecodeUnsignedLeb128(&stream);
1044 break;
1045 case DBG_ADVANCE_LINE:
1046 entry.line_ += DecodeSignedLeb128(&stream);
1047 break;
1048 case DBG_START_LOCAL:
1049 DecodeUnsignedLeb128(&stream); // reg.
1050 DecodeUnsignedLeb128P1(&stream); // name.
1051 DecodeUnsignedLeb128P1(&stream); // descriptor.
1052 break;
1053 case DBG_START_LOCAL_EXTENDED:
1054 DecodeUnsignedLeb128(&stream); // reg.
1055 DecodeUnsignedLeb128P1(&stream); // name.
1056 DecodeUnsignedLeb128P1(&stream); // descriptor.
1057 DecodeUnsignedLeb128P1(&stream); // signature.
1058 break;
1059 case DBG_END_LOCAL:
1060 case DBG_RESTART_LOCAL:
1061 DecodeUnsignedLeb128(&stream); // reg.
1062 break;
1063 case DBG_SET_PROLOGUE_END:
1064 entry.prologue_end_ = true;
1065 break;
1066 case DBG_SET_EPILOGUE_BEGIN:
1067 entry.epilogue_begin_ = true;
1068 break;
1069 case DBG_SET_FILE: {
1070 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1071 entry.source_file_ = StringDataByIdx(name_idx);
1072 break;
1073 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001074 default: {
1075 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001076 entry.address_ += adjopcode / DBG_LINE_RANGE;
1077 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1078 if (position_cb(context, entry)) {
1079 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001080 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001081 entry.prologue_end_ = false;
1082 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001083 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001084 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001085 }
1086 }
1087}
1088
David Srbeckyb06e28e2015-12-10 13:15:00 +00001089bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001090 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001091
1092 // We know that this callback will be called in
1093 // ascending address order, so keep going until we find
1094 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001095 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001096 // The line number from the previous positions callback
1097 // wil be the final result.
1098 return true;
1099 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001100 context->line_num_ = entry.line_;
1101 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001102 }
1103}
1104
Andreas Gampe833a4852014-05-21 18:46:59 -07001105bool DexFile::IsMultiDexLocation(const char* location) {
1106 return strrchr(location, kMultiDexSeparator) != nullptr;
1107}
1108
Andreas Gampe90e34042015-04-27 20:01:52 -07001109std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1110 if (index == 0) {
1111 return "classes.dex";
1112 } else {
1113 return StringPrintf("classes%zu.dex", index + 1);
1114 }
1115}
1116
1117std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1118 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001119 return dex_location;
1120 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001121 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001122 }
1123}
1124
1125std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1126 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001127 std::string base_location = GetBaseLocation(dex_location);
1128 const char* suffix = dex_location + base_location.size();
1129 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1130 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1131 if (path != nullptr && path.get() != base_location) {
1132 return std::string(path.get()) + suffix;
1133 } else if (suffix[0] == 0) {
1134 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001135 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001136 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001137 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001138}
1139
Jeff Hao13e748b2015-08-25 20:44:19 +00001140// Read a signed integer. "zwidth" is the zero-based byte count.
1141static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1142 int32_t val = 0;
1143 for (int i = zwidth; i >= 0; --i) {
1144 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1145 }
1146 val >>= (3 - zwidth) * 8;
1147 return val;
1148}
1149
1150// Read an unsigned integer. "zwidth" is the zero-based byte count,
1151// "fill_on_right" indicates which side we want to zero-fill from.
1152static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1153 uint32_t val = 0;
1154 for (int i = zwidth; i >= 0; --i) {
1155 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1156 }
1157 if (!fill_on_right) {
1158 val >>= (3 - zwidth) * 8;
1159 }
1160 return val;
1161}
1162
1163// Read a signed long. "zwidth" is the zero-based byte count.
1164static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1165 int64_t val = 0;
1166 for (int i = zwidth; i >= 0; --i) {
1167 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1168 }
1169 val >>= (7 - zwidth) * 8;
1170 return val;
1171}
1172
1173// Read an unsigned long. "zwidth" is the zero-based byte count,
1174// "fill_on_right" indicates which side we want to zero-fill from.
1175static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1176 uint64_t val = 0;
1177 for (int i = zwidth; i >= 0; --i) {
1178 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1179 }
1180 if (!fill_on_right) {
1181 val >>= (7 - zwidth) * 8;
1182 }
1183 return val;
1184}
1185
Jeff Hao3d080862016-05-26 18:39:17 -07001186// Checks that visibility is as expected. Includes special behavior for M and
1187// before to allow runtime and build visibility when expecting runtime.
1188static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1189 if (expected == DexFile::kDexVisibilityRuntime) {
1190 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1191 if (sdk_version > 0 && sdk_version <= 23) {
1192 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1193 }
1194 }
1195 return actual == expected;
1196}
1197
Jeff Hao13e748b2015-08-25 20:44:19 +00001198const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1199 mirror::Class* klass = field->GetDeclaringClass();
1200 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1201 if (annotations_dir == nullptr) {
1202 return nullptr;
1203 }
1204 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1205 if (field_annotations == nullptr) {
1206 return nullptr;
1207 }
1208 uint32_t field_index = field->GetDexFieldIndex();
1209 uint32_t field_count = annotations_dir->fields_size_;
1210 for (uint32_t i = 0; i < field_count; ++i) {
1211 if (field_annotations[i].field_idx_ == field_index) {
1212 return GetFieldAnnotationSetItem(field_annotations[i]);
1213 }
1214 }
1215 return nullptr;
1216}
1217
1218mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1219 Handle<mirror::Class> annotation_class) const {
1220 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1221 if (annotation_set == nullptr) {
1222 return nullptr;
1223 }
1224 StackHandleScope<1> hs(Thread::Current());
1225 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1226 return GetAnnotationObjectFromAnnotationSet(
1227 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1228}
1229
1230mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1231 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1232 StackHandleScope<1> hs(Thread::Current());
1233 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1234 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1235}
1236
Jeff Hao2a5892f2015-08-31 15:00:40 -07001237mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001238 const {
1239 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1240 if (annotation_set == nullptr) {
1241 return nullptr;
1242 }
1243 StackHandleScope<1> hs(Thread::Current());
1244 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1245 return GetSignatureValue(field_class, annotation_set);
1246}
1247
1248bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1249 const {
1250 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1251 if (annotation_set == nullptr) {
1252 return false;
1253 }
1254 StackHandleScope<1> hs(Thread::Current());
1255 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1256 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1257 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1258 return annotation_item != nullptr;
1259}
1260
1261const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1262 mirror::Class* klass = method->GetDeclaringClass();
1263 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1264 if (annotations_dir == nullptr) {
1265 return nullptr;
1266 }
1267 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1268 if (method_annotations == nullptr) {
1269 return nullptr;
1270 }
1271 uint32_t method_index = method->GetDexMethodIndex();
1272 uint32_t method_count = annotations_dir->methods_size_;
1273 for (uint32_t i = 0; i < method_count; ++i) {
1274 if (method_annotations[i].method_idx_ == method_index) {
1275 return GetMethodAnnotationSetItem(method_annotations[i]);
1276 }
1277 }
1278 return nullptr;
1279}
1280
1281const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1282 const {
1283 mirror::Class* klass = method->GetDeclaringClass();
1284 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1285 if (annotations_dir == nullptr) {
1286 return nullptr;
1287 }
1288 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1289 if (parameter_annotations == nullptr) {
1290 return nullptr;
1291 }
1292 uint32_t method_index = method->GetDexMethodIndex();
1293 uint32_t parameter_count = annotations_dir->parameters_size_;
1294 for (uint32_t i = 0; i < parameter_count; ++i) {
1295 if (parameter_annotations[i].method_idx_ == method_index) {
1296 return &parameter_annotations[i];
1297 }
1298 }
1299 return nullptr;
1300}
1301
1302mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1303 mirror::Class* klass = method->GetDeclaringClass();
1304 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1305 if (annotations_dir == nullptr) {
1306 return nullptr;
1307 }
1308 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1309 if (annotation_set == nullptr) {
1310 return nullptr;
1311 }
1312 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1313 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1314 if (annotation_item == nullptr) {
1315 return nullptr;
1316 }
1317 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1318 if (annotation == nullptr) {
1319 return nullptr;
1320 }
1321 uint8_t header_byte = *(annotation++);
1322 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1323 return nullptr;
1324 }
1325 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1326 if (annotation == nullptr) {
1327 return nullptr;
1328 }
1329 AnnotationValue annotation_value;
1330 StackHandleScope<2> hs(Thread::Current());
1331 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe542451c2016-07-26 09:02:02 -07001332 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Vladimir Marko05792b92015-08-03 11:56:49 +01001333 Handle<mirror::Class> return_type(hs.NewHandle(
1334 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001335 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1336 return nullptr;
1337 }
1338 return annotation_value.value_.GetL();
1339}
1340
1341mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1342 Handle<mirror::Class> annotation_class) const {
1343 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1344 if (annotation_set == nullptr) {
1345 return nullptr;
1346 }
1347 StackHandleScope<1> hs(Thread::Current());
1348 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1349 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1350 kDexVisibilityRuntime, annotation_class);
1351}
1352
1353mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1354 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1355 StackHandleScope<1> hs(Thread::Current());
1356 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1357 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1358}
1359
Jeff Hao2a5892f2015-08-31 15:00:40 -07001360mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001361 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1362 if (annotation_set == nullptr) {
1363 return nullptr;
1364 }
1365 StackHandleScope<1> hs(Thread::Current());
1366 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1367 return GetThrowsValue(method_class, annotation_set);
1368}
1369
1370mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1371 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1372 if (parameter_annotations == nullptr) {
1373 return nullptr;
1374 }
1375 const AnnotationSetRefList* set_ref_list =
1376 GetParameterAnnotationSetRefList(parameter_annotations);
1377 if (set_ref_list == nullptr) {
1378 return nullptr;
1379 }
1380 uint32_t size = set_ref_list->size_;
1381 StackHandleScope<1> hs(Thread::Current());
1382 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1383 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1384}
1385
Jeff Hao1133db72016-04-04 19:50:14 -07001386mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1387 const {
1388 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1389 if (annotation_set == nullptr) {
1390 return nullptr;
1391 }
1392 StackHandleScope<1> hs(Thread::Current());
1393 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1394 return GetSignatureValue(method_class, annotation_set);
1395}
1396
Jeff Hao13e748b2015-08-25 20:44:19 +00001397bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1398 const {
1399 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1400 if (annotation_set == nullptr) {
1401 return false;
1402 }
1403 StackHandleScope<1> hs(Thread::Current());
1404 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1405 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1406 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001407 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001408}
1409
1410const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1411 const {
1412 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1413 if (annotations_dir == nullptr) {
1414 return nullptr;
1415 }
1416 return GetClassAnnotationSet(annotations_dir);
1417}
1418
1419mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1420 Handle<mirror::Class> annotation_class) const {
1421 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1422 if (annotation_set == nullptr) {
1423 return nullptr;
1424 }
1425 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1426 annotation_class);
1427}
1428
1429mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1430 const {
1431 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1432 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1433}
1434
Jeff Hao2a5892f2015-08-31 15:00:40 -07001435mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1436 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1437 if (annotation_set == nullptr) {
1438 return nullptr;
1439 }
1440 const AnnotationItem* annotation_item = SearchAnnotationSet(
1441 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1442 if (annotation_item == nullptr) {
1443 return nullptr;
1444 }
1445 StackHandleScope<1> hs(Thread::Current());
1446 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1447 Handle<mirror::Class> class_array_class(hs.NewHandle(
1448 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1449 if (class_array_class.Get() == nullptr) {
1450 return nullptr;
1451 }
1452 mirror::Object* obj = GetAnnotationValue(
1453 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1454 if (obj == nullptr) {
1455 return nullptr;
1456 }
1457 return obj->AsObjectArray<mirror::Class>();
1458}
1459
1460mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1461 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1462 if (annotation_set == nullptr) {
1463 return nullptr;
1464 }
1465 const AnnotationItem* annotation_item = SearchAnnotationSet(
1466 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1467 if (annotation_item == nullptr) {
1468 return nullptr;
1469 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001470 mirror::Object* obj = GetAnnotationValue(klass,
1471 annotation_item,
1472 "value",
1473 ScopedNullHandle<mirror::Class>(),
1474 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001475 if (obj == nullptr) {
1476 return nullptr;
1477 }
1478 return obj->AsClass();
1479}
1480
1481mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1482 mirror::Class* declaring_class = GetDeclaringClass(klass);
1483 if (declaring_class != nullptr) {
1484 return declaring_class;
1485 }
1486 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1487 if (annotation_set == nullptr) {
1488 return nullptr;
1489 }
1490 const AnnotationItem* annotation_item = SearchAnnotationSet(
1491 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1492 if (annotation_item == nullptr) {
1493 return nullptr;
1494 }
1495 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1496 if (annotation == nullptr) {
1497 return nullptr;
1498 }
1499 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001500 if (!ProcessAnnotationValue(klass,
1501 &annotation,
1502 &annotation_value,
1503 ScopedNullHandle<mirror::Class>(),
1504 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001505 return nullptr;
1506 }
1507 if (annotation_value.type_ != kDexAnnotationMethod) {
1508 return nullptr;
1509 }
1510 StackHandleScope<2> hs(Thread::Current());
1511 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1512 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1513 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1514 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1515 if (method == nullptr) {
1516 return nullptr;
1517 }
1518 return method->GetDeclaringClass();
1519}
1520
1521mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1522 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1523 if (annotation_set == nullptr) {
1524 return nullptr;
1525 }
1526 const AnnotationItem* annotation_item = SearchAnnotationSet(
1527 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1528 if (annotation_item == nullptr) {
1529 return nullptr;
1530 }
1531 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001532 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001533}
1534
1535bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1536 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1537 if (annotation_set == nullptr) {
1538 return false;
1539 }
1540 const AnnotationItem* annotation_item = SearchAnnotationSet(
1541 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1542 if (annotation_item == nullptr) {
1543 return false;
1544 }
1545 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1546 if (annotation == nullptr) {
1547 return false;
1548 }
1549 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001550 if (!ProcessAnnotationValue(klass,
1551 &annotation,
1552 &annotation_value,
1553 ScopedNullHandle<mirror::Class>(),
1554 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001555 return false;
1556 }
1557 if (annotation_value.type_ != kDexAnnotationNull &&
1558 annotation_value.type_ != kDexAnnotationString) {
1559 return false;
1560 }
1561 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1562 return true;
1563}
1564
1565bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1566 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1567 if (annotation_set == nullptr) {
1568 return false;
1569 }
1570 const AnnotationItem* annotation_item = SearchAnnotationSet(
1571 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1572 if (annotation_item == nullptr) {
1573 return false;
1574 }
1575 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1576 if (annotation == nullptr) {
1577 return false;
1578 }
1579 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001580 if (!ProcessAnnotationValue(klass,
1581 &annotation,
1582 &annotation_value,
1583 ScopedNullHandle<mirror::Class>(),
1584 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001585 return false;
1586 }
1587 if (annotation_value.type_ != kDexAnnotationInt) {
1588 return false;
1589 }
1590 *flags = annotation_value.value_.GetI();
1591 return true;
1592}
1593
Jeff Hao1133db72016-04-04 19:50:14 -07001594mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1595 Handle<mirror::Class> klass) const {
1596 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1597 if (annotation_set == nullptr) {
1598 return nullptr;
1599 }
1600 return GetSignatureValue(klass, annotation_set);
1601}
1602
Jeff Hao13e748b2015-08-25 20:44:19 +00001603bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1604 Handle<mirror::Class> annotation_class) const {
1605 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1606 if (annotation_set == nullptr) {
1607 return false;
1608 }
1609 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1610 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001611 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001612}
1613
1614mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1615 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1616 Thread* self = Thread::Current();
1617 ScopedObjectAccessUnchecked soa(self);
1618 StackHandleScope<5> hs(self);
1619 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1620 const char* name = StringDataByIdx(element_name_index);
1621 Handle<mirror::String> string_name(
1622 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1623
Andreas Gampe542451c2016-07-26 09:02:02 -07001624 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001625 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001626 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001627 if (annotation_method == nullptr) {
1628 return nullptr;
1629 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001630 Handle<mirror::Class> method_return(hs.NewHandle(
1631 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001632
1633 AnnotationValue annotation_value;
1634 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1635 return nullptr;
1636 }
1637 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1638
1639 mirror::Class* annotation_member_class =
1640 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1641 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001642 mirror::Method* method_obj_ptr;
1643 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001644 if (pointer_size == PointerSize::k64) {
1645 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1646 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001647 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001648 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1649 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001650 }
1651 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001652
1653 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1654 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1655 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1656 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1657 return nullptr;
1658 }
1659
1660 JValue result;
1661 ArtMethod* annotation_member_init =
1662 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1663 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1664 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1665 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1666 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1667 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1668 };
1669 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1670 if (self->IsExceptionPending()) {
1671 LOG(INFO) << "Exception in AnnotationMember.<init>";
1672 return nullptr;
1673 }
1674
1675 return new_member.Get();
1676}
1677
1678const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1679 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1680 Handle<mirror::Class> annotation_class) const {
1681 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1682 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001683 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001684 continue;
1685 }
1686 const uint8_t* annotation = annotation_item->annotation_;
1687 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1688 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1689 klass->GetDexFile(), type_index, klass.Get());
1690 if (resolved_class == nullptr) {
1691 std::string temp;
1692 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1693 klass->GetDescriptor(&temp), type_index);
1694 CHECK(Thread::Current()->IsExceptionPending());
1695 Thread::Current()->ClearException();
1696 continue;
1697 }
1698 if (resolved_class == annotation_class.Get()) {
1699 return annotation_item;
1700 }
1701 }
1702
1703 return nullptr;
1704}
1705
1706mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1707 const AnnotationSetItem* annotation_set, uint32_t visibility,
1708 Handle<mirror::Class> annotation_class) const {
1709 const AnnotationItem* annotation_item =
1710 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1711 if (annotation_item == nullptr) {
1712 return nullptr;
1713 }
1714 const uint8_t* annotation = annotation_item->annotation_;
1715 return ProcessEncodedAnnotation(klass, &annotation);
1716}
1717
1718mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1719 const AnnotationItem* annotation_item, const char* annotation_name,
1720 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1721 const uint8_t* annotation =
1722 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1723 if (annotation == nullptr) {
1724 return nullptr;
1725 }
1726 AnnotationValue annotation_value;
1727 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1728 return nullptr;
1729 }
1730 if (annotation_value.type_ != expected_type) {
1731 return nullptr;
1732 }
1733 return annotation_value.value_.GetL();
1734}
1735
Jeff Hao2a5892f2015-08-31 15:00:40 -07001736mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001737 const AnnotationSetItem* annotation_set) const {
1738 StackHandleScope<1> hs(Thread::Current());
1739 const AnnotationItem* annotation_item =
1740 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1741 if (annotation_item == nullptr) {
1742 return nullptr;
1743 }
1744 mirror::Class* string_class = mirror::String::GetJavaLangString();
1745 Handle<mirror::Class> string_array_class(hs.NewHandle(
1746 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001747 if (string_array_class.Get() == nullptr) {
1748 return nullptr;
1749 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001750 mirror::Object* obj =
1751 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1752 if (obj == nullptr) {
1753 return nullptr;
1754 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001755 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001756}
1757
Jeff Hao2a5892f2015-08-31 15:00:40 -07001758mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001759 const AnnotationSetItem* annotation_set) const {
1760 StackHandleScope<1> hs(Thread::Current());
1761 const AnnotationItem* annotation_item =
1762 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1763 if (annotation_item == nullptr) {
1764 return nullptr;
1765 }
1766 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1767 Handle<mirror::Class> class_array_class(hs.NewHandle(
1768 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001769 if (class_array_class.Get() == nullptr) {
1770 return nullptr;
1771 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001772 mirror::Object* obj =
1773 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1774 if (obj == nullptr) {
1775 return nullptr;
1776 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001777 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001778}
1779
1780mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1781 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1782 Thread* self = Thread::Current();
1783 ScopedObjectAccessUnchecked soa(self);
1784 StackHandleScope<2> hs(self);
1785 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1786 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1787 if (annotation_set == nullptr) {
1788 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1789 }
1790
1791 uint32_t size = annotation_set->size_;
1792 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1793 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1794 if (result.Get() == nullptr) {
1795 return nullptr;
1796 }
1797
1798 uint32_t dest_index = 0;
1799 for (uint32_t i = 0; i < size; ++i) {
1800 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001801 // Note that we do not use IsVisibilityCompatible here because older code
1802 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001803 if (annotation_item->visibility_ != visibility) {
1804 continue;
1805 }
1806 const uint8_t* annotation = annotation_item->annotation_;
1807 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1808 if (annotation_obj != nullptr) {
1809 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1810 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001811 } else if (self->IsExceptionPending()) {
1812 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001813 }
1814 }
1815
1816 if (dest_index == size) {
1817 return result.Get();
1818 }
1819
1820 mirror::ObjectArray<mirror::Object>* trimmed_result =
1821 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001822 if (trimmed_result == nullptr) {
1823 return nullptr;
1824 }
1825
Jeff Hao13e748b2015-08-25 20:44:19 +00001826 for (uint32_t i = 0; i < dest_index; ++i) {
1827 mirror::Object* obj = result->GetWithoutChecks(i);
1828 trimmed_result->SetWithoutChecks<false>(i, obj);
1829 }
1830
1831 return trimmed_result;
1832}
1833
1834mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1835 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1836 Thread* self = Thread::Current();
1837 ScopedObjectAccessUnchecked soa(self);
1838 StackHandleScope<1> hs(self);
1839 mirror::Class* annotation_array_class =
1840 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1841 mirror::Class* annotation_array_array_class =
1842 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001843 if (annotation_array_array_class == nullptr) {
1844 return nullptr;
1845 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001846 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1847 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1848 if (annotation_array_array.Get() == nullptr) {
1849 LOG(ERROR) << "Annotation set ref array allocation failed";
1850 return nullptr;
1851 }
1852 for (uint32_t index = 0; index < size; ++index) {
1853 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1854 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1855 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1856 if (annotation_set == nullptr) {
1857 return nullptr;
1858 }
1859 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1860 }
1861 return annotation_array_array.Get();
1862}
1863
1864bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1865 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1866 DexFile::AnnotationResultStyle result_style) const {
1867 Thread* self = Thread::Current();
1868 mirror::Object* element_object = nullptr;
1869 bool set_object = false;
1870 Primitive::Type primitive_type = Primitive::kPrimVoid;
1871 const uint8_t* annotation = *annotation_ptr;
1872 uint8_t header_byte = *(annotation++);
1873 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1874 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1875 int32_t width = value_arg + 1;
1876 annotation_value->type_ = value_type;
1877
1878 switch (value_type) {
1879 case kDexAnnotationByte:
1880 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1881 primitive_type = Primitive::kPrimByte;
1882 break;
1883 case kDexAnnotationShort:
1884 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1885 primitive_type = Primitive::kPrimShort;
1886 break;
1887 case kDexAnnotationChar:
1888 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1889 false)));
1890 primitive_type = Primitive::kPrimChar;
1891 break;
1892 case kDexAnnotationInt:
1893 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1894 primitive_type = Primitive::kPrimInt;
1895 break;
1896 case kDexAnnotationLong:
1897 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1898 primitive_type = Primitive::kPrimLong;
1899 break;
1900 case kDexAnnotationFloat:
1901 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1902 primitive_type = Primitive::kPrimFloat;
1903 break;
1904 case kDexAnnotationDouble:
1905 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1906 primitive_type = Primitive::kPrimDouble;
1907 break;
1908 case kDexAnnotationBoolean:
1909 annotation_value->value_.SetZ(value_arg != 0);
1910 primitive_type = Primitive::kPrimBoolean;
1911 width = 0;
1912 break;
1913 case kDexAnnotationString: {
1914 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1915 if (result_style == kAllRaw) {
1916 annotation_value->value_.SetI(index);
1917 } else {
1918 StackHandleScope<1> hs(self);
1919 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1920 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1921 klass->GetDexFile(), index, dex_cache);
1922 set_object = true;
1923 if (element_object == nullptr) {
1924 return false;
1925 }
1926 }
1927 break;
1928 }
1929 case kDexAnnotationType: {
1930 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1931 if (result_style == kAllRaw) {
1932 annotation_value->value_.SetI(index);
1933 } else {
1934 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1935 klass->GetDexFile(), index, klass.Get());
1936 set_object = true;
1937 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001938 CHECK(self->IsExceptionPending());
1939 if (result_style == kAllObjects) {
1940 const char* msg = StringByTypeIdx(index);
1941 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1942 element_object = self->GetException();
1943 self->ClearException();
1944 } else {
1945 return false;
1946 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001947 }
1948 }
1949 break;
1950 }
1951 case kDexAnnotationMethod: {
1952 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1953 if (result_style == kAllRaw) {
1954 annotation_value->value_.SetI(index);
1955 } else {
1956 StackHandleScope<2> hs(self);
1957 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1958 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07001959 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1960 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00001961 klass->GetDexFile(), index, dex_cache, class_loader);
1962 if (method == nullptr) {
1963 return false;
1964 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001965 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001966 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07001967 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00001968 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001969 if (pointer_size == PointerSize::k64) {
1970 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
1971 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001972 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001973 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
1974 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001975 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001976 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001977 if (pointer_size == PointerSize::k64) {
1978 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
1979 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001980 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001981 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
1982 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001983 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001984 }
1985 if (element_object == nullptr) {
1986 return false;
1987 }
1988 }
1989 break;
1990 }
1991 case kDexAnnotationField: {
1992 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1993 if (result_style == kAllRaw) {
1994 annotation_value->value_.SetI(index);
1995 } else {
1996 StackHandleScope<2> hs(self);
1997 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1998 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1999 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2000 klass->GetDexFile(), index, dex_cache, class_loader);
2001 if (field == nullptr) {
2002 return false;
2003 }
2004 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002005 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2006 if (pointer_size == PointerSize::k64) {
2007 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002008 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002009 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002010 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002011 if (element_object == nullptr) {
2012 return false;
2013 }
2014 }
2015 break;
2016 }
2017 case kDexAnnotationEnum: {
2018 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2019 if (result_style == kAllRaw) {
2020 annotation_value->value_.SetI(index);
2021 } else {
2022 StackHandleScope<3> hs(self);
2023 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2024 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2025 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2026 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002027 if (enum_field == nullptr) {
2028 return false;
2029 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002030 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002031 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2032 element_object = enum_field->GetObject(field_class.Get());
2033 set_object = true;
2034 }
2035 }
2036 break;
2037 }
2038 case kDexAnnotationArray:
2039 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2040 return false;
2041 } else {
2042 ScopedObjectAccessUnchecked soa(self);
2043 StackHandleScope<2> hs(self);
2044 uint32_t size = DecodeUnsignedLeb128(&annotation);
2045 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2046 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2047 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2048 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2049 if (new_array.Get() == nullptr) {
2050 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2051 return false;
2052 }
2053 AnnotationValue new_annotation_value;
2054 for (uint32_t i = 0; i < size; ++i) {
2055 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2056 kPrimitivesOrObjects)) {
2057 return false;
2058 }
2059 if (!component_type->IsPrimitive()) {
2060 mirror::Object* obj = new_annotation_value.value_.GetL();
2061 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2062 } else {
2063 switch (new_annotation_value.type_) {
2064 case kDexAnnotationByte:
2065 new_array->AsByteArray()->SetWithoutChecks<false>(
2066 i, new_annotation_value.value_.GetB());
2067 break;
2068 case kDexAnnotationShort:
2069 new_array->AsShortArray()->SetWithoutChecks<false>(
2070 i, new_annotation_value.value_.GetS());
2071 break;
2072 case kDexAnnotationChar:
2073 new_array->AsCharArray()->SetWithoutChecks<false>(
2074 i, new_annotation_value.value_.GetC());
2075 break;
2076 case kDexAnnotationInt:
2077 new_array->AsIntArray()->SetWithoutChecks<false>(
2078 i, new_annotation_value.value_.GetI());
2079 break;
2080 case kDexAnnotationLong:
2081 new_array->AsLongArray()->SetWithoutChecks<false>(
2082 i, new_annotation_value.value_.GetJ());
2083 break;
2084 case kDexAnnotationFloat:
2085 new_array->AsFloatArray()->SetWithoutChecks<false>(
2086 i, new_annotation_value.value_.GetF());
2087 break;
2088 case kDexAnnotationDouble:
2089 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2090 i, new_annotation_value.value_.GetD());
2091 break;
2092 case kDexAnnotationBoolean:
2093 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2094 i, new_annotation_value.value_.GetZ());
2095 break;
2096 default:
2097 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2098 return false;
2099 }
2100 }
2101 }
2102 element_object = new_array.Get();
2103 set_object = true;
2104 width = 0;
2105 }
2106 break;
2107 case kDexAnnotationAnnotation:
2108 if (result_style == kAllRaw) {
2109 return false;
2110 }
2111 element_object = ProcessEncodedAnnotation(klass, &annotation);
2112 if (element_object == nullptr) {
2113 return false;
2114 }
2115 set_object = true;
2116 width = 0;
2117 break;
2118 case kDexAnnotationNull:
2119 if (result_style == kAllRaw) {
2120 annotation_value->value_.SetI(0);
2121 } else {
2122 CHECK(element_object == nullptr);
2123 set_object = true;
2124 }
2125 width = 0;
2126 break;
2127 default:
2128 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2129 return false;
2130 }
2131
2132 annotation += width;
2133 *annotation_ptr = annotation;
2134
2135 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2136 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2137 set_object = true;
2138 }
2139
2140 if (set_object) {
2141 annotation_value->value_.SetL(element_object);
2142 }
2143
2144 return true;
2145}
2146
2147mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2148 const uint8_t** annotation) const {
2149 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2150 uint32_t size = DecodeUnsignedLeb128(annotation);
2151
2152 Thread* self = Thread::Current();
2153 ScopedObjectAccessUnchecked soa(self);
2154 StackHandleScope<2> hs(self);
2155 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2156 Handle<mirror::Class> annotation_class(hs.NewHandle(
2157 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2158 if (annotation_class.Get() == nullptr) {
2159 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2160 << type_index;
2161 DCHECK(Thread::Current()->IsExceptionPending());
2162 Thread::Current()->ClearException();
2163 return nullptr;
2164 }
2165
2166 mirror::Class* annotation_member_class =
2167 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2168 mirror::Class* annotation_member_array_class =
2169 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002170 if (annotation_member_array_class == nullptr) {
2171 return nullptr;
2172 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002173 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002174 if (size > 0) {
2175 element_array =
2176 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2177 if (element_array == nullptr) {
2178 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2179 return nullptr;
2180 }
2181 }
2182
2183 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2184 for (uint32_t i = 0; i < size; ++i) {
2185 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2186 if (new_member == nullptr) {
2187 return nullptr;
2188 }
2189 h_element_array->SetWithoutChecks<false>(i, new_member);
2190 }
2191
2192 JValue result;
2193 ArtMethod* create_annotation_method =
2194 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2195 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2196 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2197 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2198 if (self->IsExceptionPending()) {
2199 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2200 return nullptr;
2201 }
2202
2203 return result.GetL();
2204}
2205
2206const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2207 const char* descriptor, uint32_t visibility) const {
2208 const AnnotationItem* result = nullptr;
2209 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2210 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002211 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002212 continue;
2213 }
2214 const uint8_t* annotation = annotation_item->annotation_;
2215 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2216
2217 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2218 result = annotation_item;
2219 break;
2220 }
2221 }
2222 return result;
2223}
2224
2225const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2226 DecodeUnsignedLeb128(&annotation); // unused type_index
2227 uint32_t size = DecodeUnsignedLeb128(&annotation);
2228
2229 while (size != 0) {
2230 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2231 const char* element_name = GetStringData(GetStringId(element_name_index));
2232 if (strcmp(name, element_name) == 0) {
2233 return annotation;
2234 }
2235 SkipAnnotationValue(&annotation);
2236 size--;
2237 }
2238 return nullptr;
2239}
2240
2241bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2242 const uint8_t* annotation = *annotation_ptr;
2243 uint8_t header_byte = *(annotation++);
2244 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2245 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2246 int32_t width = value_arg + 1;
2247
2248 switch (value_type) {
2249 case kDexAnnotationByte:
2250 case kDexAnnotationShort:
2251 case kDexAnnotationChar:
2252 case kDexAnnotationInt:
2253 case kDexAnnotationLong:
2254 case kDexAnnotationFloat:
2255 case kDexAnnotationDouble:
2256 case kDexAnnotationString:
2257 case kDexAnnotationType:
2258 case kDexAnnotationMethod:
2259 case kDexAnnotationField:
2260 case kDexAnnotationEnum:
2261 break;
2262 case kDexAnnotationArray:
2263 {
2264 uint32_t size = DecodeUnsignedLeb128(&annotation);
2265 while (size--) {
2266 if (!SkipAnnotationValue(&annotation)) {
2267 return false;
2268 }
2269 }
2270 width = 0;
2271 break;
2272 }
2273 case kDexAnnotationAnnotation:
2274 {
2275 DecodeUnsignedLeb128(&annotation); // unused type_index
2276 uint32_t size = DecodeUnsignedLeb128(&annotation);
2277 while (size--) {
2278 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2279 if (!SkipAnnotationValue(&annotation)) {
2280 return false;
2281 }
2282 }
2283 width = 0;
2284 break;
2285 }
2286 case kDexAnnotationBoolean:
2287 case kDexAnnotationNull:
2288 width = 0;
2289 break;
2290 default:
2291 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2292 return false;
2293 }
2294
2295 annotation += width;
2296 *annotation_ptr = annotation;
2297 return true;
2298}
2299
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002300std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2301 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2302 dex_file.GetLocation().c_str(),
2303 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2304 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2305 return os;
2306}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002307
Ian Rogersd91d6d62013-09-25 20:26:14 -07002308std::string Signature::ToString() const {
2309 if (dex_file_ == nullptr) {
2310 CHECK(proto_id_ == nullptr);
2311 return "<no signature>";
2312 }
2313 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2314 std::string result;
2315 if (params == nullptr) {
2316 result += "()";
2317 } else {
2318 result += "(";
2319 for (uint32_t i = 0; i < params->Size(); ++i) {
2320 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2321 }
2322 result += ")";
2323 }
2324 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2325 return result;
2326}
2327
Vladimir Markod9cffea2013-11-25 15:08:02 +00002328bool Signature::operator==(const StringPiece& rhs) const {
2329 if (dex_file_ == nullptr) {
2330 return false;
2331 }
2332 StringPiece tail(rhs);
2333 if (!tail.starts_with("(")) {
2334 return false; // Invalid signature
2335 }
2336 tail.remove_prefix(1); // "(";
2337 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2338 if (params != nullptr) {
2339 for (uint32_t i = 0; i < params->Size(); ++i) {
2340 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2341 if (!tail.starts_with(param)) {
2342 return false;
2343 }
2344 tail.remove_prefix(param.length());
2345 }
2346 }
2347 if (!tail.starts_with(")")) {
2348 return false;
2349 }
2350 tail.remove_prefix(1); // ")";
2351 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2352}
2353
Ian Rogersd91d6d62013-09-25 20:26:14 -07002354std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2355 return os << sig.ToString();
2356}
2357
Ian Rogers0571d352011-11-03 19:51:38 -07002358// Decodes the header section from the class data bytes.
2359void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002360 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002361 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2362 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2363 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2364 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2365}
2366
2367void ClassDataItemIterator::ReadClassDataField() {
2368 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2369 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002370 // The user of the iterator is responsible for checking if there
2371 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002372}
2373
2374void ClassDataItemIterator::ReadClassDataMethod() {
2375 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2376 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2377 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002378 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002379 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002380 }
Ian Rogers0571d352011-11-03 19:51:38 -07002381}
2382
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002383EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002384 const DexFile& dex_file,
2385 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002386 : EncodedStaticFieldValueIterator(dex_file,
2387 nullptr,
2388 nullptr,
2389 nullptr,
2390 class_def,
2391 -1,
2392 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002393}
2394
2395EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002396 const DexFile& dex_file,
2397 Handle<mirror::DexCache>* dex_cache,
2398 Handle<mirror::ClassLoader>* class_loader,
2399 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002400 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002401 : EncodedStaticFieldValueIterator(dex_file,
2402 dex_cache, class_loader,
2403 linker,
2404 class_def,
2405 -1,
2406 kByte) {
2407 DCHECK(dex_cache_ != nullptr);
2408 DCHECK(class_loader_ != nullptr);
2409}
2410
2411EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2412 const DexFile& dex_file,
2413 Handle<mirror::DexCache>* dex_cache,
2414 Handle<mirror::ClassLoader>* class_loader,
2415 ClassLinker* linker,
2416 const DexFile::ClassDef& class_def,
2417 size_t pos,
2418 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002419 : dex_file_(dex_file),
2420 dex_cache_(dex_cache),
2421 class_loader_(class_loader),
2422 linker_(linker),
2423 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002424 pos_(pos),
2425 type_(type) {
2426 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002427 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002428 array_size_ = 0;
2429 } else {
2430 array_size_ = DecodeUnsignedLeb128(&ptr_);
2431 }
2432 if (array_size_ > 0) {
2433 Next();
2434 }
2435}
2436
2437void EncodedStaticFieldValueIterator::Next() {
2438 pos_++;
2439 if (pos_ >= array_size_) {
2440 return;
2441 }
Ian Rogers13735952014-10-08 12:43:28 -07002442 uint8_t value_type = *ptr_++;
2443 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002444 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002445 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002446 switch (type_) {
2447 case kBoolean:
2448 jval_.i = (value_arg != 0) ? 1 : 0;
2449 width = 0;
2450 break;
2451 case kByte:
2452 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002453 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002454 break;
2455 case kShort:
2456 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002457 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002458 break;
2459 case kChar:
2460 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002461 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002462 break;
2463 case kInt:
2464 jval_.i = ReadSignedInt(ptr_, value_arg);
2465 break;
2466 case kLong:
2467 jval_.j = ReadSignedLong(ptr_, value_arg);
2468 break;
2469 case kFloat:
2470 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2471 break;
2472 case kDouble:
2473 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2474 break;
2475 case kString:
2476 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002477 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2478 break;
2479 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002480 case kMethod:
2481 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002482 case kArray:
2483 case kAnnotation:
2484 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002485 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002486 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002487 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002488 width = 0;
2489 break;
2490 default:
2491 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002492 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002493 }
2494 ptr_ += width;
2495}
2496
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002497template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002498void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002499 DCHECK(dex_cache_ != nullptr);
2500 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002501 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002502 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2503 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002504 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2505 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2506 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2507 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2508 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2509 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2510 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002511 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002512 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002513 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002514 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002515 break;
2516 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002517 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002518 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2519 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002520 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002521 break;
2522 }
Ian Rogers0571d352011-11-03 19:51:38 -07002523 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2524 }
2525}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002526template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2527template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002528
2529CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2530 handler_.address_ = -1;
2531 int32_t offset = -1;
2532
2533 // Short-circuit the overwhelmingly common cases.
2534 switch (code_item.tries_size_) {
2535 case 0:
2536 break;
2537 case 1: {
2538 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2539 uint32_t start = tries->start_addr_;
2540 if (address >= start) {
2541 uint32_t end = start + tries->insn_count_;
2542 if (address < end) {
2543 offset = tries->handler_off_;
2544 }
2545 }
2546 break;
2547 }
2548 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002549 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002550 }
Logan Chien736df022012-04-27 16:25:57 +08002551 Init(code_item, offset);
2552}
2553
2554CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2555 const DexFile::TryItem& try_item) {
2556 handler_.address_ = -1;
2557 Init(code_item, try_item.handler_off_);
2558}
2559
2560void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2561 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002562 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002563 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002564 } else {
2565 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002566 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002567 remaining_count_ = -1;
2568 catch_all_ = false;
2569 DCHECK(!HasNext());
2570 }
2571}
2572
Ian Rogers13735952014-10-08 12:43:28 -07002573void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002574 current_data_ = handler_data;
2575 remaining_count_ = DecodeSignedLeb128(&current_data_);
2576
2577 // If remaining_count_ is non-positive, then it is the negative of
2578 // the number of catch types, and the catches are followed by a
2579 // catch-all handler.
2580 if (remaining_count_ <= 0) {
2581 catch_all_ = true;
2582 remaining_count_ = -remaining_count_;
2583 } else {
2584 catch_all_ = false;
2585 }
2586 Next();
2587}
2588
2589void CatchHandlerIterator::Next() {
2590 if (remaining_count_ > 0) {
2591 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2592 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2593 remaining_count_--;
2594 return;
2595 }
2596
2597 if (catch_all_) {
2598 handler_.type_idx_ = DexFile::kDexNoIndex16;
2599 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2600 catch_all_ = false;
2601 return;
2602 }
2603
2604 // no more handler
2605 remaining_count_ = -1;
2606}
2607
Carl Shapiro1fb86202011-06-27 17:43:13 -07002608} // namespace art