blob: 5a203afd1a6cf92be275d67551113bd0f8c2f3f1 [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(
Aart Bik37d6a3b2016-06-21 18:30:10 -0700112 DexFile::OpenFile(fd.release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 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
Aart Bik37d6a3b2016-06-21 18:30:10 -0700123bool DexFile::Open(const char* filename,
124 const char* location,
125 bool verify_checksum,
126 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800127 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800128 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700129 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700130 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000131 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
132 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700133 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsZipMagic(magic)) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700137 return DexFile::OpenZip(fd.release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700138 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 if (IsDexMagic(magic)) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700140 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(),
141 location,
142 /* verify */ true,
143 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 error_msg));
145 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800146 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700147 return true;
148 } else {
149 return false;
150 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700151 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700152 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400153 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700154}
155
Andreas Gampe0cba0042015-04-29 20:47:16 -0700156static bool ContainsClassesDex(int fd, const char* filename) {
157 std::string error_msg;
158 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
159 if (zip_archive.get() == nullptr) {
160 return false;
161 }
162 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
163 return (zip_entry.get() != nullptr);
164}
165
166bool DexFile::MaybeDex(const char* filename) {
167 uint32_t magic;
168 std::string error_msg;
169 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
170 if (fd.get() == -1) {
171 return false;
172 }
173 if (IsZipMagic(magic)) {
174 return ContainsClassesDex(fd.release(), filename);
175 } else if (IsDexMagic(magic)) {
176 return true;
177 }
178 return false;
179}
180
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800181int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800183 return 0;
184 } else {
185 return mem_map_->GetProtect();
186 }
187}
188
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200189bool DexFile::IsReadOnly() const {
190 return GetPermissions() == PROT_READ;
191}
192
Brian Carlstrome0948e12013-08-29 09:36:15 -0700193bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200194 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700195 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200196 return false;
197 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700198 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 }
200}
201
Brian Carlstrome0948e12013-08-29 09:36:15 -0700202bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200203 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700204 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 return false;
206 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700207 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200208 }
209}
210
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800211std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
212 const std::string& location,
213 uint32_t location_checksum,
214 const OatDexFile* oat_dex_file,
215 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700216 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800217 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800218 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800219 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
220 size,
221 location,
222 location_checksum,
223 nullptr,
224 oat_dex_file,
225 error_msg);
226 if (verify && !DexFileVerifier::Verify(dex_file.get(),
227 dex_file->Begin(),
228 dex_file->Size(),
229 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700230 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800231 error_msg)) {
232 return nullptr;
233 }
234
235 return dex_file;
236}
237
Aart Bik37d6a3b2016-06-21 18:30:10 -0700238std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
239 const char* location,
240 bool verify,
241 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800242 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800243 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700244 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700245 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000246 {
247 ScopedFd delayed_close(fd);
248 struct stat sbuf;
249 memset(&sbuf, 0, sizeof(sbuf));
250 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800251 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000252 return nullptr;
253 }
254 if (S_ISDIR(sbuf.st_mode)) {
255 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
256 return nullptr;
257 }
258 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800259 map.reset(MemMap::MapFile(length,
260 PROT_READ,
261 MAP_PRIVATE,
262 fd,
263 0,
264 /*low_4gb*/false,
265 location,
266 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000267 if (map.get() == nullptr) {
268 DCHECK(!error_msg->empty());
269 return nullptr;
270 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700271 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800272
273 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700274 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800275 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700276 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800277 }
278
279 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
280
Andreas Gampe928f72b2014-09-09 19:53:48 -0700281 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
282 error_msg));
283 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700284 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
285 error_msg->c_str());
286 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800287 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800288
Andreas Gampe928f72b2014-09-09 19:53:48 -0700289 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700290 location,
291 verify_checksum,
292 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800294 }
295
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800296 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700297}
298
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700299const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700300
Aart Bik37d6a3b2016-06-21 18:30:10 -0700301bool DexFile::OpenZip(int fd,
302 const std::string& location,
303 bool verify_checksum,
304 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800305 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800306 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700307 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700308 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700309 if (zip_archive.get() == nullptr) {
310 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700311 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700312 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700313 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800314}
315
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800316std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
317 uint32_t location_checksum,
318 MemMap* mem_map,
319 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800320 return OpenMemory(mem_map->Begin(),
321 mem_map->Size(),
322 location,
323 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700324 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800325 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800327}
328
Aart Bik37d6a3b2016-06-21 18:30:10 -0700329std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
330 const char* entry_name,
331 const std::string& location,
332 bool verify_checksum,
333 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800334 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800335 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800336 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700337 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700338 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700339 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700340 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700341 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700342 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700343 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700344 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700345 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700346 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700348 }
Ian Rogers700a4022014-05-19 16:49:03 -0700349 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700350 error_msg));
351 if (dex_file.get() == nullptr) {
352 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
353 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700354 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700355 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800356 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700357 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700359 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700361 }
362 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700363 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700364 location.c_str(),
365 verify_checksum,
366 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700367 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700368 return nullptr;
369 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700370 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800371 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700372}
373
Andreas Gampe90e34042015-04-27 20:01:52 -0700374// Technically we do not have a limitation with respect to the number of dex files that can be in a
375// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
376// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
377// seems an excessive number.
378static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
379
Aart Bik37d6a3b2016-06-21 18:30:10 -0700380bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
381 const std::string& location,
382 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800383 std::string* error_msg,
384 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800385 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700386 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700387 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700388 std::unique_ptr<const DexFile> dex_file(
389 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700390 if (dex_file.get() == nullptr) {
391 return false;
392 } else {
393 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800394 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700395
396 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700397
398 // We could try to avoid std::string allocations by working on a char array directly. As we
399 // do not expect a lot of iterations, this seems too involved and brittle.
400
Andreas Gampe90e34042015-04-27 20:01:52 -0700401 for (size_t i = 1; ; ++i) {
402 std::string name = GetMultiDexClassesDexName(i);
403 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700404 std::unique_ptr<const DexFile> next_dex_file(
405 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700406 if (next_dex_file.get() == nullptr) {
407 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
408 LOG(WARNING) << error_msg;
409 }
410 break;
411 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800412 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700413 }
414
Andreas Gampe90e34042015-04-27 20:01:52 -0700415 if (i == kWarnOnManyDexFilesThreshold) {
416 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
417 << " dex files. Please consider coalescing and shrinking the number to "
418 " avoid runtime overhead.";
419 }
420
421 if (i == std::numeric_limits<size_t>::max()) {
422 LOG(ERROR) << "Overflow in number of dex files!";
423 break;
424 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700425 }
426
427 return true;
428 }
429}
430
431
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800432std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
433 size_t size,
434 const std::string& location,
435 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800436 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700437 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800438 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700439 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800440 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700441 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700442 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800443 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700444 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800445 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700446}
447
Ian Rogers13735952014-10-08 12:43:28 -0700448DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800449 const std::string& location,
450 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800451 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700452 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800453 : begin_(base),
454 size_(size),
455 location_(location),
456 location_checksum_(location_checksum),
457 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800458 header_(reinterpret_cast<const Header*>(base)),
459 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
460 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
461 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
462 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
463 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700464 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700465 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700466 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800467 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300468 const uint8_t* lookup_data = (oat_dex_file != nullptr)
469 ? oat_dex_file->GetLookupTableData()
470 : nullptr;
471 if (lookup_data != nullptr) {
472 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
473 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
474 } else {
475 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
476 }
477 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800478}
479
Jesse Wilson6bf19152011-09-29 13:12:33 -0400480DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700481 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
482 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
483 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
484 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400485}
486
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700488 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700489 return false;
490 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700491 return true;
492}
493
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700494bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800495 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700496 std::ostringstream oss;
497 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800498 << " " << header_->magic_[0]
499 << " " << header_->magic_[1]
500 << " " << header_->magic_[2]
501 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700503 return false;
504 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800505 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700506 std::ostringstream oss;
507 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800508 << " " << header_->magic_[4]
509 << " " << header_->magic_[5]
510 << " " << header_->magic_[6]
511 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700512 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700513 return false;
514 }
515 return true;
516}
517
Ian Rogers13735952014-10-08 12:43:28 -0700518bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800519 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
520}
521
Ian Rogers13735952014-10-08 12:43:28 -0700522bool DexFile::IsVersionValid(const uint8_t* magic) {
523 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700524 for (uint32_t i = 0; i < kNumDexVersions; i++) {
525 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
526 return true;
527 }
528 }
529 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800530}
531
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700532uint32_t DexFile::Header::GetVersion() const {
533 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700534 return atoi(version);
535}
536
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800537const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
538 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300539 if (LIKELY(lookup_table_ != nullptr)) {
540 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
541 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700542 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300543
Roland Levillainab880f42016-05-12 16:24:36 +0100544 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300545 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700546 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700547 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700548 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300549 const TypeId* type_id = FindTypeId(descriptor);
550 if (type_id != nullptr) {
551 uint16_t type_idx = GetIndexForTypeId(*type_id);
552 for (size_t i = 0; i < num_class_defs; ++i) {
553 const ClassDef& class_def = GetClassDef(i);
554 if (class_def.class_idx_ == type_idx) {
555 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700556 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700557 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700558 }
Ian Rogers68b56852014-08-29 20:19:11 -0700559 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700560}
561
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700562const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
563 size_t num_class_defs = NumClassDefs();
564 for (size_t i = 0; i < num_class_defs; ++i) {
565 const ClassDef& class_def = GetClassDef(i);
566 if (class_def.class_idx_ == type_idx) {
567 return &class_def;
568 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700569 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700570 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700571}
572
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800573const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100574 const DexFile::StringId& name,
575 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800576 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
577 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
578 const uint32_t name_idx = GetIndexForStringId(name);
579 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t lo = 0;
581 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800582 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700583 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800584 const DexFile::FieldId& field = GetFieldId(mid);
585 if (class_idx > field.class_idx_) {
586 lo = mid + 1;
587 } else if (class_idx < field.class_idx_) {
588 hi = mid - 1;
589 } else {
590 if (name_idx > field.name_idx_) {
591 lo = mid + 1;
592 } else if (name_idx < field.name_idx_) {
593 hi = mid - 1;
594 } else {
595 if (type_idx > field.type_idx_) {
596 lo = mid + 1;
597 } else if (type_idx < field.type_idx_) {
598 hi = mid - 1;
599 } else {
600 return &field;
601 }
602 }
603 }
604 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700605 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800606}
607
608const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700609 const DexFile::StringId& name,
610 const DexFile::ProtoId& signature) const {
611 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800612 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700613 const uint32_t name_idx = GetIndexForStringId(name);
614 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700615 int32_t lo = 0;
616 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700617 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700618 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700619 const DexFile::MethodId& method = GetMethodId(mid);
620 if (class_idx > method.class_idx_) {
621 lo = mid + 1;
622 } else if (class_idx < method.class_idx_) {
623 hi = mid - 1;
624 } else {
625 if (name_idx > method.name_idx_) {
626 lo = mid + 1;
627 } else if (name_idx < method.name_idx_) {
628 hi = mid - 1;
629 } else {
630 if (proto_idx > method.proto_idx_) {
631 lo = mid + 1;
632 } else if (proto_idx < method.proto_idx_) {
633 hi = mid - 1;
634 } else {
635 return &method;
636 }
637 }
638 }
639 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700640 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700641}
642
Ian Rogers637c65b2013-05-31 11:46:00 -0700643const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700644 int32_t lo = 0;
645 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700646 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700647 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700648 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700649 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700650 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
651 if (compare > 0) {
652 lo = mid + 1;
653 } else if (compare < 0) {
654 hi = mid - 1;
655 } else {
656 return &str_id;
657 }
658 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700659 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700660}
661
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300662const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
663 int32_t lo = 0;
664 int32_t hi = NumTypeIds() - 1;
665 while (hi >= lo) {
666 int32_t mid = (hi + lo) / 2;
667 const TypeId& type_id = GetTypeId(mid);
668 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
669 const char* str = GetStringData(str_id);
670 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
671 if (compare > 0) {
672 lo = mid + 1;
673 } else if (compare < 0) {
674 hi = mid - 1;
675 } else {
676 return &type_id;
677 }
678 }
679 return nullptr;
680}
681
Vladimir Markoa48aef42014-12-03 17:53:53 +0000682const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700683 int32_t lo = 0;
684 int32_t hi = NumStringIds() - 1;
685 while (hi >= lo) {
686 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700687 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700688 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000689 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700690 if (compare > 0) {
691 lo = mid + 1;
692 } else if (compare < 0) {
693 hi = mid - 1;
694 } else {
695 return &str_id;
696 }
697 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700698 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700699}
700
701const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700702 int32_t lo = 0;
703 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700704 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700705 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700706 const TypeId& type_id = GetTypeId(mid);
707 if (string_idx > type_id.descriptor_idx_) {
708 lo = mid + 1;
709 } else if (string_idx < type_id.descriptor_idx_) {
710 hi = mid - 1;
711 } else {
712 return &type_id;
713 }
714 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700715 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700716}
717
718const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000719 const uint16_t* signature_type_idxs,
720 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700721 int32_t lo = 0;
722 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700723 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700724 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700725 const DexFile::ProtoId& proto = GetProtoId(mid);
726 int compare = return_type_idx - proto.return_type_idx_;
727 if (compare == 0) {
728 DexFileParameterIterator it(*this, proto);
729 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000730 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800731 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700732 it.Next();
733 i++;
734 }
735 if (compare == 0) {
736 if (it.HasNext()) {
737 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000738 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700739 compare = 1;
740 }
741 }
742 }
743 if (compare > 0) {
744 lo = mid + 1;
745 } else if (compare < 0) {
746 hi = mid - 1;
747 } else {
748 return &proto;
749 }
750 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700751 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700752}
753
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000754void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
755 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300756}
757
Ian Rogers0571d352011-11-03 19:51:38 -0700758// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700759bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
760 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700761 if (signature[0] != '(') {
762 return false;
763 }
764 size_t offset = 1;
765 size_t end = signature.size();
766 bool process_return = false;
767 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000768 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700769 char c = signature[offset];
770 offset++;
771 if (c == ')') {
772 process_return = true;
773 continue;
774 }
Ian Rogers0571d352011-11-03 19:51:38 -0700775 while (c == '[') { // process array prefix
776 if (offset >= end) { // expect some descriptor following [
777 return false;
778 }
779 c = signature[offset];
780 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700781 }
782 if (c == 'L') { // process type descriptors
783 do {
784 if (offset >= end) { // unexpected early termination of descriptor
785 return false;
786 }
787 c = signature[offset];
788 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700789 } while (c != ';');
790 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000791 // TODO: avoid creating a std::string just to get a 0-terminated char array
792 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700793 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700794 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700795 return false;
796 }
797 uint16_t type_idx = GetIndexForTypeId(*type_id);
798 if (!process_return) {
799 param_type_idxs->push_back(type_idx);
800 } else {
801 *return_type_idx = type_idx;
802 return offset == end; // return true if the signature had reached a sensible end
803 }
804 }
805 return false; // failed to correctly parse return type
806}
807
Ian Rogersd91d6d62013-09-25 20:26:14 -0700808const Signature DexFile::CreateSignature(const StringPiece& signature) const {
809 uint16_t return_type_idx;
810 std::vector<uint16_t> param_type_indices;
811 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
812 if (!success) {
813 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700814 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700815 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700816 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700817 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700818 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700819 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700820}
821
Mathieu Chartiere401d142015-04-22 13:56:20 -0700822int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700823 // For native method, lineno should be -2 to indicate it is native. Note that
824 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700825 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700826 return -2;
827 }
828
TDYa127c8dc1012012-04-19 07:03:33 -0700829 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700830 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700831
832 // A method with no line number info should return -1
833 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000834 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700835 return context.line_num_;
836}
837
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700838int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700839 // Note: Signed type is important for max and min.
840 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700841 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700842
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700843 while (min <= max) {
844 int32_t mid = min + ((max - min) / 2);
845
846 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
847 uint32_t start = ti->start_addr_;
848 uint32_t end = start + ti->insn_count_;
849
Ian Rogers0571d352011-11-03 19:51:38 -0700850 if (address < start) {
851 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700852 } else if (address >= end) {
853 min = mid + 1;
854 } else { // We have a winner!
855 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700856 }
857 }
858 // No match.
859 return -1;
860}
861
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700862int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
863 int32_t try_item = FindTryItem(code_item, address);
864 if (try_item == -1) {
865 return -1;
866 } else {
867 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
868 }
869}
870
David Srbeckyb06e28e2015-12-10 13:15:00 +0000871bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
872 DexDebugNewLocalCb local_cb, void* context) const {
873 DCHECK(local_cb != nullptr);
874 if (code_item == nullptr) {
875 return false;
876 }
877 const uint8_t* stream = GetDebugInfoStream(code_item);
878 if (stream == nullptr) {
879 return false;
880 }
881 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700882
David Srbeckyb06e28e2015-12-10 13:15:00 +0000883 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800884 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000885 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
886 local_in_reg[arg_reg].name_ = "this";
887 local_in_reg[arg_reg].descriptor_ = descriptor;
888 local_in_reg[arg_reg].signature_ = nullptr;
889 local_in_reg[arg_reg].start_address_ = 0;
890 local_in_reg[arg_reg].reg_ = arg_reg;
891 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700892 arg_reg++;
893 }
894
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800895 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000896 DecodeUnsignedLeb128(&stream); // Line.
897 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
898 uint32_t i;
899 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700900 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700901 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800902 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000903 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000905 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700906 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000907 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
908 local_in_reg[arg_reg].descriptor_ = descriptor;
909 local_in_reg[arg_reg].signature_ = nullptr;
910 local_in_reg[arg_reg].start_address_ = 0;
911 local_in_reg[arg_reg].reg_ = arg_reg;
912 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700913 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 case 'D':
915 case 'J':
916 arg_reg += 2;
917 break;
918 default:
919 arg_reg += 1;
920 break;
921 }
922 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000923 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800924 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
925 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700927 }
928
David Srbeckyb06e28e2015-12-10 13:15:00 +0000929 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700930 for (;;) {
931 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700932 switch (opcode) {
933 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000934 // Emit all variables which are still alive at the end of the method.
935 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
936 if (local_in_reg[reg].is_live_) {
937 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
938 local_cb(context, local_in_reg[reg]);
939 }
940 }
941 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 case DBG_ADVANCE_PC:
943 address += DecodeUnsignedLeb128(&stream);
944 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000946 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700947 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000949 case DBG_START_LOCAL_EXTENDED: {
950 uint16_t reg = DecodeUnsignedLeb128(&stream);
951 if (reg >= code_item->registers_size_) {
952 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800953 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000954 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955 }
956
David Srbeckyb06e28e2015-12-10 13:15:00 +0000957 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
958 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
959 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700960 if (opcode == DBG_START_LOCAL_EXTENDED) {
961 signature_idx = DecodeUnsignedLeb128P1(&stream);
962 }
963
Shih-wei Liao195487c2011-08-20 13:29:04 -0700964 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000965 if (local_in_reg[reg].is_live_) {
966 local_in_reg[reg].end_address_ = address;
967 local_cb(context, local_in_reg[reg]);
968 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969
David Srbeckyb06e28e2015-12-10 13:15:00 +0000970 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
971 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
972 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
973 local_in_reg[reg].start_address_ = address;
974 local_in_reg[reg].reg_ = reg;
975 local_in_reg[reg].is_live_ = true;
976 break;
977 }
978 case DBG_END_LOCAL: {
979 uint16_t reg = DecodeUnsignedLeb128(&stream);
980 if (reg >= code_item->registers_size_) {
981 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
982 << code_item->registers_size_ << ") in " << GetLocation();
983 return false;
984 }
985 if (!local_in_reg[reg].is_live_) {
986 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
987 return false;
988 }
989 local_in_reg[reg].end_address_ = address;
990 local_cb(context, local_in_reg[reg]);
991 local_in_reg[reg].is_live_ = false;
992 break;
993 }
994 case DBG_RESTART_LOCAL: {
995 uint16_t reg = DecodeUnsignedLeb128(&stream);
996 if (reg >= code_item->registers_size_) {
997 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
998 << code_item->registers_size_ << ") in " << GetLocation();
999 return false;
1000 }
1001 // If the register is live, the "restart" is superfluous,
1002 // and we don't want to mess with the existing start address.
1003 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001004 local_in_reg[reg].start_address_ = address;
1005 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001006 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001007 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001008 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001009 case DBG_SET_PROLOGUE_END:
1010 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001011 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001012 case DBG_SET_FILE:
1013 DecodeUnsignedLeb128P1(&stream); // name.
1014 break;
1015 default:
1016 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1017 break;
1018 }
1019 }
1020}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001021
David Srbeckyb06e28e2015-12-10 13:15:00 +00001022bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1023 void* context) const {
1024 DCHECK(position_cb != nullptr);
1025 if (code_item == nullptr) {
1026 return false;
1027 }
1028 const uint8_t* stream = GetDebugInfoStream(code_item);
1029 if (stream == nullptr) {
1030 return false;
1031 }
1032
1033 PositionInfo entry = PositionInfo();
1034 entry.line_ = DecodeUnsignedLeb128(&stream);
1035 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1036 for (uint32_t i = 0; i < parameters_size; ++i) {
1037 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1038 }
1039
1040 for (;;) {
1041 uint8_t opcode = *stream++;
1042 switch (opcode) {
1043 case DBG_END_SEQUENCE:
1044 return true; // end of stream.
1045 case DBG_ADVANCE_PC:
1046 entry.address_ += DecodeUnsignedLeb128(&stream);
1047 break;
1048 case DBG_ADVANCE_LINE:
1049 entry.line_ += DecodeSignedLeb128(&stream);
1050 break;
1051 case DBG_START_LOCAL:
1052 DecodeUnsignedLeb128(&stream); // reg.
1053 DecodeUnsignedLeb128P1(&stream); // name.
1054 DecodeUnsignedLeb128P1(&stream); // descriptor.
1055 break;
1056 case DBG_START_LOCAL_EXTENDED:
1057 DecodeUnsignedLeb128(&stream); // reg.
1058 DecodeUnsignedLeb128P1(&stream); // name.
1059 DecodeUnsignedLeb128P1(&stream); // descriptor.
1060 DecodeUnsignedLeb128P1(&stream); // signature.
1061 break;
1062 case DBG_END_LOCAL:
1063 case DBG_RESTART_LOCAL:
1064 DecodeUnsignedLeb128(&stream); // reg.
1065 break;
1066 case DBG_SET_PROLOGUE_END:
1067 entry.prologue_end_ = true;
1068 break;
1069 case DBG_SET_EPILOGUE_BEGIN:
1070 entry.epilogue_begin_ = true;
1071 break;
1072 case DBG_SET_FILE: {
1073 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1074 entry.source_file_ = StringDataByIdx(name_idx);
1075 break;
1076 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001077 default: {
1078 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001079 entry.address_ += adjopcode / DBG_LINE_RANGE;
1080 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1081 if (position_cb(context, entry)) {
1082 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001083 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001084 entry.prologue_end_ = false;
1085 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001086 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001087 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001088 }
1089 }
1090}
1091
David Srbeckyb06e28e2015-12-10 13:15:00 +00001092bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001093 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001094
1095 // We know that this callback will be called in
1096 // ascending address order, so keep going until we find
1097 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001098 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001099 // The line number from the previous positions callback
1100 // wil be the final result.
1101 return true;
1102 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001103 context->line_num_ = entry.line_;
1104 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001105 }
1106}
1107
Andreas Gampe833a4852014-05-21 18:46:59 -07001108bool DexFile::IsMultiDexLocation(const char* location) {
1109 return strrchr(location, kMultiDexSeparator) != nullptr;
1110}
1111
Andreas Gampe90e34042015-04-27 20:01:52 -07001112std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1113 if (index == 0) {
1114 return "classes.dex";
1115 } else {
1116 return StringPrintf("classes%zu.dex", index + 1);
1117 }
1118}
1119
1120std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1121 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001122 return dex_location;
1123 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001124 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001125 }
1126}
1127
1128std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1129 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001130 std::string base_location = GetBaseLocation(dex_location);
1131 const char* suffix = dex_location + base_location.size();
1132 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1133 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1134 if (path != nullptr && path.get() != base_location) {
1135 return std::string(path.get()) + suffix;
1136 } else if (suffix[0] == 0) {
1137 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001138 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001139 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001140 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001141}
1142
Jeff Hao13e748b2015-08-25 20:44:19 +00001143// Read a signed integer. "zwidth" is the zero-based byte count.
1144static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1145 int32_t val = 0;
1146 for (int i = zwidth; i >= 0; --i) {
1147 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1148 }
1149 val >>= (3 - zwidth) * 8;
1150 return val;
1151}
1152
1153// Read an unsigned integer. "zwidth" is the zero-based byte count,
1154// "fill_on_right" indicates which side we want to zero-fill from.
1155static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1156 uint32_t val = 0;
1157 for (int i = zwidth; i >= 0; --i) {
1158 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1159 }
1160 if (!fill_on_right) {
1161 val >>= (3 - zwidth) * 8;
1162 }
1163 return val;
1164}
1165
1166// Read a signed long. "zwidth" is the zero-based byte count.
1167static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1168 int64_t val = 0;
1169 for (int i = zwidth; i >= 0; --i) {
1170 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1171 }
1172 val >>= (7 - zwidth) * 8;
1173 return val;
1174}
1175
1176// Read an unsigned long. "zwidth" is the zero-based byte count,
1177// "fill_on_right" indicates which side we want to zero-fill from.
1178static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1179 uint64_t val = 0;
1180 for (int i = zwidth; i >= 0; --i) {
1181 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1182 }
1183 if (!fill_on_right) {
1184 val >>= (7 - zwidth) * 8;
1185 }
1186 return val;
1187}
1188
Jeff Hao3d080862016-05-26 18:39:17 -07001189// Checks that visibility is as expected. Includes special behavior for M and
1190// before to allow runtime and build visibility when expecting runtime.
1191static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1192 if (expected == DexFile::kDexVisibilityRuntime) {
1193 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1194 if (sdk_version > 0 && sdk_version <= 23) {
1195 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1196 }
1197 }
1198 return actual == expected;
1199}
1200
Jeff Hao13e748b2015-08-25 20:44:19 +00001201const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1202 mirror::Class* klass = field->GetDeclaringClass();
1203 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1204 if (annotations_dir == nullptr) {
1205 return nullptr;
1206 }
1207 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1208 if (field_annotations == nullptr) {
1209 return nullptr;
1210 }
1211 uint32_t field_index = field->GetDexFieldIndex();
1212 uint32_t field_count = annotations_dir->fields_size_;
1213 for (uint32_t i = 0; i < field_count; ++i) {
1214 if (field_annotations[i].field_idx_ == field_index) {
1215 return GetFieldAnnotationSetItem(field_annotations[i]);
1216 }
1217 }
1218 return nullptr;
1219}
1220
1221mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1222 Handle<mirror::Class> annotation_class) const {
1223 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1224 if (annotation_set == nullptr) {
1225 return nullptr;
1226 }
1227 StackHandleScope<1> hs(Thread::Current());
1228 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1229 return GetAnnotationObjectFromAnnotationSet(
1230 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1231}
1232
1233mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1234 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1235 StackHandleScope<1> hs(Thread::Current());
1236 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1237 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1238}
1239
Jeff Hao2a5892f2015-08-31 15:00:40 -07001240mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001241 const {
1242 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1243 if (annotation_set == nullptr) {
1244 return nullptr;
1245 }
1246 StackHandleScope<1> hs(Thread::Current());
1247 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1248 return GetSignatureValue(field_class, annotation_set);
1249}
1250
1251bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1252 const {
1253 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1254 if (annotation_set == nullptr) {
1255 return false;
1256 }
1257 StackHandleScope<1> hs(Thread::Current());
1258 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1259 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1260 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1261 return annotation_item != nullptr;
1262}
1263
1264const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1265 mirror::Class* klass = method->GetDeclaringClass();
1266 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1267 if (annotations_dir == nullptr) {
1268 return nullptr;
1269 }
1270 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1271 if (method_annotations == nullptr) {
1272 return nullptr;
1273 }
1274 uint32_t method_index = method->GetDexMethodIndex();
1275 uint32_t method_count = annotations_dir->methods_size_;
1276 for (uint32_t i = 0; i < method_count; ++i) {
1277 if (method_annotations[i].method_idx_ == method_index) {
1278 return GetMethodAnnotationSetItem(method_annotations[i]);
1279 }
1280 }
1281 return nullptr;
1282}
1283
1284const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1285 const {
1286 mirror::Class* klass = method->GetDeclaringClass();
1287 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1288 if (annotations_dir == nullptr) {
1289 return nullptr;
1290 }
1291 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1292 if (parameter_annotations == nullptr) {
1293 return nullptr;
1294 }
1295 uint32_t method_index = method->GetDexMethodIndex();
1296 uint32_t parameter_count = annotations_dir->parameters_size_;
1297 for (uint32_t i = 0; i < parameter_count; ++i) {
1298 if (parameter_annotations[i].method_idx_ == method_index) {
1299 return &parameter_annotations[i];
1300 }
1301 }
1302 return nullptr;
1303}
1304
1305mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1306 mirror::Class* klass = method->GetDeclaringClass();
1307 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1308 if (annotations_dir == nullptr) {
1309 return nullptr;
1310 }
1311 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1312 if (annotation_set == nullptr) {
1313 return nullptr;
1314 }
1315 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1316 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1317 if (annotation_item == nullptr) {
1318 return nullptr;
1319 }
1320 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1321 if (annotation == nullptr) {
1322 return nullptr;
1323 }
1324 uint8_t header_byte = *(annotation++);
1325 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1326 return nullptr;
1327 }
1328 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1329 if (annotation == nullptr) {
1330 return nullptr;
1331 }
1332 AnnotationValue annotation_value;
1333 StackHandleScope<2> hs(Thread::Current());
1334 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001335 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1336 Handle<mirror::Class> return_type(hs.NewHandle(
1337 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001338 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1339 return nullptr;
1340 }
1341 return annotation_value.value_.GetL();
1342}
1343
1344mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1345 Handle<mirror::Class> annotation_class) const {
1346 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1347 if (annotation_set == nullptr) {
1348 return nullptr;
1349 }
1350 StackHandleScope<1> hs(Thread::Current());
1351 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1352 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1353 kDexVisibilityRuntime, annotation_class);
1354}
1355
1356mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1357 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1358 StackHandleScope<1> hs(Thread::Current());
1359 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1360 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1361}
1362
Jeff Hao2a5892f2015-08-31 15:00:40 -07001363mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001364 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1365 if (annotation_set == nullptr) {
1366 return nullptr;
1367 }
1368 StackHandleScope<1> hs(Thread::Current());
1369 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1370 return GetThrowsValue(method_class, annotation_set);
1371}
1372
1373mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1374 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1375 if (parameter_annotations == nullptr) {
1376 return nullptr;
1377 }
1378 const AnnotationSetRefList* set_ref_list =
1379 GetParameterAnnotationSetRefList(parameter_annotations);
1380 if (set_ref_list == nullptr) {
1381 return nullptr;
1382 }
1383 uint32_t size = set_ref_list->size_;
1384 StackHandleScope<1> hs(Thread::Current());
1385 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1386 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1387}
1388
Jeff Hao1133db72016-04-04 19:50:14 -07001389mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1390 const {
1391 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1392 if (annotation_set == nullptr) {
1393 return nullptr;
1394 }
1395 StackHandleScope<1> hs(Thread::Current());
1396 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1397 return GetSignatureValue(method_class, annotation_set);
1398}
1399
Jeff Hao13e748b2015-08-25 20:44:19 +00001400bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1401 const {
1402 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1403 if (annotation_set == nullptr) {
1404 return false;
1405 }
1406 StackHandleScope<1> hs(Thread::Current());
1407 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1408 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1409 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001410 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001411}
1412
1413const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1414 const {
1415 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1416 if (annotations_dir == nullptr) {
1417 return nullptr;
1418 }
1419 return GetClassAnnotationSet(annotations_dir);
1420}
1421
1422mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1423 Handle<mirror::Class> annotation_class) const {
1424 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1425 if (annotation_set == nullptr) {
1426 return nullptr;
1427 }
1428 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1429 annotation_class);
1430}
1431
1432mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1433 const {
1434 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1435 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1436}
1437
Jeff Hao2a5892f2015-08-31 15:00:40 -07001438mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1439 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1440 if (annotation_set == nullptr) {
1441 return nullptr;
1442 }
1443 const AnnotationItem* annotation_item = SearchAnnotationSet(
1444 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1445 if (annotation_item == nullptr) {
1446 return nullptr;
1447 }
1448 StackHandleScope<1> hs(Thread::Current());
1449 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1450 Handle<mirror::Class> class_array_class(hs.NewHandle(
1451 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1452 if (class_array_class.Get() == nullptr) {
1453 return nullptr;
1454 }
1455 mirror::Object* obj = GetAnnotationValue(
1456 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1457 if (obj == nullptr) {
1458 return nullptr;
1459 }
1460 return obj->AsObjectArray<mirror::Class>();
1461}
1462
1463mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1464 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1465 if (annotation_set == nullptr) {
1466 return nullptr;
1467 }
1468 const AnnotationItem* annotation_item = SearchAnnotationSet(
1469 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1470 if (annotation_item == nullptr) {
1471 return nullptr;
1472 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001473 mirror::Object* obj = GetAnnotationValue(klass,
1474 annotation_item,
1475 "value",
1476 ScopedNullHandle<mirror::Class>(),
1477 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001478 if (obj == nullptr) {
1479 return nullptr;
1480 }
1481 return obj->AsClass();
1482}
1483
1484mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1485 mirror::Class* declaring_class = GetDeclaringClass(klass);
1486 if (declaring_class != nullptr) {
1487 return declaring_class;
1488 }
1489 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1490 if (annotation_set == nullptr) {
1491 return nullptr;
1492 }
1493 const AnnotationItem* annotation_item = SearchAnnotationSet(
1494 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1495 if (annotation_item == nullptr) {
1496 return nullptr;
1497 }
1498 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1499 if (annotation == nullptr) {
1500 return nullptr;
1501 }
1502 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001503 if (!ProcessAnnotationValue(klass,
1504 &annotation,
1505 &annotation_value,
1506 ScopedNullHandle<mirror::Class>(),
1507 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001508 return nullptr;
1509 }
1510 if (annotation_value.type_ != kDexAnnotationMethod) {
1511 return nullptr;
1512 }
1513 StackHandleScope<2> hs(Thread::Current());
1514 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1515 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1516 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1517 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1518 if (method == nullptr) {
1519 return nullptr;
1520 }
1521 return method->GetDeclaringClass();
1522}
1523
1524mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1525 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1526 if (annotation_set == nullptr) {
1527 return nullptr;
1528 }
1529 const AnnotationItem* annotation_item = SearchAnnotationSet(
1530 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1531 if (annotation_item == nullptr) {
1532 return nullptr;
1533 }
1534 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001535 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001536}
1537
1538bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1539 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1540 if (annotation_set == nullptr) {
1541 return false;
1542 }
1543 const AnnotationItem* annotation_item = SearchAnnotationSet(
1544 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1545 if (annotation_item == nullptr) {
1546 return false;
1547 }
1548 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1549 if (annotation == nullptr) {
1550 return false;
1551 }
1552 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001553 if (!ProcessAnnotationValue(klass,
1554 &annotation,
1555 &annotation_value,
1556 ScopedNullHandle<mirror::Class>(),
1557 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001558 return false;
1559 }
1560 if (annotation_value.type_ != kDexAnnotationNull &&
1561 annotation_value.type_ != kDexAnnotationString) {
1562 return false;
1563 }
1564 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1565 return true;
1566}
1567
1568bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1569 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1570 if (annotation_set == nullptr) {
1571 return false;
1572 }
1573 const AnnotationItem* annotation_item = SearchAnnotationSet(
1574 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1575 if (annotation_item == nullptr) {
1576 return false;
1577 }
1578 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1579 if (annotation == nullptr) {
1580 return false;
1581 }
1582 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001583 if (!ProcessAnnotationValue(klass,
1584 &annotation,
1585 &annotation_value,
1586 ScopedNullHandle<mirror::Class>(),
1587 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001588 return false;
1589 }
1590 if (annotation_value.type_ != kDexAnnotationInt) {
1591 return false;
1592 }
1593 *flags = annotation_value.value_.GetI();
1594 return true;
1595}
1596
Jeff Hao1133db72016-04-04 19:50:14 -07001597mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1598 Handle<mirror::Class> klass) const {
1599 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1600 if (annotation_set == nullptr) {
1601 return nullptr;
1602 }
1603 return GetSignatureValue(klass, annotation_set);
1604}
1605
Jeff Hao13e748b2015-08-25 20:44:19 +00001606bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1607 Handle<mirror::Class> annotation_class) const {
1608 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1609 if (annotation_set == nullptr) {
1610 return false;
1611 }
1612 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1613 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001614 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001615}
1616
1617mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1618 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1619 Thread* self = Thread::Current();
1620 ScopedObjectAccessUnchecked soa(self);
1621 StackHandleScope<5> hs(self);
1622 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1623 const char* name = StringDataByIdx(element_name_index);
1624 Handle<mirror::String> string_name(
1625 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1626
1627 ArtMethod* annotation_method =
1628 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1629 if (annotation_method == nullptr) {
1630 return nullptr;
1631 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001632 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1633 Handle<mirror::Class> method_return(hs.NewHandle(
1634 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001635
1636 AnnotationValue annotation_value;
1637 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1638 return nullptr;
1639 }
1640 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1641
1642 mirror::Class* annotation_member_class =
1643 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1644 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1645 Handle<mirror::Method> method_object(
1646 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1647
1648 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1649 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1650 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1651 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1652 return nullptr;
1653 }
1654
1655 JValue result;
1656 ArtMethod* annotation_member_init =
1657 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1658 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1659 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1660 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1661 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1662 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1663 };
1664 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1665 if (self->IsExceptionPending()) {
1666 LOG(INFO) << "Exception in AnnotationMember.<init>";
1667 return nullptr;
1668 }
1669
1670 return new_member.Get();
1671}
1672
1673const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1674 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1675 Handle<mirror::Class> annotation_class) const {
1676 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1677 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001678 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001679 continue;
1680 }
1681 const uint8_t* annotation = annotation_item->annotation_;
1682 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1683 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1684 klass->GetDexFile(), type_index, klass.Get());
1685 if (resolved_class == nullptr) {
1686 std::string temp;
1687 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1688 klass->GetDescriptor(&temp), type_index);
1689 CHECK(Thread::Current()->IsExceptionPending());
1690 Thread::Current()->ClearException();
1691 continue;
1692 }
1693 if (resolved_class == annotation_class.Get()) {
1694 return annotation_item;
1695 }
1696 }
1697
1698 return nullptr;
1699}
1700
1701mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1702 const AnnotationSetItem* annotation_set, uint32_t visibility,
1703 Handle<mirror::Class> annotation_class) const {
1704 const AnnotationItem* annotation_item =
1705 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1706 if (annotation_item == nullptr) {
1707 return nullptr;
1708 }
1709 const uint8_t* annotation = annotation_item->annotation_;
1710 return ProcessEncodedAnnotation(klass, &annotation);
1711}
1712
1713mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1714 const AnnotationItem* annotation_item, const char* annotation_name,
1715 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1716 const uint8_t* annotation =
1717 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1718 if (annotation == nullptr) {
1719 return nullptr;
1720 }
1721 AnnotationValue annotation_value;
1722 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1723 return nullptr;
1724 }
1725 if (annotation_value.type_ != expected_type) {
1726 return nullptr;
1727 }
1728 return annotation_value.value_.GetL();
1729}
1730
Jeff Hao2a5892f2015-08-31 15:00:40 -07001731mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001732 const AnnotationSetItem* annotation_set) const {
1733 StackHandleScope<1> hs(Thread::Current());
1734 const AnnotationItem* annotation_item =
1735 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1736 if (annotation_item == nullptr) {
1737 return nullptr;
1738 }
1739 mirror::Class* string_class = mirror::String::GetJavaLangString();
1740 Handle<mirror::Class> string_array_class(hs.NewHandle(
1741 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001742 if (string_array_class.Get() == nullptr) {
1743 return nullptr;
1744 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001745 mirror::Object* obj =
1746 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1747 if (obj == nullptr) {
1748 return nullptr;
1749 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001750 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001751}
1752
Jeff Hao2a5892f2015-08-31 15:00:40 -07001753mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001754 const AnnotationSetItem* annotation_set) const {
1755 StackHandleScope<1> hs(Thread::Current());
1756 const AnnotationItem* annotation_item =
1757 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1758 if (annotation_item == nullptr) {
1759 return nullptr;
1760 }
1761 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1762 Handle<mirror::Class> class_array_class(hs.NewHandle(
1763 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001764 if (class_array_class.Get() == nullptr) {
1765 return nullptr;
1766 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001767 mirror::Object* obj =
1768 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1769 if (obj == nullptr) {
1770 return nullptr;
1771 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001772 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001773}
1774
1775mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1776 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1777 Thread* self = Thread::Current();
1778 ScopedObjectAccessUnchecked soa(self);
1779 StackHandleScope<2> hs(self);
1780 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1781 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1782 if (annotation_set == nullptr) {
1783 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1784 }
1785
1786 uint32_t size = annotation_set->size_;
1787 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1788 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1789 if (result.Get() == nullptr) {
1790 return nullptr;
1791 }
1792
1793 uint32_t dest_index = 0;
1794 for (uint32_t i = 0; i < size; ++i) {
1795 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001796 // Note that we do not use IsVisibilityCompatible here because older code
1797 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001798 if (annotation_item->visibility_ != visibility) {
1799 continue;
1800 }
1801 const uint8_t* annotation = annotation_item->annotation_;
1802 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1803 if (annotation_obj != nullptr) {
1804 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1805 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001806 } else if (self->IsExceptionPending()) {
1807 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001808 }
1809 }
1810
1811 if (dest_index == size) {
1812 return result.Get();
1813 }
1814
1815 mirror::ObjectArray<mirror::Object>* trimmed_result =
1816 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001817 if (trimmed_result == nullptr) {
1818 return nullptr;
1819 }
1820
Jeff Hao13e748b2015-08-25 20:44:19 +00001821 for (uint32_t i = 0; i < dest_index; ++i) {
1822 mirror::Object* obj = result->GetWithoutChecks(i);
1823 trimmed_result->SetWithoutChecks<false>(i, obj);
1824 }
1825
1826 return trimmed_result;
1827}
1828
1829mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1830 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1831 Thread* self = Thread::Current();
1832 ScopedObjectAccessUnchecked soa(self);
1833 StackHandleScope<1> hs(self);
1834 mirror::Class* annotation_array_class =
1835 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1836 mirror::Class* annotation_array_array_class =
1837 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001838 if (annotation_array_array_class == nullptr) {
1839 return nullptr;
1840 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001841 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1842 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1843 if (annotation_array_array.Get() == nullptr) {
1844 LOG(ERROR) << "Annotation set ref array allocation failed";
1845 return nullptr;
1846 }
1847 for (uint32_t index = 0; index < size; ++index) {
1848 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1849 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1850 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1851 if (annotation_set == nullptr) {
1852 return nullptr;
1853 }
1854 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1855 }
1856 return annotation_array_array.Get();
1857}
1858
1859bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1860 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1861 DexFile::AnnotationResultStyle result_style) const {
1862 Thread* self = Thread::Current();
1863 mirror::Object* element_object = nullptr;
1864 bool set_object = false;
1865 Primitive::Type primitive_type = Primitive::kPrimVoid;
1866 const uint8_t* annotation = *annotation_ptr;
1867 uint8_t header_byte = *(annotation++);
1868 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1869 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1870 int32_t width = value_arg + 1;
1871 annotation_value->type_ = value_type;
1872
1873 switch (value_type) {
1874 case kDexAnnotationByte:
1875 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1876 primitive_type = Primitive::kPrimByte;
1877 break;
1878 case kDexAnnotationShort:
1879 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1880 primitive_type = Primitive::kPrimShort;
1881 break;
1882 case kDexAnnotationChar:
1883 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1884 false)));
1885 primitive_type = Primitive::kPrimChar;
1886 break;
1887 case kDexAnnotationInt:
1888 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1889 primitive_type = Primitive::kPrimInt;
1890 break;
1891 case kDexAnnotationLong:
1892 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1893 primitive_type = Primitive::kPrimLong;
1894 break;
1895 case kDexAnnotationFloat:
1896 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1897 primitive_type = Primitive::kPrimFloat;
1898 break;
1899 case kDexAnnotationDouble:
1900 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1901 primitive_type = Primitive::kPrimDouble;
1902 break;
1903 case kDexAnnotationBoolean:
1904 annotation_value->value_.SetZ(value_arg != 0);
1905 primitive_type = Primitive::kPrimBoolean;
1906 width = 0;
1907 break;
1908 case kDexAnnotationString: {
1909 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1910 if (result_style == kAllRaw) {
1911 annotation_value->value_.SetI(index);
1912 } else {
1913 StackHandleScope<1> hs(self);
1914 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1915 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1916 klass->GetDexFile(), index, dex_cache);
1917 set_object = true;
1918 if (element_object == nullptr) {
1919 return false;
1920 }
1921 }
1922 break;
1923 }
1924 case kDexAnnotationType: {
1925 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1926 if (result_style == kAllRaw) {
1927 annotation_value->value_.SetI(index);
1928 } else {
1929 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1930 klass->GetDexFile(), index, klass.Get());
1931 set_object = true;
1932 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001933 CHECK(self->IsExceptionPending());
1934 if (result_style == kAllObjects) {
1935 const char* msg = StringByTypeIdx(index);
1936 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1937 element_object = self->GetException();
1938 self->ClearException();
1939 } else {
1940 return false;
1941 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001942 }
1943 }
1944 break;
1945 }
1946 case kDexAnnotationMethod: {
1947 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1948 if (result_style == kAllRaw) {
1949 annotation_value->value_.SetI(index);
1950 } else {
1951 StackHandleScope<2> hs(self);
1952 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1953 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1954 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1955 klass->GetDexFile(), index, dex_cache, class_loader);
1956 if (method == nullptr) {
1957 return false;
1958 }
1959 set_object = true;
1960 if (method->IsConstructor()) {
1961 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1962 } else {
1963 element_object = mirror::Method::CreateFromArtMethod(self, method);
1964 }
1965 if (element_object == nullptr) {
1966 return false;
1967 }
1968 }
1969 break;
1970 }
1971 case kDexAnnotationField: {
1972 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1973 if (result_style == kAllRaw) {
1974 annotation_value->value_.SetI(index);
1975 } else {
1976 StackHandleScope<2> hs(self);
1977 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1978 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1979 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1980 klass->GetDexFile(), index, dex_cache, class_loader);
1981 if (field == nullptr) {
1982 return false;
1983 }
1984 set_object = true;
1985 element_object = mirror::Field::CreateFromArtField(self, field, true);
1986 if (element_object == nullptr) {
1987 return false;
1988 }
1989 }
1990 break;
1991 }
1992 case kDexAnnotationEnum: {
1993 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1994 if (result_style == kAllRaw) {
1995 annotation_value->value_.SetI(index);
1996 } else {
1997 StackHandleScope<3> hs(self);
1998 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1999 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2000 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2001 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002002 if (enum_field == nullptr) {
2003 return false;
2004 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002005 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002006 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2007 element_object = enum_field->GetObject(field_class.Get());
2008 set_object = true;
2009 }
2010 }
2011 break;
2012 }
2013 case kDexAnnotationArray:
2014 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2015 return false;
2016 } else {
2017 ScopedObjectAccessUnchecked soa(self);
2018 StackHandleScope<2> hs(self);
2019 uint32_t size = DecodeUnsignedLeb128(&annotation);
2020 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2021 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2022 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2023 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2024 if (new_array.Get() == nullptr) {
2025 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2026 return false;
2027 }
2028 AnnotationValue new_annotation_value;
2029 for (uint32_t i = 0; i < size; ++i) {
2030 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2031 kPrimitivesOrObjects)) {
2032 return false;
2033 }
2034 if (!component_type->IsPrimitive()) {
2035 mirror::Object* obj = new_annotation_value.value_.GetL();
2036 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2037 } else {
2038 switch (new_annotation_value.type_) {
2039 case kDexAnnotationByte:
2040 new_array->AsByteArray()->SetWithoutChecks<false>(
2041 i, new_annotation_value.value_.GetB());
2042 break;
2043 case kDexAnnotationShort:
2044 new_array->AsShortArray()->SetWithoutChecks<false>(
2045 i, new_annotation_value.value_.GetS());
2046 break;
2047 case kDexAnnotationChar:
2048 new_array->AsCharArray()->SetWithoutChecks<false>(
2049 i, new_annotation_value.value_.GetC());
2050 break;
2051 case kDexAnnotationInt:
2052 new_array->AsIntArray()->SetWithoutChecks<false>(
2053 i, new_annotation_value.value_.GetI());
2054 break;
2055 case kDexAnnotationLong:
2056 new_array->AsLongArray()->SetWithoutChecks<false>(
2057 i, new_annotation_value.value_.GetJ());
2058 break;
2059 case kDexAnnotationFloat:
2060 new_array->AsFloatArray()->SetWithoutChecks<false>(
2061 i, new_annotation_value.value_.GetF());
2062 break;
2063 case kDexAnnotationDouble:
2064 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2065 i, new_annotation_value.value_.GetD());
2066 break;
2067 case kDexAnnotationBoolean:
2068 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2069 i, new_annotation_value.value_.GetZ());
2070 break;
2071 default:
2072 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2073 return false;
2074 }
2075 }
2076 }
2077 element_object = new_array.Get();
2078 set_object = true;
2079 width = 0;
2080 }
2081 break;
2082 case kDexAnnotationAnnotation:
2083 if (result_style == kAllRaw) {
2084 return false;
2085 }
2086 element_object = ProcessEncodedAnnotation(klass, &annotation);
2087 if (element_object == nullptr) {
2088 return false;
2089 }
2090 set_object = true;
2091 width = 0;
2092 break;
2093 case kDexAnnotationNull:
2094 if (result_style == kAllRaw) {
2095 annotation_value->value_.SetI(0);
2096 } else {
2097 CHECK(element_object == nullptr);
2098 set_object = true;
2099 }
2100 width = 0;
2101 break;
2102 default:
2103 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2104 return false;
2105 }
2106
2107 annotation += width;
2108 *annotation_ptr = annotation;
2109
2110 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2111 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2112 set_object = true;
2113 }
2114
2115 if (set_object) {
2116 annotation_value->value_.SetL(element_object);
2117 }
2118
2119 return true;
2120}
2121
2122mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2123 const uint8_t** annotation) const {
2124 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2125 uint32_t size = DecodeUnsignedLeb128(annotation);
2126
2127 Thread* self = Thread::Current();
2128 ScopedObjectAccessUnchecked soa(self);
2129 StackHandleScope<2> hs(self);
2130 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2131 Handle<mirror::Class> annotation_class(hs.NewHandle(
2132 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2133 if (annotation_class.Get() == nullptr) {
2134 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2135 << type_index;
2136 DCHECK(Thread::Current()->IsExceptionPending());
2137 Thread::Current()->ClearException();
2138 return nullptr;
2139 }
2140
2141 mirror::Class* annotation_member_class =
2142 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2143 mirror::Class* annotation_member_array_class =
2144 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002145 if (annotation_member_array_class == nullptr) {
2146 return nullptr;
2147 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002148 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002149 if (size > 0) {
2150 element_array =
2151 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2152 if (element_array == nullptr) {
2153 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2154 return nullptr;
2155 }
2156 }
2157
2158 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2159 for (uint32_t i = 0; i < size; ++i) {
2160 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2161 if (new_member == nullptr) {
2162 return nullptr;
2163 }
2164 h_element_array->SetWithoutChecks<false>(i, new_member);
2165 }
2166
2167 JValue result;
2168 ArtMethod* create_annotation_method =
2169 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2170 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2171 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2172 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2173 if (self->IsExceptionPending()) {
2174 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2175 return nullptr;
2176 }
2177
2178 return result.GetL();
2179}
2180
2181const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2182 const char* descriptor, uint32_t visibility) const {
2183 const AnnotationItem* result = nullptr;
2184 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2185 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002186 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002187 continue;
2188 }
2189 const uint8_t* annotation = annotation_item->annotation_;
2190 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2191
2192 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2193 result = annotation_item;
2194 break;
2195 }
2196 }
2197 return result;
2198}
2199
2200const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2201 DecodeUnsignedLeb128(&annotation); // unused type_index
2202 uint32_t size = DecodeUnsignedLeb128(&annotation);
2203
2204 while (size != 0) {
2205 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2206 const char* element_name = GetStringData(GetStringId(element_name_index));
2207 if (strcmp(name, element_name) == 0) {
2208 return annotation;
2209 }
2210 SkipAnnotationValue(&annotation);
2211 size--;
2212 }
2213 return nullptr;
2214}
2215
2216bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2217 const uint8_t* annotation = *annotation_ptr;
2218 uint8_t header_byte = *(annotation++);
2219 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2220 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2221 int32_t width = value_arg + 1;
2222
2223 switch (value_type) {
2224 case kDexAnnotationByte:
2225 case kDexAnnotationShort:
2226 case kDexAnnotationChar:
2227 case kDexAnnotationInt:
2228 case kDexAnnotationLong:
2229 case kDexAnnotationFloat:
2230 case kDexAnnotationDouble:
2231 case kDexAnnotationString:
2232 case kDexAnnotationType:
2233 case kDexAnnotationMethod:
2234 case kDexAnnotationField:
2235 case kDexAnnotationEnum:
2236 break;
2237 case kDexAnnotationArray:
2238 {
2239 uint32_t size = DecodeUnsignedLeb128(&annotation);
2240 while (size--) {
2241 if (!SkipAnnotationValue(&annotation)) {
2242 return false;
2243 }
2244 }
2245 width = 0;
2246 break;
2247 }
2248 case kDexAnnotationAnnotation:
2249 {
2250 DecodeUnsignedLeb128(&annotation); // unused type_index
2251 uint32_t size = DecodeUnsignedLeb128(&annotation);
2252 while (size--) {
2253 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2254 if (!SkipAnnotationValue(&annotation)) {
2255 return false;
2256 }
2257 }
2258 width = 0;
2259 break;
2260 }
2261 case kDexAnnotationBoolean:
2262 case kDexAnnotationNull:
2263 width = 0;
2264 break;
2265 default:
2266 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2267 return false;
2268 }
2269
2270 annotation += width;
2271 *annotation_ptr = annotation;
2272 return true;
2273}
2274
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002275std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2276 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2277 dex_file.GetLocation().c_str(),
2278 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2279 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2280 return os;
2281}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002282
Ian Rogersd91d6d62013-09-25 20:26:14 -07002283std::string Signature::ToString() const {
2284 if (dex_file_ == nullptr) {
2285 CHECK(proto_id_ == nullptr);
2286 return "<no signature>";
2287 }
2288 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2289 std::string result;
2290 if (params == nullptr) {
2291 result += "()";
2292 } else {
2293 result += "(";
2294 for (uint32_t i = 0; i < params->Size(); ++i) {
2295 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2296 }
2297 result += ")";
2298 }
2299 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2300 return result;
2301}
2302
Vladimir Markod9cffea2013-11-25 15:08:02 +00002303bool Signature::operator==(const StringPiece& rhs) const {
2304 if (dex_file_ == nullptr) {
2305 return false;
2306 }
2307 StringPiece tail(rhs);
2308 if (!tail.starts_with("(")) {
2309 return false; // Invalid signature
2310 }
2311 tail.remove_prefix(1); // "(";
2312 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2313 if (params != nullptr) {
2314 for (uint32_t i = 0; i < params->Size(); ++i) {
2315 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2316 if (!tail.starts_with(param)) {
2317 return false;
2318 }
2319 tail.remove_prefix(param.length());
2320 }
2321 }
2322 if (!tail.starts_with(")")) {
2323 return false;
2324 }
2325 tail.remove_prefix(1); // ")";
2326 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2327}
2328
Ian Rogersd91d6d62013-09-25 20:26:14 -07002329std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2330 return os << sig.ToString();
2331}
2332
Ian Rogers0571d352011-11-03 19:51:38 -07002333// Decodes the header section from the class data bytes.
2334void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002335 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002336 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2337 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2338 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2339 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2340}
2341
2342void ClassDataItemIterator::ReadClassDataField() {
2343 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2344 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002345 // The user of the iterator is responsible for checking if there
2346 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002347}
2348
2349void ClassDataItemIterator::ReadClassDataMethod() {
2350 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2351 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2352 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002353 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002354 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002355 }
Ian Rogers0571d352011-11-03 19:51:38 -07002356}
2357
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002358EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002359 const DexFile& dex_file,
2360 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002361 : EncodedStaticFieldValueIterator(dex_file,
2362 nullptr,
2363 nullptr,
2364 nullptr,
2365 class_def,
2366 -1,
2367 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002368}
2369
2370EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002371 const DexFile& dex_file,
2372 Handle<mirror::DexCache>* dex_cache,
2373 Handle<mirror::ClassLoader>* class_loader,
2374 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002375 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002376 : EncodedStaticFieldValueIterator(dex_file,
2377 dex_cache, class_loader,
2378 linker,
2379 class_def,
2380 -1,
2381 kByte) {
2382 DCHECK(dex_cache_ != nullptr);
2383 DCHECK(class_loader_ != nullptr);
2384}
2385
2386EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2387 const DexFile& dex_file,
2388 Handle<mirror::DexCache>* dex_cache,
2389 Handle<mirror::ClassLoader>* class_loader,
2390 ClassLinker* linker,
2391 const DexFile::ClassDef& class_def,
2392 size_t pos,
2393 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002394 : dex_file_(dex_file),
2395 dex_cache_(dex_cache),
2396 class_loader_(class_loader),
2397 linker_(linker),
2398 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002399 pos_(pos),
2400 type_(type) {
2401 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002402 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002403 array_size_ = 0;
2404 } else {
2405 array_size_ = DecodeUnsignedLeb128(&ptr_);
2406 }
2407 if (array_size_ > 0) {
2408 Next();
2409 }
2410}
2411
2412void EncodedStaticFieldValueIterator::Next() {
2413 pos_++;
2414 if (pos_ >= array_size_) {
2415 return;
2416 }
Ian Rogers13735952014-10-08 12:43:28 -07002417 uint8_t value_type = *ptr_++;
2418 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002419 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002420 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002421 switch (type_) {
2422 case kBoolean:
2423 jval_.i = (value_arg != 0) ? 1 : 0;
2424 width = 0;
2425 break;
2426 case kByte:
2427 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002428 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002429 break;
2430 case kShort:
2431 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002432 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002433 break;
2434 case kChar:
2435 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002436 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002437 break;
2438 case kInt:
2439 jval_.i = ReadSignedInt(ptr_, value_arg);
2440 break;
2441 case kLong:
2442 jval_.j = ReadSignedLong(ptr_, value_arg);
2443 break;
2444 case kFloat:
2445 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2446 break;
2447 case kDouble:
2448 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2449 break;
2450 case kString:
2451 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002452 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2453 break;
2454 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002455 case kMethod:
2456 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002457 case kArray:
2458 case kAnnotation:
2459 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002460 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002461 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002462 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002463 width = 0;
2464 break;
2465 default:
2466 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002467 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002468 }
2469 ptr_ += width;
2470}
2471
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002472template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002473void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002474 DCHECK(dex_cache_ != nullptr);
2475 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002476 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002477 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2478 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002479 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2480 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2481 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2482 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2483 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2484 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2485 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002486 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002487 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002488 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002489 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002490 break;
2491 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002492 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002493 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2494 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002495 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002496 break;
2497 }
Ian Rogers0571d352011-11-03 19:51:38 -07002498 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2499 }
2500}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002501template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2502template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002503
2504CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2505 handler_.address_ = -1;
2506 int32_t offset = -1;
2507
2508 // Short-circuit the overwhelmingly common cases.
2509 switch (code_item.tries_size_) {
2510 case 0:
2511 break;
2512 case 1: {
2513 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2514 uint32_t start = tries->start_addr_;
2515 if (address >= start) {
2516 uint32_t end = start + tries->insn_count_;
2517 if (address < end) {
2518 offset = tries->handler_off_;
2519 }
2520 }
2521 break;
2522 }
2523 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002524 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002525 }
Logan Chien736df022012-04-27 16:25:57 +08002526 Init(code_item, offset);
2527}
2528
2529CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2530 const DexFile::TryItem& try_item) {
2531 handler_.address_ = -1;
2532 Init(code_item, try_item.handler_off_);
2533}
2534
2535void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2536 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002537 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002538 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002539 } else {
2540 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002541 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002542 remaining_count_ = -1;
2543 catch_all_ = false;
2544 DCHECK(!HasNext());
2545 }
2546}
2547
Ian Rogers13735952014-10-08 12:43:28 -07002548void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002549 current_data_ = handler_data;
2550 remaining_count_ = DecodeSignedLeb128(&current_data_);
2551
2552 // If remaining_count_ is non-positive, then it is the negative of
2553 // the number of catch types, and the catches are followed by a
2554 // catch-all handler.
2555 if (remaining_count_ <= 0) {
2556 catch_all_ = true;
2557 remaining_count_ = -remaining_count_;
2558 } else {
2559 catch_all_ = false;
2560 }
2561 Next();
2562}
2563
2564void CatchHandlerIterator::Next() {
2565 if (remaining_count_ > 0) {
2566 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2567 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2568 remaining_count_--;
2569 return;
2570 }
2571
2572 if (catch_all_) {
2573 handler_.type_idx_ = DexFile::kDexNoIndex16;
2574 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2575 catch_all_ = false;
2576 return;
2577 }
2578
2579 // no more handler
2580 remaining_count_ = -1;
2581}
2582
Carl Shapiro1fb86202011-06-27 17:43:13 -07002583} // namespace art