blob: 061babd43ee4bb2e54fd153474ad8ab745daf8c4 [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.
Narayan Kamath52e66502016-08-01 14:20:31 +010066 {'0', '3', '7', '\0'},
67 // Dex version 038: Android "O" and beyond.
68 {'0', '3', '8', '\0'}
Alex Lightc4961812016-03-23 10:20:41 -070069};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070070
Ian Rogers8d31bbd2013-10-13 10:44:14 -070071bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070072 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070073 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070074
75 // Strip ":...", which is the location
76 const char* zip_entry_name = kClassesDex;
77 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010078 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070079
Vladimir Markoaa4497d2014-09-05 14:01:17 +010080 if (DexFile::IsMultiDexLocation(filename)) {
81 file_part_storage = GetBaseLocation(filename);
82 file_part = file_part_storage.c_str();
83 zip_entry_name = filename + file_part_storage.size() + 1;
84 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070085 }
86
Andreas Gampe43e10b02016-07-15 17:17:34 -070087 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
88 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070089 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070090 return false;
91 }
92 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070093 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070094 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070095 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080096 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
97 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080098 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070099 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700100 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700101 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700102 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
103 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800104 return false;
105 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700106 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800107 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700108 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700109 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700110 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700111 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700112 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return false;
114 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700115 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return true;
117 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700118 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700120}
121
Aart Bik37d6a3b2016-06-21 18:30:10 -0700122bool DexFile::Open(const char* filename,
123 const char* location,
124 bool verify_checksum,
125 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800126 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800127 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700128 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700130 File fd = OpenAndReadMagic(filename, &magic, error_msg);
131 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700133 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700134 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700135 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700136 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700137 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700138 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700139 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700140 location,
141 /* verify */ true,
142 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 error_msg));
144 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800145 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700146 return true;
147 } else {
148 return false;
149 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700150 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700151 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400152 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700153}
154
Andreas Gampe0cba0042015-04-29 20:47:16 -0700155static bool ContainsClassesDex(int fd, const char* filename) {
156 std::string error_msg;
157 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
158 if (zip_archive.get() == nullptr) {
159 return false;
160 }
161 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
162 return (zip_entry.get() != nullptr);
163}
164
165bool DexFile::MaybeDex(const char* filename) {
166 uint32_t magic;
167 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700168 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
169 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700170 return false;
171 }
172 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700173 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700174 } else if (IsDexMagic(magic)) {
175 return true;
176 }
177 return false;
178}
179
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800180int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700181 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800182 return 0;
183 } else {
184 return mem_map_->GetProtect();
185 }
186}
187
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200188bool DexFile::IsReadOnly() const {
189 return GetPermissions() == PROT_READ;
190}
191
Brian Carlstrome0948e12013-08-29 09:36:15 -0700192bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700194 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195 return false;
196 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700197 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200198 }
199}
200
Brian Carlstrome0948e12013-08-29 09:36:15 -0700201bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700203 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200204 return false;
205 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700206 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200207 }
208}
209
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800210std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
211 const std::string& location,
212 uint32_t location_checksum,
213 const OatDexFile* oat_dex_file,
214 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700215 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800216 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800217 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800218 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
219 size,
220 location,
221 location_checksum,
222 nullptr,
223 oat_dex_file,
224 error_msg);
225 if (verify && !DexFileVerifier::Verify(dex_file.get(),
226 dex_file->Begin(),
227 dex_file->Size(),
228 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700229 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800230 error_msg)) {
231 return nullptr;
232 }
233
234 return dex_file;
235}
236
Aart Bik37d6a3b2016-06-21 18:30:10 -0700237std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
238 const char* location,
239 bool verify,
240 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800241 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800242 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700243 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700244 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000245 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700246 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000247 struct stat sbuf;
248 memset(&sbuf, 0, sizeof(sbuf));
249 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800250 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000251 return nullptr;
252 }
253 if (S_ISDIR(sbuf.st_mode)) {
254 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
255 return nullptr;
256 }
257 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800258 map.reset(MemMap::MapFile(length,
259 PROT_READ,
260 MAP_PRIVATE,
261 fd,
262 0,
263 /*low_4gb*/false,
264 location,
265 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000266 if (map.get() == nullptr) {
267 DCHECK(!error_msg->empty());
268 return nullptr;
269 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700270 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800271
272 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700273 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800274 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700275 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800276 }
277
278 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
279
Andreas Gampe928f72b2014-09-09 19:53:48 -0700280 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
281 error_msg));
282 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
284 error_msg->c_str());
285 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800286 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800287
Andreas Gampe928f72b2014-09-09 19:53:48 -0700288 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700289 location,
290 verify_checksum,
291 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700292 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800293 }
294
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800295 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700296}
297
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700298const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700299
Aart Bik37d6a3b2016-06-21 18:30:10 -0700300bool DexFile::OpenZip(int fd,
301 const std::string& location,
302 bool verify_checksum,
303 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800304 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800305 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700306 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700307 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 if (zip_archive.get() == nullptr) {
309 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700310 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700311 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700312 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800313}
314
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800315std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
316 uint32_t location_checksum,
317 MemMap* mem_map,
318 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800319 return OpenMemory(mem_map->Begin(),
320 mem_map->Size(),
321 location,
322 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700323 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800324 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700325 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800326}
327
Aart Bik37d6a3b2016-06-21 18:30:10 -0700328std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
329 const char* entry_name,
330 const std::string& location,
331 bool verify_checksum,
332 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800333 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800334 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800335 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700336 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700337 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700338 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700339 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700340 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700341 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700342 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700343 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700344 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700345 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700346 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700347 }
Ian Rogers700a4022014-05-19 16:49:03 -0700348 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700349 error_msg));
350 if (dex_file.get() == nullptr) {
351 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
352 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700353 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800355 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700356 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700357 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700358 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700359 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700360 }
361 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700362 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700363 location.c_str(),
364 verify_checksum,
365 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700367 return nullptr;
368 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800370 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700371}
372
Andreas Gampe90e34042015-04-27 20:01:52 -0700373// Technically we do not have a limitation with respect to the number of dex files that can be in a
374// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
375// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
376// seems an excessive number.
377static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
378
Aart Bik37d6a3b2016-06-21 18:30:10 -0700379bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
380 const std::string& location,
381 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800382 std::string* error_msg,
383 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800384 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700385 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700386 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700387 std::unique_ptr<const DexFile> dex_file(
388 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700389 if (dex_file.get() == nullptr) {
390 return false;
391 } else {
392 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800393 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700394
395 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700396
397 // We could try to avoid std::string allocations by working on a char array directly. As we
398 // do not expect a lot of iterations, this seems too involved and brittle.
399
Andreas Gampe90e34042015-04-27 20:01:52 -0700400 for (size_t i = 1; ; ++i) {
401 std::string name = GetMultiDexClassesDexName(i);
402 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700403 std::unique_ptr<const DexFile> next_dex_file(
404 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700405 if (next_dex_file.get() == nullptr) {
406 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
407 LOG(WARNING) << error_msg;
408 }
409 break;
410 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700412 }
413
Andreas Gampe90e34042015-04-27 20:01:52 -0700414 if (i == kWarnOnManyDexFilesThreshold) {
415 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
416 << " dex files. Please consider coalescing and shrinking the number to "
417 " avoid runtime overhead.";
418 }
419
420 if (i == std::numeric_limits<size_t>::max()) {
421 LOG(ERROR) << "Overflow in number of dex files!";
422 break;
423 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700424 }
425
426 return true;
427 }
428}
429
430
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800431std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
432 size_t size,
433 const std::string& location,
434 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800435 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700436 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800437 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700438 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800439 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700440 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800442 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700443 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800444 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700445}
446
Ian Rogers13735952014-10-08 12:43:28 -0700447DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800448 const std::string& location,
449 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800450 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700451 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800452 : begin_(base),
453 size_(size),
454 location_(location),
455 location_checksum_(location_checksum),
456 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800457 header_(reinterpret_cast<const Header*>(base)),
458 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
459 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
460 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
461 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
462 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700463 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700464 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700465 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800466 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300467 const uint8_t* lookup_data = (oat_dex_file != nullptr)
468 ? oat_dex_file->GetLookupTableData()
469 : nullptr;
470 if (lookup_data != nullptr) {
471 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
472 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
473 } else {
474 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
475 }
476 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800477}
478
Jesse Wilson6bf19152011-09-29 13:12:33 -0400479DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700480 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
481 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
482 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
483 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400484}
485
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700488 return false;
489 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700490 return true;
491}
492
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700493bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800494 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700495 std::ostringstream oss;
496 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800497 << " " << header_->magic_[0]
498 << " " << header_->magic_[1]
499 << " " << header_->magic_[2]
500 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700501 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700502 return false;
503 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800504 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700505 std::ostringstream oss;
506 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800507 << " " << header_->magic_[4]
508 << " " << header_->magic_[5]
509 << " " << header_->magic_[6]
510 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700512 return false;
513 }
514 return true;
515}
516
Ian Rogers13735952014-10-08 12:43:28 -0700517bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800518 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
519}
520
Ian Rogers13735952014-10-08 12:43:28 -0700521bool DexFile::IsVersionValid(const uint8_t* magic) {
522 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700523 for (uint32_t i = 0; i < kNumDexVersions; i++) {
524 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
525 return true;
526 }
527 }
528 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800529}
530
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700531uint32_t DexFile::Header::GetVersion() const {
532 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700533 return atoi(version);
534}
535
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800536const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
537 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300538 if (LIKELY(lookup_table_ != nullptr)) {
539 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
540 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700541 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300542
Roland Levillainab880f42016-05-12 16:24:36 +0100543 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300544 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700545 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700546 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700547 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300548 const TypeId* type_id = FindTypeId(descriptor);
549 if (type_id != nullptr) {
550 uint16_t type_idx = GetIndexForTypeId(*type_id);
551 for (size_t i = 0; i < num_class_defs; ++i) {
552 const ClassDef& class_def = GetClassDef(i);
553 if (class_def.class_idx_ == type_idx) {
554 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700555 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700556 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700557 }
Ian Rogers68b56852014-08-29 20:19:11 -0700558 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700559}
560
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700561const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
562 size_t num_class_defs = NumClassDefs();
563 for (size_t i = 0; i < num_class_defs; ++i) {
564 const ClassDef& class_def = GetClassDef(i);
565 if (class_def.class_idx_ == type_idx) {
566 return &class_def;
567 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700568 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700569 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700570}
571
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800572const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100573 const DexFile::StringId& name,
574 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800575 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
576 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
577 const uint32_t name_idx = GetIndexForStringId(name);
578 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700579 int32_t lo = 0;
580 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800581 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700582 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800583 const DexFile::FieldId& field = GetFieldId(mid);
584 if (class_idx > field.class_idx_) {
585 lo = mid + 1;
586 } else if (class_idx < field.class_idx_) {
587 hi = mid - 1;
588 } else {
589 if (name_idx > field.name_idx_) {
590 lo = mid + 1;
591 } else if (name_idx < field.name_idx_) {
592 hi = mid - 1;
593 } else {
594 if (type_idx > field.type_idx_) {
595 lo = mid + 1;
596 } else if (type_idx < field.type_idx_) {
597 hi = mid - 1;
598 } else {
599 return &field;
600 }
601 }
602 }
603 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700604 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800605}
606
607const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700608 const DexFile::StringId& name,
609 const DexFile::ProtoId& signature) const {
610 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800611 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700612 const uint32_t name_idx = GetIndexForStringId(name);
613 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700614 int32_t lo = 0;
615 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700616 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700617 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700618 const DexFile::MethodId& method = GetMethodId(mid);
619 if (class_idx > method.class_idx_) {
620 lo = mid + 1;
621 } else if (class_idx < method.class_idx_) {
622 hi = mid - 1;
623 } else {
624 if (name_idx > method.name_idx_) {
625 lo = mid + 1;
626 } else if (name_idx < method.name_idx_) {
627 hi = mid - 1;
628 } else {
629 if (proto_idx > method.proto_idx_) {
630 lo = mid + 1;
631 } else if (proto_idx < method.proto_idx_) {
632 hi = mid - 1;
633 } else {
634 return &method;
635 }
636 }
637 }
638 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700639 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700640}
641
Ian Rogers637c65b2013-05-31 11:46:00 -0700642const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700643 int32_t lo = 0;
644 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700645 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700646 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700647 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700648 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700649 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
650 if (compare > 0) {
651 lo = mid + 1;
652 } else if (compare < 0) {
653 hi = mid - 1;
654 } else {
655 return &str_id;
656 }
657 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700658 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700659}
660
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300661const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
662 int32_t lo = 0;
663 int32_t hi = NumTypeIds() - 1;
664 while (hi >= lo) {
665 int32_t mid = (hi + lo) / 2;
666 const TypeId& type_id = GetTypeId(mid);
667 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
668 const char* str = GetStringData(str_id);
669 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
670 if (compare > 0) {
671 lo = mid + 1;
672 } else if (compare < 0) {
673 hi = mid - 1;
674 } else {
675 return &type_id;
676 }
677 }
678 return nullptr;
679}
680
Vladimir Markoa48aef42014-12-03 17:53:53 +0000681const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700682 int32_t lo = 0;
683 int32_t hi = NumStringIds() - 1;
684 while (hi >= lo) {
685 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700686 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700687 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000688 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700689 if (compare > 0) {
690 lo = mid + 1;
691 } else if (compare < 0) {
692 hi = mid - 1;
693 } else {
694 return &str_id;
695 }
696 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700697 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700698}
699
700const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700701 int32_t lo = 0;
702 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700703 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700704 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700705 const TypeId& type_id = GetTypeId(mid);
706 if (string_idx > type_id.descriptor_idx_) {
707 lo = mid + 1;
708 } else if (string_idx < type_id.descriptor_idx_) {
709 hi = mid - 1;
710 } else {
711 return &type_id;
712 }
713 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700714 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700715}
716
717const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000718 const uint16_t* signature_type_idxs,
719 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700720 int32_t lo = 0;
721 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700722 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700723 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700724 const DexFile::ProtoId& proto = GetProtoId(mid);
725 int compare = return_type_idx - proto.return_type_idx_;
726 if (compare == 0) {
727 DexFileParameterIterator it(*this, proto);
728 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000729 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800730 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700731 it.Next();
732 i++;
733 }
734 if (compare == 0) {
735 if (it.HasNext()) {
736 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000737 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700738 compare = 1;
739 }
740 }
741 }
742 if (compare > 0) {
743 lo = mid + 1;
744 } else if (compare < 0) {
745 hi = mid - 1;
746 } else {
747 return &proto;
748 }
749 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700750 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700751}
752
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000753void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
754 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300755}
756
Ian Rogers0571d352011-11-03 19:51:38 -0700757// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700758bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
759 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700760 if (signature[0] != '(') {
761 return false;
762 }
763 size_t offset = 1;
764 size_t end = signature.size();
765 bool process_return = false;
766 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000767 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700768 char c = signature[offset];
769 offset++;
770 if (c == ')') {
771 process_return = true;
772 continue;
773 }
Ian Rogers0571d352011-11-03 19:51:38 -0700774 while (c == '[') { // process array prefix
775 if (offset >= end) { // expect some descriptor following [
776 return false;
777 }
778 c = signature[offset];
779 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700780 }
781 if (c == 'L') { // process type descriptors
782 do {
783 if (offset >= end) { // unexpected early termination of descriptor
784 return false;
785 }
786 c = signature[offset];
787 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700788 } while (c != ';');
789 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000790 // TODO: avoid creating a std::string just to get a 0-terminated char array
791 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700792 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700793 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700794 return false;
795 }
796 uint16_t type_idx = GetIndexForTypeId(*type_id);
797 if (!process_return) {
798 param_type_idxs->push_back(type_idx);
799 } else {
800 *return_type_idx = type_idx;
801 return offset == end; // return true if the signature had reached a sensible end
802 }
803 }
804 return false; // failed to correctly parse return type
805}
806
Ian Rogersd91d6d62013-09-25 20:26:14 -0700807const Signature DexFile::CreateSignature(const StringPiece& signature) const {
808 uint16_t return_type_idx;
809 std::vector<uint16_t> param_type_indices;
810 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
811 if (!success) {
812 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700813 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700814 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700816 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700817 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700818 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700819}
820
Mathieu Chartiere401d142015-04-22 13:56:20 -0700821int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700822 // For native method, lineno should be -2 to indicate it is native. Note that
823 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700824 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700825 return -2;
826 }
827
TDYa127c8dc1012012-04-19 07:03:33 -0700828 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700829 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700830
831 // A method with no line number info should return -1
832 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000833 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700834 return context.line_num_;
835}
836
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700837int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700838 // Note: Signed type is important for max and min.
839 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700840 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700841
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700842 while (min <= max) {
843 int32_t mid = min + ((max - min) / 2);
844
845 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
846 uint32_t start = ti->start_addr_;
847 uint32_t end = start + ti->insn_count_;
848
Ian Rogers0571d352011-11-03 19:51:38 -0700849 if (address < start) {
850 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700851 } else if (address >= end) {
852 min = mid + 1;
853 } else { // We have a winner!
854 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700855 }
856 }
857 // No match.
858 return -1;
859}
860
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700861int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
862 int32_t try_item = FindTryItem(code_item, address);
863 if (try_item == -1) {
864 return -1;
865 } else {
866 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
867 }
868}
869
David Srbeckyb06e28e2015-12-10 13:15:00 +0000870bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
871 DexDebugNewLocalCb local_cb, void* context) const {
872 DCHECK(local_cb != nullptr);
873 if (code_item == nullptr) {
874 return false;
875 }
876 const uint8_t* stream = GetDebugInfoStream(code_item);
877 if (stream == nullptr) {
878 return false;
879 }
880 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800883 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000884 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
885 local_in_reg[arg_reg].name_ = "this";
886 local_in_reg[arg_reg].descriptor_ = descriptor;
887 local_in_reg[arg_reg].signature_ = nullptr;
888 local_in_reg[arg_reg].start_address_ = 0;
889 local_in_reg[arg_reg].reg_ = arg_reg;
890 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 arg_reg++;
892 }
893
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800894 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000895 DecodeUnsignedLeb128(&stream); // Line.
896 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
897 uint32_t i;
898 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700899 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700900 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800901 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000902 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700903 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000904 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700905 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
907 local_in_reg[arg_reg].descriptor_ = descriptor;
908 local_in_reg[arg_reg].signature_ = nullptr;
909 local_in_reg[arg_reg].start_address_ = 0;
910 local_in_reg[arg_reg].reg_ = arg_reg;
911 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700912 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700913 case 'D':
914 case 'J':
915 arg_reg += 2;
916 break;
917 default:
918 arg_reg += 1;
919 break;
920 }
921 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000922 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800923 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
924 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000925 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 }
927
David Srbeckyb06e28e2015-12-10 13:15:00 +0000928 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 for (;;) {
930 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700931 switch (opcode) {
932 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000933 // Emit all variables which are still alive at the end of the method.
934 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
935 if (local_in_reg[reg].is_live_) {
936 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
937 local_cb(context, local_in_reg[reg]);
938 }
939 }
940 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 case DBG_ADVANCE_PC:
942 address += DecodeUnsignedLeb128(&stream);
943 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000945 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700946 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700947 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000948 case DBG_START_LOCAL_EXTENDED: {
949 uint16_t reg = DecodeUnsignedLeb128(&stream);
950 if (reg >= code_item->registers_size_) {
951 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800952 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000953 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700954 }
955
David Srbeckyb06e28e2015-12-10 13:15:00 +0000956 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
957 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
958 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700959 if (opcode == DBG_START_LOCAL_EXTENDED) {
960 signature_idx = DecodeUnsignedLeb128P1(&stream);
961 }
962
Shih-wei Liao195487c2011-08-20 13:29:04 -0700963 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000964 if (local_in_reg[reg].is_live_) {
965 local_in_reg[reg].end_address_ = address;
966 local_cb(context, local_in_reg[reg]);
967 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700968
David Srbeckyb06e28e2015-12-10 13:15:00 +0000969 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
970 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
971 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
972 local_in_reg[reg].start_address_ = address;
973 local_in_reg[reg].reg_ = reg;
974 local_in_reg[reg].is_live_ = true;
975 break;
976 }
977 case DBG_END_LOCAL: {
978 uint16_t reg = DecodeUnsignedLeb128(&stream);
979 if (reg >= code_item->registers_size_) {
980 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
981 << code_item->registers_size_ << ") in " << GetLocation();
982 return false;
983 }
984 if (!local_in_reg[reg].is_live_) {
985 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
986 return false;
987 }
988 local_in_reg[reg].end_address_ = address;
989 local_cb(context, local_in_reg[reg]);
990 local_in_reg[reg].is_live_ = false;
991 break;
992 }
993 case DBG_RESTART_LOCAL: {
994 uint16_t reg = DecodeUnsignedLeb128(&stream);
995 if (reg >= code_item->registers_size_) {
996 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
997 << code_item->registers_size_ << ") in " << GetLocation();
998 return false;
999 }
1000 // If the register is live, the "restart" is superfluous,
1001 // and we don't want to mess with the existing start address.
1002 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001003 local_in_reg[reg].start_address_ = address;
1004 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001005 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001006 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001007 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001008 case DBG_SET_PROLOGUE_END:
1009 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001010 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001011 case DBG_SET_FILE:
1012 DecodeUnsignedLeb128P1(&stream); // name.
1013 break;
1014 default:
1015 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1016 break;
1017 }
1018 }
1019}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001020
David Srbeckyb06e28e2015-12-10 13:15:00 +00001021bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1022 void* context) const {
1023 DCHECK(position_cb != nullptr);
1024 if (code_item == nullptr) {
1025 return false;
1026 }
1027 const uint8_t* stream = GetDebugInfoStream(code_item);
1028 if (stream == nullptr) {
1029 return false;
1030 }
1031
1032 PositionInfo entry = PositionInfo();
1033 entry.line_ = DecodeUnsignedLeb128(&stream);
1034 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1035 for (uint32_t i = 0; i < parameters_size; ++i) {
1036 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1037 }
1038
1039 for (;;) {
1040 uint8_t opcode = *stream++;
1041 switch (opcode) {
1042 case DBG_END_SEQUENCE:
1043 return true; // end of stream.
1044 case DBG_ADVANCE_PC:
1045 entry.address_ += DecodeUnsignedLeb128(&stream);
1046 break;
1047 case DBG_ADVANCE_LINE:
1048 entry.line_ += DecodeSignedLeb128(&stream);
1049 break;
1050 case DBG_START_LOCAL:
1051 DecodeUnsignedLeb128(&stream); // reg.
1052 DecodeUnsignedLeb128P1(&stream); // name.
1053 DecodeUnsignedLeb128P1(&stream); // descriptor.
1054 break;
1055 case DBG_START_LOCAL_EXTENDED:
1056 DecodeUnsignedLeb128(&stream); // reg.
1057 DecodeUnsignedLeb128P1(&stream); // name.
1058 DecodeUnsignedLeb128P1(&stream); // descriptor.
1059 DecodeUnsignedLeb128P1(&stream); // signature.
1060 break;
1061 case DBG_END_LOCAL:
1062 case DBG_RESTART_LOCAL:
1063 DecodeUnsignedLeb128(&stream); // reg.
1064 break;
1065 case DBG_SET_PROLOGUE_END:
1066 entry.prologue_end_ = true;
1067 break;
1068 case DBG_SET_EPILOGUE_BEGIN:
1069 entry.epilogue_begin_ = true;
1070 break;
1071 case DBG_SET_FILE: {
1072 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1073 entry.source_file_ = StringDataByIdx(name_idx);
1074 break;
1075 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001076 default: {
1077 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001078 entry.address_ += adjopcode / DBG_LINE_RANGE;
1079 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1080 if (position_cb(context, entry)) {
1081 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001082 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001083 entry.prologue_end_ = false;
1084 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001085 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001086 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001087 }
1088 }
1089}
1090
David Srbeckyb06e28e2015-12-10 13:15:00 +00001091bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001092 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001093
1094 // We know that this callback will be called in
1095 // ascending address order, so keep going until we find
1096 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001097 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001098 // The line number from the previous positions callback
1099 // wil be the final result.
1100 return true;
1101 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001102 context->line_num_ = entry.line_;
1103 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001104 }
1105}
1106
Andreas Gampe833a4852014-05-21 18:46:59 -07001107bool DexFile::IsMultiDexLocation(const char* location) {
1108 return strrchr(location, kMultiDexSeparator) != nullptr;
1109}
1110
Andreas Gampe90e34042015-04-27 20:01:52 -07001111std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1112 if (index == 0) {
1113 return "classes.dex";
1114 } else {
1115 return StringPrintf("classes%zu.dex", index + 1);
1116 }
1117}
1118
1119std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1120 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001121 return dex_location;
1122 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001123 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001124 }
1125}
1126
1127std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1128 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001129 std::string base_location = GetBaseLocation(dex_location);
1130 const char* suffix = dex_location + base_location.size();
1131 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1132 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1133 if (path != nullptr && path.get() != base_location) {
1134 return std::string(path.get()) + suffix;
1135 } else if (suffix[0] == 0) {
1136 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001137 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001138 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001139 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001140}
1141
Jeff Hao13e748b2015-08-25 20:44:19 +00001142// Read a signed integer. "zwidth" is the zero-based byte count.
1143static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1144 int32_t val = 0;
1145 for (int i = zwidth; i >= 0; --i) {
1146 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1147 }
1148 val >>= (3 - zwidth) * 8;
1149 return val;
1150}
1151
1152// Read an unsigned integer. "zwidth" is the zero-based byte count,
1153// "fill_on_right" indicates which side we want to zero-fill from.
1154static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1155 uint32_t val = 0;
1156 for (int i = zwidth; i >= 0; --i) {
1157 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1158 }
1159 if (!fill_on_right) {
1160 val >>= (3 - zwidth) * 8;
1161 }
1162 return val;
1163}
1164
1165// Read a signed long. "zwidth" is the zero-based byte count.
1166static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1167 int64_t val = 0;
1168 for (int i = zwidth; i >= 0; --i) {
1169 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1170 }
1171 val >>= (7 - zwidth) * 8;
1172 return val;
1173}
1174
1175// Read an unsigned long. "zwidth" is the zero-based byte count,
1176// "fill_on_right" indicates which side we want to zero-fill from.
1177static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1178 uint64_t val = 0;
1179 for (int i = zwidth; i >= 0; --i) {
1180 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1181 }
1182 if (!fill_on_right) {
1183 val >>= (7 - zwidth) * 8;
1184 }
1185 return val;
1186}
1187
Jeff Hao3d080862016-05-26 18:39:17 -07001188// Checks that visibility is as expected. Includes special behavior for M and
1189// before to allow runtime and build visibility when expecting runtime.
1190static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1191 if (expected == DexFile::kDexVisibilityRuntime) {
1192 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1193 if (sdk_version > 0 && sdk_version <= 23) {
1194 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1195 }
1196 }
1197 return actual == expected;
1198}
1199
Jeff Hao13e748b2015-08-25 20:44:19 +00001200const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1201 mirror::Class* klass = field->GetDeclaringClass();
1202 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1203 if (annotations_dir == nullptr) {
1204 return nullptr;
1205 }
1206 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1207 if (field_annotations == nullptr) {
1208 return nullptr;
1209 }
1210 uint32_t field_index = field->GetDexFieldIndex();
1211 uint32_t field_count = annotations_dir->fields_size_;
1212 for (uint32_t i = 0; i < field_count; ++i) {
1213 if (field_annotations[i].field_idx_ == field_index) {
1214 return GetFieldAnnotationSetItem(field_annotations[i]);
1215 }
1216 }
1217 return nullptr;
1218}
1219
1220mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1221 Handle<mirror::Class> annotation_class) const {
1222 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1223 if (annotation_set == nullptr) {
1224 return nullptr;
1225 }
1226 StackHandleScope<1> hs(Thread::Current());
1227 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1228 return GetAnnotationObjectFromAnnotationSet(
1229 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1230}
1231
1232mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1233 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1234 StackHandleScope<1> hs(Thread::Current());
1235 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1236 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1237}
1238
Jeff Hao2a5892f2015-08-31 15:00:40 -07001239mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001240 const {
1241 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1242 if (annotation_set == nullptr) {
1243 return nullptr;
1244 }
1245 StackHandleScope<1> hs(Thread::Current());
1246 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1247 return GetSignatureValue(field_class, annotation_set);
1248}
1249
1250bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1251 const {
1252 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1253 if (annotation_set == nullptr) {
1254 return false;
1255 }
1256 StackHandleScope<1> hs(Thread::Current());
1257 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1258 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1259 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1260 return annotation_item != nullptr;
1261}
1262
1263const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1264 mirror::Class* klass = method->GetDeclaringClass();
1265 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1266 if (annotations_dir == nullptr) {
1267 return nullptr;
1268 }
1269 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1270 if (method_annotations == nullptr) {
1271 return nullptr;
1272 }
1273 uint32_t method_index = method->GetDexMethodIndex();
1274 uint32_t method_count = annotations_dir->methods_size_;
1275 for (uint32_t i = 0; i < method_count; ++i) {
1276 if (method_annotations[i].method_idx_ == method_index) {
1277 return GetMethodAnnotationSetItem(method_annotations[i]);
1278 }
1279 }
1280 return nullptr;
1281}
1282
1283const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1284 const {
1285 mirror::Class* klass = method->GetDeclaringClass();
1286 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1287 if (annotations_dir == nullptr) {
1288 return nullptr;
1289 }
1290 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1291 if (parameter_annotations == nullptr) {
1292 return nullptr;
1293 }
1294 uint32_t method_index = method->GetDexMethodIndex();
1295 uint32_t parameter_count = annotations_dir->parameters_size_;
1296 for (uint32_t i = 0; i < parameter_count; ++i) {
1297 if (parameter_annotations[i].method_idx_ == method_index) {
1298 return &parameter_annotations[i];
1299 }
1300 }
1301 return nullptr;
1302}
1303
1304mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1305 mirror::Class* klass = method->GetDeclaringClass();
1306 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1307 if (annotations_dir == nullptr) {
1308 return nullptr;
1309 }
1310 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1311 if (annotation_set == nullptr) {
1312 return nullptr;
1313 }
1314 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1315 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1316 if (annotation_item == nullptr) {
1317 return nullptr;
1318 }
1319 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1320 if (annotation == nullptr) {
1321 return nullptr;
1322 }
1323 uint8_t header_byte = *(annotation++);
1324 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1325 return nullptr;
1326 }
1327 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1328 if (annotation == nullptr) {
1329 return nullptr;
1330 }
1331 AnnotationValue annotation_value;
1332 StackHandleScope<2> hs(Thread::Current());
1333 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe542451c2016-07-26 09:02:02 -07001334 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Vladimir Marko05792b92015-08-03 11:56:49 +01001335 Handle<mirror::Class> return_type(hs.NewHandle(
1336 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001337 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1338 return nullptr;
1339 }
1340 return annotation_value.value_.GetL();
1341}
1342
1343mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1344 Handle<mirror::Class> annotation_class) const {
1345 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1346 if (annotation_set == nullptr) {
1347 return nullptr;
1348 }
1349 StackHandleScope<1> hs(Thread::Current());
1350 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1351 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1352 kDexVisibilityRuntime, annotation_class);
1353}
1354
1355mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1356 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1357 StackHandleScope<1> hs(Thread::Current());
1358 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1359 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1360}
1361
Jeff Hao2a5892f2015-08-31 15:00:40 -07001362mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001363 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1364 if (annotation_set == nullptr) {
1365 return nullptr;
1366 }
1367 StackHandleScope<1> hs(Thread::Current());
1368 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1369 return GetThrowsValue(method_class, annotation_set);
1370}
1371
1372mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1373 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1374 if (parameter_annotations == nullptr) {
1375 return nullptr;
1376 }
1377 const AnnotationSetRefList* set_ref_list =
1378 GetParameterAnnotationSetRefList(parameter_annotations);
1379 if (set_ref_list == nullptr) {
1380 return nullptr;
1381 }
1382 uint32_t size = set_ref_list->size_;
1383 StackHandleScope<1> hs(Thread::Current());
1384 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1385 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1386}
1387
Jeff Hao1133db72016-04-04 19:50:14 -07001388mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1389 const {
1390 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1391 if (annotation_set == nullptr) {
1392 return nullptr;
1393 }
1394 StackHandleScope<1> hs(Thread::Current());
1395 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1396 return GetSignatureValue(method_class, annotation_set);
1397}
1398
Jeff Hao13e748b2015-08-25 20:44:19 +00001399bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1400 const {
1401 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1402 if (annotation_set == nullptr) {
1403 return false;
1404 }
1405 StackHandleScope<1> hs(Thread::Current());
1406 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1407 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1408 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001409 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001410}
1411
1412const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1413 const {
1414 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1415 if (annotations_dir == nullptr) {
1416 return nullptr;
1417 }
1418 return GetClassAnnotationSet(annotations_dir);
1419}
1420
1421mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1422 Handle<mirror::Class> annotation_class) const {
1423 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1424 if (annotation_set == nullptr) {
1425 return nullptr;
1426 }
1427 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1428 annotation_class);
1429}
1430
1431mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1432 const {
1433 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1434 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1435}
1436
Jeff Hao2a5892f2015-08-31 15:00:40 -07001437mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1438 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1439 if (annotation_set == nullptr) {
1440 return nullptr;
1441 }
1442 const AnnotationItem* annotation_item = SearchAnnotationSet(
1443 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1444 if (annotation_item == nullptr) {
1445 return nullptr;
1446 }
1447 StackHandleScope<1> hs(Thread::Current());
1448 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1449 Handle<mirror::Class> class_array_class(hs.NewHandle(
1450 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1451 if (class_array_class.Get() == nullptr) {
1452 return nullptr;
1453 }
1454 mirror::Object* obj = GetAnnotationValue(
1455 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1456 if (obj == nullptr) {
1457 return nullptr;
1458 }
1459 return obj->AsObjectArray<mirror::Class>();
1460}
1461
1462mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1463 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1464 if (annotation_set == nullptr) {
1465 return nullptr;
1466 }
1467 const AnnotationItem* annotation_item = SearchAnnotationSet(
1468 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1469 if (annotation_item == nullptr) {
1470 return nullptr;
1471 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001472 mirror::Object* obj = GetAnnotationValue(klass,
1473 annotation_item,
1474 "value",
1475 ScopedNullHandle<mirror::Class>(),
1476 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001477 if (obj == nullptr) {
1478 return nullptr;
1479 }
1480 return obj->AsClass();
1481}
1482
1483mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1484 mirror::Class* declaring_class = GetDeclaringClass(klass);
1485 if (declaring_class != nullptr) {
1486 return declaring_class;
1487 }
1488 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1489 if (annotation_set == nullptr) {
1490 return nullptr;
1491 }
1492 const AnnotationItem* annotation_item = SearchAnnotationSet(
1493 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1494 if (annotation_item == nullptr) {
1495 return nullptr;
1496 }
1497 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1498 if (annotation == nullptr) {
1499 return nullptr;
1500 }
1501 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001502 if (!ProcessAnnotationValue(klass,
1503 &annotation,
1504 &annotation_value,
1505 ScopedNullHandle<mirror::Class>(),
1506 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001507 return nullptr;
1508 }
1509 if (annotation_value.type_ != kDexAnnotationMethod) {
1510 return nullptr;
1511 }
1512 StackHandleScope<2> hs(Thread::Current());
1513 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1514 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1515 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1516 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1517 if (method == nullptr) {
1518 return nullptr;
1519 }
1520 return method->GetDeclaringClass();
1521}
1522
1523mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1524 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1525 if (annotation_set == nullptr) {
1526 return nullptr;
1527 }
1528 const AnnotationItem* annotation_item = SearchAnnotationSet(
1529 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1530 if (annotation_item == nullptr) {
1531 return nullptr;
1532 }
1533 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001534 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001535}
1536
1537bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1538 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1539 if (annotation_set == nullptr) {
1540 return false;
1541 }
1542 const AnnotationItem* annotation_item = SearchAnnotationSet(
1543 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1544 if (annotation_item == nullptr) {
1545 return false;
1546 }
1547 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1548 if (annotation == nullptr) {
1549 return false;
1550 }
1551 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001552 if (!ProcessAnnotationValue(klass,
1553 &annotation,
1554 &annotation_value,
1555 ScopedNullHandle<mirror::Class>(),
1556 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001557 return false;
1558 }
1559 if (annotation_value.type_ != kDexAnnotationNull &&
1560 annotation_value.type_ != kDexAnnotationString) {
1561 return false;
1562 }
1563 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1564 return true;
1565}
1566
1567bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1568 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1569 if (annotation_set == nullptr) {
1570 return false;
1571 }
1572 const AnnotationItem* annotation_item = SearchAnnotationSet(
1573 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1574 if (annotation_item == nullptr) {
1575 return false;
1576 }
1577 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1578 if (annotation == nullptr) {
1579 return false;
1580 }
1581 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001582 if (!ProcessAnnotationValue(klass,
1583 &annotation,
1584 &annotation_value,
1585 ScopedNullHandle<mirror::Class>(),
1586 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001587 return false;
1588 }
1589 if (annotation_value.type_ != kDexAnnotationInt) {
1590 return false;
1591 }
1592 *flags = annotation_value.value_.GetI();
1593 return true;
1594}
1595
Jeff Hao1133db72016-04-04 19:50:14 -07001596mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1597 Handle<mirror::Class> klass) const {
1598 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1599 if (annotation_set == nullptr) {
1600 return nullptr;
1601 }
1602 return GetSignatureValue(klass, annotation_set);
1603}
1604
Jeff Hao13e748b2015-08-25 20:44:19 +00001605bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1606 Handle<mirror::Class> annotation_class) const {
1607 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1608 if (annotation_set == nullptr) {
1609 return false;
1610 }
1611 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1612 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001613 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001614}
1615
1616mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1617 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1618 Thread* self = Thread::Current();
1619 ScopedObjectAccessUnchecked soa(self);
1620 StackHandleScope<5> hs(self);
1621 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1622 const char* name = StringDataByIdx(element_name_index);
1623 Handle<mirror::String> string_name(
1624 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1625
Andreas Gampe542451c2016-07-26 09:02:02 -07001626 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001627 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001628 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001629 if (annotation_method == nullptr) {
1630 return nullptr;
1631 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001632 Handle<mirror::Class> method_return(hs.NewHandle(
1633 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001634
1635 AnnotationValue annotation_value;
1636 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1637 return nullptr;
1638 }
1639 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1640
1641 mirror::Class* annotation_member_class =
1642 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1643 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001644 mirror::Method* method_obj_ptr;
1645 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001646 if (pointer_size == PointerSize::k64) {
1647 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1648 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001649 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001650 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1651 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001652 }
1653 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001654
1655 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1656 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1657 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1658 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1659 return nullptr;
1660 }
1661
1662 JValue result;
1663 ArtMethod* annotation_member_init =
1664 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1665 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1666 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1667 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1668 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1669 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1670 };
1671 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1672 if (self->IsExceptionPending()) {
1673 LOG(INFO) << "Exception in AnnotationMember.<init>";
1674 return nullptr;
1675 }
1676
1677 return new_member.Get();
1678}
1679
1680const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1681 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1682 Handle<mirror::Class> annotation_class) const {
1683 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1684 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001685 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001686 continue;
1687 }
1688 const uint8_t* annotation = annotation_item->annotation_;
1689 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1690 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1691 klass->GetDexFile(), type_index, klass.Get());
1692 if (resolved_class == nullptr) {
1693 std::string temp;
1694 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1695 klass->GetDescriptor(&temp), type_index);
1696 CHECK(Thread::Current()->IsExceptionPending());
1697 Thread::Current()->ClearException();
1698 continue;
1699 }
1700 if (resolved_class == annotation_class.Get()) {
1701 return annotation_item;
1702 }
1703 }
1704
1705 return nullptr;
1706}
1707
1708mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1709 const AnnotationSetItem* annotation_set, uint32_t visibility,
1710 Handle<mirror::Class> annotation_class) const {
1711 const AnnotationItem* annotation_item =
1712 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1713 if (annotation_item == nullptr) {
1714 return nullptr;
1715 }
1716 const uint8_t* annotation = annotation_item->annotation_;
1717 return ProcessEncodedAnnotation(klass, &annotation);
1718}
1719
1720mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1721 const AnnotationItem* annotation_item, const char* annotation_name,
1722 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1723 const uint8_t* annotation =
1724 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1725 if (annotation == nullptr) {
1726 return nullptr;
1727 }
1728 AnnotationValue annotation_value;
1729 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1730 return nullptr;
1731 }
1732 if (annotation_value.type_ != expected_type) {
1733 return nullptr;
1734 }
1735 return annotation_value.value_.GetL();
1736}
1737
Jeff Hao2a5892f2015-08-31 15:00:40 -07001738mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001739 const AnnotationSetItem* annotation_set) const {
1740 StackHandleScope<1> hs(Thread::Current());
1741 const AnnotationItem* annotation_item =
1742 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1743 if (annotation_item == nullptr) {
1744 return nullptr;
1745 }
1746 mirror::Class* string_class = mirror::String::GetJavaLangString();
1747 Handle<mirror::Class> string_array_class(hs.NewHandle(
1748 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001749 if (string_array_class.Get() == nullptr) {
1750 return nullptr;
1751 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001752 mirror::Object* obj =
1753 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1754 if (obj == nullptr) {
1755 return nullptr;
1756 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001757 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001758}
1759
Jeff Hao2a5892f2015-08-31 15:00:40 -07001760mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001761 const AnnotationSetItem* annotation_set) const {
1762 StackHandleScope<1> hs(Thread::Current());
1763 const AnnotationItem* annotation_item =
1764 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1765 if (annotation_item == nullptr) {
1766 return nullptr;
1767 }
1768 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1769 Handle<mirror::Class> class_array_class(hs.NewHandle(
1770 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001771 if (class_array_class.Get() == nullptr) {
1772 return nullptr;
1773 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001774 mirror::Object* obj =
1775 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1776 if (obj == nullptr) {
1777 return nullptr;
1778 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001779 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001780}
1781
1782mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1783 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1784 Thread* self = Thread::Current();
1785 ScopedObjectAccessUnchecked soa(self);
1786 StackHandleScope<2> hs(self);
1787 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1788 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1789 if (annotation_set == nullptr) {
1790 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1791 }
1792
1793 uint32_t size = annotation_set->size_;
1794 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1795 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1796 if (result.Get() == nullptr) {
1797 return nullptr;
1798 }
1799
1800 uint32_t dest_index = 0;
1801 for (uint32_t i = 0; i < size; ++i) {
1802 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001803 // Note that we do not use IsVisibilityCompatible here because older code
1804 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001805 if (annotation_item->visibility_ != visibility) {
1806 continue;
1807 }
1808 const uint8_t* annotation = annotation_item->annotation_;
1809 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1810 if (annotation_obj != nullptr) {
1811 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1812 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001813 } else if (self->IsExceptionPending()) {
1814 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001815 }
1816 }
1817
1818 if (dest_index == size) {
1819 return result.Get();
1820 }
1821
1822 mirror::ObjectArray<mirror::Object>* trimmed_result =
1823 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001824 if (trimmed_result == nullptr) {
1825 return nullptr;
1826 }
1827
Jeff Hao13e748b2015-08-25 20:44:19 +00001828 for (uint32_t i = 0; i < dest_index; ++i) {
1829 mirror::Object* obj = result->GetWithoutChecks(i);
1830 trimmed_result->SetWithoutChecks<false>(i, obj);
1831 }
1832
1833 return trimmed_result;
1834}
1835
1836mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1837 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1838 Thread* self = Thread::Current();
1839 ScopedObjectAccessUnchecked soa(self);
1840 StackHandleScope<1> hs(self);
1841 mirror::Class* annotation_array_class =
1842 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1843 mirror::Class* annotation_array_array_class =
1844 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001845 if (annotation_array_array_class == nullptr) {
1846 return nullptr;
1847 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001848 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1849 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1850 if (annotation_array_array.Get() == nullptr) {
1851 LOG(ERROR) << "Annotation set ref array allocation failed";
1852 return nullptr;
1853 }
1854 for (uint32_t index = 0; index < size; ++index) {
1855 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1856 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1857 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1858 if (annotation_set == nullptr) {
1859 return nullptr;
1860 }
1861 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1862 }
1863 return annotation_array_array.Get();
1864}
1865
1866bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1867 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1868 DexFile::AnnotationResultStyle result_style) const {
1869 Thread* self = Thread::Current();
1870 mirror::Object* element_object = nullptr;
1871 bool set_object = false;
1872 Primitive::Type primitive_type = Primitive::kPrimVoid;
1873 const uint8_t* annotation = *annotation_ptr;
1874 uint8_t header_byte = *(annotation++);
1875 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1876 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1877 int32_t width = value_arg + 1;
1878 annotation_value->type_ = value_type;
1879
1880 switch (value_type) {
1881 case kDexAnnotationByte:
1882 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1883 primitive_type = Primitive::kPrimByte;
1884 break;
1885 case kDexAnnotationShort:
1886 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1887 primitive_type = Primitive::kPrimShort;
1888 break;
1889 case kDexAnnotationChar:
1890 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1891 false)));
1892 primitive_type = Primitive::kPrimChar;
1893 break;
1894 case kDexAnnotationInt:
1895 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1896 primitive_type = Primitive::kPrimInt;
1897 break;
1898 case kDexAnnotationLong:
1899 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1900 primitive_type = Primitive::kPrimLong;
1901 break;
1902 case kDexAnnotationFloat:
1903 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1904 primitive_type = Primitive::kPrimFloat;
1905 break;
1906 case kDexAnnotationDouble:
1907 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1908 primitive_type = Primitive::kPrimDouble;
1909 break;
1910 case kDexAnnotationBoolean:
1911 annotation_value->value_.SetZ(value_arg != 0);
1912 primitive_type = Primitive::kPrimBoolean;
1913 width = 0;
1914 break;
1915 case kDexAnnotationString: {
1916 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1917 if (result_style == kAllRaw) {
1918 annotation_value->value_.SetI(index);
1919 } else {
1920 StackHandleScope<1> hs(self);
1921 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1922 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1923 klass->GetDexFile(), index, dex_cache);
1924 set_object = true;
1925 if (element_object == nullptr) {
1926 return false;
1927 }
1928 }
1929 break;
1930 }
1931 case kDexAnnotationType: {
1932 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1933 if (result_style == kAllRaw) {
1934 annotation_value->value_.SetI(index);
1935 } else {
1936 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1937 klass->GetDexFile(), index, klass.Get());
1938 set_object = true;
1939 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001940 CHECK(self->IsExceptionPending());
1941 if (result_style == kAllObjects) {
1942 const char* msg = StringByTypeIdx(index);
1943 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1944 element_object = self->GetException();
1945 self->ClearException();
1946 } else {
1947 return false;
1948 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001949 }
1950 }
1951 break;
1952 }
1953 case kDexAnnotationMethod: {
1954 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1955 if (result_style == kAllRaw) {
1956 annotation_value->value_.SetI(index);
1957 } else {
1958 StackHandleScope<2> hs(self);
1959 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1960 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07001961 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1962 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00001963 klass->GetDexFile(), index, dex_cache, class_loader);
1964 if (method == nullptr) {
1965 return false;
1966 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001967 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001968 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07001969 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00001970 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001971 if (pointer_size == PointerSize::k64) {
1972 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
1973 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001974 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001975 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
1976 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001977 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001978 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001979 if (pointer_size == PointerSize::k64) {
1980 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
1981 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001982 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001983 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
1984 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001985 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001986 }
1987 if (element_object == nullptr) {
1988 return false;
1989 }
1990 }
1991 break;
1992 }
1993 case kDexAnnotationField: {
1994 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1995 if (result_style == kAllRaw) {
1996 annotation_value->value_.SetI(index);
1997 } else {
1998 StackHandleScope<2> hs(self);
1999 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2000 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2001 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2002 klass->GetDexFile(), index, dex_cache, class_loader);
2003 if (field == nullptr) {
2004 return false;
2005 }
2006 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002007 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2008 if (pointer_size == PointerSize::k64) {
2009 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002010 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002011 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002012 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002013 if (element_object == nullptr) {
2014 return false;
2015 }
2016 }
2017 break;
2018 }
2019 case kDexAnnotationEnum: {
2020 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2021 if (result_style == kAllRaw) {
2022 annotation_value->value_.SetI(index);
2023 } else {
2024 StackHandleScope<3> hs(self);
2025 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2026 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2027 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2028 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002029 if (enum_field == nullptr) {
2030 return false;
2031 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002032 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002033 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2034 element_object = enum_field->GetObject(field_class.Get());
2035 set_object = true;
2036 }
2037 }
2038 break;
2039 }
2040 case kDexAnnotationArray:
2041 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2042 return false;
2043 } else {
2044 ScopedObjectAccessUnchecked soa(self);
2045 StackHandleScope<2> hs(self);
2046 uint32_t size = DecodeUnsignedLeb128(&annotation);
2047 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2048 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2049 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2050 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2051 if (new_array.Get() == nullptr) {
2052 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2053 return false;
2054 }
2055 AnnotationValue new_annotation_value;
2056 for (uint32_t i = 0; i < size; ++i) {
2057 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2058 kPrimitivesOrObjects)) {
2059 return false;
2060 }
2061 if (!component_type->IsPrimitive()) {
2062 mirror::Object* obj = new_annotation_value.value_.GetL();
2063 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2064 } else {
2065 switch (new_annotation_value.type_) {
2066 case kDexAnnotationByte:
2067 new_array->AsByteArray()->SetWithoutChecks<false>(
2068 i, new_annotation_value.value_.GetB());
2069 break;
2070 case kDexAnnotationShort:
2071 new_array->AsShortArray()->SetWithoutChecks<false>(
2072 i, new_annotation_value.value_.GetS());
2073 break;
2074 case kDexAnnotationChar:
2075 new_array->AsCharArray()->SetWithoutChecks<false>(
2076 i, new_annotation_value.value_.GetC());
2077 break;
2078 case kDexAnnotationInt:
2079 new_array->AsIntArray()->SetWithoutChecks<false>(
2080 i, new_annotation_value.value_.GetI());
2081 break;
2082 case kDexAnnotationLong:
2083 new_array->AsLongArray()->SetWithoutChecks<false>(
2084 i, new_annotation_value.value_.GetJ());
2085 break;
2086 case kDexAnnotationFloat:
2087 new_array->AsFloatArray()->SetWithoutChecks<false>(
2088 i, new_annotation_value.value_.GetF());
2089 break;
2090 case kDexAnnotationDouble:
2091 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2092 i, new_annotation_value.value_.GetD());
2093 break;
2094 case kDexAnnotationBoolean:
2095 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2096 i, new_annotation_value.value_.GetZ());
2097 break;
2098 default:
2099 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2100 return false;
2101 }
2102 }
2103 }
2104 element_object = new_array.Get();
2105 set_object = true;
2106 width = 0;
2107 }
2108 break;
2109 case kDexAnnotationAnnotation:
2110 if (result_style == kAllRaw) {
2111 return false;
2112 }
2113 element_object = ProcessEncodedAnnotation(klass, &annotation);
2114 if (element_object == nullptr) {
2115 return false;
2116 }
2117 set_object = true;
2118 width = 0;
2119 break;
2120 case kDexAnnotationNull:
2121 if (result_style == kAllRaw) {
2122 annotation_value->value_.SetI(0);
2123 } else {
2124 CHECK(element_object == nullptr);
2125 set_object = true;
2126 }
2127 width = 0;
2128 break;
2129 default:
2130 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2131 return false;
2132 }
2133
2134 annotation += width;
2135 *annotation_ptr = annotation;
2136
2137 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2138 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2139 set_object = true;
2140 }
2141
2142 if (set_object) {
2143 annotation_value->value_.SetL(element_object);
2144 }
2145
2146 return true;
2147}
2148
2149mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2150 const uint8_t** annotation) const {
2151 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2152 uint32_t size = DecodeUnsignedLeb128(annotation);
2153
2154 Thread* self = Thread::Current();
2155 ScopedObjectAccessUnchecked soa(self);
2156 StackHandleScope<2> hs(self);
2157 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2158 Handle<mirror::Class> annotation_class(hs.NewHandle(
2159 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2160 if (annotation_class.Get() == nullptr) {
2161 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2162 << type_index;
2163 DCHECK(Thread::Current()->IsExceptionPending());
2164 Thread::Current()->ClearException();
2165 return nullptr;
2166 }
2167
2168 mirror::Class* annotation_member_class =
2169 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2170 mirror::Class* annotation_member_array_class =
2171 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002172 if (annotation_member_array_class == nullptr) {
2173 return nullptr;
2174 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002175 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002176 if (size > 0) {
2177 element_array =
2178 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2179 if (element_array == nullptr) {
2180 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2181 return nullptr;
2182 }
2183 }
2184
2185 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2186 for (uint32_t i = 0; i < size; ++i) {
2187 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2188 if (new_member == nullptr) {
2189 return nullptr;
2190 }
2191 h_element_array->SetWithoutChecks<false>(i, new_member);
2192 }
2193
2194 JValue result;
2195 ArtMethod* create_annotation_method =
2196 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2197 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2198 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2199 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2200 if (self->IsExceptionPending()) {
2201 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2202 return nullptr;
2203 }
2204
2205 return result.GetL();
2206}
2207
2208const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2209 const char* descriptor, uint32_t visibility) const {
2210 const AnnotationItem* result = nullptr;
2211 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2212 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002213 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002214 continue;
2215 }
2216 const uint8_t* annotation = annotation_item->annotation_;
2217 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2218
2219 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2220 result = annotation_item;
2221 break;
2222 }
2223 }
2224 return result;
2225}
2226
2227const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2228 DecodeUnsignedLeb128(&annotation); // unused type_index
2229 uint32_t size = DecodeUnsignedLeb128(&annotation);
2230
2231 while (size != 0) {
2232 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2233 const char* element_name = GetStringData(GetStringId(element_name_index));
2234 if (strcmp(name, element_name) == 0) {
2235 return annotation;
2236 }
2237 SkipAnnotationValue(&annotation);
2238 size--;
2239 }
2240 return nullptr;
2241}
2242
2243bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2244 const uint8_t* annotation = *annotation_ptr;
2245 uint8_t header_byte = *(annotation++);
2246 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2247 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2248 int32_t width = value_arg + 1;
2249
2250 switch (value_type) {
2251 case kDexAnnotationByte:
2252 case kDexAnnotationShort:
2253 case kDexAnnotationChar:
2254 case kDexAnnotationInt:
2255 case kDexAnnotationLong:
2256 case kDexAnnotationFloat:
2257 case kDexAnnotationDouble:
2258 case kDexAnnotationString:
2259 case kDexAnnotationType:
2260 case kDexAnnotationMethod:
2261 case kDexAnnotationField:
2262 case kDexAnnotationEnum:
2263 break;
2264 case kDexAnnotationArray:
2265 {
2266 uint32_t size = DecodeUnsignedLeb128(&annotation);
2267 while (size--) {
2268 if (!SkipAnnotationValue(&annotation)) {
2269 return false;
2270 }
2271 }
2272 width = 0;
2273 break;
2274 }
2275 case kDexAnnotationAnnotation:
2276 {
2277 DecodeUnsignedLeb128(&annotation); // unused type_index
2278 uint32_t size = DecodeUnsignedLeb128(&annotation);
2279 while (size--) {
2280 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2281 if (!SkipAnnotationValue(&annotation)) {
2282 return false;
2283 }
2284 }
2285 width = 0;
2286 break;
2287 }
2288 case kDexAnnotationBoolean:
2289 case kDexAnnotationNull:
2290 width = 0;
2291 break;
2292 default:
2293 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2294 return false;
2295 }
2296
2297 annotation += width;
2298 *annotation_ptr = annotation;
2299 return true;
2300}
2301
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002302std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2303 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2304 dex_file.GetLocation().c_str(),
2305 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2306 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2307 return os;
2308}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002309
Ian Rogersd91d6d62013-09-25 20:26:14 -07002310std::string Signature::ToString() const {
2311 if (dex_file_ == nullptr) {
2312 CHECK(proto_id_ == nullptr);
2313 return "<no signature>";
2314 }
2315 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2316 std::string result;
2317 if (params == nullptr) {
2318 result += "()";
2319 } else {
2320 result += "(";
2321 for (uint32_t i = 0; i < params->Size(); ++i) {
2322 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2323 }
2324 result += ")";
2325 }
2326 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2327 return result;
2328}
2329
Vladimir Markod9cffea2013-11-25 15:08:02 +00002330bool Signature::operator==(const StringPiece& rhs) const {
2331 if (dex_file_ == nullptr) {
2332 return false;
2333 }
2334 StringPiece tail(rhs);
2335 if (!tail.starts_with("(")) {
2336 return false; // Invalid signature
2337 }
2338 tail.remove_prefix(1); // "(";
2339 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2340 if (params != nullptr) {
2341 for (uint32_t i = 0; i < params->Size(); ++i) {
2342 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2343 if (!tail.starts_with(param)) {
2344 return false;
2345 }
2346 tail.remove_prefix(param.length());
2347 }
2348 }
2349 if (!tail.starts_with(")")) {
2350 return false;
2351 }
2352 tail.remove_prefix(1); // ")";
2353 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2354}
2355
Ian Rogersd91d6d62013-09-25 20:26:14 -07002356std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2357 return os << sig.ToString();
2358}
2359
Ian Rogers0571d352011-11-03 19:51:38 -07002360// Decodes the header section from the class data bytes.
2361void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002362 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002363 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2364 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2365 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2366 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2367}
2368
2369void ClassDataItemIterator::ReadClassDataField() {
2370 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2371 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002372 // The user of the iterator is responsible for checking if there
2373 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002374}
2375
2376void ClassDataItemIterator::ReadClassDataMethod() {
2377 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2378 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2379 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002380 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002381 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002382 }
Ian Rogers0571d352011-11-03 19:51:38 -07002383}
2384
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002385EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002386 const DexFile& dex_file,
2387 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002388 : EncodedStaticFieldValueIterator(dex_file,
2389 nullptr,
2390 nullptr,
2391 nullptr,
2392 class_def,
2393 -1,
2394 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002395}
2396
2397EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002398 const DexFile& dex_file,
2399 Handle<mirror::DexCache>* dex_cache,
2400 Handle<mirror::ClassLoader>* class_loader,
2401 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002402 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002403 : EncodedStaticFieldValueIterator(dex_file,
2404 dex_cache, class_loader,
2405 linker,
2406 class_def,
2407 -1,
2408 kByte) {
2409 DCHECK(dex_cache_ != nullptr);
2410 DCHECK(class_loader_ != nullptr);
2411}
2412
2413EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2414 const DexFile& dex_file,
2415 Handle<mirror::DexCache>* dex_cache,
2416 Handle<mirror::ClassLoader>* class_loader,
2417 ClassLinker* linker,
2418 const DexFile::ClassDef& class_def,
2419 size_t pos,
2420 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002421 : dex_file_(dex_file),
2422 dex_cache_(dex_cache),
2423 class_loader_(class_loader),
2424 linker_(linker),
2425 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002426 pos_(pos),
2427 type_(type) {
2428 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002429 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002430 array_size_ = 0;
2431 } else {
2432 array_size_ = DecodeUnsignedLeb128(&ptr_);
2433 }
2434 if (array_size_ > 0) {
2435 Next();
2436 }
2437}
2438
2439void EncodedStaticFieldValueIterator::Next() {
2440 pos_++;
2441 if (pos_ >= array_size_) {
2442 return;
2443 }
Ian Rogers13735952014-10-08 12:43:28 -07002444 uint8_t value_type = *ptr_++;
2445 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002446 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002447 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002448 switch (type_) {
2449 case kBoolean:
2450 jval_.i = (value_arg != 0) ? 1 : 0;
2451 width = 0;
2452 break;
2453 case kByte:
2454 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002455 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002456 break;
2457 case kShort:
2458 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002459 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002460 break;
2461 case kChar:
2462 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002463 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002464 break;
2465 case kInt:
2466 jval_.i = ReadSignedInt(ptr_, value_arg);
2467 break;
2468 case kLong:
2469 jval_.j = ReadSignedLong(ptr_, value_arg);
2470 break;
2471 case kFloat:
2472 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2473 break;
2474 case kDouble:
2475 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2476 break;
2477 case kString:
2478 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002479 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2480 break;
2481 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002482 case kMethod:
2483 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002484 case kArray:
2485 case kAnnotation:
2486 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002487 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002488 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002489 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002490 width = 0;
2491 break;
2492 default:
2493 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002494 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002495 }
2496 ptr_ += width;
2497}
2498
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002499template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002500void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002501 DCHECK(dex_cache_ != nullptr);
2502 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002503 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002504 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2505 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002506 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2507 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2508 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2509 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2510 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2511 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2512 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002513 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002514 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002515 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002516 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002517 break;
2518 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002519 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002520 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2521 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002522 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002523 break;
2524 }
Ian Rogers0571d352011-11-03 19:51:38 -07002525 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2526 }
2527}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002528template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2529template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002530
2531CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2532 handler_.address_ = -1;
2533 int32_t offset = -1;
2534
2535 // Short-circuit the overwhelmingly common cases.
2536 switch (code_item.tries_size_) {
2537 case 0:
2538 break;
2539 case 1: {
2540 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2541 uint32_t start = tries->start_addr_;
2542 if (address >= start) {
2543 uint32_t end = start + tries->insn_count_;
2544 if (address < end) {
2545 offset = tries->handler_off_;
2546 }
2547 }
2548 break;
2549 }
2550 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002551 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002552 }
Logan Chien736df022012-04-27 16:25:57 +08002553 Init(code_item, offset);
2554}
2555
2556CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2557 const DexFile::TryItem& try_item) {
2558 handler_.address_ = -1;
2559 Init(code_item, try_item.handler_off_);
2560}
2561
2562void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2563 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002564 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002565 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002566 } else {
2567 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002568 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002569 remaining_count_ = -1;
2570 catch_all_ = false;
2571 DCHECK(!HasNext());
2572 }
2573}
2574
Ian Rogers13735952014-10-08 12:43:28 -07002575void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002576 current_data_ = handler_data;
2577 remaining_count_ = DecodeSignedLeb128(&current_data_);
2578
2579 // If remaining_count_ is non-positive, then it is the negative of
2580 // the number of catch types, and the catches are followed by a
2581 // catch-all handler.
2582 if (remaining_count_ <= 0) {
2583 catch_all_ = true;
2584 remaining_count_ = -remaining_count_;
2585 } else {
2586 catch_all_ = false;
2587 }
2588 Next();
2589}
2590
2591void CatchHandlerIterator::Next() {
2592 if (remaining_count_ > 0) {
2593 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2594 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2595 remaining_count_--;
2596 return;
2597 }
2598
2599 if (catch_all_) {
2600 handler_.type_idx_ = DexFile::kDexNoIndex16;
2601 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2602 catch_all_ = false;
2603 return;
2604 }
2605
2606 // no more handler
2607 remaining_count_ = -1;
2608}
2609
Carl Shapiro1fb86202011-06-27 17:43:13 -07002610} // namespace art