blob: 60caa73b729295585cdfb8c9e78566dffbb7a3e8 [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' };
Alex Lightc4961812016-03-23 10:20:41 -070065const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
66 {'0', '3', '5', '\0'},
67 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
68 // files with that version number would erroneously be accepted and run.
69 {'0', '3', '7', '\0'}
70};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070071
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070073 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070075
76 // Strip ":...", which is the location
77 const char* zip_entry_name = kClassesDex;
78 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010079 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070080
Vladimir Markoaa4497d2014-09-05 14:01:17 +010081 if (DexFile::IsMultiDexLocation(filename)) {
82 file_part_storage = GetBaseLocation(filename);
83 file_part = file_part_storage.c_str();
84 zip_entry_name = filename + file_part_storage.size() + 1;
85 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070086 }
87
88 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000089 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070090 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070091 return false;
92 }
93 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 std::unique_ptr<ZipArchive> zip_archive(
95 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
96 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080097 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
98 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700100 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700101 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700103 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
104 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return false;
106 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 std::unique_ptr<const DexFile> dex_file(
112 DexFile::OpenFile(fd.release(), filename, false, error_msg));
113 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
115 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700116 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return true;
118 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700119 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800120 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700121}
122
Andreas Gampe833a4852014-05-21 18:46:59 -0700123bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800124 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800125 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000128 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
129 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700131 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700132 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700137 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
138 error_msg));
139 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800140 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 return true;
142 } else {
143 return false;
144 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700145 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700146 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400147 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700148}
149
Andreas Gampe0cba0042015-04-29 20:47:16 -0700150static bool ContainsClassesDex(int fd, const char* filename) {
151 std::string error_msg;
152 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
153 if (zip_archive.get() == nullptr) {
154 return false;
155 }
156 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
157 return (zip_entry.get() != nullptr);
158}
159
160bool DexFile::MaybeDex(const char* filename) {
161 uint32_t magic;
162 std::string error_msg;
163 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
164 if (fd.get() == -1) {
165 return false;
166 }
167 if (IsZipMagic(magic)) {
168 return ContainsClassesDex(fd.release(), filename);
169 } else if (IsDexMagic(magic)) {
170 return true;
171 }
172 return false;
173}
174
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800175int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700176 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800177 return 0;
178 } else {
179 return mem_map_->GetProtect();
180 }
181}
182
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183bool DexFile::IsReadOnly() const {
184 return GetPermissions() == PROT_READ;
185}
186
Brian Carlstrome0948e12013-08-29 09:36:15 -0700187bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200188 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700189 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200190 return false;
191 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700192 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193 }
194}
195
Brian Carlstrome0948e12013-08-29 09:36:15 -0700196bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200197 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700198 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 return false;
200 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700201 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 }
203}
204
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800205std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
206 const std::string& location,
207 uint32_t location_checksum,
208 const OatDexFile* oat_dex_file,
209 bool verify,
210 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800211 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800212 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
213 size,
214 location,
215 location_checksum,
216 nullptr,
217 oat_dex_file,
218 error_msg);
219 if (verify && !DexFileVerifier::Verify(dex_file.get(),
220 dex_file->Begin(),
221 dex_file->Size(),
222 location.c_str(),
223 error_msg)) {
224 return nullptr;
225 }
226
227 return dex_file;
228}
229
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800230std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
231 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800232 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700233 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700234 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000235 {
236 ScopedFd delayed_close(fd);
237 struct stat sbuf;
238 memset(&sbuf, 0, sizeof(sbuf));
239 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800240 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000241 return nullptr;
242 }
243 if (S_ISDIR(sbuf.st_mode)) {
244 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
245 return nullptr;
246 }
247 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800248 map.reset(MemMap::MapFile(length,
249 PROT_READ,
250 MAP_PRIVATE,
251 fd,
252 0,
253 /*low_4gb*/false,
254 location,
255 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000256 if (map.get() == nullptr) {
257 DCHECK(!error_msg->empty());
258 return nullptr;
259 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700260 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800261
262 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700263 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800264 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800266 }
267
268 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
269
Andreas Gampe928f72b2014-09-09 19:53:48 -0700270 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
271 error_msg));
272 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700273 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
274 error_msg->c_str());
275 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800276 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800277
Andreas Gampe928f72b2014-09-09 19:53:48 -0700278 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
279 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800281 }
282
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800283 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700284}
285
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700286const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700287
Andreas Gampe833a4852014-05-21 18:46:59 -0700288bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800290 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700291 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700292 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 if (zip_archive.get() == nullptr) {
294 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700296 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800298}
299
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800300std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
301 uint32_t location_checksum,
302 MemMap* mem_map,
303 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304 return OpenMemory(mem_map->Begin(),
305 mem_map->Size(),
306 location,
307 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800309 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311}
312
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800313std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
314 const std::string& location, std::string* error_msg,
315 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800316 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800317 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700318 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700319 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700320 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700321 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700322 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700324 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700325 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700327 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700328 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700329 }
Ian Rogers700a4022014-05-19 16:49:03 -0700330 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700331 error_msg));
332 if (dex_file.get() == nullptr) {
333 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
334 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800337 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700338 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700339 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700341 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700342 }
343 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700344 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
345 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700346 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700347 return nullptr;
348 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700349 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800350 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700351}
352
Andreas Gampe90e34042015-04-27 20:01:52 -0700353// Technically we do not have a limitation with respect to the number of dex files that can be in a
354// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
355// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
356// seems an excessive number.
357static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
358
Andreas Gampe833a4852014-05-21 18:46:59 -0700359bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800360 std::string* error_msg,
361 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800362 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700363 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 ZipOpenErrorCode error_code;
365 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
366 &error_code));
367 if (dex_file.get() == nullptr) {
368 return false;
369 } else {
370 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800371 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700372
373 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700374
375 // We could try to avoid std::string allocations by working on a char array directly. As we
376 // do not expect a lot of iterations, this seems too involved and brittle.
377
Andreas Gampe90e34042015-04-27 20:01:52 -0700378 for (size_t i = 1; ; ++i) {
379 std::string name = GetMultiDexClassesDexName(i);
380 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700381 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
382 error_msg, &error_code));
383 if (next_dex_file.get() == nullptr) {
384 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
385 LOG(WARNING) << error_msg;
386 }
387 break;
388 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800389 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700390 }
391
Andreas Gampe90e34042015-04-27 20:01:52 -0700392 if (i == kWarnOnManyDexFilesThreshold) {
393 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
394 << " dex files. Please consider coalescing and shrinking the number to "
395 " avoid runtime overhead.";
396 }
397
398 if (i == std::numeric_limits<size_t>::max()) {
399 LOG(ERROR) << "Overflow in number of dex files!";
400 break;
401 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700402 }
403
404 return true;
405 }
406}
407
408
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
410 size_t size,
411 const std::string& location,
412 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800413 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700414 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800415 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700416 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800417 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800420 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700421 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800422 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700423}
424
Ian Rogers13735952014-10-08 12:43:28 -0700425DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800426 const std::string& location,
427 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800428 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700429 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800430 : begin_(base),
431 size_(size),
432 location_(location),
433 location_checksum_(location_checksum),
434 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800435 header_(reinterpret_cast<const Header*>(base)),
436 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
437 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
438 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
439 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
440 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700441 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700442 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700443 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800444 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300445 const uint8_t* lookup_data = (oat_dex_file != nullptr)
446 ? oat_dex_file->GetLookupTableData()
447 : nullptr;
448 if (lookup_data != nullptr) {
449 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
450 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
451 } else {
452 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
453 }
454 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800455}
456
Jesse Wilson6bf19152011-09-29 13:12:33 -0400457DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700458 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
459 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
460 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
461 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400462}
463
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700464bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700465 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700466 return false;
467 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700468 return true;
469}
470
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700471bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800472 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700473 std::ostringstream oss;
474 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800475 << " " << header_->magic_[0]
476 << " " << header_->magic_[1]
477 << " " << header_->magic_[2]
478 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700479 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700480 return false;
481 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800482 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700483 std::ostringstream oss;
484 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800485 << " " << header_->magic_[4]
486 << " " << header_->magic_[5]
487 << " " << header_->magic_[6]
488 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700489 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700490 return false;
491 }
492 return true;
493}
494
Ian Rogers13735952014-10-08 12:43:28 -0700495bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800496 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
497}
498
Ian Rogers13735952014-10-08 12:43:28 -0700499bool DexFile::IsVersionValid(const uint8_t* magic) {
500 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700501 for (uint32_t i = 0; i < kNumDexVersions; i++) {
502 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
503 return true;
504 }
505 }
506 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800507}
508
Ian Rogersd81871c2011-10-03 13:57:23 -0700509uint32_t DexFile::GetVersion() const {
510 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
511 return atoi(version);
512}
513
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800514const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
515 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300516 if (LIKELY(lookup_table_ != nullptr)) {
517 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
518 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700519 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300520
Ian Rogers68b56852014-08-29 20:19:11 -0700521 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300522 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700523 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700524 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700525 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300526 const TypeId* type_id = FindTypeId(descriptor);
527 if (type_id != nullptr) {
528 uint16_t type_idx = GetIndexForTypeId(*type_id);
529 for (size_t i = 0; i < num_class_defs; ++i) {
530 const ClassDef& class_def = GetClassDef(i);
531 if (class_def.class_idx_ == type_idx) {
532 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700533 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700534 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700535 }
Ian Rogers68b56852014-08-29 20:19:11 -0700536 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537}
538
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700539const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
540 size_t num_class_defs = NumClassDefs();
541 for (size_t i = 0; i < num_class_defs; ++i) {
542 const ClassDef& class_def = GetClassDef(i);
543 if (class_def.class_idx_ == type_idx) {
544 return &class_def;
545 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700546 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700547 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700548}
549
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800550const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
551 const DexFile::StringId& name,
552 const DexFile::TypeId& type) const {
553 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
554 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
555 const uint32_t name_idx = GetIndexForStringId(name);
556 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700557 int32_t lo = 0;
558 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800559 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700560 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800561 const DexFile::FieldId& field = GetFieldId(mid);
562 if (class_idx > field.class_idx_) {
563 lo = mid + 1;
564 } else if (class_idx < field.class_idx_) {
565 hi = mid - 1;
566 } else {
567 if (name_idx > field.name_idx_) {
568 lo = mid + 1;
569 } else if (name_idx < field.name_idx_) {
570 hi = mid - 1;
571 } else {
572 if (type_idx > field.type_idx_) {
573 lo = mid + 1;
574 } else if (type_idx < field.type_idx_) {
575 hi = mid - 1;
576 } else {
577 return &field;
578 }
579 }
580 }
581 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700582 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800583}
584
585const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700586 const DexFile::StringId& name,
587 const DexFile::ProtoId& signature) const {
588 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800589 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700590 const uint32_t name_idx = GetIndexForStringId(name);
591 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t lo = 0;
593 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700594 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700595 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700596 const DexFile::MethodId& method = GetMethodId(mid);
597 if (class_idx > method.class_idx_) {
598 lo = mid + 1;
599 } else if (class_idx < method.class_idx_) {
600 hi = mid - 1;
601 } else {
602 if (name_idx > method.name_idx_) {
603 lo = mid + 1;
604 } else if (name_idx < method.name_idx_) {
605 hi = mid - 1;
606 } else {
607 if (proto_idx > method.proto_idx_) {
608 lo = mid + 1;
609 } else if (proto_idx < method.proto_idx_) {
610 hi = mid - 1;
611 } else {
612 return &method;
613 }
614 }
615 }
616 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700617 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700618}
619
Ian Rogers637c65b2013-05-31 11:46:00 -0700620const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700621 int32_t lo = 0;
622 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700623 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700624 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700625 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700626 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700627 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
628 if (compare > 0) {
629 lo = mid + 1;
630 } else if (compare < 0) {
631 hi = mid - 1;
632 } else {
633 return &str_id;
634 }
635 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700637}
638
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300639const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
640 int32_t lo = 0;
641 int32_t hi = NumTypeIds() - 1;
642 while (hi >= lo) {
643 int32_t mid = (hi + lo) / 2;
644 const TypeId& type_id = GetTypeId(mid);
645 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
646 const char* str = GetStringData(str_id);
647 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
648 if (compare > 0) {
649 lo = mid + 1;
650 } else if (compare < 0) {
651 hi = mid - 1;
652 } else {
653 return &type_id;
654 }
655 }
656 return nullptr;
657}
658
Vladimir Markoa48aef42014-12-03 17:53:53 +0000659const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700660 int32_t lo = 0;
661 int32_t hi = NumStringIds() - 1;
662 while (hi >= lo) {
663 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700664 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700665 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000666 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700667 if (compare > 0) {
668 lo = mid + 1;
669 } else if (compare < 0) {
670 hi = mid - 1;
671 } else {
672 return &str_id;
673 }
674 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700675 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700676}
677
678const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700679 int32_t lo = 0;
680 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700681 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700682 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700683 const TypeId& type_id = GetTypeId(mid);
684 if (string_idx > type_id.descriptor_idx_) {
685 lo = mid + 1;
686 } else if (string_idx < type_id.descriptor_idx_) {
687 hi = mid - 1;
688 } else {
689 return &type_id;
690 }
691 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700692 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700693}
694
695const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000696 const uint16_t* signature_type_idxs,
697 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700698 int32_t lo = 0;
699 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700700 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700701 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700702 const DexFile::ProtoId& proto = GetProtoId(mid);
703 int compare = return_type_idx - proto.return_type_idx_;
704 if (compare == 0) {
705 DexFileParameterIterator it(*this, proto);
706 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000707 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800708 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700709 it.Next();
710 i++;
711 }
712 if (compare == 0) {
713 if (it.HasNext()) {
714 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000715 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700716 compare = 1;
717 }
718 }
719 }
720 if (compare > 0) {
721 lo = mid + 1;
722 } else if (compare < 0) {
723 hi = mid - 1;
724 } else {
725 return &proto;
726 }
727 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700729}
730
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000731void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
732 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300733}
734
Ian Rogers0571d352011-11-03 19:51:38 -0700735// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700736bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
737 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700738 if (signature[0] != '(') {
739 return false;
740 }
741 size_t offset = 1;
742 size_t end = signature.size();
743 bool process_return = false;
744 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000745 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700746 char c = signature[offset];
747 offset++;
748 if (c == ')') {
749 process_return = true;
750 continue;
751 }
Ian Rogers0571d352011-11-03 19:51:38 -0700752 while (c == '[') { // process array prefix
753 if (offset >= end) { // expect some descriptor following [
754 return false;
755 }
756 c = signature[offset];
757 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700758 }
759 if (c == 'L') { // process type descriptors
760 do {
761 if (offset >= end) { // unexpected early termination of descriptor
762 return false;
763 }
764 c = signature[offset];
765 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700766 } while (c != ';');
767 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000768 // TODO: avoid creating a std::string just to get a 0-terminated char array
769 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700770 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700772 return false;
773 }
774 uint16_t type_idx = GetIndexForTypeId(*type_id);
775 if (!process_return) {
776 param_type_idxs->push_back(type_idx);
777 } else {
778 *return_type_idx = type_idx;
779 return offset == end; // return true if the signature had reached a sensible end
780 }
781 }
782 return false; // failed to correctly parse return type
783}
784
Ian Rogersd91d6d62013-09-25 20:26:14 -0700785const Signature DexFile::CreateSignature(const StringPiece& signature) const {
786 uint16_t return_type_idx;
787 std::vector<uint16_t> param_type_indices;
788 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
789 if (!success) {
790 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700791 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700792 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700793 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700794 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700795 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700796 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700797}
798
Mathieu Chartiere401d142015-04-22 13:56:20 -0700799int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700800 // For native method, lineno should be -2 to indicate it is native. Note that
801 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700803 return -2;
804 }
805
TDYa127c8dc1012012-04-19 07:03:33 -0700806 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700807 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700808
809 // A method with no line number info should return -1
810 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000811 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700812 return context.line_num_;
813}
814
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700815int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700816 // Note: Signed type is important for max and min.
817 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700818 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700819
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700820 while (min <= max) {
821 int32_t mid = min + ((max - min) / 2);
822
823 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
824 uint32_t start = ti->start_addr_;
825 uint32_t end = start + ti->insn_count_;
826
Ian Rogers0571d352011-11-03 19:51:38 -0700827 if (address < start) {
828 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700829 } else if (address >= end) {
830 min = mid + 1;
831 } else { // We have a winner!
832 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700833 }
834 }
835 // No match.
836 return -1;
837}
838
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700839int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
840 int32_t try_item = FindTryItem(code_item, address);
841 if (try_item == -1) {
842 return -1;
843 } else {
844 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
845 }
846}
847
David Srbeckyb06e28e2015-12-10 13:15:00 +0000848bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
849 DexDebugNewLocalCb local_cb, void* context) const {
850 DCHECK(local_cb != nullptr);
851 if (code_item == nullptr) {
852 return false;
853 }
854 const uint8_t* stream = GetDebugInfoStream(code_item);
855 if (stream == nullptr) {
856 return false;
857 }
858 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700859
David Srbeckyb06e28e2015-12-10 13:15:00 +0000860 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000862 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
863 local_in_reg[arg_reg].name_ = "this";
864 local_in_reg[arg_reg].descriptor_ = descriptor;
865 local_in_reg[arg_reg].signature_ = nullptr;
866 local_in_reg[arg_reg].start_address_ = 0;
867 local_in_reg[arg_reg].reg_ = arg_reg;
868 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700869 arg_reg++;
870 }
871
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800872 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000873 DecodeUnsignedLeb128(&stream); // Line.
874 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
875 uint32_t i;
876 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700877 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700878 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800879 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000880 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700883 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000884 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
885 local_in_reg[arg_reg].descriptor_ = descriptor;
886 local_in_reg[arg_reg].signature_ = nullptr;
887 local_in_reg[arg_reg].start_address_ = 0;
888 local_in_reg[arg_reg].reg_ = arg_reg;
889 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700890 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 case 'D':
892 case 'J':
893 arg_reg += 2;
894 break;
895 default:
896 arg_reg += 1;
897 break;
898 }
899 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000900 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800901 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
902 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000903 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 }
905
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 for (;;) {
908 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700909 switch (opcode) {
910 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000911 // Emit all variables which are still alive at the end of the method.
912 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
913 if (local_in_reg[reg].is_live_) {
914 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
915 local_cb(context, local_in_reg[reg]);
916 }
917 }
918 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 case DBG_ADVANCE_PC:
920 address += DecodeUnsignedLeb128(&stream);
921 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000923 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 case DBG_START_LOCAL_EXTENDED: {
927 uint16_t reg = DecodeUnsignedLeb128(&stream);
928 if (reg >= code_item->registers_size_) {
929 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800930 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000931 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700932 }
933
David Srbeckyb06e28e2015-12-10 13:15:00 +0000934 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
935 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
936 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700937 if (opcode == DBG_START_LOCAL_EXTENDED) {
938 signature_idx = DecodeUnsignedLeb128P1(&stream);
939 }
940
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000942 if (local_in_reg[reg].is_live_) {
943 local_in_reg[reg].end_address_ = address;
944 local_cb(context, local_in_reg[reg]);
945 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700946
David Srbeckyb06e28e2015-12-10 13:15:00 +0000947 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
948 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
949 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
950 local_in_reg[reg].start_address_ = address;
951 local_in_reg[reg].reg_ = reg;
952 local_in_reg[reg].is_live_ = true;
953 break;
954 }
955 case DBG_END_LOCAL: {
956 uint16_t reg = DecodeUnsignedLeb128(&stream);
957 if (reg >= code_item->registers_size_) {
958 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
959 << code_item->registers_size_ << ") in " << GetLocation();
960 return false;
961 }
962 if (!local_in_reg[reg].is_live_) {
963 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
964 return false;
965 }
966 local_in_reg[reg].end_address_ = address;
967 local_cb(context, local_in_reg[reg]);
968 local_in_reg[reg].is_live_ = false;
969 break;
970 }
971 case DBG_RESTART_LOCAL: {
972 uint16_t reg = DecodeUnsignedLeb128(&stream);
973 if (reg >= code_item->registers_size_) {
974 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
975 << code_item->registers_size_ << ") in " << GetLocation();
976 return false;
977 }
978 // If the register is live, the "restart" is superfluous,
979 // and we don't want to mess with the existing start address.
980 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700981 local_in_reg[reg].start_address_ = address;
982 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700983 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700984 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000985 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700986 case DBG_SET_PROLOGUE_END:
987 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700988 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000989 case DBG_SET_FILE:
990 DecodeUnsignedLeb128P1(&stream); // name.
991 break;
992 default:
993 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
994 break;
995 }
996 }
997}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700998
David Srbeckyb06e28e2015-12-10 13:15:00 +0000999bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1000 void* context) const {
1001 DCHECK(position_cb != nullptr);
1002 if (code_item == nullptr) {
1003 return false;
1004 }
1005 const uint8_t* stream = GetDebugInfoStream(code_item);
1006 if (stream == nullptr) {
1007 return false;
1008 }
1009
1010 PositionInfo entry = PositionInfo();
1011 entry.line_ = DecodeUnsignedLeb128(&stream);
1012 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1013 for (uint32_t i = 0; i < parameters_size; ++i) {
1014 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1015 }
1016
1017 for (;;) {
1018 uint8_t opcode = *stream++;
1019 switch (opcode) {
1020 case DBG_END_SEQUENCE:
1021 return true; // end of stream.
1022 case DBG_ADVANCE_PC:
1023 entry.address_ += DecodeUnsignedLeb128(&stream);
1024 break;
1025 case DBG_ADVANCE_LINE:
1026 entry.line_ += DecodeSignedLeb128(&stream);
1027 break;
1028 case DBG_START_LOCAL:
1029 DecodeUnsignedLeb128(&stream); // reg.
1030 DecodeUnsignedLeb128P1(&stream); // name.
1031 DecodeUnsignedLeb128P1(&stream); // descriptor.
1032 break;
1033 case DBG_START_LOCAL_EXTENDED:
1034 DecodeUnsignedLeb128(&stream); // reg.
1035 DecodeUnsignedLeb128P1(&stream); // name.
1036 DecodeUnsignedLeb128P1(&stream); // descriptor.
1037 DecodeUnsignedLeb128P1(&stream); // signature.
1038 break;
1039 case DBG_END_LOCAL:
1040 case DBG_RESTART_LOCAL:
1041 DecodeUnsignedLeb128(&stream); // reg.
1042 break;
1043 case DBG_SET_PROLOGUE_END:
1044 entry.prologue_end_ = true;
1045 break;
1046 case DBG_SET_EPILOGUE_BEGIN:
1047 entry.epilogue_begin_ = true;
1048 break;
1049 case DBG_SET_FILE: {
1050 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1051 entry.source_file_ = StringDataByIdx(name_idx);
1052 break;
1053 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001054 default: {
1055 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001056 entry.address_ += adjopcode / DBG_LINE_RANGE;
1057 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1058 if (position_cb(context, entry)) {
1059 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001060 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001061 entry.prologue_end_ = false;
1062 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001063 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001064 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001065 }
1066 }
1067}
1068
David Srbeckyb06e28e2015-12-10 13:15:00 +00001069bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001070 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001071
1072 // We know that this callback will be called in
1073 // ascending address order, so keep going until we find
1074 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001075 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001076 // The line number from the previous positions callback
1077 // wil be the final result.
1078 return true;
1079 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001080 context->line_num_ = entry.line_;
1081 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001082 }
1083}
1084
Andreas Gampe833a4852014-05-21 18:46:59 -07001085bool DexFile::IsMultiDexLocation(const char* location) {
1086 return strrchr(location, kMultiDexSeparator) != nullptr;
1087}
1088
Andreas Gampe90e34042015-04-27 20:01:52 -07001089std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1090 if (index == 0) {
1091 return "classes.dex";
1092 } else {
1093 return StringPrintf("classes%zu.dex", index + 1);
1094 }
1095}
1096
1097std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1098 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001099 return dex_location;
1100 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001101 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001102 }
1103}
1104
1105std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1106 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001107 std::string base_location = GetBaseLocation(dex_location);
1108 const char* suffix = dex_location + base_location.size();
1109 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1110 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1111 if (path != nullptr && path.get() != base_location) {
1112 return std::string(path.get()) + suffix;
1113 } else if (suffix[0] == 0) {
1114 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001115 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001116 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001117 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001118}
1119
Jeff Hao13e748b2015-08-25 20:44:19 +00001120// Read a signed integer. "zwidth" is the zero-based byte count.
1121static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1122 int32_t val = 0;
1123 for (int i = zwidth; i >= 0; --i) {
1124 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1125 }
1126 val >>= (3 - zwidth) * 8;
1127 return val;
1128}
1129
1130// Read an unsigned integer. "zwidth" is the zero-based byte count,
1131// "fill_on_right" indicates which side we want to zero-fill from.
1132static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1133 uint32_t val = 0;
1134 for (int i = zwidth; i >= 0; --i) {
1135 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1136 }
1137 if (!fill_on_right) {
1138 val >>= (3 - zwidth) * 8;
1139 }
1140 return val;
1141}
1142
1143// Read a signed long. "zwidth" is the zero-based byte count.
1144static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1145 int64_t val = 0;
1146 for (int i = zwidth; i >= 0; --i) {
1147 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1148 }
1149 val >>= (7 - zwidth) * 8;
1150 return val;
1151}
1152
1153// Read an unsigned long. "zwidth" is the zero-based byte count,
1154// "fill_on_right" indicates which side we want to zero-fill from.
1155static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1156 uint64_t val = 0;
1157 for (int i = zwidth; i >= 0; --i) {
1158 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1159 }
1160 if (!fill_on_right) {
1161 val >>= (7 - zwidth) * 8;
1162 }
1163 return val;
1164}
1165
1166const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1167 mirror::Class* klass = field->GetDeclaringClass();
1168 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1169 if (annotations_dir == nullptr) {
1170 return nullptr;
1171 }
1172 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1173 if (field_annotations == nullptr) {
1174 return nullptr;
1175 }
1176 uint32_t field_index = field->GetDexFieldIndex();
1177 uint32_t field_count = annotations_dir->fields_size_;
1178 for (uint32_t i = 0; i < field_count; ++i) {
1179 if (field_annotations[i].field_idx_ == field_index) {
1180 return GetFieldAnnotationSetItem(field_annotations[i]);
1181 }
1182 }
1183 return nullptr;
1184}
1185
1186mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1187 Handle<mirror::Class> annotation_class) const {
1188 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1189 if (annotation_set == nullptr) {
1190 return nullptr;
1191 }
1192 StackHandleScope<1> hs(Thread::Current());
1193 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1194 return GetAnnotationObjectFromAnnotationSet(
1195 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1196}
1197
1198mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1199 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1200 StackHandleScope<1> hs(Thread::Current());
1201 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1202 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1203}
1204
Jeff Hao2a5892f2015-08-31 15:00:40 -07001205mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001206 const {
1207 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1208 if (annotation_set == nullptr) {
1209 return nullptr;
1210 }
1211 StackHandleScope<1> hs(Thread::Current());
1212 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1213 return GetSignatureValue(field_class, annotation_set);
1214}
1215
1216bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1217 const {
1218 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1219 if (annotation_set == nullptr) {
1220 return false;
1221 }
1222 StackHandleScope<1> hs(Thread::Current());
1223 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1224 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1225 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1226 return annotation_item != nullptr;
1227}
1228
1229const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1230 mirror::Class* klass = method->GetDeclaringClass();
1231 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1232 if (annotations_dir == nullptr) {
1233 return nullptr;
1234 }
1235 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1236 if (method_annotations == nullptr) {
1237 return nullptr;
1238 }
1239 uint32_t method_index = method->GetDexMethodIndex();
1240 uint32_t method_count = annotations_dir->methods_size_;
1241 for (uint32_t i = 0; i < method_count; ++i) {
1242 if (method_annotations[i].method_idx_ == method_index) {
1243 return GetMethodAnnotationSetItem(method_annotations[i]);
1244 }
1245 }
1246 return nullptr;
1247}
1248
1249const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1250 const {
1251 mirror::Class* klass = method->GetDeclaringClass();
1252 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1253 if (annotations_dir == nullptr) {
1254 return nullptr;
1255 }
1256 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1257 if (parameter_annotations == nullptr) {
1258 return nullptr;
1259 }
1260 uint32_t method_index = method->GetDexMethodIndex();
1261 uint32_t parameter_count = annotations_dir->parameters_size_;
1262 for (uint32_t i = 0; i < parameter_count; ++i) {
1263 if (parameter_annotations[i].method_idx_ == method_index) {
1264 return &parameter_annotations[i];
1265 }
1266 }
1267 return nullptr;
1268}
1269
1270mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1271 mirror::Class* klass = method->GetDeclaringClass();
1272 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1273 if (annotations_dir == nullptr) {
1274 return nullptr;
1275 }
1276 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1277 if (annotation_set == nullptr) {
1278 return nullptr;
1279 }
1280 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1281 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1282 if (annotation_item == nullptr) {
1283 return nullptr;
1284 }
1285 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1286 if (annotation == nullptr) {
1287 return nullptr;
1288 }
1289 uint8_t header_byte = *(annotation++);
1290 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1291 return nullptr;
1292 }
1293 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1294 if (annotation == nullptr) {
1295 return nullptr;
1296 }
1297 AnnotationValue annotation_value;
1298 StackHandleScope<2> hs(Thread::Current());
1299 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001300 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1301 Handle<mirror::Class> return_type(hs.NewHandle(
1302 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001303 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1304 return nullptr;
1305 }
1306 return annotation_value.value_.GetL();
1307}
1308
1309mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1310 Handle<mirror::Class> annotation_class) const {
1311 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1312 if (annotation_set == nullptr) {
1313 return nullptr;
1314 }
1315 StackHandleScope<1> hs(Thread::Current());
1316 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1317 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1318 kDexVisibilityRuntime, annotation_class);
1319}
1320
1321mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1322 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1323 StackHandleScope<1> hs(Thread::Current());
1324 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1325 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1326}
1327
Jeff Hao2a5892f2015-08-31 15:00:40 -07001328mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001329 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1330 if (annotation_set == nullptr) {
1331 return nullptr;
1332 }
1333 StackHandleScope<1> hs(Thread::Current());
1334 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1335 return GetThrowsValue(method_class, annotation_set);
1336}
1337
1338mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1339 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1340 if (parameter_annotations == nullptr) {
1341 return nullptr;
1342 }
1343 const AnnotationSetRefList* set_ref_list =
1344 GetParameterAnnotationSetRefList(parameter_annotations);
1345 if (set_ref_list == nullptr) {
1346 return nullptr;
1347 }
1348 uint32_t size = set_ref_list->size_;
1349 StackHandleScope<1> hs(Thread::Current());
1350 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1351 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1352}
1353
1354bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1355 const {
1356 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1357 if (annotation_set == nullptr) {
1358 return false;
1359 }
1360 StackHandleScope<1> hs(Thread::Current());
1361 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1362 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1363 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001364 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001365}
1366
1367const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1368 const {
1369 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1370 if (annotations_dir == nullptr) {
1371 return nullptr;
1372 }
1373 return GetClassAnnotationSet(annotations_dir);
1374}
1375
1376mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1377 Handle<mirror::Class> annotation_class) const {
1378 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1379 if (annotation_set == nullptr) {
1380 return nullptr;
1381 }
1382 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1383 annotation_class);
1384}
1385
1386mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1387 const {
1388 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1389 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1390}
1391
Jeff Hao2a5892f2015-08-31 15:00:40 -07001392mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1393 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1394 if (annotation_set == nullptr) {
1395 return nullptr;
1396 }
1397 const AnnotationItem* annotation_item = SearchAnnotationSet(
1398 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1399 if (annotation_item == nullptr) {
1400 return nullptr;
1401 }
1402 StackHandleScope<1> hs(Thread::Current());
1403 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1404 Handle<mirror::Class> class_array_class(hs.NewHandle(
1405 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1406 if (class_array_class.Get() == nullptr) {
1407 return nullptr;
1408 }
1409 mirror::Object* obj = GetAnnotationValue(
1410 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1411 if (obj == nullptr) {
1412 return nullptr;
1413 }
1414 return obj->AsObjectArray<mirror::Class>();
1415}
1416
1417mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1418 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1419 if (annotation_set == nullptr) {
1420 return nullptr;
1421 }
1422 const AnnotationItem* annotation_item = SearchAnnotationSet(
1423 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1424 if (annotation_item == nullptr) {
1425 return nullptr;
1426 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001427 mirror::Object* obj = GetAnnotationValue(klass,
1428 annotation_item,
1429 "value",
1430 ScopedNullHandle<mirror::Class>(),
1431 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001432 if (obj == nullptr) {
1433 return nullptr;
1434 }
1435 return obj->AsClass();
1436}
1437
1438mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1439 mirror::Class* declaring_class = GetDeclaringClass(klass);
1440 if (declaring_class != nullptr) {
1441 return declaring_class;
1442 }
1443 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1444 if (annotation_set == nullptr) {
1445 return nullptr;
1446 }
1447 const AnnotationItem* annotation_item = SearchAnnotationSet(
1448 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1449 if (annotation_item == nullptr) {
1450 return nullptr;
1451 }
1452 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1453 if (annotation == nullptr) {
1454 return nullptr;
1455 }
1456 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001457 if (!ProcessAnnotationValue(klass,
1458 &annotation,
1459 &annotation_value,
1460 ScopedNullHandle<mirror::Class>(),
1461 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001462 return nullptr;
1463 }
1464 if (annotation_value.type_ != kDexAnnotationMethod) {
1465 return nullptr;
1466 }
1467 StackHandleScope<2> hs(Thread::Current());
1468 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1469 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1470 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1471 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1472 if (method == nullptr) {
1473 return nullptr;
1474 }
1475 return method->GetDeclaringClass();
1476}
1477
1478mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1479 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1480 if (annotation_set == nullptr) {
1481 return nullptr;
1482 }
1483 const AnnotationItem* annotation_item = SearchAnnotationSet(
1484 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1485 if (annotation_item == nullptr) {
1486 return nullptr;
1487 }
1488 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001489 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001490}
1491
1492bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1493 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1494 if (annotation_set == nullptr) {
1495 return false;
1496 }
1497 const AnnotationItem* annotation_item = SearchAnnotationSet(
1498 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1499 if (annotation_item == nullptr) {
1500 return false;
1501 }
1502 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1503 if (annotation == nullptr) {
1504 return false;
1505 }
1506 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001507 if (!ProcessAnnotationValue(klass,
1508 &annotation,
1509 &annotation_value,
1510 ScopedNullHandle<mirror::Class>(),
1511 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001512 return false;
1513 }
1514 if (annotation_value.type_ != kDexAnnotationNull &&
1515 annotation_value.type_ != kDexAnnotationString) {
1516 return false;
1517 }
1518 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1519 return true;
1520}
1521
1522bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1523 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1524 if (annotation_set == nullptr) {
1525 return false;
1526 }
1527 const AnnotationItem* annotation_item = SearchAnnotationSet(
1528 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1529 if (annotation_item == nullptr) {
1530 return false;
1531 }
1532 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1533 if (annotation == nullptr) {
1534 return false;
1535 }
1536 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001537 if (!ProcessAnnotationValue(klass,
1538 &annotation,
1539 &annotation_value,
1540 ScopedNullHandle<mirror::Class>(),
1541 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001542 return false;
1543 }
1544 if (annotation_value.type_ != kDexAnnotationInt) {
1545 return false;
1546 }
1547 *flags = annotation_value.value_.GetI();
1548 return true;
1549}
1550
Jeff Hao13e748b2015-08-25 20:44:19 +00001551bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1552 Handle<mirror::Class> annotation_class) const {
1553 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1554 if (annotation_set == nullptr) {
1555 return false;
1556 }
1557 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1558 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001559 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001560}
1561
1562mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1563 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1564 Thread* self = Thread::Current();
1565 ScopedObjectAccessUnchecked soa(self);
1566 StackHandleScope<5> hs(self);
1567 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1568 const char* name = StringDataByIdx(element_name_index);
1569 Handle<mirror::String> string_name(
1570 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1571
1572 ArtMethod* annotation_method =
1573 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1574 if (annotation_method == nullptr) {
1575 return nullptr;
1576 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001577 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1578 Handle<mirror::Class> method_return(hs.NewHandle(
1579 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001580
1581 AnnotationValue annotation_value;
1582 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1583 return nullptr;
1584 }
1585 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1586
1587 mirror::Class* annotation_member_class =
1588 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1589 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1590 Handle<mirror::Method> method_object(
1591 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1592
1593 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1594 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1595 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1596 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1597 return nullptr;
1598 }
1599
1600 JValue result;
1601 ArtMethod* annotation_member_init =
1602 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1603 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1604 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1605 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1606 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1607 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1608 };
1609 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1610 if (self->IsExceptionPending()) {
1611 LOG(INFO) << "Exception in AnnotationMember.<init>";
1612 return nullptr;
1613 }
1614
1615 return new_member.Get();
1616}
1617
1618const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1619 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1620 Handle<mirror::Class> annotation_class) const {
1621 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1622 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1623 if (annotation_item->visibility_ != visibility) {
1624 continue;
1625 }
1626 const uint8_t* annotation = annotation_item->annotation_;
1627 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1628 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1629 klass->GetDexFile(), type_index, klass.Get());
1630 if (resolved_class == nullptr) {
1631 std::string temp;
1632 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1633 klass->GetDescriptor(&temp), type_index);
1634 CHECK(Thread::Current()->IsExceptionPending());
1635 Thread::Current()->ClearException();
1636 continue;
1637 }
1638 if (resolved_class == annotation_class.Get()) {
1639 return annotation_item;
1640 }
1641 }
1642
1643 return nullptr;
1644}
1645
1646mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1647 const AnnotationSetItem* annotation_set, uint32_t visibility,
1648 Handle<mirror::Class> annotation_class) const {
1649 const AnnotationItem* annotation_item =
1650 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1651 if (annotation_item == nullptr) {
1652 return nullptr;
1653 }
1654 const uint8_t* annotation = annotation_item->annotation_;
1655 return ProcessEncodedAnnotation(klass, &annotation);
1656}
1657
1658mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1659 const AnnotationItem* annotation_item, const char* annotation_name,
1660 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1661 const uint8_t* annotation =
1662 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1663 if (annotation == nullptr) {
1664 return nullptr;
1665 }
1666 AnnotationValue annotation_value;
1667 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1668 return nullptr;
1669 }
1670 if (annotation_value.type_ != expected_type) {
1671 return nullptr;
1672 }
1673 return annotation_value.value_.GetL();
1674}
1675
Jeff Hao2a5892f2015-08-31 15:00:40 -07001676mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001677 const AnnotationSetItem* annotation_set) const {
1678 StackHandleScope<1> hs(Thread::Current());
1679 const AnnotationItem* annotation_item =
1680 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1681 if (annotation_item == nullptr) {
1682 return nullptr;
1683 }
1684 mirror::Class* string_class = mirror::String::GetJavaLangString();
1685 Handle<mirror::Class> string_array_class(hs.NewHandle(
1686 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001687 if (string_array_class.Get() == nullptr) {
1688 return nullptr;
1689 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001690 mirror::Object* obj =
1691 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1692 if (obj == nullptr) {
1693 return nullptr;
1694 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001695 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001696}
1697
Jeff Hao2a5892f2015-08-31 15:00:40 -07001698mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001699 const AnnotationSetItem* annotation_set) const {
1700 StackHandleScope<1> hs(Thread::Current());
1701 const AnnotationItem* annotation_item =
1702 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1703 if (annotation_item == nullptr) {
1704 return nullptr;
1705 }
1706 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1707 Handle<mirror::Class> class_array_class(hs.NewHandle(
1708 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001709 if (class_array_class.Get() == nullptr) {
1710 return nullptr;
1711 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001712 mirror::Object* obj =
1713 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1714 if (obj == nullptr) {
1715 return nullptr;
1716 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001717 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001718}
1719
1720mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1721 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1722 Thread* self = Thread::Current();
1723 ScopedObjectAccessUnchecked soa(self);
1724 StackHandleScope<2> hs(self);
1725 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1726 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1727 if (annotation_set == nullptr) {
1728 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1729 }
1730
1731 uint32_t size = annotation_set->size_;
1732 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1733 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1734 if (result.Get() == nullptr) {
1735 return nullptr;
1736 }
1737
1738 uint32_t dest_index = 0;
1739 for (uint32_t i = 0; i < size; ++i) {
1740 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1741 if (annotation_item->visibility_ != visibility) {
1742 continue;
1743 }
1744 const uint8_t* annotation = annotation_item->annotation_;
1745 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1746 if (annotation_obj != nullptr) {
1747 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1748 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001749 } else if (self->IsExceptionPending()) {
1750 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001751 }
1752 }
1753
1754 if (dest_index == size) {
1755 return result.Get();
1756 }
1757
1758 mirror::ObjectArray<mirror::Object>* trimmed_result =
1759 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001760 if (trimmed_result == nullptr) {
1761 return nullptr;
1762 }
1763
Jeff Hao13e748b2015-08-25 20:44:19 +00001764 for (uint32_t i = 0; i < dest_index; ++i) {
1765 mirror::Object* obj = result->GetWithoutChecks(i);
1766 trimmed_result->SetWithoutChecks<false>(i, obj);
1767 }
1768
1769 return trimmed_result;
1770}
1771
1772mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1773 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1774 Thread* self = Thread::Current();
1775 ScopedObjectAccessUnchecked soa(self);
1776 StackHandleScope<1> hs(self);
1777 mirror::Class* annotation_array_class =
1778 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1779 mirror::Class* annotation_array_array_class =
1780 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001781 if (annotation_array_array_class == nullptr) {
1782 return nullptr;
1783 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001784 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1785 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1786 if (annotation_array_array.Get() == nullptr) {
1787 LOG(ERROR) << "Annotation set ref array allocation failed";
1788 return nullptr;
1789 }
1790 for (uint32_t index = 0; index < size; ++index) {
1791 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1792 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1793 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1794 if (annotation_set == nullptr) {
1795 return nullptr;
1796 }
1797 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1798 }
1799 return annotation_array_array.Get();
1800}
1801
1802bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1803 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1804 DexFile::AnnotationResultStyle result_style) const {
1805 Thread* self = Thread::Current();
1806 mirror::Object* element_object = nullptr;
1807 bool set_object = false;
1808 Primitive::Type primitive_type = Primitive::kPrimVoid;
1809 const uint8_t* annotation = *annotation_ptr;
1810 uint8_t header_byte = *(annotation++);
1811 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1812 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1813 int32_t width = value_arg + 1;
1814 annotation_value->type_ = value_type;
1815
1816 switch (value_type) {
1817 case kDexAnnotationByte:
1818 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1819 primitive_type = Primitive::kPrimByte;
1820 break;
1821 case kDexAnnotationShort:
1822 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1823 primitive_type = Primitive::kPrimShort;
1824 break;
1825 case kDexAnnotationChar:
1826 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1827 false)));
1828 primitive_type = Primitive::kPrimChar;
1829 break;
1830 case kDexAnnotationInt:
1831 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1832 primitive_type = Primitive::kPrimInt;
1833 break;
1834 case kDexAnnotationLong:
1835 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1836 primitive_type = Primitive::kPrimLong;
1837 break;
1838 case kDexAnnotationFloat:
1839 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1840 primitive_type = Primitive::kPrimFloat;
1841 break;
1842 case kDexAnnotationDouble:
1843 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1844 primitive_type = Primitive::kPrimDouble;
1845 break;
1846 case kDexAnnotationBoolean:
1847 annotation_value->value_.SetZ(value_arg != 0);
1848 primitive_type = Primitive::kPrimBoolean;
1849 width = 0;
1850 break;
1851 case kDexAnnotationString: {
1852 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1853 if (result_style == kAllRaw) {
1854 annotation_value->value_.SetI(index);
1855 } else {
1856 StackHandleScope<1> hs(self);
1857 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1858 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1859 klass->GetDexFile(), index, dex_cache);
1860 set_object = true;
1861 if (element_object == nullptr) {
1862 return false;
1863 }
1864 }
1865 break;
1866 }
1867 case kDexAnnotationType: {
1868 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1869 if (result_style == kAllRaw) {
1870 annotation_value->value_.SetI(index);
1871 } else {
1872 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1873 klass->GetDexFile(), index, klass.Get());
1874 set_object = true;
1875 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001876 CHECK(self->IsExceptionPending());
1877 if (result_style == kAllObjects) {
1878 const char* msg = StringByTypeIdx(index);
1879 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1880 element_object = self->GetException();
1881 self->ClearException();
1882 } else {
1883 return false;
1884 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001885 }
1886 }
1887 break;
1888 }
1889 case kDexAnnotationMethod: {
1890 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1891 if (result_style == kAllRaw) {
1892 annotation_value->value_.SetI(index);
1893 } else {
1894 StackHandleScope<2> hs(self);
1895 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1896 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1897 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1898 klass->GetDexFile(), index, dex_cache, class_loader);
1899 if (method == nullptr) {
1900 return false;
1901 }
1902 set_object = true;
1903 if (method->IsConstructor()) {
1904 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1905 } else {
1906 element_object = mirror::Method::CreateFromArtMethod(self, method);
1907 }
1908 if (element_object == nullptr) {
1909 return false;
1910 }
1911 }
1912 break;
1913 }
1914 case kDexAnnotationField: {
1915 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1916 if (result_style == kAllRaw) {
1917 annotation_value->value_.SetI(index);
1918 } else {
1919 StackHandleScope<2> hs(self);
1920 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1921 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1922 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1923 klass->GetDexFile(), index, dex_cache, class_loader);
1924 if (field == nullptr) {
1925 return false;
1926 }
1927 set_object = true;
1928 element_object = mirror::Field::CreateFromArtField(self, field, true);
1929 if (element_object == nullptr) {
1930 return false;
1931 }
1932 }
1933 break;
1934 }
1935 case kDexAnnotationEnum: {
1936 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1937 if (result_style == kAllRaw) {
1938 annotation_value->value_.SetI(index);
1939 } else {
1940 StackHandleScope<3> hs(self);
1941 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1942 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1943 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1944 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001945 if (enum_field == nullptr) {
1946 return false;
1947 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001948 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001949 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1950 element_object = enum_field->GetObject(field_class.Get());
1951 set_object = true;
1952 }
1953 }
1954 break;
1955 }
1956 case kDexAnnotationArray:
1957 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1958 return false;
1959 } else {
1960 ScopedObjectAccessUnchecked soa(self);
1961 StackHandleScope<2> hs(self);
1962 uint32_t size = DecodeUnsignedLeb128(&annotation);
1963 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1964 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1965 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1966 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1967 if (new_array.Get() == nullptr) {
1968 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1969 return false;
1970 }
1971 AnnotationValue new_annotation_value;
1972 for (uint32_t i = 0; i < size; ++i) {
1973 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1974 kPrimitivesOrObjects)) {
1975 return false;
1976 }
1977 if (!component_type->IsPrimitive()) {
1978 mirror::Object* obj = new_annotation_value.value_.GetL();
1979 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1980 } else {
1981 switch (new_annotation_value.type_) {
1982 case kDexAnnotationByte:
1983 new_array->AsByteArray()->SetWithoutChecks<false>(
1984 i, new_annotation_value.value_.GetB());
1985 break;
1986 case kDexAnnotationShort:
1987 new_array->AsShortArray()->SetWithoutChecks<false>(
1988 i, new_annotation_value.value_.GetS());
1989 break;
1990 case kDexAnnotationChar:
1991 new_array->AsCharArray()->SetWithoutChecks<false>(
1992 i, new_annotation_value.value_.GetC());
1993 break;
1994 case kDexAnnotationInt:
1995 new_array->AsIntArray()->SetWithoutChecks<false>(
1996 i, new_annotation_value.value_.GetI());
1997 break;
1998 case kDexAnnotationLong:
1999 new_array->AsLongArray()->SetWithoutChecks<false>(
2000 i, new_annotation_value.value_.GetJ());
2001 break;
2002 case kDexAnnotationFloat:
2003 new_array->AsFloatArray()->SetWithoutChecks<false>(
2004 i, new_annotation_value.value_.GetF());
2005 break;
2006 case kDexAnnotationDouble:
2007 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2008 i, new_annotation_value.value_.GetD());
2009 break;
2010 case kDexAnnotationBoolean:
2011 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2012 i, new_annotation_value.value_.GetZ());
2013 break;
2014 default:
2015 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2016 return false;
2017 }
2018 }
2019 }
2020 element_object = new_array.Get();
2021 set_object = true;
2022 width = 0;
2023 }
2024 break;
2025 case kDexAnnotationAnnotation:
2026 if (result_style == kAllRaw) {
2027 return false;
2028 }
2029 element_object = ProcessEncodedAnnotation(klass, &annotation);
2030 if (element_object == nullptr) {
2031 return false;
2032 }
2033 set_object = true;
2034 width = 0;
2035 break;
2036 case kDexAnnotationNull:
2037 if (result_style == kAllRaw) {
2038 annotation_value->value_.SetI(0);
2039 } else {
2040 CHECK(element_object == nullptr);
2041 set_object = true;
2042 }
2043 width = 0;
2044 break;
2045 default:
2046 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2047 return false;
2048 }
2049
2050 annotation += width;
2051 *annotation_ptr = annotation;
2052
2053 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2054 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2055 set_object = true;
2056 }
2057
2058 if (set_object) {
2059 annotation_value->value_.SetL(element_object);
2060 }
2061
2062 return true;
2063}
2064
2065mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2066 const uint8_t** annotation) const {
2067 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2068 uint32_t size = DecodeUnsignedLeb128(annotation);
2069
2070 Thread* self = Thread::Current();
2071 ScopedObjectAccessUnchecked soa(self);
2072 StackHandleScope<2> hs(self);
2073 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2074 Handle<mirror::Class> annotation_class(hs.NewHandle(
2075 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2076 if (annotation_class.Get() == nullptr) {
2077 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2078 << type_index;
2079 DCHECK(Thread::Current()->IsExceptionPending());
2080 Thread::Current()->ClearException();
2081 return nullptr;
2082 }
2083
2084 mirror::Class* annotation_member_class =
2085 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2086 mirror::Class* annotation_member_array_class =
2087 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002088 if (annotation_member_array_class == nullptr) {
2089 return nullptr;
2090 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002091 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002092 if (size > 0) {
2093 element_array =
2094 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2095 if (element_array == nullptr) {
2096 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2097 return nullptr;
2098 }
2099 }
2100
2101 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2102 for (uint32_t i = 0; i < size; ++i) {
2103 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2104 if (new_member == nullptr) {
2105 return nullptr;
2106 }
2107 h_element_array->SetWithoutChecks<false>(i, new_member);
2108 }
2109
2110 JValue result;
2111 ArtMethod* create_annotation_method =
2112 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2113 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2114 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2115 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2116 if (self->IsExceptionPending()) {
2117 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2118 return nullptr;
2119 }
2120
2121 return result.GetL();
2122}
2123
2124const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2125 const char* descriptor, uint32_t visibility) const {
2126 const AnnotationItem* result = nullptr;
2127 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2128 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2129 if (annotation_item->visibility_ != visibility) {
2130 continue;
2131 }
2132 const uint8_t* annotation = annotation_item->annotation_;
2133 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2134
2135 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2136 result = annotation_item;
2137 break;
2138 }
2139 }
2140 return result;
2141}
2142
2143const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2144 DecodeUnsignedLeb128(&annotation); // unused type_index
2145 uint32_t size = DecodeUnsignedLeb128(&annotation);
2146
2147 while (size != 0) {
2148 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2149 const char* element_name = GetStringData(GetStringId(element_name_index));
2150 if (strcmp(name, element_name) == 0) {
2151 return annotation;
2152 }
2153 SkipAnnotationValue(&annotation);
2154 size--;
2155 }
2156 return nullptr;
2157}
2158
2159bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2160 const uint8_t* annotation = *annotation_ptr;
2161 uint8_t header_byte = *(annotation++);
2162 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2163 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2164 int32_t width = value_arg + 1;
2165
2166 switch (value_type) {
2167 case kDexAnnotationByte:
2168 case kDexAnnotationShort:
2169 case kDexAnnotationChar:
2170 case kDexAnnotationInt:
2171 case kDexAnnotationLong:
2172 case kDexAnnotationFloat:
2173 case kDexAnnotationDouble:
2174 case kDexAnnotationString:
2175 case kDexAnnotationType:
2176 case kDexAnnotationMethod:
2177 case kDexAnnotationField:
2178 case kDexAnnotationEnum:
2179 break;
2180 case kDexAnnotationArray:
2181 {
2182 uint32_t size = DecodeUnsignedLeb128(&annotation);
2183 while (size--) {
2184 if (!SkipAnnotationValue(&annotation)) {
2185 return false;
2186 }
2187 }
2188 width = 0;
2189 break;
2190 }
2191 case kDexAnnotationAnnotation:
2192 {
2193 DecodeUnsignedLeb128(&annotation); // unused type_index
2194 uint32_t size = DecodeUnsignedLeb128(&annotation);
2195 while (size--) {
2196 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2197 if (!SkipAnnotationValue(&annotation)) {
2198 return false;
2199 }
2200 }
2201 width = 0;
2202 break;
2203 }
2204 case kDexAnnotationBoolean:
2205 case kDexAnnotationNull:
2206 width = 0;
2207 break;
2208 default:
2209 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2210 return false;
2211 }
2212
2213 annotation += width;
2214 *annotation_ptr = annotation;
2215 return true;
2216}
2217
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002218std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2219 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2220 dex_file.GetLocation().c_str(),
2221 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2222 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2223 return os;
2224}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002225
Ian Rogersd91d6d62013-09-25 20:26:14 -07002226std::string Signature::ToString() const {
2227 if (dex_file_ == nullptr) {
2228 CHECK(proto_id_ == nullptr);
2229 return "<no signature>";
2230 }
2231 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2232 std::string result;
2233 if (params == nullptr) {
2234 result += "()";
2235 } else {
2236 result += "(";
2237 for (uint32_t i = 0; i < params->Size(); ++i) {
2238 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2239 }
2240 result += ")";
2241 }
2242 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2243 return result;
2244}
2245
Vladimir Markod9cffea2013-11-25 15:08:02 +00002246bool Signature::operator==(const StringPiece& rhs) const {
2247 if (dex_file_ == nullptr) {
2248 return false;
2249 }
2250 StringPiece tail(rhs);
2251 if (!tail.starts_with("(")) {
2252 return false; // Invalid signature
2253 }
2254 tail.remove_prefix(1); // "(";
2255 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2256 if (params != nullptr) {
2257 for (uint32_t i = 0; i < params->Size(); ++i) {
2258 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2259 if (!tail.starts_with(param)) {
2260 return false;
2261 }
2262 tail.remove_prefix(param.length());
2263 }
2264 }
2265 if (!tail.starts_with(")")) {
2266 return false;
2267 }
2268 tail.remove_prefix(1); // ")";
2269 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2270}
2271
Ian Rogersd91d6d62013-09-25 20:26:14 -07002272std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2273 return os << sig.ToString();
2274}
2275
Ian Rogers0571d352011-11-03 19:51:38 -07002276// Decodes the header section from the class data bytes.
2277void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002278 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002279 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2280 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2281 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2282 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2283}
2284
2285void ClassDataItemIterator::ReadClassDataField() {
2286 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2287 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002288 // The user of the iterator is responsible for checking if there
2289 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002290}
2291
2292void ClassDataItemIterator::ReadClassDataMethod() {
2293 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2294 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2295 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002296 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002297 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002298 }
Ian Rogers0571d352011-11-03 19:51:38 -07002299}
2300
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002301EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002302 const DexFile& dex_file,
2303 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002304 : EncodedStaticFieldValueIterator(dex_file,
2305 nullptr,
2306 nullptr,
2307 nullptr,
2308 class_def,
2309 -1,
2310 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002311}
2312
2313EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002314 const DexFile& dex_file,
2315 Handle<mirror::DexCache>* dex_cache,
2316 Handle<mirror::ClassLoader>* class_loader,
2317 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002318 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002319 : EncodedStaticFieldValueIterator(dex_file,
2320 dex_cache, class_loader,
2321 linker,
2322 class_def,
2323 -1,
2324 kByte) {
2325 DCHECK(dex_cache_ != nullptr);
2326 DCHECK(class_loader_ != nullptr);
2327}
2328
2329EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2330 const DexFile& dex_file,
2331 Handle<mirror::DexCache>* dex_cache,
2332 Handle<mirror::ClassLoader>* class_loader,
2333 ClassLinker* linker,
2334 const DexFile::ClassDef& class_def,
2335 size_t pos,
2336 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002337 : dex_file_(dex_file),
2338 dex_cache_(dex_cache),
2339 class_loader_(class_loader),
2340 linker_(linker),
2341 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002342 pos_(pos),
2343 type_(type) {
2344 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002345 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002346 array_size_ = 0;
2347 } else {
2348 array_size_ = DecodeUnsignedLeb128(&ptr_);
2349 }
2350 if (array_size_ > 0) {
2351 Next();
2352 }
2353}
2354
2355void EncodedStaticFieldValueIterator::Next() {
2356 pos_++;
2357 if (pos_ >= array_size_) {
2358 return;
2359 }
Ian Rogers13735952014-10-08 12:43:28 -07002360 uint8_t value_type = *ptr_++;
2361 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002362 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002363 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002364 switch (type_) {
2365 case kBoolean:
2366 jval_.i = (value_arg != 0) ? 1 : 0;
2367 width = 0;
2368 break;
2369 case kByte:
2370 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002371 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002372 break;
2373 case kShort:
2374 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002375 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002376 break;
2377 case kChar:
2378 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002379 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002380 break;
2381 case kInt:
2382 jval_.i = ReadSignedInt(ptr_, value_arg);
2383 break;
2384 case kLong:
2385 jval_.j = ReadSignedLong(ptr_, value_arg);
2386 break;
2387 case kFloat:
2388 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2389 break;
2390 case kDouble:
2391 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2392 break;
2393 case kString:
2394 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002395 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2396 break;
2397 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002398 case kMethod:
2399 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002400 case kArray:
2401 case kAnnotation:
2402 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002403 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002404 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002405 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002406 width = 0;
2407 break;
2408 default:
2409 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002410 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002411 }
2412 ptr_ += width;
2413}
2414
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002415template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002416void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002417 DCHECK(dex_cache_ != nullptr);
2418 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002419 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002420 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2421 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002422 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2423 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2424 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2425 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2426 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2427 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2428 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002429 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002430 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002431 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002432 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002433 break;
2434 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002435 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002436 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2437 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002438 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002439 break;
2440 }
Ian Rogers0571d352011-11-03 19:51:38 -07002441 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2442 }
2443}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002444template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2445template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002446
2447CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2448 handler_.address_ = -1;
2449 int32_t offset = -1;
2450
2451 // Short-circuit the overwhelmingly common cases.
2452 switch (code_item.tries_size_) {
2453 case 0:
2454 break;
2455 case 1: {
2456 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2457 uint32_t start = tries->start_addr_;
2458 if (address >= start) {
2459 uint32_t end = start + tries->insn_count_;
2460 if (address < end) {
2461 offset = tries->handler_off_;
2462 }
2463 }
2464 break;
2465 }
2466 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002467 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002468 }
Logan Chien736df022012-04-27 16:25:57 +08002469 Init(code_item, offset);
2470}
2471
2472CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2473 const DexFile::TryItem& try_item) {
2474 handler_.address_ = -1;
2475 Init(code_item, try_item.handler_off_);
2476}
2477
2478void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2479 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002480 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002481 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002482 } else {
2483 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002484 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002485 remaining_count_ = -1;
2486 catch_all_ = false;
2487 DCHECK(!HasNext());
2488 }
2489}
2490
Ian Rogers13735952014-10-08 12:43:28 -07002491void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002492 current_data_ = handler_data;
2493 remaining_count_ = DecodeSignedLeb128(&current_data_);
2494
2495 // If remaining_count_ is non-positive, then it is the negative of
2496 // the number of catch types, and the catches are followed by a
2497 // catch-all handler.
2498 if (remaining_count_ <= 0) {
2499 catch_all_ = true;
2500 remaining_count_ = -remaining_count_;
2501 } else {
2502 catch_all_ = false;
2503 }
2504 Next();
2505}
2506
2507void CatchHandlerIterator::Next() {
2508 if (remaining_count_ > 0) {
2509 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2510 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2511 remaining_count_--;
2512 return;
2513 }
2514
2515 if (catch_all_) {
2516 handler_.type_idx_ = DexFile::kDexNoIndex16;
2517 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2518 catch_all_ = false;
2519 return;
2520 }
2521
2522 // no more handler
2523 remaining_count_ = -1;
2524}
2525
Carl Shapiro1fb86202011-06-27 17:43:13 -07002526} // namespace art