blob: af12abfc08dd0a0cc299e9eb4cd6abe9ff8c185c [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
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700509uint32_t DexFile::Header::GetVersion() const {
510 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700511 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
Roland Levillainab880f42016-05-12 16:24:36 +0100521 // Fast path for rare 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,
Roland Levillainab880f42016-05-12 16:24:36 +0100551 const DexFile::StringId& name,
552 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800553 // 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
Jeff Hao1133db72016-04-04 19:50:14 -07001354mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1355 const {
1356 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1357 if (annotation_set == nullptr) {
1358 return nullptr;
1359 }
1360 StackHandleScope<1> hs(Thread::Current());
1361 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1362 return GetSignatureValue(method_class, annotation_set);
1363}
1364
Jeff Hao13e748b2015-08-25 20:44:19 +00001365bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1366 const {
1367 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1368 if (annotation_set == nullptr) {
1369 return false;
1370 }
1371 StackHandleScope<1> hs(Thread::Current());
1372 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1373 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1374 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001375 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001376}
1377
1378const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1379 const {
1380 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1381 if (annotations_dir == nullptr) {
1382 return nullptr;
1383 }
1384 return GetClassAnnotationSet(annotations_dir);
1385}
1386
1387mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1388 Handle<mirror::Class> annotation_class) const {
1389 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1390 if (annotation_set == nullptr) {
1391 return nullptr;
1392 }
1393 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1394 annotation_class);
1395}
1396
1397mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1398 const {
1399 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1400 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1401}
1402
Jeff Hao2a5892f2015-08-31 15:00:40 -07001403mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1404 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1405 if (annotation_set == nullptr) {
1406 return nullptr;
1407 }
1408 const AnnotationItem* annotation_item = SearchAnnotationSet(
1409 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1410 if (annotation_item == nullptr) {
1411 return nullptr;
1412 }
1413 StackHandleScope<1> hs(Thread::Current());
1414 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1415 Handle<mirror::Class> class_array_class(hs.NewHandle(
1416 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1417 if (class_array_class.Get() == nullptr) {
1418 return nullptr;
1419 }
1420 mirror::Object* obj = GetAnnotationValue(
1421 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1422 if (obj == nullptr) {
1423 return nullptr;
1424 }
1425 return obj->AsObjectArray<mirror::Class>();
1426}
1427
1428mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1429 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1430 if (annotation_set == nullptr) {
1431 return nullptr;
1432 }
1433 const AnnotationItem* annotation_item = SearchAnnotationSet(
1434 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1435 if (annotation_item == nullptr) {
1436 return nullptr;
1437 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001438 mirror::Object* obj = GetAnnotationValue(klass,
1439 annotation_item,
1440 "value",
1441 ScopedNullHandle<mirror::Class>(),
1442 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001443 if (obj == nullptr) {
1444 return nullptr;
1445 }
1446 return obj->AsClass();
1447}
1448
1449mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1450 mirror::Class* declaring_class = GetDeclaringClass(klass);
1451 if (declaring_class != nullptr) {
1452 return declaring_class;
1453 }
1454 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1455 if (annotation_set == nullptr) {
1456 return nullptr;
1457 }
1458 const AnnotationItem* annotation_item = SearchAnnotationSet(
1459 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1460 if (annotation_item == nullptr) {
1461 return nullptr;
1462 }
1463 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1464 if (annotation == nullptr) {
1465 return nullptr;
1466 }
1467 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001468 if (!ProcessAnnotationValue(klass,
1469 &annotation,
1470 &annotation_value,
1471 ScopedNullHandle<mirror::Class>(),
1472 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001473 return nullptr;
1474 }
1475 if (annotation_value.type_ != kDexAnnotationMethod) {
1476 return nullptr;
1477 }
1478 StackHandleScope<2> hs(Thread::Current());
1479 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1480 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1481 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1482 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1483 if (method == nullptr) {
1484 return nullptr;
1485 }
1486 return method->GetDeclaringClass();
1487}
1488
1489mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1490 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1491 if (annotation_set == nullptr) {
1492 return nullptr;
1493 }
1494 const AnnotationItem* annotation_item = SearchAnnotationSet(
1495 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1496 if (annotation_item == nullptr) {
1497 return nullptr;
1498 }
1499 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001500 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001501}
1502
1503bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1504 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1505 if (annotation_set == nullptr) {
1506 return false;
1507 }
1508 const AnnotationItem* annotation_item = SearchAnnotationSet(
1509 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1510 if (annotation_item == nullptr) {
1511 return false;
1512 }
1513 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1514 if (annotation == nullptr) {
1515 return false;
1516 }
1517 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001518 if (!ProcessAnnotationValue(klass,
1519 &annotation,
1520 &annotation_value,
1521 ScopedNullHandle<mirror::Class>(),
1522 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001523 return false;
1524 }
1525 if (annotation_value.type_ != kDexAnnotationNull &&
1526 annotation_value.type_ != kDexAnnotationString) {
1527 return false;
1528 }
1529 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1530 return true;
1531}
1532
1533bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1534 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1535 if (annotation_set == nullptr) {
1536 return false;
1537 }
1538 const AnnotationItem* annotation_item = SearchAnnotationSet(
1539 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1540 if (annotation_item == nullptr) {
1541 return false;
1542 }
1543 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1544 if (annotation == nullptr) {
1545 return false;
1546 }
1547 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001548 if (!ProcessAnnotationValue(klass,
1549 &annotation,
1550 &annotation_value,
1551 ScopedNullHandle<mirror::Class>(),
1552 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001553 return false;
1554 }
1555 if (annotation_value.type_ != kDexAnnotationInt) {
1556 return false;
1557 }
1558 *flags = annotation_value.value_.GetI();
1559 return true;
1560}
1561
Jeff Hao1133db72016-04-04 19:50:14 -07001562mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1563 Handle<mirror::Class> klass) const {
1564 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1565 if (annotation_set == nullptr) {
1566 return nullptr;
1567 }
1568 return GetSignatureValue(klass, annotation_set);
1569}
1570
Jeff Hao13e748b2015-08-25 20:44:19 +00001571bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1572 Handle<mirror::Class> annotation_class) const {
1573 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1574 if (annotation_set == nullptr) {
1575 return false;
1576 }
1577 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1578 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001579 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001580}
1581
1582mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1583 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1584 Thread* self = Thread::Current();
1585 ScopedObjectAccessUnchecked soa(self);
1586 StackHandleScope<5> hs(self);
1587 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1588 const char* name = StringDataByIdx(element_name_index);
1589 Handle<mirror::String> string_name(
1590 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1591
1592 ArtMethod* annotation_method =
1593 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1594 if (annotation_method == nullptr) {
1595 return nullptr;
1596 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001597 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1598 Handle<mirror::Class> method_return(hs.NewHandle(
1599 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001600
1601 AnnotationValue annotation_value;
1602 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1603 return nullptr;
1604 }
1605 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1606
1607 mirror::Class* annotation_member_class =
1608 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1609 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1610 Handle<mirror::Method> method_object(
1611 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1612
1613 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1614 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1615 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1616 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1617 return nullptr;
1618 }
1619
1620 JValue result;
1621 ArtMethod* annotation_member_init =
1622 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1623 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1624 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1625 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1626 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1627 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1628 };
1629 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1630 if (self->IsExceptionPending()) {
1631 LOG(INFO) << "Exception in AnnotationMember.<init>";
1632 return nullptr;
1633 }
1634
1635 return new_member.Get();
1636}
1637
1638const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1639 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1640 Handle<mirror::Class> annotation_class) const {
1641 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1642 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1643 if (annotation_item->visibility_ != visibility) {
1644 continue;
1645 }
1646 const uint8_t* annotation = annotation_item->annotation_;
1647 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1648 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1649 klass->GetDexFile(), type_index, klass.Get());
1650 if (resolved_class == nullptr) {
1651 std::string temp;
1652 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1653 klass->GetDescriptor(&temp), type_index);
1654 CHECK(Thread::Current()->IsExceptionPending());
1655 Thread::Current()->ClearException();
1656 continue;
1657 }
1658 if (resolved_class == annotation_class.Get()) {
1659 return annotation_item;
1660 }
1661 }
1662
1663 return nullptr;
1664}
1665
1666mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1667 const AnnotationSetItem* annotation_set, uint32_t visibility,
1668 Handle<mirror::Class> annotation_class) const {
1669 const AnnotationItem* annotation_item =
1670 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1671 if (annotation_item == nullptr) {
1672 return nullptr;
1673 }
1674 const uint8_t* annotation = annotation_item->annotation_;
1675 return ProcessEncodedAnnotation(klass, &annotation);
1676}
1677
1678mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1679 const AnnotationItem* annotation_item, const char* annotation_name,
1680 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1681 const uint8_t* annotation =
1682 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1683 if (annotation == nullptr) {
1684 return nullptr;
1685 }
1686 AnnotationValue annotation_value;
1687 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1688 return nullptr;
1689 }
1690 if (annotation_value.type_ != expected_type) {
1691 return nullptr;
1692 }
1693 return annotation_value.value_.GetL();
1694}
1695
Jeff Hao2a5892f2015-08-31 15:00:40 -07001696mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001697 const AnnotationSetItem* annotation_set) const {
1698 StackHandleScope<1> hs(Thread::Current());
1699 const AnnotationItem* annotation_item =
1700 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1701 if (annotation_item == nullptr) {
1702 return nullptr;
1703 }
1704 mirror::Class* string_class = mirror::String::GetJavaLangString();
1705 Handle<mirror::Class> string_array_class(hs.NewHandle(
1706 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001707 if (string_array_class.Get() == nullptr) {
1708 return nullptr;
1709 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001710 mirror::Object* obj =
1711 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1712 if (obj == nullptr) {
1713 return nullptr;
1714 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001715 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001716}
1717
Jeff Hao2a5892f2015-08-31 15:00:40 -07001718mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001719 const AnnotationSetItem* annotation_set) const {
1720 StackHandleScope<1> hs(Thread::Current());
1721 const AnnotationItem* annotation_item =
1722 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1723 if (annotation_item == nullptr) {
1724 return nullptr;
1725 }
1726 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1727 Handle<mirror::Class> class_array_class(hs.NewHandle(
1728 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001729 if (class_array_class.Get() == nullptr) {
1730 return nullptr;
1731 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001732 mirror::Object* obj =
1733 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1734 if (obj == nullptr) {
1735 return nullptr;
1736 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001737 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001738}
1739
1740mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1741 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1742 Thread* self = Thread::Current();
1743 ScopedObjectAccessUnchecked soa(self);
1744 StackHandleScope<2> hs(self);
1745 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1746 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1747 if (annotation_set == nullptr) {
1748 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1749 }
1750
1751 uint32_t size = annotation_set->size_;
1752 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1753 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1754 if (result.Get() == nullptr) {
1755 return nullptr;
1756 }
1757
1758 uint32_t dest_index = 0;
1759 for (uint32_t i = 0; i < size; ++i) {
1760 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1761 if (annotation_item->visibility_ != visibility) {
1762 continue;
1763 }
1764 const uint8_t* annotation = annotation_item->annotation_;
1765 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1766 if (annotation_obj != nullptr) {
1767 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1768 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001769 } else if (self->IsExceptionPending()) {
1770 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001771 }
1772 }
1773
1774 if (dest_index == size) {
1775 return result.Get();
1776 }
1777
1778 mirror::ObjectArray<mirror::Object>* trimmed_result =
1779 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001780 if (trimmed_result == nullptr) {
1781 return nullptr;
1782 }
1783
Jeff Hao13e748b2015-08-25 20:44:19 +00001784 for (uint32_t i = 0; i < dest_index; ++i) {
1785 mirror::Object* obj = result->GetWithoutChecks(i);
1786 trimmed_result->SetWithoutChecks<false>(i, obj);
1787 }
1788
1789 return trimmed_result;
1790}
1791
1792mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1793 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1794 Thread* self = Thread::Current();
1795 ScopedObjectAccessUnchecked soa(self);
1796 StackHandleScope<1> hs(self);
1797 mirror::Class* annotation_array_class =
1798 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1799 mirror::Class* annotation_array_array_class =
1800 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001801 if (annotation_array_array_class == nullptr) {
1802 return nullptr;
1803 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001804 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1805 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1806 if (annotation_array_array.Get() == nullptr) {
1807 LOG(ERROR) << "Annotation set ref array allocation failed";
1808 return nullptr;
1809 }
1810 for (uint32_t index = 0; index < size; ++index) {
1811 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1812 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1813 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1814 if (annotation_set == nullptr) {
1815 return nullptr;
1816 }
1817 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1818 }
1819 return annotation_array_array.Get();
1820}
1821
1822bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1823 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1824 DexFile::AnnotationResultStyle result_style) const {
1825 Thread* self = Thread::Current();
1826 mirror::Object* element_object = nullptr;
1827 bool set_object = false;
1828 Primitive::Type primitive_type = Primitive::kPrimVoid;
1829 const uint8_t* annotation = *annotation_ptr;
1830 uint8_t header_byte = *(annotation++);
1831 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1832 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1833 int32_t width = value_arg + 1;
1834 annotation_value->type_ = value_type;
1835
1836 switch (value_type) {
1837 case kDexAnnotationByte:
1838 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1839 primitive_type = Primitive::kPrimByte;
1840 break;
1841 case kDexAnnotationShort:
1842 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1843 primitive_type = Primitive::kPrimShort;
1844 break;
1845 case kDexAnnotationChar:
1846 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1847 false)));
1848 primitive_type = Primitive::kPrimChar;
1849 break;
1850 case kDexAnnotationInt:
1851 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1852 primitive_type = Primitive::kPrimInt;
1853 break;
1854 case kDexAnnotationLong:
1855 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1856 primitive_type = Primitive::kPrimLong;
1857 break;
1858 case kDexAnnotationFloat:
1859 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1860 primitive_type = Primitive::kPrimFloat;
1861 break;
1862 case kDexAnnotationDouble:
1863 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1864 primitive_type = Primitive::kPrimDouble;
1865 break;
1866 case kDexAnnotationBoolean:
1867 annotation_value->value_.SetZ(value_arg != 0);
1868 primitive_type = Primitive::kPrimBoolean;
1869 width = 0;
1870 break;
1871 case kDexAnnotationString: {
1872 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1873 if (result_style == kAllRaw) {
1874 annotation_value->value_.SetI(index);
1875 } else {
1876 StackHandleScope<1> hs(self);
1877 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1878 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1879 klass->GetDexFile(), index, dex_cache);
1880 set_object = true;
1881 if (element_object == nullptr) {
1882 return false;
1883 }
1884 }
1885 break;
1886 }
1887 case kDexAnnotationType: {
1888 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1889 if (result_style == kAllRaw) {
1890 annotation_value->value_.SetI(index);
1891 } else {
1892 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1893 klass->GetDexFile(), index, klass.Get());
1894 set_object = true;
1895 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001896 CHECK(self->IsExceptionPending());
1897 if (result_style == kAllObjects) {
1898 const char* msg = StringByTypeIdx(index);
1899 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1900 element_object = self->GetException();
1901 self->ClearException();
1902 } else {
1903 return false;
1904 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001905 }
1906 }
1907 break;
1908 }
1909 case kDexAnnotationMethod: {
1910 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1911 if (result_style == kAllRaw) {
1912 annotation_value->value_.SetI(index);
1913 } else {
1914 StackHandleScope<2> hs(self);
1915 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1916 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1917 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1918 klass->GetDexFile(), index, dex_cache, class_loader);
1919 if (method == nullptr) {
1920 return false;
1921 }
1922 set_object = true;
1923 if (method->IsConstructor()) {
1924 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1925 } else {
1926 element_object = mirror::Method::CreateFromArtMethod(self, method);
1927 }
1928 if (element_object == nullptr) {
1929 return false;
1930 }
1931 }
1932 break;
1933 }
1934 case kDexAnnotationField: {
1935 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1936 if (result_style == kAllRaw) {
1937 annotation_value->value_.SetI(index);
1938 } else {
1939 StackHandleScope<2> hs(self);
1940 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1941 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1942 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1943 klass->GetDexFile(), index, dex_cache, class_loader);
1944 if (field == nullptr) {
1945 return false;
1946 }
1947 set_object = true;
1948 element_object = mirror::Field::CreateFromArtField(self, field, true);
1949 if (element_object == nullptr) {
1950 return false;
1951 }
1952 }
1953 break;
1954 }
1955 case kDexAnnotationEnum: {
1956 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1957 if (result_style == kAllRaw) {
1958 annotation_value->value_.SetI(index);
1959 } else {
1960 StackHandleScope<3> hs(self);
1961 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1962 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1963 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1964 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001965 if (enum_field == nullptr) {
1966 return false;
1967 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001968 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001969 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1970 element_object = enum_field->GetObject(field_class.Get());
1971 set_object = true;
1972 }
1973 }
1974 break;
1975 }
1976 case kDexAnnotationArray:
1977 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1978 return false;
1979 } else {
1980 ScopedObjectAccessUnchecked soa(self);
1981 StackHandleScope<2> hs(self);
1982 uint32_t size = DecodeUnsignedLeb128(&annotation);
1983 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1984 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1985 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1986 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1987 if (new_array.Get() == nullptr) {
1988 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1989 return false;
1990 }
1991 AnnotationValue new_annotation_value;
1992 for (uint32_t i = 0; i < size; ++i) {
1993 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1994 kPrimitivesOrObjects)) {
1995 return false;
1996 }
1997 if (!component_type->IsPrimitive()) {
1998 mirror::Object* obj = new_annotation_value.value_.GetL();
1999 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2000 } else {
2001 switch (new_annotation_value.type_) {
2002 case kDexAnnotationByte:
2003 new_array->AsByteArray()->SetWithoutChecks<false>(
2004 i, new_annotation_value.value_.GetB());
2005 break;
2006 case kDexAnnotationShort:
2007 new_array->AsShortArray()->SetWithoutChecks<false>(
2008 i, new_annotation_value.value_.GetS());
2009 break;
2010 case kDexAnnotationChar:
2011 new_array->AsCharArray()->SetWithoutChecks<false>(
2012 i, new_annotation_value.value_.GetC());
2013 break;
2014 case kDexAnnotationInt:
2015 new_array->AsIntArray()->SetWithoutChecks<false>(
2016 i, new_annotation_value.value_.GetI());
2017 break;
2018 case kDexAnnotationLong:
2019 new_array->AsLongArray()->SetWithoutChecks<false>(
2020 i, new_annotation_value.value_.GetJ());
2021 break;
2022 case kDexAnnotationFloat:
2023 new_array->AsFloatArray()->SetWithoutChecks<false>(
2024 i, new_annotation_value.value_.GetF());
2025 break;
2026 case kDexAnnotationDouble:
2027 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2028 i, new_annotation_value.value_.GetD());
2029 break;
2030 case kDexAnnotationBoolean:
2031 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2032 i, new_annotation_value.value_.GetZ());
2033 break;
2034 default:
2035 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2036 return false;
2037 }
2038 }
2039 }
2040 element_object = new_array.Get();
2041 set_object = true;
2042 width = 0;
2043 }
2044 break;
2045 case kDexAnnotationAnnotation:
2046 if (result_style == kAllRaw) {
2047 return false;
2048 }
2049 element_object = ProcessEncodedAnnotation(klass, &annotation);
2050 if (element_object == nullptr) {
2051 return false;
2052 }
2053 set_object = true;
2054 width = 0;
2055 break;
2056 case kDexAnnotationNull:
2057 if (result_style == kAllRaw) {
2058 annotation_value->value_.SetI(0);
2059 } else {
2060 CHECK(element_object == nullptr);
2061 set_object = true;
2062 }
2063 width = 0;
2064 break;
2065 default:
2066 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2067 return false;
2068 }
2069
2070 annotation += width;
2071 *annotation_ptr = annotation;
2072
2073 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2074 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2075 set_object = true;
2076 }
2077
2078 if (set_object) {
2079 annotation_value->value_.SetL(element_object);
2080 }
2081
2082 return true;
2083}
2084
2085mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2086 const uint8_t** annotation) const {
2087 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2088 uint32_t size = DecodeUnsignedLeb128(annotation);
2089
2090 Thread* self = Thread::Current();
2091 ScopedObjectAccessUnchecked soa(self);
2092 StackHandleScope<2> hs(self);
2093 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2094 Handle<mirror::Class> annotation_class(hs.NewHandle(
2095 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2096 if (annotation_class.Get() == nullptr) {
2097 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2098 << type_index;
2099 DCHECK(Thread::Current()->IsExceptionPending());
2100 Thread::Current()->ClearException();
2101 return nullptr;
2102 }
2103
2104 mirror::Class* annotation_member_class =
2105 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2106 mirror::Class* annotation_member_array_class =
2107 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002108 if (annotation_member_array_class == nullptr) {
2109 return nullptr;
2110 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002111 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002112 if (size > 0) {
2113 element_array =
2114 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2115 if (element_array == nullptr) {
2116 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2117 return nullptr;
2118 }
2119 }
2120
2121 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2122 for (uint32_t i = 0; i < size; ++i) {
2123 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2124 if (new_member == nullptr) {
2125 return nullptr;
2126 }
2127 h_element_array->SetWithoutChecks<false>(i, new_member);
2128 }
2129
2130 JValue result;
2131 ArtMethod* create_annotation_method =
2132 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2133 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2134 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2135 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2136 if (self->IsExceptionPending()) {
2137 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2138 return nullptr;
2139 }
2140
2141 return result.GetL();
2142}
2143
2144const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2145 const char* descriptor, uint32_t visibility) const {
2146 const AnnotationItem* result = nullptr;
2147 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2148 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2149 if (annotation_item->visibility_ != visibility) {
2150 continue;
2151 }
2152 const uint8_t* annotation = annotation_item->annotation_;
2153 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2154
2155 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2156 result = annotation_item;
2157 break;
2158 }
2159 }
2160 return result;
2161}
2162
2163const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2164 DecodeUnsignedLeb128(&annotation); // unused type_index
2165 uint32_t size = DecodeUnsignedLeb128(&annotation);
2166
2167 while (size != 0) {
2168 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2169 const char* element_name = GetStringData(GetStringId(element_name_index));
2170 if (strcmp(name, element_name) == 0) {
2171 return annotation;
2172 }
2173 SkipAnnotationValue(&annotation);
2174 size--;
2175 }
2176 return nullptr;
2177}
2178
2179bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2180 const uint8_t* annotation = *annotation_ptr;
2181 uint8_t header_byte = *(annotation++);
2182 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2183 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2184 int32_t width = value_arg + 1;
2185
2186 switch (value_type) {
2187 case kDexAnnotationByte:
2188 case kDexAnnotationShort:
2189 case kDexAnnotationChar:
2190 case kDexAnnotationInt:
2191 case kDexAnnotationLong:
2192 case kDexAnnotationFloat:
2193 case kDexAnnotationDouble:
2194 case kDexAnnotationString:
2195 case kDexAnnotationType:
2196 case kDexAnnotationMethod:
2197 case kDexAnnotationField:
2198 case kDexAnnotationEnum:
2199 break;
2200 case kDexAnnotationArray:
2201 {
2202 uint32_t size = DecodeUnsignedLeb128(&annotation);
2203 while (size--) {
2204 if (!SkipAnnotationValue(&annotation)) {
2205 return false;
2206 }
2207 }
2208 width = 0;
2209 break;
2210 }
2211 case kDexAnnotationAnnotation:
2212 {
2213 DecodeUnsignedLeb128(&annotation); // unused type_index
2214 uint32_t size = DecodeUnsignedLeb128(&annotation);
2215 while (size--) {
2216 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2217 if (!SkipAnnotationValue(&annotation)) {
2218 return false;
2219 }
2220 }
2221 width = 0;
2222 break;
2223 }
2224 case kDexAnnotationBoolean:
2225 case kDexAnnotationNull:
2226 width = 0;
2227 break;
2228 default:
2229 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2230 return false;
2231 }
2232
2233 annotation += width;
2234 *annotation_ptr = annotation;
2235 return true;
2236}
2237
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002238std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2239 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2240 dex_file.GetLocation().c_str(),
2241 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2242 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2243 return os;
2244}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002245
Ian Rogersd91d6d62013-09-25 20:26:14 -07002246std::string Signature::ToString() const {
2247 if (dex_file_ == nullptr) {
2248 CHECK(proto_id_ == nullptr);
2249 return "<no signature>";
2250 }
2251 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2252 std::string result;
2253 if (params == nullptr) {
2254 result += "()";
2255 } else {
2256 result += "(";
2257 for (uint32_t i = 0; i < params->Size(); ++i) {
2258 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2259 }
2260 result += ")";
2261 }
2262 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2263 return result;
2264}
2265
Vladimir Markod9cffea2013-11-25 15:08:02 +00002266bool Signature::operator==(const StringPiece& rhs) const {
2267 if (dex_file_ == nullptr) {
2268 return false;
2269 }
2270 StringPiece tail(rhs);
2271 if (!tail.starts_with("(")) {
2272 return false; // Invalid signature
2273 }
2274 tail.remove_prefix(1); // "(";
2275 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2276 if (params != nullptr) {
2277 for (uint32_t i = 0; i < params->Size(); ++i) {
2278 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2279 if (!tail.starts_with(param)) {
2280 return false;
2281 }
2282 tail.remove_prefix(param.length());
2283 }
2284 }
2285 if (!tail.starts_with(")")) {
2286 return false;
2287 }
2288 tail.remove_prefix(1); // ")";
2289 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2290}
2291
Ian Rogersd91d6d62013-09-25 20:26:14 -07002292std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2293 return os << sig.ToString();
2294}
2295
Ian Rogers0571d352011-11-03 19:51:38 -07002296// Decodes the header section from the class data bytes.
2297void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002298 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002299 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2300 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2301 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2302 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2303}
2304
2305void ClassDataItemIterator::ReadClassDataField() {
2306 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2307 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002308 // The user of the iterator is responsible for checking if there
2309 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002310}
2311
2312void ClassDataItemIterator::ReadClassDataMethod() {
2313 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2314 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2315 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002316 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002317 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002318 }
Ian Rogers0571d352011-11-03 19:51:38 -07002319}
2320
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002321EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002322 const DexFile& dex_file,
2323 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002324 : EncodedStaticFieldValueIterator(dex_file,
2325 nullptr,
2326 nullptr,
2327 nullptr,
2328 class_def,
2329 -1,
2330 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002331}
2332
2333EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002334 const DexFile& dex_file,
2335 Handle<mirror::DexCache>* dex_cache,
2336 Handle<mirror::ClassLoader>* class_loader,
2337 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002338 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002339 : EncodedStaticFieldValueIterator(dex_file,
2340 dex_cache, class_loader,
2341 linker,
2342 class_def,
2343 -1,
2344 kByte) {
2345 DCHECK(dex_cache_ != nullptr);
2346 DCHECK(class_loader_ != nullptr);
2347}
2348
2349EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2350 const DexFile& dex_file,
2351 Handle<mirror::DexCache>* dex_cache,
2352 Handle<mirror::ClassLoader>* class_loader,
2353 ClassLinker* linker,
2354 const DexFile::ClassDef& class_def,
2355 size_t pos,
2356 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002357 : dex_file_(dex_file),
2358 dex_cache_(dex_cache),
2359 class_loader_(class_loader),
2360 linker_(linker),
2361 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002362 pos_(pos),
2363 type_(type) {
2364 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002365 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002366 array_size_ = 0;
2367 } else {
2368 array_size_ = DecodeUnsignedLeb128(&ptr_);
2369 }
2370 if (array_size_ > 0) {
2371 Next();
2372 }
2373}
2374
2375void EncodedStaticFieldValueIterator::Next() {
2376 pos_++;
2377 if (pos_ >= array_size_) {
2378 return;
2379 }
Ian Rogers13735952014-10-08 12:43:28 -07002380 uint8_t value_type = *ptr_++;
2381 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002382 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002383 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002384 switch (type_) {
2385 case kBoolean:
2386 jval_.i = (value_arg != 0) ? 1 : 0;
2387 width = 0;
2388 break;
2389 case kByte:
2390 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002391 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002392 break;
2393 case kShort:
2394 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002395 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002396 break;
2397 case kChar:
2398 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002399 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002400 break;
2401 case kInt:
2402 jval_.i = ReadSignedInt(ptr_, value_arg);
2403 break;
2404 case kLong:
2405 jval_.j = ReadSignedLong(ptr_, value_arg);
2406 break;
2407 case kFloat:
2408 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2409 break;
2410 case kDouble:
2411 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2412 break;
2413 case kString:
2414 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002415 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2416 break;
2417 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002418 case kMethod:
2419 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002420 case kArray:
2421 case kAnnotation:
2422 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002423 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002424 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002425 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002426 width = 0;
2427 break;
2428 default:
2429 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002430 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002431 }
2432 ptr_ += width;
2433}
2434
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002435template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002436void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002437 DCHECK(dex_cache_ != nullptr);
2438 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002439 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002440 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2441 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002442 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2443 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2444 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2445 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2446 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2447 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2448 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002449 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002450 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002451 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002452 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002453 break;
2454 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002455 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002456 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2457 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002458 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002459 break;
2460 }
Ian Rogers0571d352011-11-03 19:51:38 -07002461 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2462 }
2463}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002464template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2465template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002466
2467CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2468 handler_.address_ = -1;
2469 int32_t offset = -1;
2470
2471 // Short-circuit the overwhelmingly common cases.
2472 switch (code_item.tries_size_) {
2473 case 0:
2474 break;
2475 case 1: {
2476 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2477 uint32_t start = tries->start_addr_;
2478 if (address >= start) {
2479 uint32_t end = start + tries->insn_count_;
2480 if (address < end) {
2481 offset = tries->handler_off_;
2482 }
2483 }
2484 break;
2485 }
2486 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002487 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002488 }
Logan Chien736df022012-04-27 16:25:57 +08002489 Init(code_item, offset);
2490}
2491
2492CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2493 const DexFile::TryItem& try_item) {
2494 handler_.address_ = -1;
2495 Init(code_item, try_item.handler_off_);
2496}
2497
2498void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2499 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002500 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002501 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002502 } else {
2503 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002504 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002505 remaining_count_ = -1;
2506 catch_all_ = false;
2507 DCHECK(!HasNext());
2508 }
2509}
2510
Ian Rogers13735952014-10-08 12:43:28 -07002511void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002512 current_data_ = handler_data;
2513 remaining_count_ = DecodeSignedLeb128(&current_data_);
2514
2515 // If remaining_count_ is non-positive, then it is the negative of
2516 // the number of catch types, and the catches are followed by a
2517 // catch-all handler.
2518 if (remaining_count_ <= 0) {
2519 catch_all_ = true;
2520 remaining_count_ = -remaining_count_;
2521 } else {
2522 catch_all_ = false;
2523 }
2524 Next();
2525}
2526
2527void CatchHandlerIterator::Next() {
2528 if (remaining_count_ > 0) {
2529 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2530 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2531 remaining_count_--;
2532 return;
2533 }
2534
2535 if (catch_all_) {
2536 handler_.type_idx_ = DexFile::kDexNoIndex16;
2537 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2538 catch_all_ = false;
2539 return;
2540 }
2541
2542 // no more handler
2543 remaining_count_ = -1;
2544}
2545
Carl Shapiro1fb86202011-06-27 17:43:13 -07002546} // namespace art