blob: 4a0a6fc8ad544453a93a2563ddf763ab8a23e5f9 [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"
Vladimir Marko5096e662015-12-08 19:25:49 +000032#include "base/file_magic.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070033#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080034#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010035#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080036#include "base/stringprintf.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000038#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070039#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080040#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070041#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030042#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070043#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000044#include "mirror/field.h"
45#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070047#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000048#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070050#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070052#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070053#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070055#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070056
Andreas Gampe277ccbd2014-11-03 21:36:10 -080057#pragma GCC diagnostic push
58#pragma GCC diagnostic ignored "-Wshadow"
59#include "ScopedFd.h"
60#pragma GCC diagnostic pop
61
Carl Shapiro1fb86202011-06-27 17:43:13 -070062namespace art {
63
Ian Rogers13735952014-10-08 12:43:28 -070064const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
65const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070066
Ian Rogers8d31bbd2013-10-13 10:44:14 -070067bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070068 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070069 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070070
71 // Strip ":...", which is the location
72 const char* zip_entry_name = kClassesDex;
73 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010074 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070075
Vladimir Markoaa4497d2014-09-05 14:01:17 +010076 if (DexFile::IsMultiDexLocation(filename)) {
77 file_part_storage = GetBaseLocation(filename);
78 file_part = file_part_storage.c_str();
79 zip_entry_name = filename + file_part_storage.size() + 1;
80 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070081 }
82
83 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000084 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070085 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070086 return false;
87 }
88 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070089 std::unique_ptr<ZipArchive> zip_archive(
90 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
91 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080092 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
93 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080094 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070095 }
Andreas Gampe833a4852014-05-21 18:46:59 -070096 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070097 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -070098 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
99 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800100 return false;
101 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700102 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800103 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700104 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700105 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700106 std::unique_ptr<const DexFile> dex_file(
107 DexFile::OpenFile(fd.release(), filename, false, error_msg));
108 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800109 return false;
110 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700111 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return true;
113 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700114 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800115 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700116}
117
Andreas Gampe833a4852014-05-21 18:46:59 -0700118bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800119 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800120 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700121 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700122 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000123 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
124 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700125 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700126 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700127 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700128 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700129 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700130 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700131 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700132 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
133 error_msg));
134 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800135 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700136 return true;
137 } else {
138 return false;
139 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700140 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700141 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400142 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700143}
144
Andreas Gampe0cba0042015-04-29 20:47:16 -0700145static bool ContainsClassesDex(int fd, const char* filename) {
146 std::string error_msg;
147 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
148 if (zip_archive.get() == nullptr) {
149 return false;
150 }
151 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
152 return (zip_entry.get() != nullptr);
153}
154
155bool DexFile::MaybeDex(const char* filename) {
156 uint32_t magic;
157 std::string error_msg;
158 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
159 if (fd.get() == -1) {
160 return false;
161 }
162 if (IsZipMagic(magic)) {
163 return ContainsClassesDex(fd.release(), filename);
164 } else if (IsDexMagic(magic)) {
165 return true;
166 }
167 return false;
168}
169
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800170int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700171 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800172 return 0;
173 } else {
174 return mem_map_->GetProtect();
175 }
176}
177
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200178bool DexFile::IsReadOnly() const {
179 return GetPermissions() == PROT_READ;
180}
181
Brian Carlstrome0948e12013-08-29 09:36:15 -0700182bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700184 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200185 return false;
186 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700187 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200188 }
189}
190
Brian Carlstrome0948e12013-08-29 09:36:15 -0700191bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200192 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700193 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194 return false;
195 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700196 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200197 }
198}
199
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800200std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
201 const std::string& location,
202 uint32_t location_checksum,
203 const OatDexFile* oat_dex_file,
204 bool verify,
205 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800206 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800207 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
208 size,
209 location,
210 location_checksum,
211 nullptr,
212 oat_dex_file,
213 error_msg);
214 if (verify && !DexFileVerifier::Verify(dex_file.get(),
215 dex_file->Begin(),
216 dex_file->Size(),
217 location.c_str(),
218 error_msg)) {
219 return nullptr;
220 }
221
222 return dex_file;
223}
224
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800225std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
226 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800227 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700228 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700229 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000230 {
231 ScopedFd delayed_close(fd);
232 struct stat sbuf;
233 memset(&sbuf, 0, sizeof(sbuf));
234 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800235 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000236 return nullptr;
237 }
238 if (S_ISDIR(sbuf.st_mode)) {
239 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
240 return nullptr;
241 }
242 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800243 map.reset(MemMap::MapFile(length,
244 PROT_READ,
245 MAP_PRIVATE,
246 fd,
247 0,
248 /*low_4gb*/false,
249 location,
250 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000251 if (map.get() == nullptr) {
252 DCHECK(!error_msg->empty());
253 return nullptr;
254 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700255 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800256
257 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700258 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800259 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700260 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800261 }
262
263 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
264
Andreas Gampe928f72b2014-09-09 19:53:48 -0700265 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
266 error_msg));
267 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700268 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
269 error_msg->c_str());
270 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800271 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800272
Andreas Gampe928f72b2014-09-09 19:53:48 -0700273 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
274 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700275 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800276 }
277
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800278 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700279}
280
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700281const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700282
Andreas Gampe833a4852014-05-21 18:46:59 -0700283bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800284 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800285 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700286 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700287 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700288 if (zip_archive.get() == nullptr) {
289 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700290 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700291 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700292 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800293}
294
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800295std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
296 uint32_t location_checksum,
297 MemMap* mem_map,
298 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800299 return OpenMemory(mem_map->Begin(),
300 mem_map->Size(),
301 location,
302 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800304 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800306}
307
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800308std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
309 const std::string& location, std::string* error_msg,
310 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800311 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800312 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700313 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700314 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700315 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700317 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700318 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700319 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700320 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700321 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700322 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700323 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700324 }
Ian Rogers700a4022014-05-19 16:49:03 -0700325 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 error_msg));
327 if (dex_file.get() == nullptr) {
328 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
329 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700330 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700331 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800332 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700333 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700334 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700337 }
338 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700339 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
340 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700341 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700342 return nullptr;
343 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700344 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800345 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700346}
347
Andreas Gampe90e34042015-04-27 20:01:52 -0700348// Technically we do not have a limitation with respect to the number of dex files that can be in a
349// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
350// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
351// seems an excessive number.
352static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
353
Andreas Gampe833a4852014-05-21 18:46:59 -0700354bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800355 std::string* error_msg,
356 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800357 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700358 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700359 ZipOpenErrorCode error_code;
360 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
361 &error_code));
362 if (dex_file.get() == nullptr) {
363 return false;
364 } else {
365 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800366 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700367
368 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700369
370 // We could try to avoid std::string allocations by working on a char array directly. As we
371 // do not expect a lot of iterations, this seems too involved and brittle.
372
Andreas Gampe90e34042015-04-27 20:01:52 -0700373 for (size_t i = 1; ; ++i) {
374 std::string name = GetMultiDexClassesDexName(i);
375 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700376 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
377 error_msg, &error_code));
378 if (next_dex_file.get() == nullptr) {
379 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
380 LOG(WARNING) << error_msg;
381 }
382 break;
383 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800384 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700385 }
386
Andreas Gampe90e34042015-04-27 20:01:52 -0700387 if (i == kWarnOnManyDexFilesThreshold) {
388 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
389 << " dex files. Please consider coalescing and shrinking the number to "
390 " avoid runtime overhead.";
391 }
392
393 if (i == std::numeric_limits<size_t>::max()) {
394 LOG(ERROR) << "Overflow in number of dex files!";
395 break;
396 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700397 }
398
399 return true;
400 }
401}
402
403
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800404std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
405 size_t size,
406 const std::string& location,
407 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800408 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700409 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800410 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700411 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800412 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700413 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700414 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800415 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700416 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800417 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700418}
419
Ian Rogers13735952014-10-08 12:43:28 -0700420DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800421 const std::string& location,
422 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800423 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700424 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800425 : begin_(base),
426 size_(size),
427 location_(location),
428 location_checksum_(location_checksum),
429 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800430 header_(reinterpret_cast<const Header*>(base)),
431 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
432 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
433 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
434 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
435 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700436 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700437 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700438 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800439 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300440 const uint8_t* lookup_data = (oat_dex_file != nullptr)
441 ? oat_dex_file->GetLookupTableData()
442 : nullptr;
443 if (lookup_data != nullptr) {
444 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
445 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
446 } else {
447 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
448 }
449 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800450}
451
Jesse Wilson6bf19152011-09-29 13:12:33 -0400452DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700453 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
454 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
455 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
456 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400457}
458
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700459bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700460 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700461 return false;
462 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700463 return true;
464}
465
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700466bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800467 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700468 std::ostringstream oss;
469 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800470 << " " << header_->magic_[0]
471 << " " << header_->magic_[1]
472 << " " << header_->magic_[2]
473 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700474 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700475 return false;
476 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800477 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700478 std::ostringstream oss;
479 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800480 << " " << header_->magic_[4]
481 << " " << header_->magic_[5]
482 << " " << header_->magic_[6]
483 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700484 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700485 return false;
486 }
487 return true;
488}
489
Ian Rogers13735952014-10-08 12:43:28 -0700490bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800491 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
492}
493
Ian Rogers13735952014-10-08 12:43:28 -0700494bool DexFile::IsVersionValid(const uint8_t* magic) {
495 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800496 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
497}
498
Ian Rogersd81871c2011-10-03 13:57:23 -0700499uint32_t DexFile::GetVersion() const {
500 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
501 return atoi(version);
502}
503
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800504const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
505 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300506 if (LIKELY(lookup_table_ != nullptr)) {
507 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
508 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700509 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300510
Ian Rogers68b56852014-08-29 20:19:11 -0700511 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300512 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700513 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700514 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700515 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300516 const TypeId* type_id = FindTypeId(descriptor);
517 if (type_id != nullptr) {
518 uint16_t type_idx = GetIndexForTypeId(*type_id);
519 for (size_t i = 0; i < num_class_defs; ++i) {
520 const ClassDef& class_def = GetClassDef(i);
521 if (class_def.class_idx_ == type_idx) {
522 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700523 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700524 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700525 }
Ian Rogers68b56852014-08-29 20:19:11 -0700526 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700527}
528
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700529const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
530 size_t num_class_defs = NumClassDefs();
531 for (size_t i = 0; i < num_class_defs; ++i) {
532 const ClassDef& class_def = GetClassDef(i);
533 if (class_def.class_idx_ == type_idx) {
534 return &class_def;
535 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700536 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700537 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700538}
539
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800540const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
541 const DexFile::StringId& name,
542 const DexFile::TypeId& type) const {
543 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
544 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
545 const uint32_t name_idx = GetIndexForStringId(name);
546 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700547 int32_t lo = 0;
548 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800549 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700550 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800551 const DexFile::FieldId& field = GetFieldId(mid);
552 if (class_idx > field.class_idx_) {
553 lo = mid + 1;
554 } else if (class_idx < field.class_idx_) {
555 hi = mid - 1;
556 } else {
557 if (name_idx > field.name_idx_) {
558 lo = mid + 1;
559 } else if (name_idx < field.name_idx_) {
560 hi = mid - 1;
561 } else {
562 if (type_idx > field.type_idx_) {
563 lo = mid + 1;
564 } else if (type_idx < field.type_idx_) {
565 hi = mid - 1;
566 } else {
567 return &field;
568 }
569 }
570 }
571 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700572 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800573}
574
575const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700576 const DexFile::StringId& name,
577 const DexFile::ProtoId& signature) const {
578 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800579 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700580 const uint32_t name_idx = GetIndexForStringId(name);
581 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700582 int32_t lo = 0;
583 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700584 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700585 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700586 const DexFile::MethodId& method = GetMethodId(mid);
587 if (class_idx > method.class_idx_) {
588 lo = mid + 1;
589 } else if (class_idx < method.class_idx_) {
590 hi = mid - 1;
591 } else {
592 if (name_idx > method.name_idx_) {
593 lo = mid + 1;
594 } else if (name_idx < method.name_idx_) {
595 hi = mid - 1;
596 } else {
597 if (proto_idx > method.proto_idx_) {
598 lo = mid + 1;
599 } else if (proto_idx < method.proto_idx_) {
600 hi = mid - 1;
601 } else {
602 return &method;
603 }
604 }
605 }
606 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700608}
609
Ian Rogers637c65b2013-05-31 11:46:00 -0700610const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700611 int32_t lo = 0;
612 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700613 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700614 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700615 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700616 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700617 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
618 if (compare > 0) {
619 lo = mid + 1;
620 } else if (compare < 0) {
621 hi = mid - 1;
622 } else {
623 return &str_id;
624 }
625 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700626 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700627}
628
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300629const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
630 int32_t lo = 0;
631 int32_t hi = NumTypeIds() - 1;
632 while (hi >= lo) {
633 int32_t mid = (hi + lo) / 2;
634 const TypeId& type_id = GetTypeId(mid);
635 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
636 const char* str = GetStringData(str_id);
637 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
638 if (compare > 0) {
639 lo = mid + 1;
640 } else if (compare < 0) {
641 hi = mid - 1;
642 } else {
643 return &type_id;
644 }
645 }
646 return nullptr;
647}
648
Vladimir Markoa48aef42014-12-03 17:53:53 +0000649const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700650 int32_t lo = 0;
651 int32_t hi = NumStringIds() - 1;
652 while (hi >= lo) {
653 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700654 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700655 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000656 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700657 if (compare > 0) {
658 lo = mid + 1;
659 } else if (compare < 0) {
660 hi = mid - 1;
661 } else {
662 return &str_id;
663 }
664 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700665 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700666}
667
668const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t lo = 0;
670 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700671 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700672 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700673 const TypeId& type_id = GetTypeId(mid);
674 if (string_idx > type_id.descriptor_idx_) {
675 lo = mid + 1;
676 } else if (string_idx < type_id.descriptor_idx_) {
677 hi = mid - 1;
678 } else {
679 return &type_id;
680 }
681 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700682 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700683}
684
685const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000686 const uint16_t* signature_type_idxs,
687 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700688 int32_t lo = 0;
689 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700690 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700691 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700692 const DexFile::ProtoId& proto = GetProtoId(mid);
693 int compare = return_type_idx - proto.return_type_idx_;
694 if (compare == 0) {
695 DexFileParameterIterator it(*this, proto);
696 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000697 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800698 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700699 it.Next();
700 i++;
701 }
702 if (compare == 0) {
703 if (it.HasNext()) {
704 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000705 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700706 compare = 1;
707 }
708 }
709 }
710 if (compare > 0) {
711 lo = mid + 1;
712 } else if (compare < 0) {
713 hi = mid - 1;
714 } else {
715 return &proto;
716 }
717 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700718 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700719}
720
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000721void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
722 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300723}
724
Ian Rogers0571d352011-11-03 19:51:38 -0700725// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700726bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
727 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700728 if (signature[0] != '(') {
729 return false;
730 }
731 size_t offset = 1;
732 size_t end = signature.size();
733 bool process_return = false;
734 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000735 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700736 char c = signature[offset];
737 offset++;
738 if (c == ')') {
739 process_return = true;
740 continue;
741 }
Ian Rogers0571d352011-11-03 19:51:38 -0700742 while (c == '[') { // process array prefix
743 if (offset >= end) { // expect some descriptor following [
744 return false;
745 }
746 c = signature[offset];
747 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700748 }
749 if (c == 'L') { // process type descriptors
750 do {
751 if (offset >= end) { // unexpected early termination of descriptor
752 return false;
753 }
754 c = signature[offset];
755 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700756 } while (c != ';');
757 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000758 // TODO: avoid creating a std::string just to get a 0-terminated char array
759 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700760 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700761 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700762 return false;
763 }
764 uint16_t type_idx = GetIndexForTypeId(*type_id);
765 if (!process_return) {
766 param_type_idxs->push_back(type_idx);
767 } else {
768 *return_type_idx = type_idx;
769 return offset == end; // return true if the signature had reached a sensible end
770 }
771 }
772 return false; // failed to correctly parse return type
773}
774
Ian Rogersd91d6d62013-09-25 20:26:14 -0700775const Signature DexFile::CreateSignature(const StringPiece& signature) const {
776 uint16_t return_type_idx;
777 std::vector<uint16_t> param_type_indices;
778 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
779 if (!success) {
780 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700781 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700782 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700783 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700784 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700785 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700786 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700787}
788
Mathieu Chartiere401d142015-04-22 13:56:20 -0700789int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700790 // For native method, lineno should be -2 to indicate it is native. Note that
791 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700793 return -2;
794 }
795
TDYa127c8dc1012012-04-19 07:03:33 -0700796 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700797 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700798
799 // A method with no line number info should return -1
800 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000801 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700802 return context.line_num_;
803}
804
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700805int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700806 // Note: Signed type is important for max and min.
807 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700808 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700809
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700810 while (min <= max) {
811 int32_t mid = min + ((max - min) / 2);
812
813 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
814 uint32_t start = ti->start_addr_;
815 uint32_t end = start + ti->insn_count_;
816
Ian Rogers0571d352011-11-03 19:51:38 -0700817 if (address < start) {
818 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700819 } else if (address >= end) {
820 min = mid + 1;
821 } else { // We have a winner!
822 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700823 }
824 }
825 // No match.
826 return -1;
827}
828
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700829int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
830 int32_t try_item = FindTryItem(code_item, address);
831 if (try_item == -1) {
832 return -1;
833 } else {
834 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
835 }
836}
837
David Srbeckyb06e28e2015-12-10 13:15:00 +0000838bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
839 DexDebugNewLocalCb local_cb, void* context) const {
840 DCHECK(local_cb != nullptr);
841 if (code_item == nullptr) {
842 return false;
843 }
844 const uint8_t* stream = GetDebugInfoStream(code_item);
845 if (stream == nullptr) {
846 return false;
847 }
848 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700849
David Srbeckyb06e28e2015-12-10 13:15:00 +0000850 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800851 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000852 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
853 local_in_reg[arg_reg].name_ = "this";
854 local_in_reg[arg_reg].descriptor_ = descriptor;
855 local_in_reg[arg_reg].signature_ = nullptr;
856 local_in_reg[arg_reg].start_address_ = 0;
857 local_in_reg[arg_reg].reg_ = arg_reg;
858 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700859 arg_reg++;
860 }
861
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000863 DecodeUnsignedLeb128(&stream); // Line.
864 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
865 uint32_t i;
866 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700867 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700868 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800869 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000870 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700871 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000872 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700873 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000874 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
875 local_in_reg[arg_reg].descriptor_ = descriptor;
876 local_in_reg[arg_reg].signature_ = nullptr;
877 local_in_reg[arg_reg].start_address_ = 0;
878 local_in_reg[arg_reg].reg_ = arg_reg;
879 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700880 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 case 'D':
882 case 'J':
883 arg_reg += 2;
884 break;
885 default:
886 arg_reg += 1;
887 break;
888 }
889 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000890 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800891 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
892 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000893 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700894 }
895
David Srbeckyb06e28e2015-12-10 13:15:00 +0000896 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700897 for (;;) {
898 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700899 switch (opcode) {
900 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000901 // Emit all variables which are still alive at the end of the method.
902 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
903 if (local_in_reg[reg].is_live_) {
904 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
905 local_cb(context, local_in_reg[reg]);
906 }
907 }
908 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700909 case DBG_ADVANCE_PC:
910 address += DecodeUnsignedLeb128(&stream);
911 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700912 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000913 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700915 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000916 case DBG_START_LOCAL_EXTENDED: {
917 uint16_t reg = DecodeUnsignedLeb128(&stream);
918 if (reg >= code_item->registers_size_) {
919 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800920 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000921 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 }
923
David Srbeckyb06e28e2015-12-10 13:15:00 +0000924 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
925 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
926 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700927 if (opcode == DBG_START_LOCAL_EXTENDED) {
928 signature_idx = DecodeUnsignedLeb128P1(&stream);
929 }
930
Shih-wei Liao195487c2011-08-20 13:29:04 -0700931 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000932 if (local_in_reg[reg].is_live_) {
933 local_in_reg[reg].end_address_ = address;
934 local_cb(context, local_in_reg[reg]);
935 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700936
David Srbeckyb06e28e2015-12-10 13:15:00 +0000937 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
938 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
939 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
940 local_in_reg[reg].start_address_ = address;
941 local_in_reg[reg].reg_ = reg;
942 local_in_reg[reg].is_live_ = true;
943 break;
944 }
945 case DBG_END_LOCAL: {
946 uint16_t reg = DecodeUnsignedLeb128(&stream);
947 if (reg >= code_item->registers_size_) {
948 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
949 << code_item->registers_size_ << ") in " << GetLocation();
950 return false;
951 }
952 if (!local_in_reg[reg].is_live_) {
953 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
954 return false;
955 }
956 local_in_reg[reg].end_address_ = address;
957 local_cb(context, local_in_reg[reg]);
958 local_in_reg[reg].is_live_ = false;
959 break;
960 }
961 case DBG_RESTART_LOCAL: {
962 uint16_t reg = DecodeUnsignedLeb128(&stream);
963 if (reg >= code_item->registers_size_) {
964 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
965 << code_item->registers_size_ << ") in " << GetLocation();
966 return false;
967 }
968 // If the register is live, the "restart" is superfluous,
969 // and we don't want to mess with the existing start address.
970 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700971 local_in_reg[reg].start_address_ = address;
972 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700973 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700974 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000975 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700976 case DBG_SET_PROLOGUE_END:
977 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700978 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000979 case DBG_SET_FILE:
980 DecodeUnsignedLeb128P1(&stream); // name.
981 break;
982 default:
983 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
984 break;
985 }
986 }
987}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700988
David Srbeckyb06e28e2015-12-10 13:15:00 +0000989bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
990 void* context) const {
991 DCHECK(position_cb != nullptr);
992 if (code_item == nullptr) {
993 return false;
994 }
995 const uint8_t* stream = GetDebugInfoStream(code_item);
996 if (stream == nullptr) {
997 return false;
998 }
999
1000 PositionInfo entry = PositionInfo();
1001 entry.line_ = DecodeUnsignedLeb128(&stream);
1002 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1003 for (uint32_t i = 0; i < parameters_size; ++i) {
1004 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1005 }
1006
1007 for (;;) {
1008 uint8_t opcode = *stream++;
1009 switch (opcode) {
1010 case DBG_END_SEQUENCE:
1011 return true; // end of stream.
1012 case DBG_ADVANCE_PC:
1013 entry.address_ += DecodeUnsignedLeb128(&stream);
1014 break;
1015 case DBG_ADVANCE_LINE:
1016 entry.line_ += DecodeSignedLeb128(&stream);
1017 break;
1018 case DBG_START_LOCAL:
1019 DecodeUnsignedLeb128(&stream); // reg.
1020 DecodeUnsignedLeb128P1(&stream); // name.
1021 DecodeUnsignedLeb128P1(&stream); // descriptor.
1022 break;
1023 case DBG_START_LOCAL_EXTENDED:
1024 DecodeUnsignedLeb128(&stream); // reg.
1025 DecodeUnsignedLeb128P1(&stream); // name.
1026 DecodeUnsignedLeb128P1(&stream); // descriptor.
1027 DecodeUnsignedLeb128P1(&stream); // signature.
1028 break;
1029 case DBG_END_LOCAL:
1030 case DBG_RESTART_LOCAL:
1031 DecodeUnsignedLeb128(&stream); // reg.
1032 break;
1033 case DBG_SET_PROLOGUE_END:
1034 entry.prologue_end_ = true;
1035 break;
1036 case DBG_SET_EPILOGUE_BEGIN:
1037 entry.epilogue_begin_ = true;
1038 break;
1039 case DBG_SET_FILE: {
1040 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1041 entry.source_file_ = StringDataByIdx(name_idx);
1042 break;
1043 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001044 default: {
1045 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001046 entry.address_ += adjopcode / DBG_LINE_RANGE;
1047 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1048 if (position_cb(context, entry)) {
1049 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001050 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001051 entry.prologue_end_ = false;
1052 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001053 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001054 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001055 }
1056 }
1057}
1058
David Srbeckyb06e28e2015-12-10 13:15:00 +00001059bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001060 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001061
1062 // We know that this callback will be called in
1063 // ascending address order, so keep going until we find
1064 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001065 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001066 // The line number from the previous positions callback
1067 // wil be the final result.
1068 return true;
1069 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001070 context->line_num_ = entry.line_;
1071 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001072 }
1073}
1074
Andreas Gampe833a4852014-05-21 18:46:59 -07001075bool DexFile::IsMultiDexLocation(const char* location) {
1076 return strrchr(location, kMultiDexSeparator) != nullptr;
1077}
1078
Andreas Gampe90e34042015-04-27 20:01:52 -07001079std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1080 if (index == 0) {
1081 return "classes.dex";
1082 } else {
1083 return StringPrintf("classes%zu.dex", index + 1);
1084 }
1085}
1086
1087std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1088 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001089 return dex_location;
1090 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001091 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001092 }
1093}
1094
1095std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1096 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001097 std::string base_location = GetBaseLocation(dex_location);
1098 const char* suffix = dex_location + base_location.size();
1099 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1100 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1101 if (path != nullptr && path.get() != base_location) {
1102 return std::string(path.get()) + suffix;
1103 } else if (suffix[0] == 0) {
1104 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001105 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001106 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001107 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001108}
1109
Jeff Hao13e748b2015-08-25 20:44:19 +00001110// Read a signed integer. "zwidth" is the zero-based byte count.
1111static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1112 int32_t val = 0;
1113 for (int i = zwidth; i >= 0; --i) {
1114 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1115 }
1116 val >>= (3 - zwidth) * 8;
1117 return val;
1118}
1119
1120// Read an unsigned integer. "zwidth" is the zero-based byte count,
1121// "fill_on_right" indicates which side we want to zero-fill from.
1122static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1123 uint32_t val = 0;
1124 for (int i = zwidth; i >= 0; --i) {
1125 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1126 }
1127 if (!fill_on_right) {
1128 val >>= (3 - zwidth) * 8;
1129 }
1130 return val;
1131}
1132
1133// Read a signed long. "zwidth" is the zero-based byte count.
1134static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1135 int64_t val = 0;
1136 for (int i = zwidth; i >= 0; --i) {
1137 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1138 }
1139 val >>= (7 - zwidth) * 8;
1140 return val;
1141}
1142
1143// Read an unsigned long. "zwidth" is the zero-based byte count,
1144// "fill_on_right" indicates which side we want to zero-fill from.
1145static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1146 uint64_t val = 0;
1147 for (int i = zwidth; i >= 0; --i) {
1148 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1149 }
1150 if (!fill_on_right) {
1151 val >>= (7 - zwidth) * 8;
1152 }
1153 return val;
1154}
1155
1156const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1157 mirror::Class* klass = field->GetDeclaringClass();
1158 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1159 if (annotations_dir == nullptr) {
1160 return nullptr;
1161 }
1162 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1163 if (field_annotations == nullptr) {
1164 return nullptr;
1165 }
1166 uint32_t field_index = field->GetDexFieldIndex();
1167 uint32_t field_count = annotations_dir->fields_size_;
1168 for (uint32_t i = 0; i < field_count; ++i) {
1169 if (field_annotations[i].field_idx_ == field_index) {
1170 return GetFieldAnnotationSetItem(field_annotations[i]);
1171 }
1172 }
1173 return nullptr;
1174}
1175
1176mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1177 Handle<mirror::Class> annotation_class) const {
1178 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1179 if (annotation_set == nullptr) {
1180 return nullptr;
1181 }
1182 StackHandleScope<1> hs(Thread::Current());
1183 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1184 return GetAnnotationObjectFromAnnotationSet(
1185 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1186}
1187
1188mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1189 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1190 StackHandleScope<1> hs(Thread::Current());
1191 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1192 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1193}
1194
Jeff Hao2a5892f2015-08-31 15:00:40 -07001195mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001196 const {
1197 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1198 if (annotation_set == nullptr) {
1199 return nullptr;
1200 }
1201 StackHandleScope<1> hs(Thread::Current());
1202 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1203 return GetSignatureValue(field_class, annotation_set);
1204}
1205
1206bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1207 const {
1208 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1209 if (annotation_set == nullptr) {
1210 return false;
1211 }
1212 StackHandleScope<1> hs(Thread::Current());
1213 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1214 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1215 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1216 return annotation_item != nullptr;
1217}
1218
1219const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1220 mirror::Class* klass = method->GetDeclaringClass();
1221 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1222 if (annotations_dir == nullptr) {
1223 return nullptr;
1224 }
1225 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1226 if (method_annotations == nullptr) {
1227 return nullptr;
1228 }
1229 uint32_t method_index = method->GetDexMethodIndex();
1230 uint32_t method_count = annotations_dir->methods_size_;
1231 for (uint32_t i = 0; i < method_count; ++i) {
1232 if (method_annotations[i].method_idx_ == method_index) {
1233 return GetMethodAnnotationSetItem(method_annotations[i]);
1234 }
1235 }
1236 return nullptr;
1237}
1238
1239const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1240 const {
1241 mirror::Class* klass = method->GetDeclaringClass();
1242 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1243 if (annotations_dir == nullptr) {
1244 return nullptr;
1245 }
1246 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1247 if (parameter_annotations == nullptr) {
1248 return nullptr;
1249 }
1250 uint32_t method_index = method->GetDexMethodIndex();
1251 uint32_t parameter_count = annotations_dir->parameters_size_;
1252 for (uint32_t i = 0; i < parameter_count; ++i) {
1253 if (parameter_annotations[i].method_idx_ == method_index) {
1254 return &parameter_annotations[i];
1255 }
1256 }
1257 return nullptr;
1258}
1259
1260mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1261 mirror::Class* klass = method->GetDeclaringClass();
1262 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1263 if (annotations_dir == nullptr) {
1264 return nullptr;
1265 }
1266 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1267 if (annotation_set == nullptr) {
1268 return nullptr;
1269 }
1270 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1271 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1272 if (annotation_item == nullptr) {
1273 return nullptr;
1274 }
1275 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1276 if (annotation == nullptr) {
1277 return nullptr;
1278 }
1279 uint8_t header_byte = *(annotation++);
1280 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1281 return nullptr;
1282 }
1283 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1284 if (annotation == nullptr) {
1285 return nullptr;
1286 }
1287 AnnotationValue annotation_value;
1288 StackHandleScope<2> hs(Thread::Current());
1289 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001290 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1291 Handle<mirror::Class> return_type(hs.NewHandle(
1292 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001293 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1294 return nullptr;
1295 }
1296 return annotation_value.value_.GetL();
1297}
1298
1299mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1300 Handle<mirror::Class> annotation_class) const {
1301 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1302 if (annotation_set == nullptr) {
1303 return nullptr;
1304 }
1305 StackHandleScope<1> hs(Thread::Current());
1306 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1307 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1308 kDexVisibilityRuntime, annotation_class);
1309}
1310
1311mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1312 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1313 StackHandleScope<1> hs(Thread::Current());
1314 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1315 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1316}
1317
Jeff Hao2a5892f2015-08-31 15:00:40 -07001318mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001319 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1320 if (annotation_set == nullptr) {
1321 return nullptr;
1322 }
1323 StackHandleScope<1> hs(Thread::Current());
1324 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1325 return GetThrowsValue(method_class, annotation_set);
1326}
1327
1328mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1329 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1330 if (parameter_annotations == nullptr) {
1331 return nullptr;
1332 }
1333 const AnnotationSetRefList* set_ref_list =
1334 GetParameterAnnotationSetRefList(parameter_annotations);
1335 if (set_ref_list == nullptr) {
1336 return nullptr;
1337 }
1338 uint32_t size = set_ref_list->size_;
1339 StackHandleScope<1> hs(Thread::Current());
1340 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1341 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1342}
1343
1344bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1345 const {
1346 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1347 if (annotation_set == nullptr) {
1348 return false;
1349 }
1350 StackHandleScope<1> hs(Thread::Current());
1351 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1352 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1353 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001354 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001355}
1356
1357const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1358 const {
1359 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1360 if (annotations_dir == nullptr) {
1361 return nullptr;
1362 }
1363 return GetClassAnnotationSet(annotations_dir);
1364}
1365
1366mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1367 Handle<mirror::Class> annotation_class) const {
1368 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1369 if (annotation_set == nullptr) {
1370 return nullptr;
1371 }
1372 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1373 annotation_class);
1374}
1375
1376mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1377 const {
1378 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1379 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1380}
1381
Jeff Hao2a5892f2015-08-31 15:00:40 -07001382mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1383 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1384 if (annotation_set == nullptr) {
1385 return nullptr;
1386 }
1387 const AnnotationItem* annotation_item = SearchAnnotationSet(
1388 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1389 if (annotation_item == nullptr) {
1390 return nullptr;
1391 }
1392 StackHandleScope<1> hs(Thread::Current());
1393 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1394 Handle<mirror::Class> class_array_class(hs.NewHandle(
1395 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1396 if (class_array_class.Get() == nullptr) {
1397 return nullptr;
1398 }
1399 mirror::Object* obj = GetAnnotationValue(
1400 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1401 if (obj == nullptr) {
1402 return nullptr;
1403 }
1404 return obj->AsObjectArray<mirror::Class>();
1405}
1406
1407mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1408 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1409 if (annotation_set == nullptr) {
1410 return nullptr;
1411 }
1412 const AnnotationItem* annotation_item = SearchAnnotationSet(
1413 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1414 if (annotation_item == nullptr) {
1415 return nullptr;
1416 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001417 mirror::Object* obj = GetAnnotationValue(klass,
1418 annotation_item,
1419 "value",
1420 ScopedNullHandle<mirror::Class>(),
1421 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001422 if (obj == nullptr) {
1423 return nullptr;
1424 }
1425 return obj->AsClass();
1426}
1427
1428mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1429 mirror::Class* declaring_class = GetDeclaringClass(klass);
1430 if (declaring_class != nullptr) {
1431 return declaring_class;
1432 }
1433 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1434 if (annotation_set == nullptr) {
1435 return nullptr;
1436 }
1437 const AnnotationItem* annotation_item = SearchAnnotationSet(
1438 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1439 if (annotation_item == nullptr) {
1440 return nullptr;
1441 }
1442 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1443 if (annotation == nullptr) {
1444 return nullptr;
1445 }
1446 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001447 if (!ProcessAnnotationValue(klass,
1448 &annotation,
1449 &annotation_value,
1450 ScopedNullHandle<mirror::Class>(),
1451 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001452 return nullptr;
1453 }
1454 if (annotation_value.type_ != kDexAnnotationMethod) {
1455 return nullptr;
1456 }
1457 StackHandleScope<2> hs(Thread::Current());
1458 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1459 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1460 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1461 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1462 if (method == nullptr) {
1463 return nullptr;
1464 }
1465 return method->GetDeclaringClass();
1466}
1467
1468mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1469 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1470 if (annotation_set == nullptr) {
1471 return nullptr;
1472 }
1473 const AnnotationItem* annotation_item = SearchAnnotationSet(
1474 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1475 if (annotation_item == nullptr) {
1476 return nullptr;
1477 }
1478 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001479 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001480}
1481
1482bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1483 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1484 if (annotation_set == nullptr) {
1485 return false;
1486 }
1487 const AnnotationItem* annotation_item = SearchAnnotationSet(
1488 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1489 if (annotation_item == nullptr) {
1490 return false;
1491 }
1492 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1493 if (annotation == nullptr) {
1494 return false;
1495 }
1496 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001497 if (!ProcessAnnotationValue(klass,
1498 &annotation,
1499 &annotation_value,
1500 ScopedNullHandle<mirror::Class>(),
1501 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001502 return false;
1503 }
1504 if (annotation_value.type_ != kDexAnnotationNull &&
1505 annotation_value.type_ != kDexAnnotationString) {
1506 return false;
1507 }
1508 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1509 return true;
1510}
1511
1512bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1513 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1514 if (annotation_set == nullptr) {
1515 return false;
1516 }
1517 const AnnotationItem* annotation_item = SearchAnnotationSet(
1518 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1519 if (annotation_item == nullptr) {
1520 return false;
1521 }
1522 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1523 if (annotation == nullptr) {
1524 return false;
1525 }
1526 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001527 if (!ProcessAnnotationValue(klass,
1528 &annotation,
1529 &annotation_value,
1530 ScopedNullHandle<mirror::Class>(),
1531 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001532 return false;
1533 }
1534 if (annotation_value.type_ != kDexAnnotationInt) {
1535 return false;
1536 }
1537 *flags = annotation_value.value_.GetI();
1538 return true;
1539}
1540
Jeff Hao13e748b2015-08-25 20:44:19 +00001541bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1542 Handle<mirror::Class> annotation_class) const {
1543 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1544 if (annotation_set == nullptr) {
1545 return false;
1546 }
1547 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1548 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001549 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001550}
1551
1552mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1553 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1554 Thread* self = Thread::Current();
1555 ScopedObjectAccessUnchecked soa(self);
1556 StackHandleScope<5> hs(self);
1557 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1558 const char* name = StringDataByIdx(element_name_index);
1559 Handle<mirror::String> string_name(
1560 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1561
1562 ArtMethod* annotation_method =
1563 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1564 if (annotation_method == nullptr) {
1565 return nullptr;
1566 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001567 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1568 Handle<mirror::Class> method_return(hs.NewHandle(
1569 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001570
1571 AnnotationValue annotation_value;
1572 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1573 return nullptr;
1574 }
1575 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1576
1577 mirror::Class* annotation_member_class =
1578 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1579 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1580 Handle<mirror::Method> method_object(
1581 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1582
1583 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1584 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1585 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1586 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1587 return nullptr;
1588 }
1589
1590 JValue result;
1591 ArtMethod* annotation_member_init =
1592 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1593 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1594 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1595 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1596 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1597 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1598 };
1599 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1600 if (self->IsExceptionPending()) {
1601 LOG(INFO) << "Exception in AnnotationMember.<init>";
1602 return nullptr;
1603 }
1604
1605 return new_member.Get();
1606}
1607
1608const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1609 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1610 Handle<mirror::Class> annotation_class) const {
1611 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1612 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1613 if (annotation_item->visibility_ != visibility) {
1614 continue;
1615 }
1616 const uint8_t* annotation = annotation_item->annotation_;
1617 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1618 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1619 klass->GetDexFile(), type_index, klass.Get());
1620 if (resolved_class == nullptr) {
1621 std::string temp;
1622 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1623 klass->GetDescriptor(&temp), type_index);
1624 CHECK(Thread::Current()->IsExceptionPending());
1625 Thread::Current()->ClearException();
1626 continue;
1627 }
1628 if (resolved_class == annotation_class.Get()) {
1629 return annotation_item;
1630 }
1631 }
1632
1633 return nullptr;
1634}
1635
1636mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1637 const AnnotationSetItem* annotation_set, uint32_t visibility,
1638 Handle<mirror::Class> annotation_class) const {
1639 const AnnotationItem* annotation_item =
1640 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1641 if (annotation_item == nullptr) {
1642 return nullptr;
1643 }
1644 const uint8_t* annotation = annotation_item->annotation_;
1645 return ProcessEncodedAnnotation(klass, &annotation);
1646}
1647
1648mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1649 const AnnotationItem* annotation_item, const char* annotation_name,
1650 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1651 const uint8_t* annotation =
1652 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1653 if (annotation == nullptr) {
1654 return nullptr;
1655 }
1656 AnnotationValue annotation_value;
1657 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1658 return nullptr;
1659 }
1660 if (annotation_value.type_ != expected_type) {
1661 return nullptr;
1662 }
1663 return annotation_value.value_.GetL();
1664}
1665
Jeff Hao2a5892f2015-08-31 15:00:40 -07001666mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001667 const AnnotationSetItem* annotation_set) const {
1668 StackHandleScope<1> hs(Thread::Current());
1669 const AnnotationItem* annotation_item =
1670 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1671 if (annotation_item == nullptr) {
1672 return nullptr;
1673 }
1674 mirror::Class* string_class = mirror::String::GetJavaLangString();
1675 Handle<mirror::Class> string_array_class(hs.NewHandle(
1676 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001677 if (string_array_class.Get() == nullptr) {
1678 return nullptr;
1679 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001680 mirror::Object* obj =
1681 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1682 if (obj == nullptr) {
1683 return nullptr;
1684 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001685 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001686}
1687
Jeff Hao2a5892f2015-08-31 15:00:40 -07001688mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001689 const AnnotationSetItem* annotation_set) const {
1690 StackHandleScope<1> hs(Thread::Current());
1691 const AnnotationItem* annotation_item =
1692 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1693 if (annotation_item == nullptr) {
1694 return nullptr;
1695 }
1696 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1697 Handle<mirror::Class> class_array_class(hs.NewHandle(
1698 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001699 if (class_array_class.Get() == nullptr) {
1700 return nullptr;
1701 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001702 mirror::Object* obj =
1703 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1704 if (obj == nullptr) {
1705 return nullptr;
1706 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001707 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001708}
1709
1710mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1711 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1712 Thread* self = Thread::Current();
1713 ScopedObjectAccessUnchecked soa(self);
1714 StackHandleScope<2> hs(self);
1715 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1716 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1717 if (annotation_set == nullptr) {
1718 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1719 }
1720
1721 uint32_t size = annotation_set->size_;
1722 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1723 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1724 if (result.Get() == nullptr) {
1725 return nullptr;
1726 }
1727
1728 uint32_t dest_index = 0;
1729 for (uint32_t i = 0; i < size; ++i) {
1730 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1731 if (annotation_item->visibility_ != visibility) {
1732 continue;
1733 }
1734 const uint8_t* annotation = annotation_item->annotation_;
1735 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1736 if (annotation_obj != nullptr) {
1737 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1738 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001739 } else if (self->IsExceptionPending()) {
1740 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001741 }
1742 }
1743
1744 if (dest_index == size) {
1745 return result.Get();
1746 }
1747
1748 mirror::ObjectArray<mirror::Object>* trimmed_result =
1749 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001750 if (trimmed_result == nullptr) {
1751 return nullptr;
1752 }
1753
Jeff Hao13e748b2015-08-25 20:44:19 +00001754 for (uint32_t i = 0; i < dest_index; ++i) {
1755 mirror::Object* obj = result->GetWithoutChecks(i);
1756 trimmed_result->SetWithoutChecks<false>(i, obj);
1757 }
1758
1759 return trimmed_result;
1760}
1761
1762mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1763 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1764 Thread* self = Thread::Current();
1765 ScopedObjectAccessUnchecked soa(self);
1766 StackHandleScope<1> hs(self);
1767 mirror::Class* annotation_array_class =
1768 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1769 mirror::Class* annotation_array_array_class =
1770 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001771 if (annotation_array_array_class == nullptr) {
1772 return nullptr;
1773 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001774 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1775 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1776 if (annotation_array_array.Get() == nullptr) {
1777 LOG(ERROR) << "Annotation set ref array allocation failed";
1778 return nullptr;
1779 }
1780 for (uint32_t index = 0; index < size; ++index) {
1781 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1782 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1783 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1784 if (annotation_set == nullptr) {
1785 return nullptr;
1786 }
1787 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1788 }
1789 return annotation_array_array.Get();
1790}
1791
1792bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1793 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1794 DexFile::AnnotationResultStyle result_style) const {
1795 Thread* self = Thread::Current();
1796 mirror::Object* element_object = nullptr;
1797 bool set_object = false;
1798 Primitive::Type primitive_type = Primitive::kPrimVoid;
1799 const uint8_t* annotation = *annotation_ptr;
1800 uint8_t header_byte = *(annotation++);
1801 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1802 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1803 int32_t width = value_arg + 1;
1804 annotation_value->type_ = value_type;
1805
1806 switch (value_type) {
1807 case kDexAnnotationByte:
1808 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1809 primitive_type = Primitive::kPrimByte;
1810 break;
1811 case kDexAnnotationShort:
1812 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1813 primitive_type = Primitive::kPrimShort;
1814 break;
1815 case kDexAnnotationChar:
1816 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1817 false)));
1818 primitive_type = Primitive::kPrimChar;
1819 break;
1820 case kDexAnnotationInt:
1821 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1822 primitive_type = Primitive::kPrimInt;
1823 break;
1824 case kDexAnnotationLong:
1825 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1826 primitive_type = Primitive::kPrimLong;
1827 break;
1828 case kDexAnnotationFloat:
1829 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1830 primitive_type = Primitive::kPrimFloat;
1831 break;
1832 case kDexAnnotationDouble:
1833 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1834 primitive_type = Primitive::kPrimDouble;
1835 break;
1836 case kDexAnnotationBoolean:
1837 annotation_value->value_.SetZ(value_arg != 0);
1838 primitive_type = Primitive::kPrimBoolean;
1839 width = 0;
1840 break;
1841 case kDexAnnotationString: {
1842 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1843 if (result_style == kAllRaw) {
1844 annotation_value->value_.SetI(index);
1845 } else {
1846 StackHandleScope<1> hs(self);
1847 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1848 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1849 klass->GetDexFile(), index, dex_cache);
1850 set_object = true;
1851 if (element_object == nullptr) {
1852 return false;
1853 }
1854 }
1855 break;
1856 }
1857 case kDexAnnotationType: {
1858 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1859 if (result_style == kAllRaw) {
1860 annotation_value->value_.SetI(index);
1861 } else {
1862 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1863 klass->GetDexFile(), index, klass.Get());
1864 set_object = true;
1865 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001866 CHECK(self->IsExceptionPending());
1867 if (result_style == kAllObjects) {
1868 const char* msg = StringByTypeIdx(index);
1869 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1870 element_object = self->GetException();
1871 self->ClearException();
1872 } else {
1873 return false;
1874 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001875 }
1876 }
1877 break;
1878 }
1879 case kDexAnnotationMethod: {
1880 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1881 if (result_style == kAllRaw) {
1882 annotation_value->value_.SetI(index);
1883 } else {
1884 StackHandleScope<2> hs(self);
1885 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1886 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1887 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1888 klass->GetDexFile(), index, dex_cache, class_loader);
1889 if (method == nullptr) {
1890 return false;
1891 }
1892 set_object = true;
1893 if (method->IsConstructor()) {
1894 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1895 } else {
1896 element_object = mirror::Method::CreateFromArtMethod(self, method);
1897 }
1898 if (element_object == nullptr) {
1899 return false;
1900 }
1901 }
1902 break;
1903 }
1904 case kDexAnnotationField: {
1905 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1906 if (result_style == kAllRaw) {
1907 annotation_value->value_.SetI(index);
1908 } else {
1909 StackHandleScope<2> hs(self);
1910 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1911 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1912 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1913 klass->GetDexFile(), index, dex_cache, class_loader);
1914 if (field == nullptr) {
1915 return false;
1916 }
1917 set_object = true;
1918 element_object = mirror::Field::CreateFromArtField(self, field, true);
1919 if (element_object == nullptr) {
1920 return false;
1921 }
1922 }
1923 break;
1924 }
1925 case kDexAnnotationEnum: {
1926 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1927 if (result_style == kAllRaw) {
1928 annotation_value->value_.SetI(index);
1929 } else {
1930 StackHandleScope<3> hs(self);
1931 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1932 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1933 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1934 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001935 if (enum_field == nullptr) {
1936 return false;
1937 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001938 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001939 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1940 element_object = enum_field->GetObject(field_class.Get());
1941 set_object = true;
1942 }
1943 }
1944 break;
1945 }
1946 case kDexAnnotationArray:
1947 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1948 return false;
1949 } else {
1950 ScopedObjectAccessUnchecked soa(self);
1951 StackHandleScope<2> hs(self);
1952 uint32_t size = DecodeUnsignedLeb128(&annotation);
1953 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1954 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1955 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1956 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1957 if (new_array.Get() == nullptr) {
1958 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1959 return false;
1960 }
1961 AnnotationValue new_annotation_value;
1962 for (uint32_t i = 0; i < size; ++i) {
1963 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1964 kPrimitivesOrObjects)) {
1965 return false;
1966 }
1967 if (!component_type->IsPrimitive()) {
1968 mirror::Object* obj = new_annotation_value.value_.GetL();
1969 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1970 } else {
1971 switch (new_annotation_value.type_) {
1972 case kDexAnnotationByte:
1973 new_array->AsByteArray()->SetWithoutChecks<false>(
1974 i, new_annotation_value.value_.GetB());
1975 break;
1976 case kDexAnnotationShort:
1977 new_array->AsShortArray()->SetWithoutChecks<false>(
1978 i, new_annotation_value.value_.GetS());
1979 break;
1980 case kDexAnnotationChar:
1981 new_array->AsCharArray()->SetWithoutChecks<false>(
1982 i, new_annotation_value.value_.GetC());
1983 break;
1984 case kDexAnnotationInt:
1985 new_array->AsIntArray()->SetWithoutChecks<false>(
1986 i, new_annotation_value.value_.GetI());
1987 break;
1988 case kDexAnnotationLong:
1989 new_array->AsLongArray()->SetWithoutChecks<false>(
1990 i, new_annotation_value.value_.GetJ());
1991 break;
1992 case kDexAnnotationFloat:
1993 new_array->AsFloatArray()->SetWithoutChecks<false>(
1994 i, new_annotation_value.value_.GetF());
1995 break;
1996 case kDexAnnotationDouble:
1997 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1998 i, new_annotation_value.value_.GetD());
1999 break;
2000 case kDexAnnotationBoolean:
2001 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2002 i, new_annotation_value.value_.GetZ());
2003 break;
2004 default:
2005 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2006 return false;
2007 }
2008 }
2009 }
2010 element_object = new_array.Get();
2011 set_object = true;
2012 width = 0;
2013 }
2014 break;
2015 case kDexAnnotationAnnotation:
2016 if (result_style == kAllRaw) {
2017 return false;
2018 }
2019 element_object = ProcessEncodedAnnotation(klass, &annotation);
2020 if (element_object == nullptr) {
2021 return false;
2022 }
2023 set_object = true;
2024 width = 0;
2025 break;
2026 case kDexAnnotationNull:
2027 if (result_style == kAllRaw) {
2028 annotation_value->value_.SetI(0);
2029 } else {
2030 CHECK(element_object == nullptr);
2031 set_object = true;
2032 }
2033 width = 0;
2034 break;
2035 default:
2036 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2037 return false;
2038 }
2039
2040 annotation += width;
2041 *annotation_ptr = annotation;
2042
2043 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2044 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2045 set_object = true;
2046 }
2047
2048 if (set_object) {
2049 annotation_value->value_.SetL(element_object);
2050 }
2051
2052 return true;
2053}
2054
2055mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2056 const uint8_t** annotation) const {
2057 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2058 uint32_t size = DecodeUnsignedLeb128(annotation);
2059
2060 Thread* self = Thread::Current();
2061 ScopedObjectAccessUnchecked soa(self);
2062 StackHandleScope<2> hs(self);
2063 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2064 Handle<mirror::Class> annotation_class(hs.NewHandle(
2065 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2066 if (annotation_class.Get() == nullptr) {
2067 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2068 << type_index;
2069 DCHECK(Thread::Current()->IsExceptionPending());
2070 Thread::Current()->ClearException();
2071 return nullptr;
2072 }
2073
2074 mirror::Class* annotation_member_class =
2075 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2076 mirror::Class* annotation_member_array_class =
2077 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002078 if (annotation_member_array_class == nullptr) {
2079 return nullptr;
2080 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002081 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002082 if (size > 0) {
2083 element_array =
2084 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2085 if (element_array == nullptr) {
2086 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2087 return nullptr;
2088 }
2089 }
2090
2091 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2092 for (uint32_t i = 0; i < size; ++i) {
2093 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2094 if (new_member == nullptr) {
2095 return nullptr;
2096 }
2097 h_element_array->SetWithoutChecks<false>(i, new_member);
2098 }
2099
2100 JValue result;
2101 ArtMethod* create_annotation_method =
2102 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2103 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2104 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2105 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2106 if (self->IsExceptionPending()) {
2107 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2108 return nullptr;
2109 }
2110
2111 return result.GetL();
2112}
2113
2114const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2115 const char* descriptor, uint32_t visibility) const {
2116 const AnnotationItem* result = nullptr;
2117 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2118 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2119 if (annotation_item->visibility_ != visibility) {
2120 continue;
2121 }
2122 const uint8_t* annotation = annotation_item->annotation_;
2123 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2124
2125 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2126 result = annotation_item;
2127 break;
2128 }
2129 }
2130 return result;
2131}
2132
2133const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2134 DecodeUnsignedLeb128(&annotation); // unused type_index
2135 uint32_t size = DecodeUnsignedLeb128(&annotation);
2136
2137 while (size != 0) {
2138 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2139 const char* element_name = GetStringData(GetStringId(element_name_index));
2140 if (strcmp(name, element_name) == 0) {
2141 return annotation;
2142 }
2143 SkipAnnotationValue(&annotation);
2144 size--;
2145 }
2146 return nullptr;
2147}
2148
2149bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2150 const uint8_t* annotation = *annotation_ptr;
2151 uint8_t header_byte = *(annotation++);
2152 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2153 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2154 int32_t width = value_arg + 1;
2155
2156 switch (value_type) {
2157 case kDexAnnotationByte:
2158 case kDexAnnotationShort:
2159 case kDexAnnotationChar:
2160 case kDexAnnotationInt:
2161 case kDexAnnotationLong:
2162 case kDexAnnotationFloat:
2163 case kDexAnnotationDouble:
2164 case kDexAnnotationString:
2165 case kDexAnnotationType:
2166 case kDexAnnotationMethod:
2167 case kDexAnnotationField:
2168 case kDexAnnotationEnum:
2169 break;
2170 case kDexAnnotationArray:
2171 {
2172 uint32_t size = DecodeUnsignedLeb128(&annotation);
2173 while (size--) {
2174 if (!SkipAnnotationValue(&annotation)) {
2175 return false;
2176 }
2177 }
2178 width = 0;
2179 break;
2180 }
2181 case kDexAnnotationAnnotation:
2182 {
2183 DecodeUnsignedLeb128(&annotation); // unused type_index
2184 uint32_t size = DecodeUnsignedLeb128(&annotation);
2185 while (size--) {
2186 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2187 if (!SkipAnnotationValue(&annotation)) {
2188 return false;
2189 }
2190 }
2191 width = 0;
2192 break;
2193 }
2194 case kDexAnnotationBoolean:
2195 case kDexAnnotationNull:
2196 width = 0;
2197 break;
2198 default:
2199 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2200 return false;
2201 }
2202
2203 annotation += width;
2204 *annotation_ptr = annotation;
2205 return true;
2206}
2207
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002208std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2209 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2210 dex_file.GetLocation().c_str(),
2211 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2212 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2213 return os;
2214}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002215
Ian Rogersd91d6d62013-09-25 20:26:14 -07002216std::string Signature::ToString() const {
2217 if (dex_file_ == nullptr) {
2218 CHECK(proto_id_ == nullptr);
2219 return "<no signature>";
2220 }
2221 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2222 std::string result;
2223 if (params == nullptr) {
2224 result += "()";
2225 } else {
2226 result += "(";
2227 for (uint32_t i = 0; i < params->Size(); ++i) {
2228 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2229 }
2230 result += ")";
2231 }
2232 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2233 return result;
2234}
2235
Vladimir Markod9cffea2013-11-25 15:08:02 +00002236bool Signature::operator==(const StringPiece& rhs) const {
2237 if (dex_file_ == nullptr) {
2238 return false;
2239 }
2240 StringPiece tail(rhs);
2241 if (!tail.starts_with("(")) {
2242 return false; // Invalid signature
2243 }
2244 tail.remove_prefix(1); // "(";
2245 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2246 if (params != nullptr) {
2247 for (uint32_t i = 0; i < params->Size(); ++i) {
2248 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2249 if (!tail.starts_with(param)) {
2250 return false;
2251 }
2252 tail.remove_prefix(param.length());
2253 }
2254 }
2255 if (!tail.starts_with(")")) {
2256 return false;
2257 }
2258 tail.remove_prefix(1); // ")";
2259 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2260}
2261
Ian Rogersd91d6d62013-09-25 20:26:14 -07002262std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2263 return os << sig.ToString();
2264}
2265
Ian Rogers0571d352011-11-03 19:51:38 -07002266// Decodes the header section from the class data bytes.
2267void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002268 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002269 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2270 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2271 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2272 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2273}
2274
2275void ClassDataItemIterator::ReadClassDataField() {
2276 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2277 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002278 // The user of the iterator is responsible for checking if there
2279 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002280}
2281
2282void ClassDataItemIterator::ReadClassDataMethod() {
2283 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2284 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2285 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002286 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002287 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002288 }
Ian Rogers0571d352011-11-03 19:51:38 -07002289}
2290
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002291EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002292 const DexFile& dex_file,
2293 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002294 : EncodedStaticFieldValueIterator(dex_file,
2295 nullptr,
2296 nullptr,
2297 nullptr,
2298 class_def,
2299 -1,
2300 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002301}
2302
2303EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002304 const DexFile& dex_file,
2305 Handle<mirror::DexCache>* dex_cache,
2306 Handle<mirror::ClassLoader>* class_loader,
2307 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002308 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002309 : EncodedStaticFieldValueIterator(dex_file,
2310 dex_cache, class_loader,
2311 linker,
2312 class_def,
2313 -1,
2314 kByte) {
2315 DCHECK(dex_cache_ != nullptr);
2316 DCHECK(class_loader_ != nullptr);
2317}
2318
2319EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2320 const DexFile& dex_file,
2321 Handle<mirror::DexCache>* dex_cache,
2322 Handle<mirror::ClassLoader>* class_loader,
2323 ClassLinker* linker,
2324 const DexFile::ClassDef& class_def,
2325 size_t pos,
2326 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002327 : dex_file_(dex_file),
2328 dex_cache_(dex_cache),
2329 class_loader_(class_loader),
2330 linker_(linker),
2331 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002332 pos_(pos),
2333 type_(type) {
2334 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002335 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002336 array_size_ = 0;
2337 } else {
2338 array_size_ = DecodeUnsignedLeb128(&ptr_);
2339 }
2340 if (array_size_ > 0) {
2341 Next();
2342 }
2343}
2344
2345void EncodedStaticFieldValueIterator::Next() {
2346 pos_++;
2347 if (pos_ >= array_size_) {
2348 return;
2349 }
Ian Rogers13735952014-10-08 12:43:28 -07002350 uint8_t value_type = *ptr_++;
2351 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002352 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002353 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002354 switch (type_) {
2355 case kBoolean:
2356 jval_.i = (value_arg != 0) ? 1 : 0;
2357 width = 0;
2358 break;
2359 case kByte:
2360 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002361 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002362 break;
2363 case kShort:
2364 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002365 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002366 break;
2367 case kChar:
2368 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002369 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002370 break;
2371 case kInt:
2372 jval_.i = ReadSignedInt(ptr_, value_arg);
2373 break;
2374 case kLong:
2375 jval_.j = ReadSignedLong(ptr_, value_arg);
2376 break;
2377 case kFloat:
2378 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2379 break;
2380 case kDouble:
2381 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2382 break;
2383 case kString:
2384 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002385 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2386 break;
2387 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002388 case kMethod:
2389 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002390 case kArray:
2391 case kAnnotation:
2392 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002393 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002394 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002395 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002396 width = 0;
2397 break;
2398 default:
2399 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002400 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002401 }
2402 ptr_ += width;
2403}
2404
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002405template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002406void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002407 DCHECK(dex_cache_ != nullptr);
2408 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002409 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002410 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2411 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002412 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2413 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2414 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2415 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2416 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2417 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2418 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002419 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002420 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002421 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002422 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002423 break;
2424 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002425 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002426 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2427 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002428 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002429 break;
2430 }
Ian Rogers0571d352011-11-03 19:51:38 -07002431 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2432 }
2433}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002434template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2435template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002436
2437CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2438 handler_.address_ = -1;
2439 int32_t offset = -1;
2440
2441 // Short-circuit the overwhelmingly common cases.
2442 switch (code_item.tries_size_) {
2443 case 0:
2444 break;
2445 case 1: {
2446 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2447 uint32_t start = tries->start_addr_;
2448 if (address >= start) {
2449 uint32_t end = start + tries->insn_count_;
2450 if (address < end) {
2451 offset = tries->handler_off_;
2452 }
2453 }
2454 break;
2455 }
2456 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002457 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002458 }
Logan Chien736df022012-04-27 16:25:57 +08002459 Init(code_item, offset);
2460}
2461
2462CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2463 const DexFile::TryItem& try_item) {
2464 handler_.address_ = -1;
2465 Init(code_item, try_item.handler_off_);
2466}
2467
2468void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2469 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002470 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002471 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002472 } else {
2473 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002474 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002475 remaining_count_ = -1;
2476 catch_all_ = false;
2477 DCHECK(!HasNext());
2478 }
2479}
2480
Ian Rogers13735952014-10-08 12:43:28 -07002481void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002482 current_data_ = handler_data;
2483 remaining_count_ = DecodeSignedLeb128(&current_data_);
2484
2485 // If remaining_count_ is non-positive, then it is the negative of
2486 // the number of catch types, and the catches are followed by a
2487 // catch-all handler.
2488 if (remaining_count_ <= 0) {
2489 catch_all_ = true;
2490 remaining_count_ = -remaining_count_;
2491 } else {
2492 catch_all_ = false;
2493 }
2494 Next();
2495}
2496
2497void CatchHandlerIterator::Next() {
2498 if (remaining_count_ > 0) {
2499 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2500 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2501 remaining_count_--;
2502 return;
2503 }
2504
2505 if (catch_all_) {
2506 handler_.type_idx_ = DexFile::kDexNoIndex16;
2507 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2508 catch_all_ = false;
2509 return;
2510 }
2511
2512 // no more handler
2513 remaining_count_ = -1;
2514}
2515
Carl Shapiro1fb86202011-06-27 17:43:13 -07002516} // namespace art