blob: a2af9d0610647c00c97fb7d7ff1d16dd55acad82 [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));
1231 Handle<mirror::Class> return_type(hs.NewHandle(method->GetReturnType()));
1232 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1233 return nullptr;
1234 }
1235 return annotation_value.value_.GetL();
1236}
1237
1238mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1239 Handle<mirror::Class> annotation_class) const {
1240 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1241 if (annotation_set == nullptr) {
1242 return nullptr;
1243 }
1244 StackHandleScope<1> hs(Thread::Current());
1245 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1246 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1247 kDexVisibilityRuntime, annotation_class);
1248}
1249
1250mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1251 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1252 StackHandleScope<1> hs(Thread::Current());
1253 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1254 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1255}
1256
Jeff Hao2a5892f2015-08-31 15:00:40 -07001257mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001258 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1259 if (annotation_set == nullptr) {
1260 return nullptr;
1261 }
1262 StackHandleScope<1> hs(Thread::Current());
1263 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1264 return GetThrowsValue(method_class, annotation_set);
1265}
1266
1267mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1268 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1269 if (parameter_annotations == nullptr) {
1270 return nullptr;
1271 }
1272 const AnnotationSetRefList* set_ref_list =
1273 GetParameterAnnotationSetRefList(parameter_annotations);
1274 if (set_ref_list == nullptr) {
1275 return nullptr;
1276 }
1277 uint32_t size = set_ref_list->size_;
1278 StackHandleScope<1> hs(Thread::Current());
1279 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1280 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1281}
1282
1283bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1284 const {
1285 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1286 if (annotation_set == nullptr) {
1287 return false;
1288 }
1289 StackHandleScope<1> hs(Thread::Current());
1290 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1291 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1292 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001293 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001294}
1295
1296const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1297 const {
1298 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1299 if (annotations_dir == nullptr) {
1300 return nullptr;
1301 }
1302 return GetClassAnnotationSet(annotations_dir);
1303}
1304
1305mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1306 Handle<mirror::Class> annotation_class) const {
1307 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1308 if (annotation_set == nullptr) {
1309 return nullptr;
1310 }
1311 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1312 annotation_class);
1313}
1314
1315mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1316 const {
1317 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1318 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1319}
1320
Jeff Hao2a5892f2015-08-31 15:00:40 -07001321mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1322 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1323 if (annotation_set == nullptr) {
1324 return nullptr;
1325 }
1326 const AnnotationItem* annotation_item = SearchAnnotationSet(
1327 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1328 if (annotation_item == nullptr) {
1329 return nullptr;
1330 }
1331 StackHandleScope<1> hs(Thread::Current());
1332 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1333 Handle<mirror::Class> class_array_class(hs.NewHandle(
1334 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1335 if (class_array_class.Get() == nullptr) {
1336 return nullptr;
1337 }
1338 mirror::Object* obj = GetAnnotationValue(
1339 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1340 if (obj == nullptr) {
1341 return nullptr;
1342 }
1343 return obj->AsObjectArray<mirror::Class>();
1344}
1345
1346mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1347 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1348 if (annotation_set == nullptr) {
1349 return nullptr;
1350 }
1351 const AnnotationItem* annotation_item = SearchAnnotationSet(
1352 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1353 if (annotation_item == nullptr) {
1354 return nullptr;
1355 }
1356 mirror::Object* obj = GetAnnotationValue(
1357 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1358 if (obj == nullptr) {
1359 return nullptr;
1360 }
1361 return obj->AsClass();
1362}
1363
1364mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1365 mirror::Class* declaring_class = GetDeclaringClass(klass);
1366 if (declaring_class != nullptr) {
1367 return declaring_class;
1368 }
1369 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1370 if (annotation_set == nullptr) {
1371 return nullptr;
1372 }
1373 const AnnotationItem* annotation_item = SearchAnnotationSet(
1374 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1375 if (annotation_item == nullptr) {
1376 return nullptr;
1377 }
1378 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1379 if (annotation == nullptr) {
1380 return nullptr;
1381 }
1382 AnnotationValue annotation_value;
1383 if (!ProcessAnnotationValue(
1384 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1385 return nullptr;
1386 }
1387 if (annotation_value.type_ != kDexAnnotationMethod) {
1388 return nullptr;
1389 }
1390 StackHandleScope<2> hs(Thread::Current());
1391 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1392 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1393 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1394 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1395 if (method == nullptr) {
1396 return nullptr;
1397 }
1398 return method->GetDeclaringClass();
1399}
1400
1401mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1402 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1403 if (annotation_set == nullptr) {
1404 return nullptr;
1405 }
1406 const AnnotationItem* annotation_item = SearchAnnotationSet(
1407 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1408 if (annotation_item == nullptr) {
1409 return nullptr;
1410 }
1411 return GetAnnotationValue(
1412 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1413}
1414
1415bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1416 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1417 if (annotation_set == nullptr) {
1418 return false;
1419 }
1420 const AnnotationItem* annotation_item = SearchAnnotationSet(
1421 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1422 if (annotation_item == nullptr) {
1423 return false;
1424 }
1425 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1426 if (annotation == nullptr) {
1427 return false;
1428 }
1429 AnnotationValue annotation_value;
1430 if (!ProcessAnnotationValue(
1431 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1432 return false;
1433 }
1434 if (annotation_value.type_ != kDexAnnotationNull &&
1435 annotation_value.type_ != kDexAnnotationString) {
1436 return false;
1437 }
1438 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1439 return true;
1440}
1441
1442bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1443 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1444 if (annotation_set == nullptr) {
1445 return false;
1446 }
1447 const AnnotationItem* annotation_item = SearchAnnotationSet(
1448 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1449 if (annotation_item == nullptr) {
1450 return false;
1451 }
1452 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1453 if (annotation == nullptr) {
1454 return false;
1455 }
1456 AnnotationValue annotation_value;
1457 if (!ProcessAnnotationValue(
1458 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1459 return false;
1460 }
1461 if (annotation_value.type_ != kDexAnnotationInt) {
1462 return false;
1463 }
1464 *flags = annotation_value.value_.GetI();
1465 return true;
1466}
1467
Jeff Hao13e748b2015-08-25 20:44:19 +00001468bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1469 Handle<mirror::Class> annotation_class) const {
1470 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1471 if (annotation_set == nullptr) {
1472 return false;
1473 }
1474 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1475 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001476 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001477}
1478
1479mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1480 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1481 Thread* self = Thread::Current();
1482 ScopedObjectAccessUnchecked soa(self);
1483 StackHandleScope<5> hs(self);
1484 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1485 const char* name = StringDataByIdx(element_name_index);
1486 Handle<mirror::String> string_name(
1487 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1488
1489 ArtMethod* annotation_method =
1490 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1491 if (annotation_method == nullptr) {
1492 return nullptr;
1493 }
1494 Handle<mirror::Class> method_return(hs.NewHandle(annotation_method->GetReturnType()));
1495
1496 AnnotationValue annotation_value;
1497 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1498 return nullptr;
1499 }
1500 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1501
1502 mirror::Class* annotation_member_class =
1503 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1504 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1505 Handle<mirror::Method> method_object(
1506 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1507
1508 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1509 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1510 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1511 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1512 return nullptr;
1513 }
1514
1515 JValue result;
1516 ArtMethod* annotation_member_init =
1517 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1518 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1519 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1520 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1521 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1522 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1523 };
1524 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1525 if (self->IsExceptionPending()) {
1526 LOG(INFO) << "Exception in AnnotationMember.<init>";
1527 return nullptr;
1528 }
1529
1530 return new_member.Get();
1531}
1532
1533const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1534 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1535 Handle<mirror::Class> annotation_class) const {
1536 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1537 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1538 if (annotation_item->visibility_ != visibility) {
1539 continue;
1540 }
1541 const uint8_t* annotation = annotation_item->annotation_;
1542 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1543 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1544 klass->GetDexFile(), type_index, klass.Get());
1545 if (resolved_class == nullptr) {
1546 std::string temp;
1547 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1548 klass->GetDescriptor(&temp), type_index);
1549 CHECK(Thread::Current()->IsExceptionPending());
1550 Thread::Current()->ClearException();
1551 continue;
1552 }
1553 if (resolved_class == annotation_class.Get()) {
1554 return annotation_item;
1555 }
1556 }
1557
1558 return nullptr;
1559}
1560
1561mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1562 const AnnotationSetItem* annotation_set, uint32_t visibility,
1563 Handle<mirror::Class> annotation_class) const {
1564 const AnnotationItem* annotation_item =
1565 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1566 if (annotation_item == nullptr) {
1567 return nullptr;
1568 }
1569 const uint8_t* annotation = annotation_item->annotation_;
1570 return ProcessEncodedAnnotation(klass, &annotation);
1571}
1572
1573mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1574 const AnnotationItem* annotation_item, const char* annotation_name,
1575 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1576 const uint8_t* annotation =
1577 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1578 if (annotation == nullptr) {
1579 return nullptr;
1580 }
1581 AnnotationValue annotation_value;
1582 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1583 return nullptr;
1584 }
1585 if (annotation_value.type_ != expected_type) {
1586 return nullptr;
1587 }
1588 return annotation_value.value_.GetL();
1589}
1590
Jeff Hao2a5892f2015-08-31 15:00:40 -07001591mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001592 const AnnotationSetItem* annotation_set) const {
1593 StackHandleScope<1> hs(Thread::Current());
1594 const AnnotationItem* annotation_item =
1595 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1596 if (annotation_item == nullptr) {
1597 return nullptr;
1598 }
1599 mirror::Class* string_class = mirror::String::GetJavaLangString();
1600 Handle<mirror::Class> string_array_class(hs.NewHandle(
1601 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001602 if (string_array_class.Get() == nullptr) {
1603 return nullptr;
1604 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001605 mirror::Object* obj =
1606 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1607 if (obj == nullptr) {
1608 return nullptr;
1609 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001610 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001611}
1612
Jeff Hao2a5892f2015-08-31 15:00:40 -07001613mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001614 const AnnotationSetItem* annotation_set) const {
1615 StackHandleScope<1> hs(Thread::Current());
1616 const AnnotationItem* annotation_item =
1617 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1618 if (annotation_item == nullptr) {
1619 return nullptr;
1620 }
1621 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1622 Handle<mirror::Class> class_array_class(hs.NewHandle(
1623 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001624 if (class_array_class.Get() == nullptr) {
1625 return nullptr;
1626 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001627 mirror::Object* obj =
1628 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1629 if (obj == nullptr) {
1630 return nullptr;
1631 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001632 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001633}
1634
1635mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1636 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1637 Thread* self = Thread::Current();
1638 ScopedObjectAccessUnchecked soa(self);
1639 StackHandleScope<2> hs(self);
1640 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1641 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1642 if (annotation_set == nullptr) {
1643 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1644 }
1645
1646 uint32_t size = annotation_set->size_;
1647 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1648 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1649 if (result.Get() == nullptr) {
1650 return nullptr;
1651 }
1652
1653 uint32_t dest_index = 0;
1654 for (uint32_t i = 0; i < size; ++i) {
1655 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1656 if (annotation_item->visibility_ != visibility) {
1657 continue;
1658 }
1659 const uint8_t* annotation = annotation_item->annotation_;
1660 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1661 if (annotation_obj != nullptr) {
1662 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1663 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001664 } else if (self->IsExceptionPending()) {
1665 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001666 }
1667 }
1668
1669 if (dest_index == size) {
1670 return result.Get();
1671 }
1672
1673 mirror::ObjectArray<mirror::Object>* trimmed_result =
1674 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001675 if (trimmed_result == nullptr) {
1676 return nullptr;
1677 }
1678
Jeff Hao13e748b2015-08-25 20:44:19 +00001679 for (uint32_t i = 0; i < dest_index; ++i) {
1680 mirror::Object* obj = result->GetWithoutChecks(i);
1681 trimmed_result->SetWithoutChecks<false>(i, obj);
1682 }
1683
1684 return trimmed_result;
1685}
1686
1687mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1688 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1689 Thread* self = Thread::Current();
1690 ScopedObjectAccessUnchecked soa(self);
1691 StackHandleScope<1> hs(self);
1692 mirror::Class* annotation_array_class =
1693 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1694 mirror::Class* annotation_array_array_class =
1695 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001696 if (annotation_array_array_class == nullptr) {
1697 return nullptr;
1698 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001699 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1700 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1701 if (annotation_array_array.Get() == nullptr) {
1702 LOG(ERROR) << "Annotation set ref array allocation failed";
1703 return nullptr;
1704 }
1705 for (uint32_t index = 0; index < size; ++index) {
1706 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1707 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1708 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1709 if (annotation_set == nullptr) {
1710 return nullptr;
1711 }
1712 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1713 }
1714 return annotation_array_array.Get();
1715}
1716
1717bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1718 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1719 DexFile::AnnotationResultStyle result_style) const {
1720 Thread* self = Thread::Current();
1721 mirror::Object* element_object = nullptr;
1722 bool set_object = false;
1723 Primitive::Type primitive_type = Primitive::kPrimVoid;
1724 const uint8_t* annotation = *annotation_ptr;
1725 uint8_t header_byte = *(annotation++);
1726 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1727 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1728 int32_t width = value_arg + 1;
1729 annotation_value->type_ = value_type;
1730
1731 switch (value_type) {
1732 case kDexAnnotationByte:
1733 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1734 primitive_type = Primitive::kPrimByte;
1735 break;
1736 case kDexAnnotationShort:
1737 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1738 primitive_type = Primitive::kPrimShort;
1739 break;
1740 case kDexAnnotationChar:
1741 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1742 false)));
1743 primitive_type = Primitive::kPrimChar;
1744 break;
1745 case kDexAnnotationInt:
1746 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1747 primitive_type = Primitive::kPrimInt;
1748 break;
1749 case kDexAnnotationLong:
1750 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1751 primitive_type = Primitive::kPrimLong;
1752 break;
1753 case kDexAnnotationFloat:
1754 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1755 primitive_type = Primitive::kPrimFloat;
1756 break;
1757 case kDexAnnotationDouble:
1758 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1759 primitive_type = Primitive::kPrimDouble;
1760 break;
1761 case kDexAnnotationBoolean:
1762 annotation_value->value_.SetZ(value_arg != 0);
1763 primitive_type = Primitive::kPrimBoolean;
1764 width = 0;
1765 break;
1766 case kDexAnnotationString: {
1767 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1768 if (result_style == kAllRaw) {
1769 annotation_value->value_.SetI(index);
1770 } else {
1771 StackHandleScope<1> hs(self);
1772 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1773 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1774 klass->GetDexFile(), index, dex_cache);
1775 set_object = true;
1776 if (element_object == nullptr) {
1777 return false;
1778 }
1779 }
1780 break;
1781 }
1782 case kDexAnnotationType: {
1783 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1784 if (result_style == kAllRaw) {
1785 annotation_value->value_.SetI(index);
1786 } else {
1787 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1788 klass->GetDexFile(), index, klass.Get());
1789 set_object = true;
1790 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001791 CHECK(self->IsExceptionPending());
1792 if (result_style == kAllObjects) {
1793 const char* msg = StringByTypeIdx(index);
1794 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1795 element_object = self->GetException();
1796 self->ClearException();
1797 } else {
1798 return false;
1799 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001800 }
1801 }
1802 break;
1803 }
1804 case kDexAnnotationMethod: {
1805 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1806 if (result_style == kAllRaw) {
1807 annotation_value->value_.SetI(index);
1808 } else {
1809 StackHandleScope<2> hs(self);
1810 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1811 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1812 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1813 klass->GetDexFile(), index, dex_cache, class_loader);
1814 if (method == nullptr) {
1815 return false;
1816 }
1817 set_object = true;
1818 if (method->IsConstructor()) {
1819 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1820 } else {
1821 element_object = mirror::Method::CreateFromArtMethod(self, method);
1822 }
1823 if (element_object == nullptr) {
1824 return false;
1825 }
1826 }
1827 break;
1828 }
1829 case kDexAnnotationField: {
1830 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1831 if (result_style == kAllRaw) {
1832 annotation_value->value_.SetI(index);
1833 } else {
1834 StackHandleScope<2> hs(self);
1835 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1836 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1837 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1838 klass->GetDexFile(), index, dex_cache, class_loader);
1839 if (field == nullptr) {
1840 return false;
1841 }
1842 set_object = true;
1843 element_object = mirror::Field::CreateFromArtField(self, field, true);
1844 if (element_object == nullptr) {
1845 return false;
1846 }
1847 }
1848 break;
1849 }
1850 case kDexAnnotationEnum: {
1851 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1852 if (result_style == kAllRaw) {
1853 annotation_value->value_.SetI(index);
1854 } else {
1855 StackHandleScope<3> hs(self);
1856 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1857 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1858 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1859 klass->GetDexFile(), index, dex_cache, class_loader, true);
1860 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1861 if (enum_field == nullptr) {
1862 return false;
1863 } else {
1864 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1865 element_object = enum_field->GetObject(field_class.Get());
1866 set_object = true;
1867 }
1868 }
1869 break;
1870 }
1871 case kDexAnnotationArray:
1872 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1873 return false;
1874 } else {
1875 ScopedObjectAccessUnchecked soa(self);
1876 StackHandleScope<2> hs(self);
1877 uint32_t size = DecodeUnsignedLeb128(&annotation);
1878 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1879 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1880 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1881 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1882 if (new_array.Get() == nullptr) {
1883 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1884 return false;
1885 }
1886 AnnotationValue new_annotation_value;
1887 for (uint32_t i = 0; i < size; ++i) {
1888 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1889 kPrimitivesOrObjects)) {
1890 return false;
1891 }
1892 if (!component_type->IsPrimitive()) {
1893 mirror::Object* obj = new_annotation_value.value_.GetL();
1894 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1895 } else {
1896 switch (new_annotation_value.type_) {
1897 case kDexAnnotationByte:
1898 new_array->AsByteArray()->SetWithoutChecks<false>(
1899 i, new_annotation_value.value_.GetB());
1900 break;
1901 case kDexAnnotationShort:
1902 new_array->AsShortArray()->SetWithoutChecks<false>(
1903 i, new_annotation_value.value_.GetS());
1904 break;
1905 case kDexAnnotationChar:
1906 new_array->AsCharArray()->SetWithoutChecks<false>(
1907 i, new_annotation_value.value_.GetC());
1908 break;
1909 case kDexAnnotationInt:
1910 new_array->AsIntArray()->SetWithoutChecks<false>(
1911 i, new_annotation_value.value_.GetI());
1912 break;
1913 case kDexAnnotationLong:
1914 new_array->AsLongArray()->SetWithoutChecks<false>(
1915 i, new_annotation_value.value_.GetJ());
1916 break;
1917 case kDexAnnotationFloat:
1918 new_array->AsFloatArray()->SetWithoutChecks<false>(
1919 i, new_annotation_value.value_.GetF());
1920 break;
1921 case kDexAnnotationDouble:
1922 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1923 i, new_annotation_value.value_.GetD());
1924 break;
1925 case kDexAnnotationBoolean:
1926 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1927 i, new_annotation_value.value_.GetZ());
1928 break;
1929 default:
1930 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1931 return false;
1932 }
1933 }
1934 }
1935 element_object = new_array.Get();
1936 set_object = true;
1937 width = 0;
1938 }
1939 break;
1940 case kDexAnnotationAnnotation:
1941 if (result_style == kAllRaw) {
1942 return false;
1943 }
1944 element_object = ProcessEncodedAnnotation(klass, &annotation);
1945 if (element_object == nullptr) {
1946 return false;
1947 }
1948 set_object = true;
1949 width = 0;
1950 break;
1951 case kDexAnnotationNull:
1952 if (result_style == kAllRaw) {
1953 annotation_value->value_.SetI(0);
1954 } else {
1955 CHECK(element_object == nullptr);
1956 set_object = true;
1957 }
1958 width = 0;
1959 break;
1960 default:
1961 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1962 return false;
1963 }
1964
1965 annotation += width;
1966 *annotation_ptr = annotation;
1967
1968 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1969 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1970 set_object = true;
1971 }
1972
1973 if (set_object) {
1974 annotation_value->value_.SetL(element_object);
1975 }
1976
1977 return true;
1978}
1979
1980mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1981 const uint8_t** annotation) const {
1982 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1983 uint32_t size = DecodeUnsignedLeb128(annotation);
1984
1985 Thread* self = Thread::Current();
1986 ScopedObjectAccessUnchecked soa(self);
1987 StackHandleScope<2> hs(self);
1988 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1989 Handle<mirror::Class> annotation_class(hs.NewHandle(
1990 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1991 if (annotation_class.Get() == nullptr) {
1992 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1993 << type_index;
1994 DCHECK(Thread::Current()->IsExceptionPending());
1995 Thread::Current()->ClearException();
1996 return nullptr;
1997 }
1998
1999 mirror::Class* annotation_member_class =
2000 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2001 mirror::Class* annotation_member_array_class =
2002 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002003 if (annotation_member_array_class == nullptr) {
2004 return nullptr;
2005 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002006 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002007 if (size > 0) {
2008 element_array =
2009 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2010 if (element_array == nullptr) {
2011 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2012 return nullptr;
2013 }
2014 }
2015
2016 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2017 for (uint32_t i = 0; i < size; ++i) {
2018 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2019 if (new_member == nullptr) {
2020 return nullptr;
2021 }
2022 h_element_array->SetWithoutChecks<false>(i, new_member);
2023 }
2024
2025 JValue result;
2026 ArtMethod* create_annotation_method =
2027 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2028 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2029 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2030 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2031 if (self->IsExceptionPending()) {
2032 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2033 return nullptr;
2034 }
2035
2036 return result.GetL();
2037}
2038
2039const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2040 const char* descriptor, uint32_t visibility) const {
2041 const AnnotationItem* result = nullptr;
2042 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2043 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2044 if (annotation_item->visibility_ != visibility) {
2045 continue;
2046 }
2047 const uint8_t* annotation = annotation_item->annotation_;
2048 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2049
2050 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2051 result = annotation_item;
2052 break;
2053 }
2054 }
2055 return result;
2056}
2057
2058const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2059 DecodeUnsignedLeb128(&annotation); // unused type_index
2060 uint32_t size = DecodeUnsignedLeb128(&annotation);
2061
2062 while (size != 0) {
2063 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2064 const char* element_name = GetStringData(GetStringId(element_name_index));
2065 if (strcmp(name, element_name) == 0) {
2066 return annotation;
2067 }
2068 SkipAnnotationValue(&annotation);
2069 size--;
2070 }
2071 return nullptr;
2072}
2073
2074bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2075 const uint8_t* annotation = *annotation_ptr;
2076 uint8_t header_byte = *(annotation++);
2077 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2078 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2079 int32_t width = value_arg + 1;
2080
2081 switch (value_type) {
2082 case kDexAnnotationByte:
2083 case kDexAnnotationShort:
2084 case kDexAnnotationChar:
2085 case kDexAnnotationInt:
2086 case kDexAnnotationLong:
2087 case kDexAnnotationFloat:
2088 case kDexAnnotationDouble:
2089 case kDexAnnotationString:
2090 case kDexAnnotationType:
2091 case kDexAnnotationMethod:
2092 case kDexAnnotationField:
2093 case kDexAnnotationEnum:
2094 break;
2095 case kDexAnnotationArray:
2096 {
2097 uint32_t size = DecodeUnsignedLeb128(&annotation);
2098 while (size--) {
2099 if (!SkipAnnotationValue(&annotation)) {
2100 return false;
2101 }
2102 }
2103 width = 0;
2104 break;
2105 }
2106 case kDexAnnotationAnnotation:
2107 {
2108 DecodeUnsignedLeb128(&annotation); // unused type_index
2109 uint32_t size = DecodeUnsignedLeb128(&annotation);
2110 while (size--) {
2111 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2112 if (!SkipAnnotationValue(&annotation)) {
2113 return false;
2114 }
2115 }
2116 width = 0;
2117 break;
2118 }
2119 case kDexAnnotationBoolean:
2120 case kDexAnnotationNull:
2121 width = 0;
2122 break;
2123 default:
2124 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2125 return false;
2126 }
2127
2128 annotation += width;
2129 *annotation_ptr = annotation;
2130 return true;
2131}
2132
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002133std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2134 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2135 dex_file.GetLocation().c_str(),
2136 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2137 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2138 return os;
2139}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002140
Ian Rogersd91d6d62013-09-25 20:26:14 -07002141std::string Signature::ToString() const {
2142 if (dex_file_ == nullptr) {
2143 CHECK(proto_id_ == nullptr);
2144 return "<no signature>";
2145 }
2146 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2147 std::string result;
2148 if (params == nullptr) {
2149 result += "()";
2150 } else {
2151 result += "(";
2152 for (uint32_t i = 0; i < params->Size(); ++i) {
2153 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2154 }
2155 result += ")";
2156 }
2157 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2158 return result;
2159}
2160
Vladimir Markod9cffea2013-11-25 15:08:02 +00002161bool Signature::operator==(const StringPiece& rhs) const {
2162 if (dex_file_ == nullptr) {
2163 return false;
2164 }
2165 StringPiece tail(rhs);
2166 if (!tail.starts_with("(")) {
2167 return false; // Invalid signature
2168 }
2169 tail.remove_prefix(1); // "(";
2170 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2171 if (params != nullptr) {
2172 for (uint32_t i = 0; i < params->Size(); ++i) {
2173 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2174 if (!tail.starts_with(param)) {
2175 return false;
2176 }
2177 tail.remove_prefix(param.length());
2178 }
2179 }
2180 if (!tail.starts_with(")")) {
2181 return false;
2182 }
2183 tail.remove_prefix(1); // ")";
2184 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2185}
2186
Ian Rogersd91d6d62013-09-25 20:26:14 -07002187std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2188 return os << sig.ToString();
2189}
2190
Ian Rogers0571d352011-11-03 19:51:38 -07002191// Decodes the header section from the class data bytes.
2192void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002193 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002194 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2195 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2196 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2197 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2198}
2199
2200void ClassDataItemIterator::ReadClassDataField() {
2201 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2202 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002203 // The user of the iterator is responsible for checking if there
2204 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002205}
2206
2207void ClassDataItemIterator::ReadClassDataMethod() {
2208 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2209 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2210 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002211 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002212 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002213 }
Ian Rogers0571d352011-11-03 19:51:38 -07002214}
2215
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002216EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2217 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2218 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2219 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002220 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2221 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002222 DCHECK(dex_cache != nullptr);
2223 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002224 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002225 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002226 array_size_ = 0;
2227 } else {
2228 array_size_ = DecodeUnsignedLeb128(&ptr_);
2229 }
2230 if (array_size_ > 0) {
2231 Next();
2232 }
2233}
2234
2235void EncodedStaticFieldValueIterator::Next() {
2236 pos_++;
2237 if (pos_ >= array_size_) {
2238 return;
2239 }
Ian Rogers13735952014-10-08 12:43:28 -07002240 uint8_t value_type = *ptr_++;
2241 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002242 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002243 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002244 switch (type_) {
2245 case kBoolean:
2246 jval_.i = (value_arg != 0) ? 1 : 0;
2247 width = 0;
2248 break;
2249 case kByte:
2250 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002251 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002252 break;
2253 case kShort:
2254 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002255 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002256 break;
2257 case kChar:
2258 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002259 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002260 break;
2261 case kInt:
2262 jval_.i = ReadSignedInt(ptr_, value_arg);
2263 break;
2264 case kLong:
2265 jval_.j = ReadSignedLong(ptr_, value_arg);
2266 break;
2267 case kFloat:
2268 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2269 break;
2270 case kDouble:
2271 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2272 break;
2273 case kString:
2274 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002275 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2276 break;
2277 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002278 case kMethod:
2279 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002280 case kArray:
2281 case kAnnotation:
2282 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002283 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002284 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002285 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002286 width = 0;
2287 break;
2288 default:
2289 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002290 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002291 }
2292 ptr_ += width;
2293}
2294
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002295template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002296void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002297 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002298 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2299 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002300 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2301 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2302 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2303 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2304 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2305 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2306 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002307 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002308 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002309 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002310 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002311 break;
2312 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002313 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002314 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2315 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002316 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002317 break;
2318 }
Ian Rogers0571d352011-11-03 19:51:38 -07002319 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2320 }
2321}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002322template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2323template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002324
2325CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2326 handler_.address_ = -1;
2327 int32_t offset = -1;
2328
2329 // Short-circuit the overwhelmingly common cases.
2330 switch (code_item.tries_size_) {
2331 case 0:
2332 break;
2333 case 1: {
2334 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2335 uint32_t start = tries->start_addr_;
2336 if (address >= start) {
2337 uint32_t end = start + tries->insn_count_;
2338 if (address < end) {
2339 offset = tries->handler_off_;
2340 }
2341 }
2342 break;
2343 }
2344 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002345 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002346 }
Logan Chien736df022012-04-27 16:25:57 +08002347 Init(code_item, offset);
2348}
2349
2350CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2351 const DexFile::TryItem& try_item) {
2352 handler_.address_ = -1;
2353 Init(code_item, try_item.handler_off_);
2354}
2355
2356void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2357 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002358 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002359 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002360 } else {
2361 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002362 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002363 remaining_count_ = -1;
2364 catch_all_ = false;
2365 DCHECK(!HasNext());
2366 }
2367}
2368
Ian Rogers13735952014-10-08 12:43:28 -07002369void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002370 current_data_ = handler_data;
2371 remaining_count_ = DecodeSignedLeb128(&current_data_);
2372
2373 // If remaining_count_ is non-positive, then it is the negative of
2374 // the number of catch types, and the catches are followed by a
2375 // catch-all handler.
2376 if (remaining_count_ <= 0) {
2377 catch_all_ = true;
2378 remaining_count_ = -remaining_count_;
2379 } else {
2380 catch_all_ = false;
2381 }
2382 Next();
2383}
2384
2385void CatchHandlerIterator::Next() {
2386 if (remaining_count_ > 0) {
2387 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2388 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2389 remaining_count_--;
2390 return;
2391 }
2392
2393 if (catch_all_) {
2394 handler_.type_idx_ = DexFile::kDexNoIndex16;
2395 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2396 catch_all_ = false;
2397 return;
2398 }
2399
2400 // no more handler
2401 remaining_count_ = -1;
2402}
2403
Carl Shapiro1fb86202011-06-27 17:43:13 -07002404} // namespace art