blob: ae62e2bfe177bbe5069d50448b017227f0792722 [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 Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010034#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080035#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000036#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080038#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070039#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070040#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000041#include "mirror/field.h"
42#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070044#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000045#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070046#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070047#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070048#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070049#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070050#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070052#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070053
Andreas Gampe277ccbd2014-11-03 21:36:10 -080054#pragma GCC diagnostic push
55#pragma GCC diagnostic ignored "-Wshadow"
56#include "ScopedFd.h"
57#pragma GCC diagnostic pop
58
Carl Shapiro1fb86202011-06-27 17:43:13 -070059namespace art {
60
Ian Rogers13735952014-10-08 12:43:28 -070061const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
62const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070063
Ian Rogers8d31bbd2013-10-13 10:44:14 -070064static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070065 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000066 ScopedFd fd(open(filename, O_RDONLY, 0));
67 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070068 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070069 return -1;
70 }
Vladimir Markofd995762013-11-06 16:36:36 +000071 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070072 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070073 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 return -1;
75 }
Vladimir Markofd995762013-11-06 16:36:36 +000076 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070077 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
78 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070079 return -1;
80 }
Vladimir Markofd995762013-11-06 16:36:36 +000081 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070082}
83
Ian Rogers8d31bbd2013-10-13 10:44:14 -070084bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070085 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070086 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070087
88 // Strip ":...", which is the location
89 const char* zip_entry_name = kClassesDex;
90 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010091 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070092
Vladimir Markoaa4497d2014-09-05 14:01:17 +010093 if (DexFile::IsMultiDexLocation(filename)) {
94 file_part_storage = GetBaseLocation(filename);
95 file_part = file_part_storage.c_str();
96 zip_entry_name = filename + file_part_storage.size() + 1;
97 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070098 }
99
100 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000101 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700102 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700103 return false;
104 }
105 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700106 std::unique_ptr<ZipArchive> zip_archive(
107 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
108 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800109 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
110 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700112 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700113 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700114 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700115 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
116 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return false;
118 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700119 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800120 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700121 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700122 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700123 std::unique_ptr<const DexFile> dex_file(
124 DexFile::OpenFile(fd.release(), filename, false, error_msg));
125 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800126 return false;
127 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700128 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800129 return true;
130 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700131 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800132 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700133}
134
Andreas Gampe833a4852014-05-21 18:46:59 -0700135bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800136 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700137 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700138 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000139 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
140 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700141 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700142 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700143 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700144 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700145 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700146 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700147 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700148 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
149 error_msg));
150 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800151 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700152 return true;
153 } else {
154 return false;
155 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700156 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700157 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400158 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700159}
160
Andreas Gampe0cba0042015-04-29 20:47:16 -0700161static bool ContainsClassesDex(int fd, const char* filename) {
162 std::string error_msg;
163 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
164 if (zip_archive.get() == nullptr) {
165 return false;
166 }
167 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
168 return (zip_entry.get() != nullptr);
169}
170
171bool DexFile::MaybeDex(const char* filename) {
172 uint32_t magic;
173 std::string error_msg;
174 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
175 if (fd.get() == -1) {
176 return false;
177 }
178 if (IsZipMagic(magic)) {
179 return ContainsClassesDex(fd.release(), filename);
180 } else if (IsDexMagic(magic)) {
181 return true;
182 }
183 return false;
184}
185
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800186int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800188 return 0;
189 } else {
190 return mem_map_->GetProtect();
191 }
192}
193
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194bool DexFile::IsReadOnly() const {
195 return GetPermissions() == PROT_READ;
196}
197
Brian Carlstrome0948e12013-08-29 09:36:15 -0700198bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700200 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200201 return false;
202 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700203 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200204 }
205}
206
Brian Carlstrome0948e12013-08-29 09:36:15 -0700207bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200208 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700209 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200210 return false;
211 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700212 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200213 }
214}
215
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800216std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
217 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700218 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700219 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000220 {
221 ScopedFd delayed_close(fd);
222 struct stat sbuf;
223 memset(&sbuf, 0, sizeof(sbuf));
224 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800225 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000226 return nullptr;
227 }
228 if (S_ISDIR(sbuf.st_mode)) {
229 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
230 return nullptr;
231 }
232 size_t length = sbuf.st_size;
233 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
234 if (map.get() == nullptr) {
235 DCHECK(!error_msg->empty());
236 return nullptr;
237 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700238 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800239
240 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700241 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800242 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700243 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800244 }
245
246 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
247
Andreas Gampe928f72b2014-09-09 19:53:48 -0700248 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
249 error_msg));
250 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700251 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
252 error_msg->c_str());
253 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800254 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800255
Andreas Gampe928f72b2014-09-09 19:53:48 -0700256 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
257 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700258 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800259 }
260
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800261 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700262}
263
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700264const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700265
Andreas Gampe833a4852014-05-21 18:46:59 -0700266bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800267 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700268 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700269 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 if (zip_archive.get() == nullptr) {
271 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700272 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700273 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700274 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800275}
276
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800277std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
278 uint32_t location_checksum,
279 MemMap* mem_map,
280 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800281 return OpenMemory(mem_map->Begin(),
282 mem_map->Size(),
283 location,
284 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700285 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800286 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700287 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800288}
289
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800290std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
291 const std::string& location, std::string* error_msg,
292 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800293 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700294 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700295 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700296 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700297 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700298 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700299 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700300 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700301 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700302 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700303 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700304 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700305 }
Ian Rogers700a4022014-05-19 16:49:03 -0700306 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700307 error_msg));
308 if (dex_file.get() == nullptr) {
309 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
310 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700311 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700312 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800313 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700314 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700315 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700316 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700317 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700318 }
319 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700320 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
321 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700322 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700323 return nullptr;
324 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700325 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800326 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700327}
328
Andreas Gampe90e34042015-04-27 20:01:52 -0700329// Technically we do not have a limitation with respect to the number of dex files that can be in a
330// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
331// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
332// seems an excessive number.
333static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
334
Andreas Gampe833a4852014-05-21 18:46:59 -0700335bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800336 std::string* error_msg,
337 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700338 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700339 ZipOpenErrorCode error_code;
340 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
341 &error_code));
342 if (dex_file.get() == nullptr) {
343 return false;
344 } else {
345 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800346 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700347
348 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700349
350 // We could try to avoid std::string allocations by working on a char array directly. As we
351 // do not expect a lot of iterations, this seems too involved and brittle.
352
Andreas Gampe90e34042015-04-27 20:01:52 -0700353 for (size_t i = 1; ; ++i) {
354 std::string name = GetMultiDexClassesDexName(i);
355 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700356 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
357 error_msg, &error_code));
358 if (next_dex_file.get() == nullptr) {
359 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
360 LOG(WARNING) << error_msg;
361 }
362 break;
363 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800364 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700365 }
366
Andreas Gampe90e34042015-04-27 20:01:52 -0700367 if (i == kWarnOnManyDexFilesThreshold) {
368 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
369 << " dex files. Please consider coalescing and shrinking the number to "
370 " avoid runtime overhead.";
371 }
372
373 if (i == std::numeric_limits<size_t>::max()) {
374 LOG(ERROR) << "Overflow in number of dex files!";
375 break;
376 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700377 }
378
379 return true;
380 }
381}
382
383
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800384std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
385 size_t size,
386 const std::string& location,
387 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800388 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700389 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800390 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700391 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800392 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700393 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800395 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700396 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800397 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700398}
399
Ian Rogers13735952014-10-08 12:43:28 -0700400DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800401 const std::string& location,
402 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800403 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700404 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800405 : begin_(base),
406 size_(size),
407 location_(location),
408 location_checksum_(location_checksum),
409 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800410 header_(reinterpret_cast<const Header*>(base)),
411 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
412 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
413 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
414 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
415 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700416 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
417 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800418 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700419 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700420 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800421 CHECK_GT(size_, 0U) << GetLocation();
422}
423
Jesse Wilson6bf19152011-09-29 13:12:33 -0400424DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700425 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
426 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
427 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
428 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700429 // Remove the index if one were created.
430 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400431}
432
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700434 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700435 return false;
436 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700437 return true;
438}
439
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700440bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800441 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700442 std::ostringstream oss;
443 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800444 << " " << header_->magic_[0]
445 << " " << header_->magic_[1]
446 << " " << header_->magic_[2]
447 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700448 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700449 return false;
450 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800451 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700452 std::ostringstream oss;
453 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800454 << " " << header_->magic_[4]
455 << " " << header_->magic_[5]
456 << " " << header_->magic_[6]
457 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700458 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700459 return false;
460 }
461 return true;
462}
463
Ian Rogers13735952014-10-08 12:43:28 -0700464bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800465 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
466}
467
Ian Rogers13735952014-10-08 12:43:28 -0700468bool DexFile::IsVersionValid(const uint8_t* magic) {
469 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800470 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
471}
472
Ian Rogersd81871c2011-10-03 13:57:23 -0700473uint32_t DexFile::GetVersion() const {
474 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
475 return atoi(version);
476}
477
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800478const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
479 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700480 // If we have an index lookup the descriptor via that as its constant time to search.
481 Index* index = class_def_index_.LoadSequentiallyConsistent();
482 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800483 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700484 return (it == index->end()) ? nullptr : it->second;
485 }
486 // Fast path for rate no class defs case.
487 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700488 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700489 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700490 }
Ian Rogers68b56852014-08-29 20:19:11 -0700491 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700492 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700493 if (string_id != nullptr) {
494 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
495 if (type_id != nullptr) {
496 uint16_t type_idx = GetIndexForTypeId(*type_id);
497 for (size_t i = 0; i < num_class_defs; ++i) {
498 const ClassDef& class_def = GetClassDef(i);
499 if (class_def.class_idx_ == type_idx) {
500 return &class_def;
501 }
502 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700503 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700504 }
Ian Rogers68b56852014-08-29 20:19:11 -0700505 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
506 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
507 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
508 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700509 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700510 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
511 if (old_misses == kMaxFailedDexClassDefLookups) {
512 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
513 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
514 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800515 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700516 for (uint32_t i = 0; i < num_class_defs; ++i) {
517 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800518 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800519 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700520 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700521 // Sanity check the index still doesn't exist, only 1 thread should build it.
522 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
523 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700524 }
525 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700526}
527
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700528const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
529 size_t num_class_defs = NumClassDefs();
530 for (size_t i = 0; i < num_class_defs; ++i) {
531 const ClassDef& class_def = GetClassDef(i);
532 if (class_def.class_idx_ == type_idx) {
533 return &class_def;
534 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700535 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700536 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537}
538
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800539const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
540 const DexFile::StringId& name,
541 const DexFile::TypeId& type) const {
542 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
543 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
544 const uint32_t name_idx = GetIndexForStringId(name);
545 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700546 int32_t lo = 0;
547 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800548 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700549 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800550 const DexFile::FieldId& field = GetFieldId(mid);
551 if (class_idx > field.class_idx_) {
552 lo = mid + 1;
553 } else if (class_idx < field.class_idx_) {
554 hi = mid - 1;
555 } else {
556 if (name_idx > field.name_idx_) {
557 lo = mid + 1;
558 } else if (name_idx < field.name_idx_) {
559 hi = mid - 1;
560 } else {
561 if (type_idx > field.type_idx_) {
562 lo = mid + 1;
563 } else if (type_idx < field.type_idx_) {
564 hi = mid - 1;
565 } else {
566 return &field;
567 }
568 }
569 }
570 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700571 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800572}
573
574const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700575 const DexFile::StringId& name,
576 const DexFile::ProtoId& signature) const {
577 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800578 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700579 const uint32_t name_idx = GetIndexForStringId(name);
580 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700581 int32_t lo = 0;
582 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700583 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700584 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700585 const DexFile::MethodId& method = GetMethodId(mid);
586 if (class_idx > method.class_idx_) {
587 lo = mid + 1;
588 } else if (class_idx < method.class_idx_) {
589 hi = mid - 1;
590 } else {
591 if (name_idx > method.name_idx_) {
592 lo = mid + 1;
593 } else if (name_idx < method.name_idx_) {
594 hi = mid - 1;
595 } else {
596 if (proto_idx > method.proto_idx_) {
597 lo = mid + 1;
598 } else if (proto_idx < method.proto_idx_) {
599 hi = mid - 1;
600 } else {
601 return &method;
602 }
603 }
604 }
605 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700606 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700607}
608
Ian Rogers637c65b2013-05-31 11:46:00 -0700609const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700610 int32_t lo = 0;
611 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700612 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700613 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700614 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700615 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700616 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
617 if (compare > 0) {
618 lo = mid + 1;
619 } else if (compare < 0) {
620 hi = mid - 1;
621 } else {
622 return &str_id;
623 }
624 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700625 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700626}
627
Vladimir Markoa48aef42014-12-03 17:53:53 +0000628const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700629 int32_t lo = 0;
630 int32_t hi = NumStringIds() - 1;
631 while (hi >= lo) {
632 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700633 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700634 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000635 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700636 if (compare > 0) {
637 lo = mid + 1;
638 } else if (compare < 0) {
639 hi = mid - 1;
640 } else {
641 return &str_id;
642 }
643 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700644 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700645}
646
647const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700648 int32_t lo = 0;
649 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700650 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700651 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700652 const TypeId& type_id = GetTypeId(mid);
653 if (string_idx > type_id.descriptor_idx_) {
654 lo = mid + 1;
655 } else if (string_idx < type_id.descriptor_idx_) {
656 hi = mid - 1;
657 } else {
658 return &type_id;
659 }
660 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700661 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700662}
663
664const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000665 const uint16_t* signature_type_idxs,
666 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700667 int32_t lo = 0;
668 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700669 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700670 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700671 const DexFile::ProtoId& proto = GetProtoId(mid);
672 int compare = return_type_idx - proto.return_type_idx_;
673 if (compare == 0) {
674 DexFileParameterIterator it(*this, proto);
675 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000676 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800677 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700678 it.Next();
679 i++;
680 }
681 if (compare == 0) {
682 if (it.HasNext()) {
683 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000684 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700685 compare = 1;
686 }
687 }
688 }
689 if (compare > 0) {
690 lo = mid + 1;
691 } else if (compare < 0) {
692 hi = mid - 1;
693 } else {
694 return &proto;
695 }
696 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700697 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700698}
699
700// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700701bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
702 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700703 if (signature[0] != '(') {
704 return false;
705 }
706 size_t offset = 1;
707 size_t end = signature.size();
708 bool process_return = false;
709 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000710 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700711 char c = signature[offset];
712 offset++;
713 if (c == ')') {
714 process_return = true;
715 continue;
716 }
Ian Rogers0571d352011-11-03 19:51:38 -0700717 while (c == '[') { // process array prefix
718 if (offset >= end) { // expect some descriptor following [
719 return false;
720 }
721 c = signature[offset];
722 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700723 }
724 if (c == 'L') { // process type descriptors
725 do {
726 if (offset >= end) { // unexpected early termination of descriptor
727 return false;
728 }
729 c = signature[offset];
730 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700731 } while (c != ';');
732 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000733 // TODO: avoid creating a std::string just to get a 0-terminated char array
734 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700735 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700736 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700737 return false;
738 }
739 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700740 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700741 return false;
742 }
743 uint16_t type_idx = GetIndexForTypeId(*type_id);
744 if (!process_return) {
745 param_type_idxs->push_back(type_idx);
746 } else {
747 *return_type_idx = type_idx;
748 return offset == end; // return true if the signature had reached a sensible end
749 }
750 }
751 return false; // failed to correctly parse return type
752}
753
Ian Rogersd91d6d62013-09-25 20:26:14 -0700754const Signature DexFile::CreateSignature(const StringPiece& signature) const {
755 uint16_t return_type_idx;
756 std::vector<uint16_t> param_type_indices;
757 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
758 if (!success) {
759 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700760 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700761 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700762 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700763 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700764 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700765 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700766}
767
Mathieu Chartiere401d142015-04-22 13:56:20 -0700768int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700769 // For native method, lineno should be -2 to indicate it is native. Note that
770 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700771 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700772 return -2;
773 }
774
TDYa127c8dc1012012-04-19 07:03:33 -0700775 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700776 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700777
778 // A method with no line number info should return -1
779 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700780 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700781 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700782 return context.line_num_;
783}
784
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700785int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700786 // Note: Signed type is important for max and min.
787 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700788 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700789
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700790 while (min <= max) {
791 int32_t mid = min + ((max - min) / 2);
792
793 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
794 uint32_t start = ti->start_addr_;
795 uint32_t end = start + ti->insn_count_;
796
Ian Rogers0571d352011-11-03 19:51:38 -0700797 if (address < start) {
798 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700799 } else if (address >= end) {
800 min = mid + 1;
801 } else { // We have a winner!
802 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700803 }
804 }
805 // No match.
806 return -1;
807}
808
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700809int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
810 int32_t try_item = FindTryItem(code_item, address);
811 if (try_item == -1) {
812 return -1;
813 } else {
814 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
815 }
816}
817
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800818void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800819 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700820 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
821 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700822 uint32_t line = DecodeUnsignedLeb128(&stream);
823 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
824 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
825 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700826 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700827
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800828 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700829 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800830 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700831 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800832 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700833 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700834 local_in_reg[arg_reg].start_address_ = 0;
835 local_in_reg[arg_reg].is_live_ = true;
836 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700837 arg_reg++;
838 }
839
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800840 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700841 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700842 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700843 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800844 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700845 return;
846 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800847 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700848 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800849 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700850 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700851 local_in_reg[arg_reg].name_ = name;
852 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700853 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700854 local_in_reg[arg_reg].start_address_ = address;
855 local_in_reg[arg_reg].is_live_ = true;
856 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700857 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700858 case 'D':
859 case 'J':
860 arg_reg += 2;
861 break;
862 default:
863 arg_reg += 1;
864 break;
865 }
866 }
867
Ian Rogers0571d352011-11-03 19:51:38 -0700868 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800869 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
870 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700871 return;
872 }
873
874 for (;;) {
875 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700876 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800877 uint32_t name_idx;
878 uint32_t descriptor_idx;
879 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 switch (opcode) {
882 case DBG_END_SEQUENCE:
883 return;
884
885 case DBG_ADVANCE_PC:
886 address += DecodeUnsignedLeb128(&stream);
887 break;
888
889 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700890 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 break;
892
893 case DBG_START_LOCAL:
894 case DBG_START_LOCAL_EXTENDED:
895 reg = DecodeUnsignedLeb128(&stream);
896 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700897 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800898 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700899 return;
900 }
901
jeffhaof8728872011-10-28 19:11:13 -0700902 name_idx = DecodeUnsignedLeb128P1(&stream);
903 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
904 if (opcode == DBG_START_LOCAL_EXTENDED) {
905 signature_idx = DecodeUnsignedLeb128P1(&stream);
906 }
907
Shih-wei Liao195487c2011-08-20 13:29:04 -0700908 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700909 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800910 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700911
Ian Rogers0571d352011-11-03 19:51:38 -0700912 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
913 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700914 local_in_reg[reg].signature_ =
915 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
916 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700917 local_in_reg[reg].start_address_ = address;
918 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700920 break;
921
922 case DBG_END_LOCAL:
923 reg = DecodeUnsignedLeb128(&stream);
924 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700925 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800926 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700927 return;
928 }
929
Elliott Hughes30646832011-10-13 16:59:46 -0700930 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800931 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700932 local_in_reg[reg].is_live_ = false;
933 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700934 break;
935
936 case DBG_RESTART_LOCAL:
937 reg = DecodeUnsignedLeb128(&stream);
938 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700939 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800940 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 return;
942 }
943
Elliott Hughes30646832011-10-13 16:59:46 -0700944 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700945 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800946 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700947 return;
948 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700949
Elliott Hughes30646832011-10-13 16:59:46 -0700950 // If the register is live, the "restart" is superfluous,
951 // and we don't want to mess with the existing start address.
952 if (!local_in_reg[reg].is_live_) {
953 local_in_reg[reg].start_address_ = address;
954 local_in_reg[reg].is_live_ = true;
955 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700956 }
957 break;
958
959 case DBG_SET_PROLOGUE_END:
960 case DBG_SET_EPILOGUE_BEGIN:
961 case DBG_SET_FILE:
962 break;
963
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700964 default: {
965 int adjopcode = opcode - DBG_FIRST_SPECIAL;
966
Shih-wei Liao195487c2011-08-20 13:29:04 -0700967 address += adjopcode / DBG_LINE_RANGE;
968 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
969
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700970 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800971 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700972 // early exit
973 return;
974 }
975 }
976 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700977 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700978 }
979 }
980}
981
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800982void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800983 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
984 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100985 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700986 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700987 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700988 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700989 nullptr);
990 if (stream != nullptr) {
991 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
992 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700993 }
994 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700995 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
996 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700997 }
998}
999
Elliott Hughes2435a572012-02-17 16:07:41 -08001000bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1001 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001002
1003 // We know that this callback will be called in
1004 // ascending address order, so keep going until we find
1005 // a match or we've just gone past it.
1006 if (address > context->address_) {
1007 // The line number from the previous positions callback
1008 // wil be the final result.
1009 return true;
1010 } else {
1011 context->line_num_ = line_num;
1012 return address == context->address_;
1013 }
1014}
1015
Andreas Gampe833a4852014-05-21 18:46:59 -07001016bool DexFile::IsMultiDexLocation(const char* location) {
1017 return strrchr(location, kMultiDexSeparator) != nullptr;
1018}
1019
Andreas Gampe90e34042015-04-27 20:01:52 -07001020std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1021 if (index == 0) {
1022 return "classes.dex";
1023 } else {
1024 return StringPrintf("classes%zu.dex", index + 1);
1025 }
1026}
1027
1028std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1029 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001030 return dex_location;
1031 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001032 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001033 }
1034}
1035
1036std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1037 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001038 std::string base_location = GetBaseLocation(dex_location);
1039 const char* suffix = dex_location + base_location.size();
1040 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1041 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1042 if (path != nullptr && path.get() != base_location) {
1043 return std::string(path.get()) + suffix;
1044 } else if (suffix[0] == 0) {
1045 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001046 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001047 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001048 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001049}
1050
Jeff Hao13e748b2015-08-25 20:44:19 +00001051// Read a signed integer. "zwidth" is the zero-based byte count.
1052static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1053 int32_t val = 0;
1054 for (int i = zwidth; i >= 0; --i) {
1055 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1056 }
1057 val >>= (3 - zwidth) * 8;
1058 return val;
1059}
1060
1061// Read an unsigned integer. "zwidth" is the zero-based byte count,
1062// "fill_on_right" indicates which side we want to zero-fill from.
1063static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1064 uint32_t val = 0;
1065 for (int i = zwidth; i >= 0; --i) {
1066 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1067 }
1068 if (!fill_on_right) {
1069 val >>= (3 - zwidth) * 8;
1070 }
1071 return val;
1072}
1073
1074// Read a signed long. "zwidth" is the zero-based byte count.
1075static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1076 int64_t val = 0;
1077 for (int i = zwidth; i >= 0; --i) {
1078 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1079 }
1080 val >>= (7 - zwidth) * 8;
1081 return val;
1082}
1083
1084// Read an unsigned long. "zwidth" is the zero-based byte count,
1085// "fill_on_right" indicates which side we want to zero-fill from.
1086static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1087 uint64_t val = 0;
1088 for (int i = zwidth; i >= 0; --i) {
1089 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1090 }
1091 if (!fill_on_right) {
1092 val >>= (7 - zwidth) * 8;
1093 }
1094 return val;
1095}
1096
1097const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1098 mirror::Class* klass = field->GetDeclaringClass();
1099 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1100 if (annotations_dir == nullptr) {
1101 return nullptr;
1102 }
1103 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1104 if (field_annotations == nullptr) {
1105 return nullptr;
1106 }
1107 uint32_t field_index = field->GetDexFieldIndex();
1108 uint32_t field_count = annotations_dir->fields_size_;
1109 for (uint32_t i = 0; i < field_count; ++i) {
1110 if (field_annotations[i].field_idx_ == field_index) {
1111 return GetFieldAnnotationSetItem(field_annotations[i]);
1112 }
1113 }
1114 return nullptr;
1115}
1116
1117mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1118 Handle<mirror::Class> annotation_class) const {
1119 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1120 if (annotation_set == nullptr) {
1121 return nullptr;
1122 }
1123 StackHandleScope<1> hs(Thread::Current());
1124 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1125 return GetAnnotationObjectFromAnnotationSet(
1126 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1127}
1128
1129mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1130 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1131 StackHandleScope<1> hs(Thread::Current());
1132 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1133 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1134}
1135
Jeff Hao2a5892f2015-08-31 15:00:40 -07001136mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001137 const {
1138 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1139 if (annotation_set == nullptr) {
1140 return nullptr;
1141 }
1142 StackHandleScope<1> hs(Thread::Current());
1143 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1144 return GetSignatureValue(field_class, annotation_set);
1145}
1146
1147bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1148 const {
1149 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1150 if (annotation_set == nullptr) {
1151 return false;
1152 }
1153 StackHandleScope<1> hs(Thread::Current());
1154 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1155 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1156 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1157 return annotation_item != nullptr;
1158}
1159
1160const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1161 mirror::Class* klass = method->GetDeclaringClass();
1162 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1163 if (annotations_dir == nullptr) {
1164 return nullptr;
1165 }
1166 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1167 if (method_annotations == nullptr) {
1168 return nullptr;
1169 }
1170 uint32_t method_index = method->GetDexMethodIndex();
1171 uint32_t method_count = annotations_dir->methods_size_;
1172 for (uint32_t i = 0; i < method_count; ++i) {
1173 if (method_annotations[i].method_idx_ == method_index) {
1174 return GetMethodAnnotationSetItem(method_annotations[i]);
1175 }
1176 }
1177 return nullptr;
1178}
1179
1180const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1181 const {
1182 mirror::Class* klass = method->GetDeclaringClass();
1183 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1184 if (annotations_dir == nullptr) {
1185 return nullptr;
1186 }
1187 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1188 if (parameter_annotations == nullptr) {
1189 return nullptr;
1190 }
1191 uint32_t method_index = method->GetDexMethodIndex();
1192 uint32_t parameter_count = annotations_dir->parameters_size_;
1193 for (uint32_t i = 0; i < parameter_count; ++i) {
1194 if (parameter_annotations[i].method_idx_ == method_index) {
1195 return &parameter_annotations[i];
1196 }
1197 }
1198 return nullptr;
1199}
1200
1201mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1202 mirror::Class* klass = method->GetDeclaringClass();
1203 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1204 if (annotations_dir == nullptr) {
1205 return nullptr;
1206 }
1207 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1208 if (annotation_set == nullptr) {
1209 return nullptr;
1210 }
1211 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1212 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1213 if (annotation_item == nullptr) {
1214 return nullptr;
1215 }
1216 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1217 if (annotation == nullptr) {
1218 return nullptr;
1219 }
1220 uint8_t header_byte = *(annotation++);
1221 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1222 return nullptr;
1223 }
1224 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1225 if (annotation == nullptr) {
1226 return nullptr;
1227 }
1228 AnnotationValue annotation_value;
1229 StackHandleScope<2> hs(Thread::Current());
1230 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001231 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1232 Handle<mirror::Class> return_type(hs.NewHandle(
1233 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001234 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1235 return nullptr;
1236 }
1237 return annotation_value.value_.GetL();
1238}
1239
1240mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1241 Handle<mirror::Class> annotation_class) const {
1242 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1243 if (annotation_set == nullptr) {
1244 return nullptr;
1245 }
1246 StackHandleScope<1> hs(Thread::Current());
1247 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1248 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1249 kDexVisibilityRuntime, annotation_class);
1250}
1251
1252mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1253 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1254 StackHandleScope<1> hs(Thread::Current());
1255 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1256 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1257}
1258
Jeff Hao2a5892f2015-08-31 15:00:40 -07001259mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001260 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1261 if (annotation_set == nullptr) {
1262 return nullptr;
1263 }
1264 StackHandleScope<1> hs(Thread::Current());
1265 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1266 return GetThrowsValue(method_class, annotation_set);
1267}
1268
1269mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1270 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1271 if (parameter_annotations == nullptr) {
1272 return nullptr;
1273 }
1274 const AnnotationSetRefList* set_ref_list =
1275 GetParameterAnnotationSetRefList(parameter_annotations);
1276 if (set_ref_list == nullptr) {
1277 return nullptr;
1278 }
1279 uint32_t size = set_ref_list->size_;
1280 StackHandleScope<1> hs(Thread::Current());
1281 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1282 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1283}
1284
1285bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1286 const {
1287 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1288 if (annotation_set == nullptr) {
1289 return false;
1290 }
1291 StackHandleScope<1> hs(Thread::Current());
1292 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1293 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1294 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001295 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001296}
1297
1298const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1299 const {
1300 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1301 if (annotations_dir == nullptr) {
1302 return nullptr;
1303 }
1304 return GetClassAnnotationSet(annotations_dir);
1305}
1306
1307mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1308 Handle<mirror::Class> annotation_class) const {
1309 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1310 if (annotation_set == nullptr) {
1311 return nullptr;
1312 }
1313 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1314 annotation_class);
1315}
1316
1317mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1318 const {
1319 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1320 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1321}
1322
Jeff Hao2a5892f2015-08-31 15:00:40 -07001323mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1324 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1325 if (annotation_set == nullptr) {
1326 return nullptr;
1327 }
1328 const AnnotationItem* annotation_item = SearchAnnotationSet(
1329 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1330 if (annotation_item == nullptr) {
1331 return nullptr;
1332 }
1333 StackHandleScope<1> hs(Thread::Current());
1334 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1335 Handle<mirror::Class> class_array_class(hs.NewHandle(
1336 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1337 if (class_array_class.Get() == nullptr) {
1338 return nullptr;
1339 }
1340 mirror::Object* obj = GetAnnotationValue(
1341 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1342 if (obj == nullptr) {
1343 return nullptr;
1344 }
1345 return obj->AsObjectArray<mirror::Class>();
1346}
1347
1348mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1349 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1350 if (annotation_set == nullptr) {
1351 return nullptr;
1352 }
1353 const AnnotationItem* annotation_item = SearchAnnotationSet(
1354 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1355 if (annotation_item == nullptr) {
1356 return nullptr;
1357 }
1358 mirror::Object* obj = GetAnnotationValue(
1359 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1360 if (obj == nullptr) {
1361 return nullptr;
1362 }
1363 return obj->AsClass();
1364}
1365
1366mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1367 mirror::Class* declaring_class = GetDeclaringClass(klass);
1368 if (declaring_class != nullptr) {
1369 return declaring_class;
1370 }
1371 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1372 if (annotation_set == nullptr) {
1373 return nullptr;
1374 }
1375 const AnnotationItem* annotation_item = SearchAnnotationSet(
1376 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1377 if (annotation_item == nullptr) {
1378 return nullptr;
1379 }
1380 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1381 if (annotation == nullptr) {
1382 return nullptr;
1383 }
1384 AnnotationValue annotation_value;
1385 if (!ProcessAnnotationValue(
1386 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1387 return nullptr;
1388 }
1389 if (annotation_value.type_ != kDexAnnotationMethod) {
1390 return nullptr;
1391 }
1392 StackHandleScope<2> hs(Thread::Current());
1393 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1394 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1395 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1396 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1397 if (method == nullptr) {
1398 return nullptr;
1399 }
1400 return method->GetDeclaringClass();
1401}
1402
1403mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1404 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1405 if (annotation_set == nullptr) {
1406 return nullptr;
1407 }
1408 const AnnotationItem* annotation_item = SearchAnnotationSet(
1409 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1410 if (annotation_item == nullptr) {
1411 return nullptr;
1412 }
1413 return GetAnnotationValue(
1414 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1415}
1416
1417bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1418 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1419 if (annotation_set == nullptr) {
1420 return false;
1421 }
1422 const AnnotationItem* annotation_item = SearchAnnotationSet(
1423 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1424 if (annotation_item == nullptr) {
1425 return false;
1426 }
1427 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1428 if (annotation == nullptr) {
1429 return false;
1430 }
1431 AnnotationValue annotation_value;
1432 if (!ProcessAnnotationValue(
1433 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1434 return false;
1435 }
1436 if (annotation_value.type_ != kDexAnnotationNull &&
1437 annotation_value.type_ != kDexAnnotationString) {
1438 return false;
1439 }
1440 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1441 return true;
1442}
1443
1444bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1445 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1446 if (annotation_set == nullptr) {
1447 return false;
1448 }
1449 const AnnotationItem* annotation_item = SearchAnnotationSet(
1450 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1451 if (annotation_item == nullptr) {
1452 return false;
1453 }
1454 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1455 if (annotation == nullptr) {
1456 return false;
1457 }
1458 AnnotationValue annotation_value;
1459 if (!ProcessAnnotationValue(
1460 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1461 return false;
1462 }
1463 if (annotation_value.type_ != kDexAnnotationInt) {
1464 return false;
1465 }
1466 *flags = annotation_value.value_.GetI();
1467 return true;
1468}
1469
Jeff Hao13e748b2015-08-25 20:44:19 +00001470bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1471 Handle<mirror::Class> annotation_class) const {
1472 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1473 if (annotation_set == nullptr) {
1474 return false;
1475 }
1476 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1477 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001478 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001479}
1480
1481mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1482 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1483 Thread* self = Thread::Current();
1484 ScopedObjectAccessUnchecked soa(self);
1485 StackHandleScope<5> hs(self);
1486 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1487 const char* name = StringDataByIdx(element_name_index);
1488 Handle<mirror::String> string_name(
1489 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1490
1491 ArtMethod* annotation_method =
1492 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1493 if (annotation_method == nullptr) {
1494 return nullptr;
1495 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001496 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1497 Handle<mirror::Class> method_return(hs.NewHandle(
1498 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001499
1500 AnnotationValue annotation_value;
1501 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1502 return nullptr;
1503 }
1504 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1505
1506 mirror::Class* annotation_member_class =
1507 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1508 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1509 Handle<mirror::Method> method_object(
1510 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1511
1512 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1513 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1514 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1515 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1516 return nullptr;
1517 }
1518
1519 JValue result;
1520 ArtMethod* annotation_member_init =
1521 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1522 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1523 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1524 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1525 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1526 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1527 };
1528 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1529 if (self->IsExceptionPending()) {
1530 LOG(INFO) << "Exception in AnnotationMember.<init>";
1531 return nullptr;
1532 }
1533
1534 return new_member.Get();
1535}
1536
1537const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1538 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1539 Handle<mirror::Class> annotation_class) const {
1540 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1541 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1542 if (annotation_item->visibility_ != visibility) {
1543 continue;
1544 }
1545 const uint8_t* annotation = annotation_item->annotation_;
1546 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1547 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1548 klass->GetDexFile(), type_index, klass.Get());
1549 if (resolved_class == nullptr) {
1550 std::string temp;
1551 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1552 klass->GetDescriptor(&temp), type_index);
1553 CHECK(Thread::Current()->IsExceptionPending());
1554 Thread::Current()->ClearException();
1555 continue;
1556 }
1557 if (resolved_class == annotation_class.Get()) {
1558 return annotation_item;
1559 }
1560 }
1561
1562 return nullptr;
1563}
1564
1565mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1566 const AnnotationSetItem* annotation_set, uint32_t visibility,
1567 Handle<mirror::Class> annotation_class) const {
1568 const AnnotationItem* annotation_item =
1569 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1570 if (annotation_item == nullptr) {
1571 return nullptr;
1572 }
1573 const uint8_t* annotation = annotation_item->annotation_;
1574 return ProcessEncodedAnnotation(klass, &annotation);
1575}
1576
1577mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1578 const AnnotationItem* annotation_item, const char* annotation_name,
1579 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1580 const uint8_t* annotation =
1581 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1582 if (annotation == nullptr) {
1583 return nullptr;
1584 }
1585 AnnotationValue annotation_value;
1586 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1587 return nullptr;
1588 }
1589 if (annotation_value.type_ != expected_type) {
1590 return nullptr;
1591 }
1592 return annotation_value.value_.GetL();
1593}
1594
Jeff Hao2a5892f2015-08-31 15:00:40 -07001595mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001596 const AnnotationSetItem* annotation_set) const {
1597 StackHandleScope<1> hs(Thread::Current());
1598 const AnnotationItem* annotation_item =
1599 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1600 if (annotation_item == nullptr) {
1601 return nullptr;
1602 }
1603 mirror::Class* string_class = mirror::String::GetJavaLangString();
1604 Handle<mirror::Class> string_array_class(hs.NewHandle(
1605 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001606 if (string_array_class.Get() == nullptr) {
1607 return nullptr;
1608 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001609 mirror::Object* obj =
1610 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1611 if (obj == nullptr) {
1612 return nullptr;
1613 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001614 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001615}
1616
Jeff Hao2a5892f2015-08-31 15:00:40 -07001617mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001618 const AnnotationSetItem* annotation_set) const {
1619 StackHandleScope<1> hs(Thread::Current());
1620 const AnnotationItem* annotation_item =
1621 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1622 if (annotation_item == nullptr) {
1623 return nullptr;
1624 }
1625 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1626 Handle<mirror::Class> class_array_class(hs.NewHandle(
1627 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001628 if (class_array_class.Get() == nullptr) {
1629 return nullptr;
1630 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001631 mirror::Object* obj =
1632 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1633 if (obj == nullptr) {
1634 return nullptr;
1635 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001636 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001637}
1638
1639mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1640 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1641 Thread* self = Thread::Current();
1642 ScopedObjectAccessUnchecked soa(self);
1643 StackHandleScope<2> hs(self);
1644 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1645 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1646 if (annotation_set == nullptr) {
1647 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1648 }
1649
1650 uint32_t size = annotation_set->size_;
1651 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1652 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1653 if (result.Get() == nullptr) {
1654 return nullptr;
1655 }
1656
1657 uint32_t dest_index = 0;
1658 for (uint32_t i = 0; i < size; ++i) {
1659 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1660 if (annotation_item->visibility_ != visibility) {
1661 continue;
1662 }
1663 const uint8_t* annotation = annotation_item->annotation_;
1664 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1665 if (annotation_obj != nullptr) {
1666 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1667 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001668 } else if (self->IsExceptionPending()) {
1669 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001670 }
1671 }
1672
1673 if (dest_index == size) {
1674 return result.Get();
1675 }
1676
1677 mirror::ObjectArray<mirror::Object>* trimmed_result =
1678 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001679 if (trimmed_result == nullptr) {
1680 return nullptr;
1681 }
1682
Jeff Hao13e748b2015-08-25 20:44:19 +00001683 for (uint32_t i = 0; i < dest_index; ++i) {
1684 mirror::Object* obj = result->GetWithoutChecks(i);
1685 trimmed_result->SetWithoutChecks<false>(i, obj);
1686 }
1687
1688 return trimmed_result;
1689}
1690
1691mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1692 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1693 Thread* self = Thread::Current();
1694 ScopedObjectAccessUnchecked soa(self);
1695 StackHandleScope<1> hs(self);
1696 mirror::Class* annotation_array_class =
1697 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1698 mirror::Class* annotation_array_array_class =
1699 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001700 if (annotation_array_array_class == nullptr) {
1701 return nullptr;
1702 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001703 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1704 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1705 if (annotation_array_array.Get() == nullptr) {
1706 LOG(ERROR) << "Annotation set ref array allocation failed";
1707 return nullptr;
1708 }
1709 for (uint32_t index = 0; index < size; ++index) {
1710 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1711 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1712 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1713 if (annotation_set == nullptr) {
1714 return nullptr;
1715 }
1716 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1717 }
1718 return annotation_array_array.Get();
1719}
1720
1721bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1722 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1723 DexFile::AnnotationResultStyle result_style) const {
1724 Thread* self = Thread::Current();
1725 mirror::Object* element_object = nullptr;
1726 bool set_object = false;
1727 Primitive::Type primitive_type = Primitive::kPrimVoid;
1728 const uint8_t* annotation = *annotation_ptr;
1729 uint8_t header_byte = *(annotation++);
1730 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1731 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1732 int32_t width = value_arg + 1;
1733 annotation_value->type_ = value_type;
1734
1735 switch (value_type) {
1736 case kDexAnnotationByte:
1737 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1738 primitive_type = Primitive::kPrimByte;
1739 break;
1740 case kDexAnnotationShort:
1741 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1742 primitive_type = Primitive::kPrimShort;
1743 break;
1744 case kDexAnnotationChar:
1745 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1746 false)));
1747 primitive_type = Primitive::kPrimChar;
1748 break;
1749 case kDexAnnotationInt:
1750 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1751 primitive_type = Primitive::kPrimInt;
1752 break;
1753 case kDexAnnotationLong:
1754 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1755 primitive_type = Primitive::kPrimLong;
1756 break;
1757 case kDexAnnotationFloat:
1758 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1759 primitive_type = Primitive::kPrimFloat;
1760 break;
1761 case kDexAnnotationDouble:
1762 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1763 primitive_type = Primitive::kPrimDouble;
1764 break;
1765 case kDexAnnotationBoolean:
1766 annotation_value->value_.SetZ(value_arg != 0);
1767 primitive_type = Primitive::kPrimBoolean;
1768 width = 0;
1769 break;
1770 case kDexAnnotationString: {
1771 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1772 if (result_style == kAllRaw) {
1773 annotation_value->value_.SetI(index);
1774 } else {
1775 StackHandleScope<1> hs(self);
1776 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1777 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1778 klass->GetDexFile(), index, dex_cache);
1779 set_object = true;
1780 if (element_object == nullptr) {
1781 return false;
1782 }
1783 }
1784 break;
1785 }
1786 case kDexAnnotationType: {
1787 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1788 if (result_style == kAllRaw) {
1789 annotation_value->value_.SetI(index);
1790 } else {
1791 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1792 klass->GetDexFile(), index, klass.Get());
1793 set_object = true;
1794 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001795 CHECK(self->IsExceptionPending());
1796 if (result_style == kAllObjects) {
1797 const char* msg = StringByTypeIdx(index);
1798 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1799 element_object = self->GetException();
1800 self->ClearException();
1801 } else {
1802 return false;
1803 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001804 }
1805 }
1806 break;
1807 }
1808 case kDexAnnotationMethod: {
1809 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1810 if (result_style == kAllRaw) {
1811 annotation_value->value_.SetI(index);
1812 } else {
1813 StackHandleScope<2> hs(self);
1814 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1815 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1816 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1817 klass->GetDexFile(), index, dex_cache, class_loader);
1818 if (method == nullptr) {
1819 return false;
1820 }
1821 set_object = true;
1822 if (method->IsConstructor()) {
1823 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1824 } else {
1825 element_object = mirror::Method::CreateFromArtMethod(self, method);
1826 }
1827 if (element_object == nullptr) {
1828 return false;
1829 }
1830 }
1831 break;
1832 }
1833 case kDexAnnotationField: {
1834 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1835 if (result_style == kAllRaw) {
1836 annotation_value->value_.SetI(index);
1837 } else {
1838 StackHandleScope<2> hs(self);
1839 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1840 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1841 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1842 klass->GetDexFile(), index, dex_cache, class_loader);
1843 if (field == nullptr) {
1844 return false;
1845 }
1846 set_object = true;
1847 element_object = mirror::Field::CreateFromArtField(self, field, true);
1848 if (element_object == nullptr) {
1849 return false;
1850 }
1851 }
1852 break;
1853 }
1854 case kDexAnnotationEnum: {
1855 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1856 if (result_style == kAllRaw) {
1857 annotation_value->value_.SetI(index);
1858 } else {
1859 StackHandleScope<3> hs(self);
1860 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1861 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1862 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1863 klass->GetDexFile(), index, dex_cache, class_loader, true);
1864 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1865 if (enum_field == nullptr) {
1866 return false;
1867 } else {
1868 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1869 element_object = enum_field->GetObject(field_class.Get());
1870 set_object = true;
1871 }
1872 }
1873 break;
1874 }
1875 case kDexAnnotationArray:
1876 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1877 return false;
1878 } else {
1879 ScopedObjectAccessUnchecked soa(self);
1880 StackHandleScope<2> hs(self);
1881 uint32_t size = DecodeUnsignedLeb128(&annotation);
1882 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1883 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1884 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1885 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1886 if (new_array.Get() == nullptr) {
1887 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1888 return false;
1889 }
1890 AnnotationValue new_annotation_value;
1891 for (uint32_t i = 0; i < size; ++i) {
1892 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1893 kPrimitivesOrObjects)) {
1894 return false;
1895 }
1896 if (!component_type->IsPrimitive()) {
1897 mirror::Object* obj = new_annotation_value.value_.GetL();
1898 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1899 } else {
1900 switch (new_annotation_value.type_) {
1901 case kDexAnnotationByte:
1902 new_array->AsByteArray()->SetWithoutChecks<false>(
1903 i, new_annotation_value.value_.GetB());
1904 break;
1905 case kDexAnnotationShort:
1906 new_array->AsShortArray()->SetWithoutChecks<false>(
1907 i, new_annotation_value.value_.GetS());
1908 break;
1909 case kDexAnnotationChar:
1910 new_array->AsCharArray()->SetWithoutChecks<false>(
1911 i, new_annotation_value.value_.GetC());
1912 break;
1913 case kDexAnnotationInt:
1914 new_array->AsIntArray()->SetWithoutChecks<false>(
1915 i, new_annotation_value.value_.GetI());
1916 break;
1917 case kDexAnnotationLong:
1918 new_array->AsLongArray()->SetWithoutChecks<false>(
1919 i, new_annotation_value.value_.GetJ());
1920 break;
1921 case kDexAnnotationFloat:
1922 new_array->AsFloatArray()->SetWithoutChecks<false>(
1923 i, new_annotation_value.value_.GetF());
1924 break;
1925 case kDexAnnotationDouble:
1926 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1927 i, new_annotation_value.value_.GetD());
1928 break;
1929 case kDexAnnotationBoolean:
1930 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1931 i, new_annotation_value.value_.GetZ());
1932 break;
1933 default:
1934 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1935 return false;
1936 }
1937 }
1938 }
1939 element_object = new_array.Get();
1940 set_object = true;
1941 width = 0;
1942 }
1943 break;
1944 case kDexAnnotationAnnotation:
1945 if (result_style == kAllRaw) {
1946 return false;
1947 }
1948 element_object = ProcessEncodedAnnotation(klass, &annotation);
1949 if (element_object == nullptr) {
1950 return false;
1951 }
1952 set_object = true;
1953 width = 0;
1954 break;
1955 case kDexAnnotationNull:
1956 if (result_style == kAllRaw) {
1957 annotation_value->value_.SetI(0);
1958 } else {
1959 CHECK(element_object == nullptr);
1960 set_object = true;
1961 }
1962 width = 0;
1963 break;
1964 default:
1965 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1966 return false;
1967 }
1968
1969 annotation += width;
1970 *annotation_ptr = annotation;
1971
1972 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1973 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1974 set_object = true;
1975 }
1976
1977 if (set_object) {
1978 annotation_value->value_.SetL(element_object);
1979 }
1980
1981 return true;
1982}
1983
1984mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1985 const uint8_t** annotation) const {
1986 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1987 uint32_t size = DecodeUnsignedLeb128(annotation);
1988
1989 Thread* self = Thread::Current();
1990 ScopedObjectAccessUnchecked soa(self);
1991 StackHandleScope<2> hs(self);
1992 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1993 Handle<mirror::Class> annotation_class(hs.NewHandle(
1994 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1995 if (annotation_class.Get() == nullptr) {
1996 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1997 << type_index;
1998 DCHECK(Thread::Current()->IsExceptionPending());
1999 Thread::Current()->ClearException();
2000 return nullptr;
2001 }
2002
2003 mirror::Class* annotation_member_class =
2004 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2005 mirror::Class* annotation_member_array_class =
2006 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002007 if (annotation_member_array_class == nullptr) {
2008 return nullptr;
2009 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002010 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002011 if (size > 0) {
2012 element_array =
2013 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2014 if (element_array == nullptr) {
2015 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2016 return nullptr;
2017 }
2018 }
2019
2020 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2021 for (uint32_t i = 0; i < size; ++i) {
2022 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2023 if (new_member == nullptr) {
2024 return nullptr;
2025 }
2026 h_element_array->SetWithoutChecks<false>(i, new_member);
2027 }
2028
2029 JValue result;
2030 ArtMethod* create_annotation_method =
2031 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2032 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2033 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2034 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2035 if (self->IsExceptionPending()) {
2036 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2037 return nullptr;
2038 }
2039
2040 return result.GetL();
2041}
2042
2043const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2044 const char* descriptor, uint32_t visibility) const {
2045 const AnnotationItem* result = nullptr;
2046 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2047 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2048 if (annotation_item->visibility_ != visibility) {
2049 continue;
2050 }
2051 const uint8_t* annotation = annotation_item->annotation_;
2052 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2053
2054 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2055 result = annotation_item;
2056 break;
2057 }
2058 }
2059 return result;
2060}
2061
2062const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2063 DecodeUnsignedLeb128(&annotation); // unused type_index
2064 uint32_t size = DecodeUnsignedLeb128(&annotation);
2065
2066 while (size != 0) {
2067 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2068 const char* element_name = GetStringData(GetStringId(element_name_index));
2069 if (strcmp(name, element_name) == 0) {
2070 return annotation;
2071 }
2072 SkipAnnotationValue(&annotation);
2073 size--;
2074 }
2075 return nullptr;
2076}
2077
2078bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2079 const uint8_t* annotation = *annotation_ptr;
2080 uint8_t header_byte = *(annotation++);
2081 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2082 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2083 int32_t width = value_arg + 1;
2084
2085 switch (value_type) {
2086 case kDexAnnotationByte:
2087 case kDexAnnotationShort:
2088 case kDexAnnotationChar:
2089 case kDexAnnotationInt:
2090 case kDexAnnotationLong:
2091 case kDexAnnotationFloat:
2092 case kDexAnnotationDouble:
2093 case kDexAnnotationString:
2094 case kDexAnnotationType:
2095 case kDexAnnotationMethod:
2096 case kDexAnnotationField:
2097 case kDexAnnotationEnum:
2098 break;
2099 case kDexAnnotationArray:
2100 {
2101 uint32_t size = DecodeUnsignedLeb128(&annotation);
2102 while (size--) {
2103 if (!SkipAnnotationValue(&annotation)) {
2104 return false;
2105 }
2106 }
2107 width = 0;
2108 break;
2109 }
2110 case kDexAnnotationAnnotation:
2111 {
2112 DecodeUnsignedLeb128(&annotation); // unused type_index
2113 uint32_t size = DecodeUnsignedLeb128(&annotation);
2114 while (size--) {
2115 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2116 if (!SkipAnnotationValue(&annotation)) {
2117 return false;
2118 }
2119 }
2120 width = 0;
2121 break;
2122 }
2123 case kDexAnnotationBoolean:
2124 case kDexAnnotationNull:
2125 width = 0;
2126 break;
2127 default:
2128 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2129 return false;
2130 }
2131
2132 annotation += width;
2133 *annotation_ptr = annotation;
2134 return true;
2135}
2136
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002137std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2138 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2139 dex_file.GetLocation().c_str(),
2140 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2141 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2142 return os;
2143}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002144
Ian Rogersd91d6d62013-09-25 20:26:14 -07002145std::string Signature::ToString() const {
2146 if (dex_file_ == nullptr) {
2147 CHECK(proto_id_ == nullptr);
2148 return "<no signature>";
2149 }
2150 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2151 std::string result;
2152 if (params == nullptr) {
2153 result += "()";
2154 } else {
2155 result += "(";
2156 for (uint32_t i = 0; i < params->Size(); ++i) {
2157 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2158 }
2159 result += ")";
2160 }
2161 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2162 return result;
2163}
2164
Vladimir Markod9cffea2013-11-25 15:08:02 +00002165bool Signature::operator==(const StringPiece& rhs) const {
2166 if (dex_file_ == nullptr) {
2167 return false;
2168 }
2169 StringPiece tail(rhs);
2170 if (!tail.starts_with("(")) {
2171 return false; // Invalid signature
2172 }
2173 tail.remove_prefix(1); // "(";
2174 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2175 if (params != nullptr) {
2176 for (uint32_t i = 0; i < params->Size(); ++i) {
2177 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2178 if (!tail.starts_with(param)) {
2179 return false;
2180 }
2181 tail.remove_prefix(param.length());
2182 }
2183 }
2184 if (!tail.starts_with(")")) {
2185 return false;
2186 }
2187 tail.remove_prefix(1); // ")";
2188 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2189}
2190
Ian Rogersd91d6d62013-09-25 20:26:14 -07002191std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2192 return os << sig.ToString();
2193}
2194
Ian Rogers0571d352011-11-03 19:51:38 -07002195// Decodes the header section from the class data bytes.
2196void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002197 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002198 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2199 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2200 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2201 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2202}
2203
2204void ClassDataItemIterator::ReadClassDataField() {
2205 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2206 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002207 // The user of the iterator is responsible for checking if there
2208 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002209}
2210
2211void ClassDataItemIterator::ReadClassDataMethod() {
2212 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2213 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2214 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002215 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002216 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002217 }
Ian Rogers0571d352011-11-03 19:51:38 -07002218}
2219
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002220EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2221 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2222 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2223 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002224 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2225 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002226 DCHECK(dex_cache != nullptr);
2227 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002228 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002229 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002230 array_size_ = 0;
2231 } else {
2232 array_size_ = DecodeUnsignedLeb128(&ptr_);
2233 }
2234 if (array_size_ > 0) {
2235 Next();
2236 }
2237}
2238
2239void EncodedStaticFieldValueIterator::Next() {
2240 pos_++;
2241 if (pos_ >= array_size_) {
2242 return;
2243 }
Ian Rogers13735952014-10-08 12:43:28 -07002244 uint8_t value_type = *ptr_++;
2245 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002246 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002247 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002248 switch (type_) {
2249 case kBoolean:
2250 jval_.i = (value_arg != 0) ? 1 : 0;
2251 width = 0;
2252 break;
2253 case kByte:
2254 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002255 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002256 break;
2257 case kShort:
2258 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002259 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002260 break;
2261 case kChar:
2262 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002263 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002264 break;
2265 case kInt:
2266 jval_.i = ReadSignedInt(ptr_, value_arg);
2267 break;
2268 case kLong:
2269 jval_.j = ReadSignedLong(ptr_, value_arg);
2270 break;
2271 case kFloat:
2272 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2273 break;
2274 case kDouble:
2275 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2276 break;
2277 case kString:
2278 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002279 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2280 break;
2281 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002282 case kMethod:
2283 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002284 case kArray:
2285 case kAnnotation:
2286 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002287 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002288 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002289 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002290 width = 0;
2291 break;
2292 default:
2293 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002294 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002295 }
2296 ptr_ += width;
2297}
2298
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002299template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002300void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002301 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002302 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2303 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002304 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2305 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2306 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2307 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2308 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2309 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2310 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002311 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002312 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002313 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002314 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002315 break;
2316 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002317 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2319 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002320 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002321 break;
2322 }
Ian Rogers0571d352011-11-03 19:51:38 -07002323 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2324 }
2325}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002326template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2327template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002328
2329CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2330 handler_.address_ = -1;
2331 int32_t offset = -1;
2332
2333 // Short-circuit the overwhelmingly common cases.
2334 switch (code_item.tries_size_) {
2335 case 0:
2336 break;
2337 case 1: {
2338 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2339 uint32_t start = tries->start_addr_;
2340 if (address >= start) {
2341 uint32_t end = start + tries->insn_count_;
2342 if (address < end) {
2343 offset = tries->handler_off_;
2344 }
2345 }
2346 break;
2347 }
2348 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002349 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002350 }
Logan Chien736df022012-04-27 16:25:57 +08002351 Init(code_item, offset);
2352}
2353
2354CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2355 const DexFile::TryItem& try_item) {
2356 handler_.address_ = -1;
2357 Init(code_item, try_item.handler_off_);
2358}
2359
2360void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2361 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002362 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002363 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002364 } else {
2365 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002366 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002367 remaining_count_ = -1;
2368 catch_all_ = false;
2369 DCHECK(!HasNext());
2370 }
2371}
2372
Ian Rogers13735952014-10-08 12:43:28 -07002373void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002374 current_data_ = handler_data;
2375 remaining_count_ = DecodeSignedLeb128(&current_data_);
2376
2377 // If remaining_count_ is non-positive, then it is the negative of
2378 // the number of catch types, and the catches are followed by a
2379 // catch-all handler.
2380 if (remaining_count_ <= 0) {
2381 catch_all_ = true;
2382 remaining_count_ = -remaining_count_;
2383 } else {
2384 catch_all_ = false;
2385 }
2386 Next();
2387}
2388
2389void CatchHandlerIterator::Next() {
2390 if (remaining_count_ > 0) {
2391 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2392 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2393 remaining_count_--;
2394 return;
2395 }
2396
2397 if (catch_all_) {
2398 handler_.type_idx_ = DexFile::kDexNoIndex16;
2399 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2400 catch_all_ = false;
2401 return;
2402 }
2403
2404 // no more handler
2405 remaining_count_ = -1;
2406}
2407
Carl Shapiro1fb86202011-06-27 17:43:13 -07002408} // namespace art