blob: dff28027f6335bd6a6969eb237df0cd009e5adc2 [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 }
ganxiaolincd16d0a2016-07-18 11:21:44 +0800341 if (zip_entry->GetUncompressedLength() == 0) {
342 *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
343 *error_code = ZipOpenErrorCode::kDexFileError;
344 return nullptr;
345 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700346 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700347 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700348 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700349 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700350 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700351 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700352 }
Ian Rogers700a4022014-05-19 16:49:03 -0700353 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 error_msg));
355 if (dex_file.get() == nullptr) {
356 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
357 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700358 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700359 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800360 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700361 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700363 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700364 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700365 }
366 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700367 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700368 location.c_str(),
369 verify_checksum,
370 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700371 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700372 return nullptr;
373 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700374 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800375 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700376}
377
Andreas Gampe90e34042015-04-27 20:01:52 -0700378// Technically we do not have a limitation with respect to the number of dex files that can be in a
379// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
380// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
381// seems an excessive number.
382static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
383
Aart Bik37d6a3b2016-06-21 18:30:10 -0700384bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
385 const std::string& location,
386 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800387 std::string* error_msg,
388 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800389 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700390 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700391 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700392 std::unique_ptr<const DexFile> dex_file(
393 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700394 if (dex_file.get() == nullptr) {
395 return false;
396 } else {
397 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800398 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700399
400 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700401
402 // We could try to avoid std::string allocations by working on a char array directly. As we
403 // do not expect a lot of iterations, this seems too involved and brittle.
404
Andreas Gampe90e34042015-04-27 20:01:52 -0700405 for (size_t i = 1; ; ++i) {
406 std::string name = GetMultiDexClassesDexName(i);
407 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700408 std::unique_ptr<const DexFile> next_dex_file(
409 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700410 if (next_dex_file.get() == nullptr) {
411 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
412 LOG(WARNING) << error_msg;
413 }
414 break;
415 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800416 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700417 }
418
Andreas Gampe90e34042015-04-27 20:01:52 -0700419 if (i == kWarnOnManyDexFilesThreshold) {
420 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
421 << " dex files. Please consider coalescing and shrinking the number to "
422 " avoid runtime overhead.";
423 }
424
425 if (i == std::numeric_limits<size_t>::max()) {
426 LOG(ERROR) << "Overflow in number of dex files!";
427 break;
428 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700429 }
430
431 return true;
432 }
433}
434
435
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800436std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
437 size_t size,
438 const std::string& location,
439 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800440 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700441 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800442 std::string* error_msg) {
ganxiaolincd16d0a2016-07-18 11:21:44 +0800443 DCHECK(base != nullptr);
444 DCHECK_NE(size, 0UL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700445 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800446 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700447 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700448 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800449 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700450 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800451 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700452}
453
Ian Rogers13735952014-10-08 12:43:28 -0700454DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800455 const std::string& location,
456 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800457 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700458 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800459 : begin_(base),
460 size_(size),
461 location_(location),
462 location_checksum_(location_checksum),
463 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800464 header_(reinterpret_cast<const Header*>(base)),
465 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
466 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
467 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
468 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
469 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700470 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700471 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700472 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800473 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300474 const uint8_t* lookup_data = (oat_dex_file != nullptr)
475 ? oat_dex_file->GetLookupTableData()
476 : nullptr;
477 if (lookup_data != nullptr) {
478 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
479 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
480 } else {
481 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
482 }
483 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800484}
485
Jesse Wilson6bf19152011-09-29 13:12:33 -0400486DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700487 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
488 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
489 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
490 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400491}
492
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700493bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700494 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700495 return false;
496 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700497 return true;
498}
499
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700500bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800501 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502 std::ostringstream oss;
503 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800504 << " " << header_->magic_[0]
505 << " " << header_->magic_[1]
506 << " " << header_->magic_[2]
507 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700509 return false;
510 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800511 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700512 std::ostringstream oss;
513 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800514 << " " << header_->magic_[4]
515 << " " << header_->magic_[5]
516 << " " << header_->magic_[6]
517 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700518 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700519 return false;
520 }
521 return true;
522}
523
Ian Rogers13735952014-10-08 12:43:28 -0700524bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800525 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
526}
527
Ian Rogers13735952014-10-08 12:43:28 -0700528bool DexFile::IsVersionValid(const uint8_t* magic) {
529 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700530 for (uint32_t i = 0; i < kNumDexVersions; i++) {
531 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
532 return true;
533 }
534 }
535 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800536}
537
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700538uint32_t DexFile::Header::GetVersion() const {
539 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700540 return atoi(version);
541}
542
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800543const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
544 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300545 if (LIKELY(lookup_table_ != nullptr)) {
546 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
547 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700548 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300549
Roland Levillainab880f42016-05-12 16:24:36 +0100550 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300551 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700552 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700553 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700554 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300555 const TypeId* type_id = FindTypeId(descriptor);
556 if (type_id != nullptr) {
557 uint16_t type_idx = GetIndexForTypeId(*type_id);
558 for (size_t i = 0; i < num_class_defs; ++i) {
559 const ClassDef& class_def = GetClassDef(i);
560 if (class_def.class_idx_ == type_idx) {
561 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700562 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700563 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700564 }
Ian Rogers68b56852014-08-29 20:19:11 -0700565 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700566}
567
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700568const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
569 size_t num_class_defs = NumClassDefs();
570 for (size_t i = 0; i < num_class_defs; ++i) {
571 const ClassDef& class_def = GetClassDef(i);
572 if (class_def.class_idx_ == type_idx) {
573 return &class_def;
574 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700575 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700576 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700577}
578
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800579const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100580 const DexFile::StringId& name,
581 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800582 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
583 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
584 const uint32_t name_idx = GetIndexForStringId(name);
585 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700586 int32_t lo = 0;
587 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800588 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700589 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800590 const DexFile::FieldId& field = GetFieldId(mid);
591 if (class_idx > field.class_idx_) {
592 lo = mid + 1;
593 } else if (class_idx < field.class_idx_) {
594 hi = mid - 1;
595 } else {
596 if (name_idx > field.name_idx_) {
597 lo = mid + 1;
598 } else if (name_idx < field.name_idx_) {
599 hi = mid - 1;
600 } else {
601 if (type_idx > field.type_idx_) {
602 lo = mid + 1;
603 } else if (type_idx < field.type_idx_) {
604 hi = mid - 1;
605 } else {
606 return &field;
607 }
608 }
609 }
610 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700611 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800612}
613
614const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700615 const DexFile::StringId& name,
616 const DexFile::ProtoId& signature) const {
617 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800618 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700619 const uint32_t name_idx = GetIndexForStringId(name);
620 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700621 int32_t lo = 0;
622 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700623 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700624 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700625 const DexFile::MethodId& method = GetMethodId(mid);
626 if (class_idx > method.class_idx_) {
627 lo = mid + 1;
628 } else if (class_idx < method.class_idx_) {
629 hi = mid - 1;
630 } else {
631 if (name_idx > method.name_idx_) {
632 lo = mid + 1;
633 } else if (name_idx < method.name_idx_) {
634 hi = mid - 1;
635 } else {
636 if (proto_idx > method.proto_idx_) {
637 lo = mid + 1;
638 } else if (proto_idx < method.proto_idx_) {
639 hi = mid - 1;
640 } else {
641 return &method;
642 }
643 }
644 }
645 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700647}
648
Ian Rogers637c65b2013-05-31 11:46:00 -0700649const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700650 int32_t lo = 0;
651 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700652 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700653 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700654 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700655 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700656 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
657 if (compare > 0) {
658 lo = mid + 1;
659 } else if (compare < 0) {
660 hi = mid - 1;
661 } else {
662 return &str_id;
663 }
664 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700665 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700666}
667
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300668const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
669 int32_t lo = 0;
670 int32_t hi = NumTypeIds() - 1;
671 while (hi >= lo) {
672 int32_t mid = (hi + lo) / 2;
673 const TypeId& type_id = GetTypeId(mid);
674 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
675 const char* str = GetStringData(str_id);
676 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
677 if (compare > 0) {
678 lo = mid + 1;
679 } else if (compare < 0) {
680 hi = mid - 1;
681 } else {
682 return &type_id;
683 }
684 }
685 return nullptr;
686}
687
Vladimir Markoa48aef42014-12-03 17:53:53 +0000688const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700689 int32_t lo = 0;
690 int32_t hi = NumStringIds() - 1;
691 while (hi >= lo) {
692 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700693 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700694 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000695 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700696 if (compare > 0) {
697 lo = mid + 1;
698 } else if (compare < 0) {
699 hi = mid - 1;
700 } else {
701 return &str_id;
702 }
703 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700704 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700705}
706
707const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700708 int32_t lo = 0;
709 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700710 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700711 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700712 const TypeId& type_id = GetTypeId(mid);
713 if (string_idx > type_id.descriptor_idx_) {
714 lo = mid + 1;
715 } else if (string_idx < type_id.descriptor_idx_) {
716 hi = mid - 1;
717 } else {
718 return &type_id;
719 }
720 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700721 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700722}
723
724const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000725 const uint16_t* signature_type_idxs,
726 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700727 int32_t lo = 0;
728 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700729 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700730 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700731 const DexFile::ProtoId& proto = GetProtoId(mid);
732 int compare = return_type_idx - proto.return_type_idx_;
733 if (compare == 0) {
734 DexFileParameterIterator it(*this, proto);
735 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000736 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800737 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700738 it.Next();
739 i++;
740 }
741 if (compare == 0) {
742 if (it.HasNext()) {
743 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000744 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700745 compare = 1;
746 }
747 }
748 }
749 if (compare > 0) {
750 lo = mid + 1;
751 } else if (compare < 0) {
752 hi = mid - 1;
753 } else {
754 return &proto;
755 }
756 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700757 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700758}
759
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000760void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
761 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300762}
763
Ian Rogers0571d352011-11-03 19:51:38 -0700764// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700765bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
766 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700767 if (signature[0] != '(') {
768 return false;
769 }
770 size_t offset = 1;
771 size_t end = signature.size();
772 bool process_return = false;
773 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000774 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700775 char c = signature[offset];
776 offset++;
777 if (c == ')') {
778 process_return = true;
779 continue;
780 }
Ian Rogers0571d352011-11-03 19:51:38 -0700781 while (c == '[') { // process array prefix
782 if (offset >= end) { // expect some descriptor following [
783 return false;
784 }
785 c = signature[offset];
786 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700787 }
788 if (c == 'L') { // process type descriptors
789 do {
790 if (offset >= end) { // unexpected early termination of descriptor
791 return false;
792 }
793 c = signature[offset];
794 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700795 } while (c != ';');
796 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000797 // TODO: avoid creating a std::string just to get a 0-terminated char array
798 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700799 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700800 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700801 return false;
802 }
803 uint16_t type_idx = GetIndexForTypeId(*type_id);
804 if (!process_return) {
805 param_type_idxs->push_back(type_idx);
806 } else {
807 *return_type_idx = type_idx;
808 return offset == end; // return true if the signature had reached a sensible end
809 }
810 }
811 return false; // failed to correctly parse return type
812}
813
Ian Rogersd91d6d62013-09-25 20:26:14 -0700814const Signature DexFile::CreateSignature(const StringPiece& signature) const {
815 uint16_t return_type_idx;
816 std::vector<uint16_t> param_type_indices;
817 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
818 if (!success) {
819 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700820 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700821 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700822 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700823 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700824 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700825 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700826}
827
Mathieu Chartiere401d142015-04-22 13:56:20 -0700828int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700829 // For native method, lineno should be -2 to indicate it is native. Note that
830 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700831 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700832 return -2;
833 }
834
TDYa127c8dc1012012-04-19 07:03:33 -0700835 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700836 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700837
838 // A method with no line number info should return -1
839 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000840 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 return context.line_num_;
842}
843
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700844int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700845 // Note: Signed type is important for max and min.
846 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700847 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700848
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700849 while (min <= max) {
850 int32_t mid = min + ((max - min) / 2);
851
852 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
853 uint32_t start = ti->start_addr_;
854 uint32_t end = start + ti->insn_count_;
855
Ian Rogers0571d352011-11-03 19:51:38 -0700856 if (address < start) {
857 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700858 } else if (address >= end) {
859 min = mid + 1;
860 } else { // We have a winner!
861 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700862 }
863 }
864 // No match.
865 return -1;
866}
867
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700868int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
869 int32_t try_item = FindTryItem(code_item, address);
870 if (try_item == -1) {
871 return -1;
872 } else {
873 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
874 }
875}
876
David Srbeckyb06e28e2015-12-10 13:15:00 +0000877bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
878 DexDebugNewLocalCb local_cb, void* context) const {
879 DCHECK(local_cb != nullptr);
880 if (code_item == nullptr) {
881 return false;
882 }
883 const uint8_t* stream = GetDebugInfoStream(code_item);
884 if (stream == nullptr) {
885 return false;
886 }
887 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700888
David Srbeckyb06e28e2015-12-10 13:15:00 +0000889 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800890 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000891 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
892 local_in_reg[arg_reg].name_ = "this";
893 local_in_reg[arg_reg].descriptor_ = descriptor;
894 local_in_reg[arg_reg].signature_ = nullptr;
895 local_in_reg[arg_reg].start_address_ = 0;
896 local_in_reg[arg_reg].reg_ = arg_reg;
897 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700898 arg_reg++;
899 }
900
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800901 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000902 DecodeUnsignedLeb128(&stream); // Line.
903 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
904 uint32_t i;
905 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700906 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700907 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800908 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000909 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000911 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700912 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000913 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
914 local_in_reg[arg_reg].descriptor_ = descriptor;
915 local_in_reg[arg_reg].signature_ = nullptr;
916 local_in_reg[arg_reg].start_address_ = 0;
917 local_in_reg[arg_reg].reg_ = arg_reg;
918 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700919 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700920 case 'D':
921 case 'J':
922 arg_reg += 2;
923 break;
924 default:
925 arg_reg += 1;
926 break;
927 }
928 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000929 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800930 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
931 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000932 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700933 }
934
David Srbeckyb06e28e2015-12-10 13:15:00 +0000935 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700936 for (;;) {
937 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700938 switch (opcode) {
939 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000940 // Emit all variables which are still alive at the end of the method.
941 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
942 if (local_in_reg[reg].is_live_) {
943 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
944 local_cb(context, local_in_reg[reg]);
945 }
946 }
947 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948 case DBG_ADVANCE_PC:
949 address += DecodeUnsignedLeb128(&stream);
950 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000952 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700953 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700954 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000955 case DBG_START_LOCAL_EXTENDED: {
956 uint16_t reg = DecodeUnsignedLeb128(&stream);
957 if (reg >= code_item->registers_size_) {
958 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800959 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000960 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700961 }
962
David Srbeckyb06e28e2015-12-10 13:15:00 +0000963 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
964 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
965 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700966 if (opcode == DBG_START_LOCAL_EXTENDED) {
967 signature_idx = DecodeUnsignedLeb128P1(&stream);
968 }
969
Shih-wei Liao195487c2011-08-20 13:29:04 -0700970 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000971 if (local_in_reg[reg].is_live_) {
972 local_in_reg[reg].end_address_ = address;
973 local_cb(context, local_in_reg[reg]);
974 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700975
David Srbeckyb06e28e2015-12-10 13:15:00 +0000976 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
977 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
978 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
979 local_in_reg[reg].start_address_ = address;
980 local_in_reg[reg].reg_ = reg;
981 local_in_reg[reg].is_live_ = true;
982 break;
983 }
984 case DBG_END_LOCAL: {
985 uint16_t reg = DecodeUnsignedLeb128(&stream);
986 if (reg >= code_item->registers_size_) {
987 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
988 << code_item->registers_size_ << ") in " << GetLocation();
989 return false;
990 }
991 if (!local_in_reg[reg].is_live_) {
992 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
993 return false;
994 }
995 local_in_reg[reg].end_address_ = address;
996 local_cb(context, local_in_reg[reg]);
997 local_in_reg[reg].is_live_ = false;
998 break;
999 }
1000 case DBG_RESTART_LOCAL: {
1001 uint16_t reg = DecodeUnsignedLeb128(&stream);
1002 if (reg >= code_item->registers_size_) {
1003 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
1004 << code_item->registers_size_ << ") in " << GetLocation();
1005 return false;
1006 }
1007 // If the register is live, the "restart" is superfluous,
1008 // and we don't want to mess with the existing start address.
1009 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001010 local_in_reg[reg].start_address_ = address;
1011 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001012 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001013 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001014 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001015 case DBG_SET_PROLOGUE_END:
1016 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001018 case DBG_SET_FILE:
1019 DecodeUnsignedLeb128P1(&stream); // name.
1020 break;
1021 default:
1022 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1023 break;
1024 }
1025 }
1026}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001027
David Srbeckyb06e28e2015-12-10 13:15:00 +00001028bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1029 void* context) const {
1030 DCHECK(position_cb != nullptr);
1031 if (code_item == nullptr) {
1032 return false;
1033 }
1034 const uint8_t* stream = GetDebugInfoStream(code_item);
1035 if (stream == nullptr) {
1036 return false;
1037 }
1038
1039 PositionInfo entry = PositionInfo();
1040 entry.line_ = DecodeUnsignedLeb128(&stream);
1041 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1042 for (uint32_t i = 0; i < parameters_size; ++i) {
1043 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1044 }
1045
1046 for (;;) {
1047 uint8_t opcode = *stream++;
1048 switch (opcode) {
1049 case DBG_END_SEQUENCE:
1050 return true; // end of stream.
1051 case DBG_ADVANCE_PC:
1052 entry.address_ += DecodeUnsignedLeb128(&stream);
1053 break;
1054 case DBG_ADVANCE_LINE:
1055 entry.line_ += DecodeSignedLeb128(&stream);
1056 break;
1057 case DBG_START_LOCAL:
1058 DecodeUnsignedLeb128(&stream); // reg.
1059 DecodeUnsignedLeb128P1(&stream); // name.
1060 DecodeUnsignedLeb128P1(&stream); // descriptor.
1061 break;
1062 case DBG_START_LOCAL_EXTENDED:
1063 DecodeUnsignedLeb128(&stream); // reg.
1064 DecodeUnsignedLeb128P1(&stream); // name.
1065 DecodeUnsignedLeb128P1(&stream); // descriptor.
1066 DecodeUnsignedLeb128P1(&stream); // signature.
1067 break;
1068 case DBG_END_LOCAL:
1069 case DBG_RESTART_LOCAL:
1070 DecodeUnsignedLeb128(&stream); // reg.
1071 break;
1072 case DBG_SET_PROLOGUE_END:
1073 entry.prologue_end_ = true;
1074 break;
1075 case DBG_SET_EPILOGUE_BEGIN:
1076 entry.epilogue_begin_ = true;
1077 break;
1078 case DBG_SET_FILE: {
1079 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1080 entry.source_file_ = StringDataByIdx(name_idx);
1081 break;
1082 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001083 default: {
1084 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001085 entry.address_ += adjopcode / DBG_LINE_RANGE;
1086 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1087 if (position_cb(context, entry)) {
1088 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001089 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001090 entry.prologue_end_ = false;
1091 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001092 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001093 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001094 }
1095 }
1096}
1097
David Srbeckyb06e28e2015-12-10 13:15:00 +00001098bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001099 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001100
1101 // We know that this callback will be called in
1102 // ascending address order, so keep going until we find
1103 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001104 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001105 // The line number from the previous positions callback
1106 // wil be the final result.
1107 return true;
1108 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001109 context->line_num_ = entry.line_;
1110 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001111 }
1112}
1113
Andreas Gampe833a4852014-05-21 18:46:59 -07001114bool DexFile::IsMultiDexLocation(const char* location) {
1115 return strrchr(location, kMultiDexSeparator) != nullptr;
1116}
1117
Andreas Gampe90e34042015-04-27 20:01:52 -07001118std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1119 if (index == 0) {
1120 return "classes.dex";
1121 } else {
1122 return StringPrintf("classes%zu.dex", index + 1);
1123 }
1124}
1125
1126std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1127 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001128 return dex_location;
1129 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001130 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001131 }
1132}
1133
1134std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1135 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001136 std::string base_location = GetBaseLocation(dex_location);
1137 const char* suffix = dex_location + base_location.size();
1138 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1139 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1140 if (path != nullptr && path.get() != base_location) {
1141 return std::string(path.get()) + suffix;
1142 } else if (suffix[0] == 0) {
1143 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001144 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001145 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001146 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001147}
1148
Jeff Hao13e748b2015-08-25 20:44:19 +00001149// Read a signed integer. "zwidth" is the zero-based byte count.
1150static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1151 int32_t val = 0;
1152 for (int i = zwidth; i >= 0; --i) {
1153 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1154 }
1155 val >>= (3 - zwidth) * 8;
1156 return val;
1157}
1158
1159// Read an unsigned integer. "zwidth" is the zero-based byte count,
1160// "fill_on_right" indicates which side we want to zero-fill from.
1161static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1162 uint32_t val = 0;
1163 for (int i = zwidth; i >= 0; --i) {
1164 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1165 }
1166 if (!fill_on_right) {
1167 val >>= (3 - zwidth) * 8;
1168 }
1169 return val;
1170}
1171
1172// Read a signed long. "zwidth" is the zero-based byte count.
1173static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1174 int64_t val = 0;
1175 for (int i = zwidth; i >= 0; --i) {
1176 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1177 }
1178 val >>= (7 - zwidth) * 8;
1179 return val;
1180}
1181
1182// Read an unsigned long. "zwidth" is the zero-based byte count,
1183// "fill_on_right" indicates which side we want to zero-fill from.
1184static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1185 uint64_t val = 0;
1186 for (int i = zwidth; i >= 0; --i) {
1187 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1188 }
1189 if (!fill_on_right) {
1190 val >>= (7 - zwidth) * 8;
1191 }
1192 return val;
1193}
1194
Jeff Hao3d080862016-05-26 18:39:17 -07001195// Checks that visibility is as expected. Includes special behavior for M and
1196// before to allow runtime and build visibility when expecting runtime.
1197static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1198 if (expected == DexFile::kDexVisibilityRuntime) {
1199 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1200 if (sdk_version > 0 && sdk_version <= 23) {
1201 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1202 }
1203 }
1204 return actual == expected;
1205}
1206
Jeff Hao13e748b2015-08-25 20:44:19 +00001207const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1208 mirror::Class* klass = field->GetDeclaringClass();
1209 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1210 if (annotations_dir == nullptr) {
1211 return nullptr;
1212 }
1213 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1214 if (field_annotations == nullptr) {
1215 return nullptr;
1216 }
1217 uint32_t field_index = field->GetDexFieldIndex();
1218 uint32_t field_count = annotations_dir->fields_size_;
1219 for (uint32_t i = 0; i < field_count; ++i) {
1220 if (field_annotations[i].field_idx_ == field_index) {
1221 return GetFieldAnnotationSetItem(field_annotations[i]);
1222 }
1223 }
1224 return nullptr;
1225}
1226
1227mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1228 Handle<mirror::Class> annotation_class) const {
1229 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1230 if (annotation_set == nullptr) {
1231 return nullptr;
1232 }
1233 StackHandleScope<1> hs(Thread::Current());
1234 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1235 return GetAnnotationObjectFromAnnotationSet(
1236 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1237}
1238
1239mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1240 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1241 StackHandleScope<1> hs(Thread::Current());
1242 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1243 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1244}
1245
Jeff Hao2a5892f2015-08-31 15:00:40 -07001246mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001247 const {
1248 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1249 if (annotation_set == nullptr) {
1250 return nullptr;
1251 }
1252 StackHandleScope<1> hs(Thread::Current());
1253 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1254 return GetSignatureValue(field_class, annotation_set);
1255}
1256
1257bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1258 const {
1259 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1260 if (annotation_set == nullptr) {
1261 return false;
1262 }
1263 StackHandleScope<1> hs(Thread::Current());
1264 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1265 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1266 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1267 return annotation_item != nullptr;
1268}
1269
1270const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1271 mirror::Class* klass = method->GetDeclaringClass();
1272 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1273 if (annotations_dir == nullptr) {
1274 return nullptr;
1275 }
1276 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1277 if (method_annotations == nullptr) {
1278 return nullptr;
1279 }
1280 uint32_t method_index = method->GetDexMethodIndex();
1281 uint32_t method_count = annotations_dir->methods_size_;
1282 for (uint32_t i = 0; i < method_count; ++i) {
1283 if (method_annotations[i].method_idx_ == method_index) {
1284 return GetMethodAnnotationSetItem(method_annotations[i]);
1285 }
1286 }
1287 return nullptr;
1288}
1289
1290const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1291 const {
1292 mirror::Class* klass = method->GetDeclaringClass();
1293 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1294 if (annotations_dir == nullptr) {
1295 return nullptr;
1296 }
1297 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1298 if (parameter_annotations == nullptr) {
1299 return nullptr;
1300 }
1301 uint32_t method_index = method->GetDexMethodIndex();
1302 uint32_t parameter_count = annotations_dir->parameters_size_;
1303 for (uint32_t i = 0; i < parameter_count; ++i) {
1304 if (parameter_annotations[i].method_idx_ == method_index) {
1305 return &parameter_annotations[i];
1306 }
1307 }
1308 return nullptr;
1309}
1310
1311mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1312 mirror::Class* klass = method->GetDeclaringClass();
1313 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1314 if (annotations_dir == nullptr) {
1315 return nullptr;
1316 }
1317 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1318 if (annotation_set == nullptr) {
1319 return nullptr;
1320 }
1321 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1322 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1323 if (annotation_item == nullptr) {
1324 return nullptr;
1325 }
1326 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1327 if (annotation == nullptr) {
1328 return nullptr;
1329 }
1330 uint8_t header_byte = *(annotation++);
1331 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1332 return nullptr;
1333 }
1334 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1335 if (annotation == nullptr) {
1336 return nullptr;
1337 }
1338 AnnotationValue annotation_value;
1339 StackHandleScope<2> hs(Thread::Current());
1340 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe542451c2016-07-26 09:02:02 -07001341 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Vladimir Marko05792b92015-08-03 11:56:49 +01001342 Handle<mirror::Class> return_type(hs.NewHandle(
1343 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001344 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1345 return nullptr;
1346 }
1347 return annotation_value.value_.GetL();
1348}
1349
1350mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1351 Handle<mirror::Class> annotation_class) const {
1352 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1353 if (annotation_set == nullptr) {
1354 return nullptr;
1355 }
1356 StackHandleScope<1> hs(Thread::Current());
1357 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1358 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1359 kDexVisibilityRuntime, annotation_class);
1360}
1361
1362mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1363 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1364 StackHandleScope<1> hs(Thread::Current());
1365 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1366 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1367}
1368
Jeff Hao2a5892f2015-08-31 15:00:40 -07001369mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001370 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1371 if (annotation_set == nullptr) {
1372 return nullptr;
1373 }
1374 StackHandleScope<1> hs(Thread::Current());
1375 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1376 return GetThrowsValue(method_class, annotation_set);
1377}
1378
1379mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1380 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1381 if (parameter_annotations == nullptr) {
1382 return nullptr;
1383 }
1384 const AnnotationSetRefList* set_ref_list =
1385 GetParameterAnnotationSetRefList(parameter_annotations);
1386 if (set_ref_list == nullptr) {
1387 return nullptr;
1388 }
1389 uint32_t size = set_ref_list->size_;
1390 StackHandleScope<1> hs(Thread::Current());
1391 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1392 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1393}
1394
Jeff Hao1133db72016-04-04 19:50:14 -07001395mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1396 const {
1397 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1398 if (annotation_set == nullptr) {
1399 return nullptr;
1400 }
1401 StackHandleScope<1> hs(Thread::Current());
1402 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1403 return GetSignatureValue(method_class, annotation_set);
1404}
1405
Jeff Hao13e748b2015-08-25 20:44:19 +00001406bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1407 const {
1408 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1409 if (annotation_set == nullptr) {
1410 return false;
1411 }
1412 StackHandleScope<1> hs(Thread::Current());
1413 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1414 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1415 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001416 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001417}
1418
1419const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1420 const {
1421 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1422 if (annotations_dir == nullptr) {
1423 return nullptr;
1424 }
1425 return GetClassAnnotationSet(annotations_dir);
1426}
1427
1428mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1429 Handle<mirror::Class> annotation_class) const {
1430 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1431 if (annotation_set == nullptr) {
1432 return nullptr;
1433 }
1434 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1435 annotation_class);
1436}
1437
1438mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1439 const {
1440 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1441 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1442}
1443
Jeff Hao2a5892f2015-08-31 15:00:40 -07001444mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1445 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1446 if (annotation_set == nullptr) {
1447 return nullptr;
1448 }
1449 const AnnotationItem* annotation_item = SearchAnnotationSet(
1450 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1451 if (annotation_item == nullptr) {
1452 return nullptr;
1453 }
1454 StackHandleScope<1> hs(Thread::Current());
1455 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1456 Handle<mirror::Class> class_array_class(hs.NewHandle(
1457 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1458 if (class_array_class.Get() == nullptr) {
1459 return nullptr;
1460 }
1461 mirror::Object* obj = GetAnnotationValue(
1462 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1463 if (obj == nullptr) {
1464 return nullptr;
1465 }
1466 return obj->AsObjectArray<mirror::Class>();
1467}
1468
1469mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1470 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1471 if (annotation_set == nullptr) {
1472 return nullptr;
1473 }
1474 const AnnotationItem* annotation_item = SearchAnnotationSet(
1475 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1476 if (annotation_item == nullptr) {
1477 return nullptr;
1478 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001479 mirror::Object* obj = GetAnnotationValue(klass,
1480 annotation_item,
1481 "value",
1482 ScopedNullHandle<mirror::Class>(),
1483 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001484 if (obj == nullptr) {
1485 return nullptr;
1486 }
1487 return obj->AsClass();
1488}
1489
1490mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1491 mirror::Class* declaring_class = GetDeclaringClass(klass);
1492 if (declaring_class != nullptr) {
1493 return declaring_class;
1494 }
1495 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1496 if (annotation_set == nullptr) {
1497 return nullptr;
1498 }
1499 const AnnotationItem* annotation_item = SearchAnnotationSet(
1500 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1501 if (annotation_item == nullptr) {
1502 return nullptr;
1503 }
1504 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1505 if (annotation == nullptr) {
1506 return nullptr;
1507 }
1508 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001509 if (!ProcessAnnotationValue(klass,
1510 &annotation,
1511 &annotation_value,
1512 ScopedNullHandle<mirror::Class>(),
1513 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001514 return nullptr;
1515 }
1516 if (annotation_value.type_ != kDexAnnotationMethod) {
1517 return nullptr;
1518 }
1519 StackHandleScope<2> hs(Thread::Current());
1520 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1521 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1522 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1523 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1524 if (method == nullptr) {
1525 return nullptr;
1526 }
1527 return method->GetDeclaringClass();
1528}
1529
1530mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1531 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1532 if (annotation_set == nullptr) {
1533 return nullptr;
1534 }
1535 const AnnotationItem* annotation_item = SearchAnnotationSet(
1536 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1537 if (annotation_item == nullptr) {
1538 return nullptr;
1539 }
1540 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001541 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001542}
1543
1544bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1545 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1546 if (annotation_set == nullptr) {
1547 return false;
1548 }
1549 const AnnotationItem* annotation_item = SearchAnnotationSet(
1550 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1551 if (annotation_item == nullptr) {
1552 return false;
1553 }
1554 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1555 if (annotation == nullptr) {
1556 return false;
1557 }
1558 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001559 if (!ProcessAnnotationValue(klass,
1560 &annotation,
1561 &annotation_value,
1562 ScopedNullHandle<mirror::Class>(),
1563 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001564 return false;
1565 }
1566 if (annotation_value.type_ != kDexAnnotationNull &&
1567 annotation_value.type_ != kDexAnnotationString) {
1568 return false;
1569 }
1570 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1571 return true;
1572}
1573
1574bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1575 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1576 if (annotation_set == nullptr) {
1577 return false;
1578 }
1579 const AnnotationItem* annotation_item = SearchAnnotationSet(
1580 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1581 if (annotation_item == nullptr) {
1582 return false;
1583 }
1584 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1585 if (annotation == nullptr) {
1586 return false;
1587 }
1588 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001589 if (!ProcessAnnotationValue(klass,
1590 &annotation,
1591 &annotation_value,
1592 ScopedNullHandle<mirror::Class>(),
1593 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001594 return false;
1595 }
1596 if (annotation_value.type_ != kDexAnnotationInt) {
1597 return false;
1598 }
1599 *flags = annotation_value.value_.GetI();
1600 return true;
1601}
1602
Jeff Hao1133db72016-04-04 19:50:14 -07001603mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1604 Handle<mirror::Class> klass) const {
1605 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1606 if (annotation_set == nullptr) {
1607 return nullptr;
1608 }
1609 return GetSignatureValue(klass, annotation_set);
1610}
1611
Jeff Hao13e748b2015-08-25 20:44:19 +00001612bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1613 Handle<mirror::Class> annotation_class) const {
1614 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1615 if (annotation_set == nullptr) {
1616 return false;
1617 }
1618 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1619 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001620 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001621}
1622
1623mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1624 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1625 Thread* self = Thread::Current();
1626 ScopedObjectAccessUnchecked soa(self);
1627 StackHandleScope<5> hs(self);
1628 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1629 const char* name = StringDataByIdx(element_name_index);
1630 Handle<mirror::String> string_name(
1631 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1632
Andreas Gampe542451c2016-07-26 09:02:02 -07001633 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001634 ArtMethod* annotation_method =
Andreas Gampe542451c2016-07-26 09:02:02 -07001635 annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
Jeff Hao13e748b2015-08-25 20:44:19 +00001636 if (annotation_method == nullptr) {
1637 return nullptr;
1638 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001639 Handle<mirror::Class> method_return(hs.NewHandle(
1640 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001641
1642 AnnotationValue annotation_value;
1643 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1644 return nullptr;
1645 }
1646 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1647
1648 mirror::Class* annotation_member_class =
1649 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1650 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001651 mirror::Method* method_obj_ptr;
1652 DCHECK(!Runtime::Current()->IsActiveTransaction());
Andreas Gampe542451c2016-07-26 09:02:02 -07001653 if (pointer_size == PointerSize::k64) {
1654 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
1655 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001656 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001657 method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
1658 self, annotation_method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001659 }
1660 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001661
1662 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1663 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1664 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1665 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1666 return nullptr;
1667 }
1668
1669 JValue result;
1670 ArtMethod* annotation_member_init =
1671 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1672 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1673 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1674 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1675 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1676 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1677 };
1678 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1679 if (self->IsExceptionPending()) {
1680 LOG(INFO) << "Exception in AnnotationMember.<init>";
1681 return nullptr;
1682 }
1683
1684 return new_member.Get();
1685}
1686
1687const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1688 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1689 Handle<mirror::Class> annotation_class) const {
1690 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1691 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001692 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001693 continue;
1694 }
1695 const uint8_t* annotation = annotation_item->annotation_;
1696 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1697 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1698 klass->GetDexFile(), type_index, klass.Get());
1699 if (resolved_class == nullptr) {
1700 std::string temp;
1701 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1702 klass->GetDescriptor(&temp), type_index);
1703 CHECK(Thread::Current()->IsExceptionPending());
1704 Thread::Current()->ClearException();
1705 continue;
1706 }
1707 if (resolved_class == annotation_class.Get()) {
1708 return annotation_item;
1709 }
1710 }
1711
1712 return nullptr;
1713}
1714
1715mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1716 const AnnotationSetItem* annotation_set, uint32_t visibility,
1717 Handle<mirror::Class> annotation_class) const {
1718 const AnnotationItem* annotation_item =
1719 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1720 if (annotation_item == nullptr) {
1721 return nullptr;
1722 }
1723 const uint8_t* annotation = annotation_item->annotation_;
1724 return ProcessEncodedAnnotation(klass, &annotation);
1725}
1726
1727mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1728 const AnnotationItem* annotation_item, const char* annotation_name,
1729 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1730 const uint8_t* annotation =
1731 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1732 if (annotation == nullptr) {
1733 return nullptr;
1734 }
1735 AnnotationValue annotation_value;
1736 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1737 return nullptr;
1738 }
1739 if (annotation_value.type_ != expected_type) {
1740 return nullptr;
1741 }
1742 return annotation_value.value_.GetL();
1743}
1744
Jeff Hao2a5892f2015-08-31 15:00:40 -07001745mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001746 const AnnotationSetItem* annotation_set) const {
1747 StackHandleScope<1> hs(Thread::Current());
1748 const AnnotationItem* annotation_item =
1749 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1750 if (annotation_item == nullptr) {
1751 return nullptr;
1752 }
1753 mirror::Class* string_class = mirror::String::GetJavaLangString();
1754 Handle<mirror::Class> string_array_class(hs.NewHandle(
1755 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001756 if (string_array_class.Get() == nullptr) {
1757 return nullptr;
1758 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001759 mirror::Object* obj =
1760 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1761 if (obj == nullptr) {
1762 return nullptr;
1763 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001764 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001765}
1766
Jeff Hao2a5892f2015-08-31 15:00:40 -07001767mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001768 const AnnotationSetItem* annotation_set) const {
1769 StackHandleScope<1> hs(Thread::Current());
1770 const AnnotationItem* annotation_item =
1771 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1772 if (annotation_item == nullptr) {
1773 return nullptr;
1774 }
1775 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1776 Handle<mirror::Class> class_array_class(hs.NewHandle(
1777 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001778 if (class_array_class.Get() == nullptr) {
1779 return nullptr;
1780 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001781 mirror::Object* obj =
1782 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1783 if (obj == nullptr) {
1784 return nullptr;
1785 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001786 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001787}
1788
1789mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1790 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1791 Thread* self = Thread::Current();
1792 ScopedObjectAccessUnchecked soa(self);
1793 StackHandleScope<2> hs(self);
1794 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1795 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1796 if (annotation_set == nullptr) {
1797 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1798 }
1799
1800 uint32_t size = annotation_set->size_;
1801 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1802 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1803 if (result.Get() == nullptr) {
1804 return nullptr;
1805 }
1806
1807 uint32_t dest_index = 0;
1808 for (uint32_t i = 0; i < size; ++i) {
1809 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001810 // Note that we do not use IsVisibilityCompatible here because older code
1811 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001812 if (annotation_item->visibility_ != visibility) {
1813 continue;
1814 }
1815 const uint8_t* annotation = annotation_item->annotation_;
1816 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1817 if (annotation_obj != nullptr) {
1818 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1819 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001820 } else if (self->IsExceptionPending()) {
1821 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001822 }
1823 }
1824
1825 if (dest_index == size) {
1826 return result.Get();
1827 }
1828
1829 mirror::ObjectArray<mirror::Object>* trimmed_result =
1830 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001831 if (trimmed_result == nullptr) {
1832 return nullptr;
1833 }
1834
Jeff Hao13e748b2015-08-25 20:44:19 +00001835 for (uint32_t i = 0; i < dest_index; ++i) {
1836 mirror::Object* obj = result->GetWithoutChecks(i);
1837 trimmed_result->SetWithoutChecks<false>(i, obj);
1838 }
1839
1840 return trimmed_result;
1841}
1842
1843mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1844 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1845 Thread* self = Thread::Current();
1846 ScopedObjectAccessUnchecked soa(self);
1847 StackHandleScope<1> hs(self);
1848 mirror::Class* annotation_array_class =
1849 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1850 mirror::Class* annotation_array_array_class =
1851 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001852 if (annotation_array_array_class == nullptr) {
1853 return nullptr;
1854 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001855 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1856 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1857 if (annotation_array_array.Get() == nullptr) {
1858 LOG(ERROR) << "Annotation set ref array allocation failed";
1859 return nullptr;
1860 }
1861 for (uint32_t index = 0; index < size; ++index) {
1862 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1863 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1864 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1865 if (annotation_set == nullptr) {
1866 return nullptr;
1867 }
1868 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1869 }
1870 return annotation_array_array.Get();
1871}
1872
1873bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1874 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1875 DexFile::AnnotationResultStyle result_style) const {
1876 Thread* self = Thread::Current();
1877 mirror::Object* element_object = nullptr;
1878 bool set_object = false;
1879 Primitive::Type primitive_type = Primitive::kPrimVoid;
1880 const uint8_t* annotation = *annotation_ptr;
1881 uint8_t header_byte = *(annotation++);
1882 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1883 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1884 int32_t width = value_arg + 1;
1885 annotation_value->type_ = value_type;
1886
1887 switch (value_type) {
1888 case kDexAnnotationByte:
1889 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1890 primitive_type = Primitive::kPrimByte;
1891 break;
1892 case kDexAnnotationShort:
1893 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1894 primitive_type = Primitive::kPrimShort;
1895 break;
1896 case kDexAnnotationChar:
1897 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1898 false)));
1899 primitive_type = Primitive::kPrimChar;
1900 break;
1901 case kDexAnnotationInt:
1902 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1903 primitive_type = Primitive::kPrimInt;
1904 break;
1905 case kDexAnnotationLong:
1906 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1907 primitive_type = Primitive::kPrimLong;
1908 break;
1909 case kDexAnnotationFloat:
1910 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1911 primitive_type = Primitive::kPrimFloat;
1912 break;
1913 case kDexAnnotationDouble:
1914 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1915 primitive_type = Primitive::kPrimDouble;
1916 break;
1917 case kDexAnnotationBoolean:
1918 annotation_value->value_.SetZ(value_arg != 0);
1919 primitive_type = Primitive::kPrimBoolean;
1920 width = 0;
1921 break;
1922 case kDexAnnotationString: {
1923 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1924 if (result_style == kAllRaw) {
1925 annotation_value->value_.SetI(index);
1926 } else {
1927 StackHandleScope<1> hs(self);
1928 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1929 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1930 klass->GetDexFile(), index, dex_cache);
1931 set_object = true;
1932 if (element_object == nullptr) {
1933 return false;
1934 }
1935 }
1936 break;
1937 }
1938 case kDexAnnotationType: {
1939 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1940 if (result_style == kAllRaw) {
1941 annotation_value->value_.SetI(index);
1942 } else {
1943 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1944 klass->GetDexFile(), index, klass.Get());
1945 set_object = true;
1946 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001947 CHECK(self->IsExceptionPending());
1948 if (result_style == kAllObjects) {
1949 const char* msg = StringByTypeIdx(index);
1950 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1951 element_object = self->GetException();
1952 self->ClearException();
1953 } else {
1954 return false;
1955 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001956 }
1957 }
1958 break;
1959 }
1960 case kDexAnnotationMethod: {
1961 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1962 if (result_style == kAllRaw) {
1963 annotation_value->value_.SetI(index);
1964 } else {
1965 StackHandleScope<2> hs(self);
1966 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1967 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07001968 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1969 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00001970 klass->GetDexFile(), index, dex_cache, class_loader);
1971 if (method == nullptr) {
1972 return false;
1973 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001974 PointerSize pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001975 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07001976 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00001977 if (method->IsConstructor()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001978 if (pointer_size == PointerSize::k64) {
1979 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
1980 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001981 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001982 element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
1983 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001984 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001985 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001986 if (pointer_size == PointerSize::k64) {
1987 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
1988 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001989 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07001990 element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
1991 false>(self, method);
Andreas Gampee01e3642016-07-25 13:06:04 -07001992 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001993 }
1994 if (element_object == nullptr) {
1995 return false;
1996 }
1997 }
1998 break;
1999 }
2000 case kDexAnnotationField: {
2001 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2002 if (result_style == kAllRaw) {
2003 annotation_value->value_.SetI(index);
2004 } else {
2005 StackHandleScope<2> hs(self);
2006 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2007 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2008 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
2009 klass->GetDexFile(), index, dex_cache, class_loader);
2010 if (field == nullptr) {
2011 return false;
2012 }
2013 set_object = true;
Andreas Gampe542451c2016-07-26 09:02:02 -07002014 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2015 if (pointer_size == PointerSize::k64) {
2016 element_object = mirror::Field::CreateFromArtField<PointerSize::k64>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002017 } else {
Andreas Gampe542451c2016-07-26 09:02:02 -07002018 element_object = mirror::Field::CreateFromArtField<PointerSize::k32>(self, field, true);
Andreas Gampee01e3642016-07-25 13:06:04 -07002019 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002020 if (element_object == nullptr) {
2021 return false;
2022 }
2023 }
2024 break;
2025 }
2026 case kDexAnnotationEnum: {
2027 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2028 if (result_style == kAllRaw) {
2029 annotation_value->value_.SetI(index);
2030 } else {
2031 StackHandleScope<3> hs(self);
2032 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2033 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2034 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2035 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002036 if (enum_field == nullptr) {
2037 return false;
2038 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002039 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002040 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2041 element_object = enum_field->GetObject(field_class.Get());
2042 set_object = true;
2043 }
2044 }
2045 break;
2046 }
2047 case kDexAnnotationArray:
2048 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2049 return false;
2050 } else {
2051 ScopedObjectAccessUnchecked soa(self);
2052 StackHandleScope<2> hs(self);
2053 uint32_t size = DecodeUnsignedLeb128(&annotation);
2054 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2055 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2056 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2057 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2058 if (new_array.Get() == nullptr) {
2059 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2060 return false;
2061 }
2062 AnnotationValue new_annotation_value;
2063 for (uint32_t i = 0; i < size; ++i) {
2064 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2065 kPrimitivesOrObjects)) {
2066 return false;
2067 }
2068 if (!component_type->IsPrimitive()) {
2069 mirror::Object* obj = new_annotation_value.value_.GetL();
2070 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2071 } else {
2072 switch (new_annotation_value.type_) {
2073 case kDexAnnotationByte:
2074 new_array->AsByteArray()->SetWithoutChecks<false>(
2075 i, new_annotation_value.value_.GetB());
2076 break;
2077 case kDexAnnotationShort:
2078 new_array->AsShortArray()->SetWithoutChecks<false>(
2079 i, new_annotation_value.value_.GetS());
2080 break;
2081 case kDexAnnotationChar:
2082 new_array->AsCharArray()->SetWithoutChecks<false>(
2083 i, new_annotation_value.value_.GetC());
2084 break;
2085 case kDexAnnotationInt:
2086 new_array->AsIntArray()->SetWithoutChecks<false>(
2087 i, new_annotation_value.value_.GetI());
2088 break;
2089 case kDexAnnotationLong:
2090 new_array->AsLongArray()->SetWithoutChecks<false>(
2091 i, new_annotation_value.value_.GetJ());
2092 break;
2093 case kDexAnnotationFloat:
2094 new_array->AsFloatArray()->SetWithoutChecks<false>(
2095 i, new_annotation_value.value_.GetF());
2096 break;
2097 case kDexAnnotationDouble:
2098 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2099 i, new_annotation_value.value_.GetD());
2100 break;
2101 case kDexAnnotationBoolean:
2102 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2103 i, new_annotation_value.value_.GetZ());
2104 break;
2105 default:
2106 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2107 return false;
2108 }
2109 }
2110 }
2111 element_object = new_array.Get();
2112 set_object = true;
2113 width = 0;
2114 }
2115 break;
2116 case kDexAnnotationAnnotation:
2117 if (result_style == kAllRaw) {
2118 return false;
2119 }
2120 element_object = ProcessEncodedAnnotation(klass, &annotation);
2121 if (element_object == nullptr) {
2122 return false;
2123 }
2124 set_object = true;
2125 width = 0;
2126 break;
2127 case kDexAnnotationNull:
2128 if (result_style == kAllRaw) {
2129 annotation_value->value_.SetI(0);
2130 } else {
2131 CHECK(element_object == nullptr);
2132 set_object = true;
2133 }
2134 width = 0;
2135 break;
2136 default:
2137 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2138 return false;
2139 }
2140
2141 annotation += width;
2142 *annotation_ptr = annotation;
2143
2144 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2145 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2146 set_object = true;
2147 }
2148
2149 if (set_object) {
2150 annotation_value->value_.SetL(element_object);
2151 }
2152
2153 return true;
2154}
2155
2156mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2157 const uint8_t** annotation) const {
2158 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2159 uint32_t size = DecodeUnsignedLeb128(annotation);
2160
2161 Thread* self = Thread::Current();
2162 ScopedObjectAccessUnchecked soa(self);
2163 StackHandleScope<2> hs(self);
2164 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2165 Handle<mirror::Class> annotation_class(hs.NewHandle(
2166 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2167 if (annotation_class.Get() == nullptr) {
2168 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2169 << type_index;
2170 DCHECK(Thread::Current()->IsExceptionPending());
2171 Thread::Current()->ClearException();
2172 return nullptr;
2173 }
2174
2175 mirror::Class* annotation_member_class =
2176 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2177 mirror::Class* annotation_member_array_class =
2178 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002179 if (annotation_member_array_class == nullptr) {
2180 return nullptr;
2181 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002182 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002183 if (size > 0) {
2184 element_array =
2185 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2186 if (element_array == nullptr) {
2187 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2188 return nullptr;
2189 }
2190 }
2191
2192 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2193 for (uint32_t i = 0; i < size; ++i) {
2194 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2195 if (new_member == nullptr) {
2196 return nullptr;
2197 }
2198 h_element_array->SetWithoutChecks<false>(i, new_member);
2199 }
2200
2201 JValue result;
2202 ArtMethod* create_annotation_method =
2203 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2204 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2205 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2206 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2207 if (self->IsExceptionPending()) {
2208 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2209 return nullptr;
2210 }
2211
2212 return result.GetL();
2213}
2214
2215const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2216 const char* descriptor, uint32_t visibility) const {
2217 const AnnotationItem* result = nullptr;
2218 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2219 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002220 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002221 continue;
2222 }
2223 const uint8_t* annotation = annotation_item->annotation_;
2224 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2225
2226 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2227 result = annotation_item;
2228 break;
2229 }
2230 }
2231 return result;
2232}
2233
2234const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2235 DecodeUnsignedLeb128(&annotation); // unused type_index
2236 uint32_t size = DecodeUnsignedLeb128(&annotation);
2237
2238 while (size != 0) {
2239 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2240 const char* element_name = GetStringData(GetStringId(element_name_index));
2241 if (strcmp(name, element_name) == 0) {
2242 return annotation;
2243 }
2244 SkipAnnotationValue(&annotation);
2245 size--;
2246 }
2247 return nullptr;
2248}
2249
2250bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2251 const uint8_t* annotation = *annotation_ptr;
2252 uint8_t header_byte = *(annotation++);
2253 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2254 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2255 int32_t width = value_arg + 1;
2256
2257 switch (value_type) {
2258 case kDexAnnotationByte:
2259 case kDexAnnotationShort:
2260 case kDexAnnotationChar:
2261 case kDexAnnotationInt:
2262 case kDexAnnotationLong:
2263 case kDexAnnotationFloat:
2264 case kDexAnnotationDouble:
2265 case kDexAnnotationString:
2266 case kDexAnnotationType:
2267 case kDexAnnotationMethod:
2268 case kDexAnnotationField:
2269 case kDexAnnotationEnum:
2270 break;
2271 case kDexAnnotationArray:
2272 {
2273 uint32_t size = DecodeUnsignedLeb128(&annotation);
2274 while (size--) {
2275 if (!SkipAnnotationValue(&annotation)) {
2276 return false;
2277 }
2278 }
2279 width = 0;
2280 break;
2281 }
2282 case kDexAnnotationAnnotation:
2283 {
2284 DecodeUnsignedLeb128(&annotation); // unused type_index
2285 uint32_t size = DecodeUnsignedLeb128(&annotation);
2286 while (size--) {
2287 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2288 if (!SkipAnnotationValue(&annotation)) {
2289 return false;
2290 }
2291 }
2292 width = 0;
2293 break;
2294 }
2295 case kDexAnnotationBoolean:
2296 case kDexAnnotationNull:
2297 width = 0;
2298 break;
2299 default:
2300 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2301 return false;
2302 }
2303
2304 annotation += width;
2305 *annotation_ptr = annotation;
2306 return true;
2307}
2308
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002309std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2310 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2311 dex_file.GetLocation().c_str(),
2312 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2313 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2314 return os;
2315}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002316
Ian Rogersd91d6d62013-09-25 20:26:14 -07002317std::string Signature::ToString() const {
2318 if (dex_file_ == nullptr) {
2319 CHECK(proto_id_ == nullptr);
2320 return "<no signature>";
2321 }
2322 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2323 std::string result;
2324 if (params == nullptr) {
2325 result += "()";
2326 } else {
2327 result += "(";
2328 for (uint32_t i = 0; i < params->Size(); ++i) {
2329 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2330 }
2331 result += ")";
2332 }
2333 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2334 return result;
2335}
2336
Vladimir Markod9cffea2013-11-25 15:08:02 +00002337bool Signature::operator==(const StringPiece& rhs) const {
2338 if (dex_file_ == nullptr) {
2339 return false;
2340 }
2341 StringPiece tail(rhs);
2342 if (!tail.starts_with("(")) {
2343 return false; // Invalid signature
2344 }
2345 tail.remove_prefix(1); // "(";
2346 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2347 if (params != nullptr) {
2348 for (uint32_t i = 0; i < params->Size(); ++i) {
2349 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2350 if (!tail.starts_with(param)) {
2351 return false;
2352 }
2353 tail.remove_prefix(param.length());
2354 }
2355 }
2356 if (!tail.starts_with(")")) {
2357 return false;
2358 }
2359 tail.remove_prefix(1); // ")";
2360 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2361}
2362
Ian Rogersd91d6d62013-09-25 20:26:14 -07002363std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2364 return os << sig.ToString();
2365}
2366
Ian Rogers0571d352011-11-03 19:51:38 -07002367// Decodes the header section from the class data bytes.
2368void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002369 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002370 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2371 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2372 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2373 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2374}
2375
2376void ClassDataItemIterator::ReadClassDataField() {
2377 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2378 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002379 // The user of the iterator is responsible for checking if there
2380 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002381}
2382
2383void ClassDataItemIterator::ReadClassDataMethod() {
2384 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2385 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2386 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002387 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002388 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002389 }
Ian Rogers0571d352011-11-03 19:51:38 -07002390}
2391
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002392EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002393 const DexFile& dex_file,
2394 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002395 : EncodedStaticFieldValueIterator(dex_file,
2396 nullptr,
2397 nullptr,
2398 nullptr,
2399 class_def,
2400 -1,
2401 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002402}
2403
2404EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002405 const DexFile& dex_file,
2406 Handle<mirror::DexCache>* dex_cache,
2407 Handle<mirror::ClassLoader>* class_loader,
2408 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002409 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002410 : EncodedStaticFieldValueIterator(dex_file,
2411 dex_cache, class_loader,
2412 linker,
2413 class_def,
2414 -1,
2415 kByte) {
2416 DCHECK(dex_cache_ != nullptr);
2417 DCHECK(class_loader_ != nullptr);
2418}
2419
2420EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2421 const DexFile& dex_file,
2422 Handle<mirror::DexCache>* dex_cache,
2423 Handle<mirror::ClassLoader>* class_loader,
2424 ClassLinker* linker,
2425 const DexFile::ClassDef& class_def,
2426 size_t pos,
2427 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002428 : dex_file_(dex_file),
2429 dex_cache_(dex_cache),
2430 class_loader_(class_loader),
2431 linker_(linker),
2432 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002433 pos_(pos),
2434 type_(type) {
2435 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002436 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002437 array_size_ = 0;
2438 } else {
2439 array_size_ = DecodeUnsignedLeb128(&ptr_);
2440 }
2441 if (array_size_ > 0) {
2442 Next();
2443 }
2444}
2445
2446void EncodedStaticFieldValueIterator::Next() {
2447 pos_++;
2448 if (pos_ >= array_size_) {
2449 return;
2450 }
Ian Rogers13735952014-10-08 12:43:28 -07002451 uint8_t value_type = *ptr_++;
2452 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002453 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002454 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002455 switch (type_) {
2456 case kBoolean:
2457 jval_.i = (value_arg != 0) ? 1 : 0;
2458 width = 0;
2459 break;
2460 case kByte:
2461 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002462 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002463 break;
2464 case kShort:
2465 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002466 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002467 break;
2468 case kChar:
2469 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002470 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002471 break;
2472 case kInt:
2473 jval_.i = ReadSignedInt(ptr_, value_arg);
2474 break;
2475 case kLong:
2476 jval_.j = ReadSignedLong(ptr_, value_arg);
2477 break;
2478 case kFloat:
2479 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2480 break;
2481 case kDouble:
2482 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2483 break;
2484 case kString:
2485 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002486 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2487 break;
2488 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002489 case kMethod:
2490 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002491 case kArray:
2492 case kAnnotation:
2493 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002494 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002495 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002496 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002497 width = 0;
2498 break;
2499 default:
2500 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002501 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002502 }
2503 ptr_ += width;
2504}
2505
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002506template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002507void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002508 DCHECK(dex_cache_ != nullptr);
2509 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002510 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002511 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2512 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002513 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2514 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2515 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2516 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2517 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2518 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2519 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002520 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002521 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002522 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002523 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002524 break;
2525 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002526 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002527 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2528 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002529 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002530 break;
2531 }
Ian Rogers0571d352011-11-03 19:51:38 -07002532 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2533 }
2534}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002535template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2536template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002537
2538CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2539 handler_.address_ = -1;
2540 int32_t offset = -1;
2541
2542 // Short-circuit the overwhelmingly common cases.
2543 switch (code_item.tries_size_) {
2544 case 0:
2545 break;
2546 case 1: {
2547 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2548 uint32_t start = tries->start_addr_;
2549 if (address >= start) {
2550 uint32_t end = start + tries->insn_count_;
2551 if (address < end) {
2552 offset = tries->handler_off_;
2553 }
2554 }
2555 break;
2556 }
2557 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002558 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002559 }
Logan Chien736df022012-04-27 16:25:57 +08002560 Init(code_item, offset);
2561}
2562
2563CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2564 const DexFile::TryItem& try_item) {
2565 handler_.address_ = -1;
2566 Init(code_item, try_item.handler_off_);
2567}
2568
2569void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2570 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002571 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002572 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002573 } else {
2574 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002575 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002576 remaining_count_ = -1;
2577 catch_all_ = false;
2578 DCHECK(!HasNext());
2579 }
2580}
2581
Ian Rogers13735952014-10-08 12:43:28 -07002582void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002583 current_data_ = handler_data;
2584 remaining_count_ = DecodeSignedLeb128(&current_data_);
2585
2586 // If remaining_count_ is non-positive, then it is the negative of
2587 // the number of catch types, and the catches are followed by a
2588 // catch-all handler.
2589 if (remaining_count_ <= 0) {
2590 catch_all_ = true;
2591 remaining_count_ = -remaining_count_;
2592 } else {
2593 catch_all_ = false;
2594 }
2595 Next();
2596}
2597
2598void CatchHandlerIterator::Next() {
2599 if (remaining_count_ > 0) {
2600 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2601 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2602 remaining_count_--;
2603 return;
2604 }
2605
2606 if (catch_all_) {
2607 handler_.type_idx_ = DexFile::kDexNoIndex16;
2608 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2609 catch_all_ = false;
2610 return;
2611 }
2612
2613 // no more handler
2614 remaining_count_ = -1;
2615}
2616
Carl Shapiro1fb86202011-06-27 17:43:13 -07002617} // namespace art