blob: 55268833301c3ab6a0fbecfd33c27b22c7997e98 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080034#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000035#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080037#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "globals.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000040#include "mirror/field.h"
41#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070043#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000044#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070045#include "safe_map.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070046#include "handle_scope-inl.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070047#include "thread.h"
Ian Rogersa6724902013-09-23 09:23:37 -070048#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070049#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070050#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070051#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070052
Andreas Gampe277ccbd2014-11-03 21:36:10 -080053#pragma GCC diagnostic push
54#pragma GCC diagnostic ignored "-Wshadow"
55#include "ScopedFd.h"
56#pragma GCC diagnostic pop
57
Carl Shapiro1fb86202011-06-27 17:43:13 -070058namespace art {
59
Ian Rogers13735952014-10-08 12:43:28 -070060const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
61const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070062
Ian Rogers8d31bbd2013-10-13 10:44:14 -070063static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070064 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000065 ScopedFd fd(open(filename, O_RDONLY, 0));
66 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070067 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 return -1;
69 }
Vladimir Markofd995762013-11-06 16:36:36 +000070 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070071 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070073 return -1;
74 }
Vladimir Markofd995762013-11-06 16:36:36 +000075 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070076 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
77 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070078 return -1;
79 }
Vladimir Markofd995762013-11-06 16:36:36 +000080 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070081}
82
Ian Rogers8d31bbd2013-10-13 10:44:14 -070083bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070084 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070086
87 // Strip ":...", which is the location
88 const char* zip_entry_name = kClassesDex;
89 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010090 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070091
Vladimir Markoaa4497d2014-09-05 14:01:17 +010092 if (DexFile::IsMultiDexLocation(filename)) {
93 file_part_storage = GetBaseLocation(filename);
94 file_part = file_part_storage.c_str();
95 zip_entry_name = filename + file_part_storage.size() + 1;
96 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070097 }
98
99 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000100 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700101 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700102 return false;
103 }
104 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700105 std::unique_ptr<ZipArchive> zip_archive(
106 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
107 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800108 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
109 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700111 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700112 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700114 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
115 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return false;
117 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700118 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800119 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700120 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700121 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 std::unique_ptr<const DexFile> dex_file(
123 DexFile::OpenFile(fd.release(), filename, false, error_msg));
124 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800125 return false;
126 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800128 return true;
129 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800131 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700132}
133
Andreas Gampe833a4852014-05-21 18:46:59 -0700134bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800135 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700136 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700137 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000138 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
139 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700140 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700142 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700143 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700144 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700145 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700146 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700147 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
148 error_msg));
149 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800150 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700151 return true;
152 } else {
153 return false;
154 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700155 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700156 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400157 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700158}
159
Andreas Gampe0cba0042015-04-29 20:47:16 -0700160static bool ContainsClassesDex(int fd, const char* filename) {
161 std::string error_msg;
162 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
163 if (zip_archive.get() == nullptr) {
164 return false;
165 }
166 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
167 return (zip_entry.get() != nullptr);
168}
169
170bool DexFile::MaybeDex(const char* filename) {
171 uint32_t magic;
172 std::string error_msg;
173 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
174 if (fd.get() == -1) {
175 return false;
176 }
177 if (IsZipMagic(magic)) {
178 return ContainsClassesDex(fd.release(), filename);
179 } else if (IsDexMagic(magic)) {
180 return true;
181 }
182 return false;
183}
184
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800185int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700186 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800187 return 0;
188 } else {
189 return mem_map_->GetProtect();
190 }
191}
192
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193bool DexFile::IsReadOnly() const {
194 return GetPermissions() == PROT_READ;
195}
196
Brian Carlstrome0948e12013-08-29 09:36:15 -0700197bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200198 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700199 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 return false;
201 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700202 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200203 }
204}
205
Brian Carlstrome0948e12013-08-29 09:36:15 -0700206bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200207 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700208 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200209 return false;
210 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700211 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200212 }
213}
214
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800215std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
216 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700217 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700218 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000219 {
220 ScopedFd delayed_close(fd);
221 struct stat sbuf;
222 memset(&sbuf, 0, sizeof(sbuf));
223 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800224 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000225 return nullptr;
226 }
227 if (S_ISDIR(sbuf.st_mode)) {
228 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
229 return nullptr;
230 }
231 size_t length = sbuf.st_size;
232 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
233 if (map.get() == nullptr) {
234 DCHECK(!error_msg->empty());
235 return nullptr;
236 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700237 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800238
239 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800241 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700242 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800243 }
244
245 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
246
Andreas Gampe928f72b2014-09-09 19:53:48 -0700247 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
248 error_msg));
249 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700250 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
251 error_msg->c_str());
252 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800253 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800254
Andreas Gampe928f72b2014-09-09 19:53:48 -0700255 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
256 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700257 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800258 }
259
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800260 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700261}
262
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700263const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264
Andreas Gampe833a4852014-05-21 18:46:59 -0700265bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800266 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700267 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700268 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700269 if (zip_archive.get() == nullptr) {
270 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700271 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700272 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800274}
275
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800276std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
277 uint32_t location_checksum,
278 MemMap* mem_map,
279 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800280 return OpenMemory(mem_map->Begin(),
281 mem_map->Size(),
282 location,
283 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700284 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800285 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700286 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800287}
288
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
290 const std::string& location, std::string* error_msg,
291 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800292 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700293 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700294 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700296 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700298 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700299 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700300 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700301 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700302 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700304 }
Ian Rogers700a4022014-05-19 16:49:03 -0700305 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700306 error_msg));
307 if (dex_file.get() == nullptr) {
308 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
309 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700310 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700311 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800312 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700313 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700314 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700315 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700317 }
318 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700319 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
320 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700321 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700322 return nullptr;
323 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700324 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700326}
327
Andreas Gampe90e34042015-04-27 20:01:52 -0700328// Technically we do not have a limitation with respect to the number of dex files that can be in a
329// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
330// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
331// seems an excessive number.
332static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
333
Andreas Gampe833a4852014-05-21 18:46:59 -0700334bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800335 std::string* error_msg,
336 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700337 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700338 ZipOpenErrorCode error_code;
339 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
340 &error_code));
341 if (dex_file.get() == nullptr) {
342 return false;
343 } else {
344 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800345 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700346
347 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700348
349 // We could try to avoid std::string allocations by working on a char array directly. As we
350 // do not expect a lot of iterations, this seems too involved and brittle.
351
Andreas Gampe90e34042015-04-27 20:01:52 -0700352 for (size_t i = 1; ; ++i) {
353 std::string name = GetMultiDexClassesDexName(i);
354 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700355 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
356 error_msg, &error_code));
357 if (next_dex_file.get() == nullptr) {
358 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
359 LOG(WARNING) << error_msg;
360 }
361 break;
362 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800363 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 }
365
Andreas Gampe90e34042015-04-27 20:01:52 -0700366 if (i == kWarnOnManyDexFilesThreshold) {
367 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
368 << " dex files. Please consider coalescing and shrinking the number to "
369 " avoid runtime overhead.";
370 }
371
372 if (i == std::numeric_limits<size_t>::max()) {
373 LOG(ERROR) << "Overflow in number of dex files!";
374 break;
375 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700376 }
377
378 return true;
379 }
380}
381
382
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800383std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
384 size_t size,
385 const std::string& location,
386 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800387 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700388 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800389 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700390 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800391 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700392 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700393 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800394 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700395 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800396 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700397}
398
Ian Rogers13735952014-10-08 12:43:28 -0700399DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800400 const std::string& location,
401 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800402 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700403 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800404 : begin_(base),
405 size_(size),
406 location_(location),
407 location_checksum_(location_checksum),
408 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800409 header_(reinterpret_cast<const Header*>(base)),
410 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
411 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
412 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
413 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
414 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700415 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
416 find_class_def_misses_(0),
Andreas Gampefd9eb392014-11-06 16:52:58 -0800417 class_def_index_(nullptr),
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800420 CHECK_GT(size_, 0U) << GetLocation();
421}
422
Jesse Wilson6bf19152011-09-29 13:12:33 -0400423DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700424 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
425 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
426 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
427 // the global reference table is otherwise empty!
Ian Rogers68b56852014-08-29 20:19:11 -0700428 // Remove the index if one were created.
429 delete class_def_index_.LoadRelaxed();
Jesse Wilson6bf19152011-09-29 13:12:33 -0400430}
431
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700434 return false;
435 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700436 return true;
437}
438
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800440 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 std::ostringstream oss;
442 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800443 << " " << header_->magic_[0]
444 << " " << header_->magic_[1]
445 << " " << header_->magic_[2]
446 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700448 return false;
449 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800450 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700451 std::ostringstream oss;
452 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800453 << " " << header_->magic_[4]
454 << " " << header_->magic_[5]
455 << " " << header_->magic_[6]
456 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700457 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700458 return false;
459 }
460 return true;
461}
462
Ian Rogers13735952014-10-08 12:43:28 -0700463bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800464 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
465}
466
Ian Rogers13735952014-10-08 12:43:28 -0700467bool DexFile::IsVersionValid(const uint8_t* magic) {
468 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800469 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
470}
471
Ian Rogersd81871c2011-10-03 13:57:23 -0700472uint32_t DexFile::GetVersion() const {
473 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
474 return atoi(version);
475}
476
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800477const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
478 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700479 // If we have an index lookup the descriptor via that as its constant time to search.
480 Index* index = class_def_index_.LoadSequentiallyConsistent();
481 if (index != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800482 auto it = index->FindWithHash(descriptor, hash);
Ian Rogers68b56852014-08-29 20:19:11 -0700483 return (it == index->end()) ? nullptr : it->second;
484 }
485 // Fast path for rate no class defs case.
486 uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700487 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700488 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700489 }
Ian Rogers68b56852014-08-29 20:19:11 -0700490 // Search for class def with 2 binary searches and then a linear search.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700491 const StringId* string_id = FindStringId(descriptor);
Ian Rogers68b56852014-08-29 20:19:11 -0700492 if (string_id != nullptr) {
493 const TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
494 if (type_id != nullptr) {
495 uint16_t type_idx = GetIndexForTypeId(*type_id);
496 for (size_t i = 0; i < num_class_defs; ++i) {
497 const ClassDef& class_def = GetClassDef(i);
498 if (class_def.class_idx_ == type_idx) {
499 return &class_def;
500 }
501 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700502 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700503 }
Ian Rogers68b56852014-08-29 20:19:11 -0700504 // A miss. If we've had kMaxFailedDexClassDefLookups misses then build an index to speed things
505 // up. This isn't done eagerly at construction as construction is not performed in multi-threaded
506 // sections of tools like dex2oat. If we're lazy we hopefully increase the chance of balancing
507 // out which thread builds the index.
Ian Rogers68b56852014-08-29 20:19:11 -0700508 const uint32_t kMaxFailedDexClassDefLookups = 100;
Ian Rogersecaebd32014-09-12 23:10:21 -0700509 uint32_t old_misses = find_class_def_misses_.FetchAndAddSequentiallyConsistent(1);
510 if (old_misses == kMaxFailedDexClassDefLookups) {
511 // Are we the ones moving the miss count past the max? Sanity check the index doesn't exist.
512 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
513 // Build the index.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800514 index = new Index();
Ian Rogersecaebd32014-09-12 23:10:21 -0700515 for (uint32_t i = 0; i < num_class_defs; ++i) {
516 const ClassDef& class_def = GetClassDef(i);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800517 const char* class_descriptor = GetClassDescriptor(class_def);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800518 index->Insert(std::make_pair(class_descriptor, &class_def));
Ian Rogers68b56852014-08-29 20:19:11 -0700519 }
Ian Rogersecaebd32014-09-12 23:10:21 -0700520 // Sanity check the index still doesn't exist, only 1 thread should build it.
521 CHECK(class_def_index_.LoadSequentiallyConsistent() == nullptr);
522 class_def_index_.StoreSequentiallyConsistent(index);
Ian Rogers68b56852014-08-29 20:19:11 -0700523 }
524 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700525}
526
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700527const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
528 size_t num_class_defs = NumClassDefs();
529 for (size_t i = 0; i < num_class_defs; ++i) {
530 const ClassDef& class_def = GetClassDef(i);
531 if (class_def.class_idx_ == type_idx) {
532 return &class_def;
533 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700534 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700535 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700536}
537
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800538const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
539 const DexFile::StringId& name,
540 const DexFile::TypeId& type) const {
541 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
542 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
543 const uint32_t name_idx = GetIndexForStringId(name);
544 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700545 int32_t lo = 0;
546 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800547 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700548 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800549 const DexFile::FieldId& field = GetFieldId(mid);
550 if (class_idx > field.class_idx_) {
551 lo = mid + 1;
552 } else if (class_idx < field.class_idx_) {
553 hi = mid - 1;
554 } else {
555 if (name_idx > field.name_idx_) {
556 lo = mid + 1;
557 } else if (name_idx < field.name_idx_) {
558 hi = mid - 1;
559 } else {
560 if (type_idx > field.type_idx_) {
561 lo = mid + 1;
562 } else if (type_idx < field.type_idx_) {
563 hi = mid - 1;
564 } else {
565 return &field;
566 }
567 }
568 }
569 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700570 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800571}
572
573const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700574 const DexFile::StringId& name,
575 const DexFile::ProtoId& signature) const {
576 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800577 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700578 const uint32_t name_idx = GetIndexForStringId(name);
579 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t lo = 0;
581 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700582 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700583 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700584 const DexFile::MethodId& method = GetMethodId(mid);
585 if (class_idx > method.class_idx_) {
586 lo = mid + 1;
587 } else if (class_idx < method.class_idx_) {
588 hi = mid - 1;
589 } else {
590 if (name_idx > method.name_idx_) {
591 lo = mid + 1;
592 } else if (name_idx < method.name_idx_) {
593 hi = mid - 1;
594 } else {
595 if (proto_idx > method.proto_idx_) {
596 lo = mid + 1;
597 } else if (proto_idx < method.proto_idx_) {
598 hi = mid - 1;
599 } else {
600 return &method;
601 }
602 }
603 }
604 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700605 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700606}
607
Ian Rogers637c65b2013-05-31 11:46:00 -0700608const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700609 int32_t lo = 0;
610 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700611 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700612 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700613 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700614 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700615 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
616 if (compare > 0) {
617 lo = mid + 1;
618 } else if (compare < 0) {
619 hi = mid - 1;
620 } else {
621 return &str_id;
622 }
623 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700624 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700625}
626
Vladimir Markoa48aef42014-12-03 17:53:53 +0000627const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700628 int32_t lo = 0;
629 int32_t hi = NumStringIds() - 1;
630 while (hi >= lo) {
631 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700632 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700633 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000634 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700635 if (compare > 0) {
636 lo = mid + 1;
637 } else if (compare < 0) {
638 hi = mid - 1;
639 } else {
640 return &str_id;
641 }
642 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700643 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700644}
645
646const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700647 int32_t lo = 0;
648 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700649 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700650 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700651 const TypeId& type_id = GetTypeId(mid);
652 if (string_idx > type_id.descriptor_idx_) {
653 lo = mid + 1;
654 } else if (string_idx < type_id.descriptor_idx_) {
655 hi = mid - 1;
656 } else {
657 return &type_id;
658 }
659 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700660 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700661}
662
663const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000664 const uint16_t* signature_type_idxs,
665 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700666 int32_t lo = 0;
667 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700668 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700670 const DexFile::ProtoId& proto = GetProtoId(mid);
671 int compare = return_type_idx - proto.return_type_idx_;
672 if (compare == 0) {
673 DexFileParameterIterator it(*this, proto);
674 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000675 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800676 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700677 it.Next();
678 i++;
679 }
680 if (compare == 0) {
681 if (it.HasNext()) {
682 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000683 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700684 compare = 1;
685 }
686 }
687 }
688 if (compare > 0) {
689 lo = mid + 1;
690 } else if (compare < 0) {
691 hi = mid - 1;
692 } else {
693 return &proto;
694 }
695 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700696 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700697}
698
699// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700700bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
701 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700702 if (signature[0] != '(') {
703 return false;
704 }
705 size_t offset = 1;
706 size_t end = signature.size();
707 bool process_return = false;
708 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000709 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700710 char c = signature[offset];
711 offset++;
712 if (c == ')') {
713 process_return = true;
714 continue;
715 }
Ian Rogers0571d352011-11-03 19:51:38 -0700716 while (c == '[') { // process array prefix
717 if (offset >= end) { // expect some descriptor following [
718 return false;
719 }
720 c = signature[offset];
721 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700722 }
723 if (c == 'L') { // process type descriptors
724 do {
725 if (offset >= end) { // unexpected early termination of descriptor
726 return false;
727 }
728 c = signature[offset];
729 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700730 } while (c != ';');
731 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000732 // TODO: avoid creating a std::string just to get a 0-terminated char array
733 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700734 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700735 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700736 return false;
737 }
738 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700739 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700740 return false;
741 }
742 uint16_t type_idx = GetIndexForTypeId(*type_id);
743 if (!process_return) {
744 param_type_idxs->push_back(type_idx);
745 } else {
746 *return_type_idx = type_idx;
747 return offset == end; // return true if the signature had reached a sensible end
748 }
749 }
750 return false; // failed to correctly parse return type
751}
752
Ian Rogersd91d6d62013-09-25 20:26:14 -0700753const Signature DexFile::CreateSignature(const StringPiece& signature) const {
754 uint16_t return_type_idx;
755 std::vector<uint16_t> param_type_indices;
756 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
757 if (!success) {
758 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700759 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700760 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700761 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700762 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700763 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700764 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700765}
766
Mathieu Chartiere401d142015-04-22 13:56:20 -0700767int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700768 // For native method, lineno should be -2 to indicate it is native. Note that
769 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700770 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700771 return -2;
772 }
773
TDYa127c8dc1012012-04-19 07:03:33 -0700774 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700775 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700776
777 // A method with no line number info should return -1
778 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700779 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700780 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700781 return context.line_num_;
782}
783
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700784int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700785 // Note: Signed type is important for max and min.
786 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700787 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700788
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700789 while (min <= max) {
790 int32_t mid = min + ((max - min) / 2);
791
792 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
793 uint32_t start = ti->start_addr_;
794 uint32_t end = start + ti->insn_count_;
795
Ian Rogers0571d352011-11-03 19:51:38 -0700796 if (address < start) {
797 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700798 } else if (address >= end) {
799 min = mid + 1;
800 } else { // We have a winner!
801 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700802 }
803 }
804 // No match.
805 return -1;
806}
807
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700808int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
809 int32_t try_item = FindTryItem(code_item, address);
810 if (try_item == -1) {
811 return -1;
812 } else {
813 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
814 }
815}
816
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800817void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800818 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700819 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
820 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700821 uint32_t line = DecodeUnsignedLeb128(&stream);
822 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
823 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
824 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700825 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700826
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700828 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800829 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700830 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800831 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700832 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700833 local_in_reg[arg_reg].start_address_ = 0;
834 local_in_reg[arg_reg].is_live_ = true;
835 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700836 arg_reg++;
837 }
838
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800839 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700840 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700841 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700842 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800843 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700844 return;
845 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800846 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700847 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800848 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700849 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700850 local_in_reg[arg_reg].name_ = name;
851 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700852 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700853 local_in_reg[arg_reg].start_address_ = address;
854 local_in_reg[arg_reg].is_live_ = true;
855 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700856 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700857 case 'D':
858 case 'J':
859 arg_reg += 2;
860 break;
861 default:
862 arg_reg += 1;
863 break;
864 }
865 }
866
Ian Rogers0571d352011-11-03 19:51:38 -0700867 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800868 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
869 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700870 return;
871 }
872
873 for (;;) {
874 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700875 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800876 uint32_t name_idx;
877 uint32_t descriptor_idx;
878 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700879
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 switch (opcode) {
881 case DBG_END_SEQUENCE:
882 return;
883
884 case DBG_ADVANCE_PC:
885 address += DecodeUnsignedLeb128(&stream);
886 break;
887
888 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700889 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890 break;
891
892 case DBG_START_LOCAL:
893 case DBG_START_LOCAL_EXTENDED:
894 reg = DecodeUnsignedLeb128(&stream);
895 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700896 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800897 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700898 return;
899 }
900
jeffhaof8728872011-10-28 19:11:13 -0700901 name_idx = DecodeUnsignedLeb128P1(&stream);
902 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
903 if (opcode == DBG_START_LOCAL_EXTENDED) {
904 signature_idx = DecodeUnsignedLeb128P1(&stream);
905 }
906
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700908 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800909 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910
Ian Rogers0571d352011-11-03 19:51:38 -0700911 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
912 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700913 local_in_reg[reg].signature_ =
914 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
915 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700916 local_in_reg[reg].start_address_ = address;
917 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700918 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 break;
920
921 case DBG_END_LOCAL:
922 reg = DecodeUnsignedLeb128(&stream);
923 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700924 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800925 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 return;
927 }
928
Elliott Hughes30646832011-10-13 16:59:46 -0700929 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800930 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700931 local_in_reg[reg].is_live_ = false;
932 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700933 break;
934
935 case DBG_RESTART_LOCAL:
936 reg = DecodeUnsignedLeb128(&stream);
937 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700938 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800939 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700940 return;
941 }
942
Elliott Hughes30646832011-10-13 16:59:46 -0700943 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700944 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800945 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700946 return;
947 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700948
Elliott Hughes30646832011-10-13 16:59:46 -0700949 // If the register is live, the "restart" is superfluous,
950 // and we don't want to mess with the existing start address.
951 if (!local_in_reg[reg].is_live_) {
952 local_in_reg[reg].start_address_ = address;
953 local_in_reg[reg].is_live_ = true;
954 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955 }
956 break;
957
958 case DBG_SET_PROLOGUE_END:
959 case DBG_SET_EPILOGUE_BEGIN:
960 case DBG_SET_FILE:
961 break;
962
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700963 default: {
964 int adjopcode = opcode - DBG_FIRST_SPECIAL;
965
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 address += adjopcode / DBG_LINE_RANGE;
967 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
968
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700969 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800970 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700971 // early exit
972 return;
973 }
974 }
975 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700976 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700977 }
978 }
979}
980
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800981void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800982 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
983 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100984 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700985 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700986 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700987 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700988 nullptr);
989 if (stream != nullptr) {
990 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
991 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700992 }
993 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700994 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
995 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700996 }
997}
998
Elliott Hughes2435a572012-02-17 16:07:41 -0800999bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1000 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001001
1002 // We know that this callback will be called in
1003 // ascending address order, so keep going until we find
1004 // a match or we've just gone past it.
1005 if (address > context->address_) {
1006 // The line number from the previous positions callback
1007 // wil be the final result.
1008 return true;
1009 } else {
1010 context->line_num_ = line_num;
1011 return address == context->address_;
1012 }
1013}
1014
Andreas Gampe833a4852014-05-21 18:46:59 -07001015bool DexFile::IsMultiDexLocation(const char* location) {
1016 return strrchr(location, kMultiDexSeparator) != nullptr;
1017}
1018
Andreas Gampe90e34042015-04-27 20:01:52 -07001019std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1020 if (index == 0) {
1021 return "classes.dex";
1022 } else {
1023 return StringPrintf("classes%zu.dex", index + 1);
1024 }
1025}
1026
1027std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1028 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001029 return dex_location;
1030 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001031 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001032 }
1033}
1034
1035std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1036 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001037 std::string base_location = GetBaseLocation(dex_location);
1038 const char* suffix = dex_location + base_location.size();
1039 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1040 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1041 if (path != nullptr && path.get() != base_location) {
1042 return std::string(path.get()) + suffix;
1043 } else if (suffix[0] == 0) {
1044 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001045 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001046 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001047 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001048}
1049
Jeff Hao13e748b2015-08-25 20:44:19 +00001050// Read a signed integer. "zwidth" is the zero-based byte count.
1051static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1052 int32_t val = 0;
1053 for (int i = zwidth; i >= 0; --i) {
1054 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1055 }
1056 val >>= (3 - zwidth) * 8;
1057 return val;
1058}
1059
1060// Read an unsigned integer. "zwidth" is the zero-based byte count,
1061// "fill_on_right" indicates which side we want to zero-fill from.
1062static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1063 uint32_t val = 0;
1064 for (int i = zwidth; i >= 0; --i) {
1065 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1066 }
1067 if (!fill_on_right) {
1068 val >>= (3 - zwidth) * 8;
1069 }
1070 return val;
1071}
1072
1073// Read a signed long. "zwidth" is the zero-based byte count.
1074static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1075 int64_t val = 0;
1076 for (int i = zwidth; i >= 0; --i) {
1077 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1078 }
1079 val >>= (7 - zwidth) * 8;
1080 return val;
1081}
1082
1083// Read an unsigned long. "zwidth" is the zero-based byte count,
1084// "fill_on_right" indicates which side we want to zero-fill from.
1085static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1086 uint64_t val = 0;
1087 for (int i = zwidth; i >= 0; --i) {
1088 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1089 }
1090 if (!fill_on_right) {
1091 val >>= (7 - zwidth) * 8;
1092 }
1093 return val;
1094}
1095
1096const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1097 mirror::Class* klass = field->GetDeclaringClass();
1098 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1099 if (annotations_dir == nullptr) {
1100 return nullptr;
1101 }
1102 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1103 if (field_annotations == nullptr) {
1104 return nullptr;
1105 }
1106 uint32_t field_index = field->GetDexFieldIndex();
1107 uint32_t field_count = annotations_dir->fields_size_;
1108 for (uint32_t i = 0; i < field_count; ++i) {
1109 if (field_annotations[i].field_idx_ == field_index) {
1110 return GetFieldAnnotationSetItem(field_annotations[i]);
1111 }
1112 }
1113 return nullptr;
1114}
1115
1116mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1117 Handle<mirror::Class> annotation_class) const {
1118 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1119 if (annotation_set == nullptr) {
1120 return nullptr;
1121 }
1122 StackHandleScope<1> hs(Thread::Current());
1123 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1124 return GetAnnotationObjectFromAnnotationSet(
1125 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1126}
1127
1128mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1129 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1130 StackHandleScope<1> hs(Thread::Current());
1131 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1132 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1133}
1134
Jeff Hao2a5892f2015-08-31 15:00:40 -07001135mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001136 const {
1137 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1138 if (annotation_set == nullptr) {
1139 return nullptr;
1140 }
1141 StackHandleScope<1> hs(Thread::Current());
1142 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1143 return GetSignatureValue(field_class, annotation_set);
1144}
1145
1146bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1147 const {
1148 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1149 if (annotation_set == nullptr) {
1150 return false;
1151 }
1152 StackHandleScope<1> hs(Thread::Current());
1153 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1154 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1155 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1156 return annotation_item != nullptr;
1157}
1158
1159const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1160 mirror::Class* klass = method->GetDeclaringClass();
1161 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1162 if (annotations_dir == nullptr) {
1163 return nullptr;
1164 }
1165 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1166 if (method_annotations == nullptr) {
1167 return nullptr;
1168 }
1169 uint32_t method_index = method->GetDexMethodIndex();
1170 uint32_t method_count = annotations_dir->methods_size_;
1171 for (uint32_t i = 0; i < method_count; ++i) {
1172 if (method_annotations[i].method_idx_ == method_index) {
1173 return GetMethodAnnotationSetItem(method_annotations[i]);
1174 }
1175 }
1176 return nullptr;
1177}
1178
1179const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1180 const {
1181 mirror::Class* klass = method->GetDeclaringClass();
1182 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1183 if (annotations_dir == nullptr) {
1184 return nullptr;
1185 }
1186 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1187 if (parameter_annotations == nullptr) {
1188 return nullptr;
1189 }
1190 uint32_t method_index = method->GetDexMethodIndex();
1191 uint32_t parameter_count = annotations_dir->parameters_size_;
1192 for (uint32_t i = 0; i < parameter_count; ++i) {
1193 if (parameter_annotations[i].method_idx_ == method_index) {
1194 return &parameter_annotations[i];
1195 }
1196 }
1197 return nullptr;
1198}
1199
1200mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1201 mirror::Class* klass = method->GetDeclaringClass();
1202 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1203 if (annotations_dir == nullptr) {
1204 return nullptr;
1205 }
1206 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1207 if (annotation_set == nullptr) {
1208 return nullptr;
1209 }
1210 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1211 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1212 if (annotation_item == nullptr) {
1213 return nullptr;
1214 }
1215 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1216 if (annotation == nullptr) {
1217 return nullptr;
1218 }
1219 uint8_t header_byte = *(annotation++);
1220 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1221 return nullptr;
1222 }
1223 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1224 if (annotation == nullptr) {
1225 return nullptr;
1226 }
1227 AnnotationValue annotation_value;
1228 StackHandleScope<2> hs(Thread::Current());
1229 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
1230 Handle<mirror::Class> return_type(hs.NewHandle(method->GetReturnType()));
1231 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1232 return nullptr;
1233 }
1234 return annotation_value.value_.GetL();
1235}
1236
1237mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1238 Handle<mirror::Class> annotation_class) const {
1239 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1240 if (annotation_set == nullptr) {
1241 return nullptr;
1242 }
1243 StackHandleScope<1> hs(Thread::Current());
1244 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1245 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1246 kDexVisibilityRuntime, annotation_class);
1247}
1248
1249mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1250 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1251 StackHandleScope<1> hs(Thread::Current());
1252 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1253 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1254}
1255
Jeff Hao2a5892f2015-08-31 15:00:40 -07001256mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001257 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1258 if (annotation_set == nullptr) {
1259 return nullptr;
1260 }
1261 StackHandleScope<1> hs(Thread::Current());
1262 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1263 return GetThrowsValue(method_class, annotation_set);
1264}
1265
1266mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1267 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1268 if (parameter_annotations == nullptr) {
1269 return nullptr;
1270 }
1271 const AnnotationSetRefList* set_ref_list =
1272 GetParameterAnnotationSetRefList(parameter_annotations);
1273 if (set_ref_list == nullptr) {
1274 return nullptr;
1275 }
1276 uint32_t size = set_ref_list->size_;
1277 StackHandleScope<1> hs(Thread::Current());
1278 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1279 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1280}
1281
1282bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1283 const {
1284 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1285 if (annotation_set == nullptr) {
1286 return false;
1287 }
1288 StackHandleScope<1> hs(Thread::Current());
1289 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1290 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1291 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001292 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001293}
1294
1295const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1296 const {
1297 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1298 if (annotations_dir == nullptr) {
1299 return nullptr;
1300 }
1301 return GetClassAnnotationSet(annotations_dir);
1302}
1303
1304mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1305 Handle<mirror::Class> annotation_class) const {
1306 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1307 if (annotation_set == nullptr) {
1308 return nullptr;
1309 }
1310 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1311 annotation_class);
1312}
1313
1314mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1315 const {
1316 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1317 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1318}
1319
Jeff Hao2a5892f2015-08-31 15:00:40 -07001320mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1321 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1322 if (annotation_set == nullptr) {
1323 return nullptr;
1324 }
1325 const AnnotationItem* annotation_item = SearchAnnotationSet(
1326 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1327 if (annotation_item == nullptr) {
1328 return nullptr;
1329 }
1330 StackHandleScope<1> hs(Thread::Current());
1331 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1332 Handle<mirror::Class> class_array_class(hs.NewHandle(
1333 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1334 if (class_array_class.Get() == nullptr) {
1335 return nullptr;
1336 }
1337 mirror::Object* obj = GetAnnotationValue(
1338 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1339 if (obj == nullptr) {
1340 return nullptr;
1341 }
1342 return obj->AsObjectArray<mirror::Class>();
1343}
1344
1345mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1346 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1347 if (annotation_set == nullptr) {
1348 return nullptr;
1349 }
1350 const AnnotationItem* annotation_item = SearchAnnotationSet(
1351 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1352 if (annotation_item == nullptr) {
1353 return nullptr;
1354 }
1355 mirror::Object* obj = GetAnnotationValue(
1356 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1357 if (obj == nullptr) {
1358 return nullptr;
1359 }
1360 return obj->AsClass();
1361}
1362
1363mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1364 mirror::Class* declaring_class = GetDeclaringClass(klass);
1365 if (declaring_class != nullptr) {
1366 return declaring_class;
1367 }
1368 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1369 if (annotation_set == nullptr) {
1370 return nullptr;
1371 }
1372 const AnnotationItem* annotation_item = SearchAnnotationSet(
1373 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1374 if (annotation_item == nullptr) {
1375 return nullptr;
1376 }
1377 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1378 if (annotation == nullptr) {
1379 return nullptr;
1380 }
1381 AnnotationValue annotation_value;
1382 if (!ProcessAnnotationValue(
1383 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1384 return nullptr;
1385 }
1386 if (annotation_value.type_ != kDexAnnotationMethod) {
1387 return nullptr;
1388 }
1389 StackHandleScope<2> hs(Thread::Current());
1390 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1391 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1392 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1393 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1394 if (method == nullptr) {
1395 return nullptr;
1396 }
1397 return method->GetDeclaringClass();
1398}
1399
1400mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1401 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1402 if (annotation_set == nullptr) {
1403 return nullptr;
1404 }
1405 const AnnotationItem* annotation_item = SearchAnnotationSet(
1406 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1407 if (annotation_item == nullptr) {
1408 return nullptr;
1409 }
1410 return GetAnnotationValue(
1411 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1412}
1413
1414bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1415 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1416 if (annotation_set == nullptr) {
1417 return false;
1418 }
1419 const AnnotationItem* annotation_item = SearchAnnotationSet(
1420 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1421 if (annotation_item == nullptr) {
1422 return false;
1423 }
1424 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1425 if (annotation == nullptr) {
1426 return false;
1427 }
1428 AnnotationValue annotation_value;
1429 if (!ProcessAnnotationValue(
1430 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1431 return false;
1432 }
1433 if (annotation_value.type_ != kDexAnnotationNull &&
1434 annotation_value.type_ != kDexAnnotationString) {
1435 return false;
1436 }
1437 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1438 return true;
1439}
1440
1441bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1442 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1443 if (annotation_set == nullptr) {
1444 return false;
1445 }
1446 const AnnotationItem* annotation_item = SearchAnnotationSet(
1447 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1448 if (annotation_item == nullptr) {
1449 return false;
1450 }
1451 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1452 if (annotation == nullptr) {
1453 return false;
1454 }
1455 AnnotationValue annotation_value;
1456 if (!ProcessAnnotationValue(
1457 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1458 return false;
1459 }
1460 if (annotation_value.type_ != kDexAnnotationInt) {
1461 return false;
1462 }
1463 *flags = annotation_value.value_.GetI();
1464 return true;
1465}
1466
Jeff Hao13e748b2015-08-25 20:44:19 +00001467bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1468 Handle<mirror::Class> annotation_class) const {
1469 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1470 if (annotation_set == nullptr) {
1471 return false;
1472 }
1473 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1474 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001475 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001476}
1477
1478mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1479 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1480 Thread* self = Thread::Current();
1481 ScopedObjectAccessUnchecked soa(self);
1482 StackHandleScope<5> hs(self);
1483 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1484 const char* name = StringDataByIdx(element_name_index);
1485 Handle<mirror::String> string_name(
1486 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1487
1488 ArtMethod* annotation_method =
1489 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1490 if (annotation_method == nullptr) {
1491 return nullptr;
1492 }
1493 Handle<mirror::Class> method_return(hs.NewHandle(annotation_method->GetReturnType()));
1494
1495 AnnotationValue annotation_value;
1496 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1497 return nullptr;
1498 }
1499 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1500
1501 mirror::Class* annotation_member_class =
1502 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1503 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1504 Handle<mirror::Method> method_object(
1505 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1506
1507 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1508 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1509 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1510 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1511 return nullptr;
1512 }
1513
1514 JValue result;
1515 ArtMethod* annotation_member_init =
1516 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1517 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1518 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1519 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1520 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1521 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1522 };
1523 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1524 if (self->IsExceptionPending()) {
1525 LOG(INFO) << "Exception in AnnotationMember.<init>";
1526 return nullptr;
1527 }
1528
1529 return new_member.Get();
1530}
1531
1532const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1533 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1534 Handle<mirror::Class> annotation_class) const {
1535 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1536 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1537 if (annotation_item->visibility_ != visibility) {
1538 continue;
1539 }
1540 const uint8_t* annotation = annotation_item->annotation_;
1541 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1542 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1543 klass->GetDexFile(), type_index, klass.Get());
1544 if (resolved_class == nullptr) {
1545 std::string temp;
1546 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1547 klass->GetDescriptor(&temp), type_index);
1548 CHECK(Thread::Current()->IsExceptionPending());
1549 Thread::Current()->ClearException();
1550 continue;
1551 }
1552 if (resolved_class == annotation_class.Get()) {
1553 return annotation_item;
1554 }
1555 }
1556
1557 return nullptr;
1558}
1559
1560mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1561 const AnnotationSetItem* annotation_set, uint32_t visibility,
1562 Handle<mirror::Class> annotation_class) const {
1563 const AnnotationItem* annotation_item =
1564 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1565 if (annotation_item == nullptr) {
1566 return nullptr;
1567 }
1568 const uint8_t* annotation = annotation_item->annotation_;
1569 return ProcessEncodedAnnotation(klass, &annotation);
1570}
1571
1572mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1573 const AnnotationItem* annotation_item, const char* annotation_name,
1574 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1575 const uint8_t* annotation =
1576 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1577 if (annotation == nullptr) {
1578 return nullptr;
1579 }
1580 AnnotationValue annotation_value;
1581 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1582 return nullptr;
1583 }
1584 if (annotation_value.type_ != expected_type) {
1585 return nullptr;
1586 }
1587 return annotation_value.value_.GetL();
1588}
1589
Jeff Hao2a5892f2015-08-31 15:00:40 -07001590mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001591 const AnnotationSetItem* annotation_set) const {
1592 StackHandleScope<1> hs(Thread::Current());
1593 const AnnotationItem* annotation_item =
1594 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1595 if (annotation_item == nullptr) {
1596 return nullptr;
1597 }
1598 mirror::Class* string_class = mirror::String::GetJavaLangString();
1599 Handle<mirror::Class> string_array_class(hs.NewHandle(
1600 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001601 if (string_array_class.Get() == nullptr) {
1602 return nullptr;
1603 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001604 mirror::Object* obj =
1605 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1606 if (obj == nullptr) {
1607 return nullptr;
1608 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001609 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001610}
1611
Jeff Hao2a5892f2015-08-31 15:00:40 -07001612mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001613 const AnnotationSetItem* annotation_set) const {
1614 StackHandleScope<1> hs(Thread::Current());
1615 const AnnotationItem* annotation_item =
1616 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1617 if (annotation_item == nullptr) {
1618 return nullptr;
1619 }
1620 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1621 Handle<mirror::Class> class_array_class(hs.NewHandle(
1622 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001623 if (class_array_class.Get() == nullptr) {
1624 return nullptr;
1625 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001626 mirror::Object* obj =
1627 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1628 if (obj == nullptr) {
1629 return nullptr;
1630 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001631 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001632}
1633
1634mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1635 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1636 Thread* self = Thread::Current();
1637 ScopedObjectAccessUnchecked soa(self);
1638 StackHandleScope<2> hs(self);
1639 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1640 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1641 if (annotation_set == nullptr) {
1642 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1643 }
1644
1645 uint32_t size = annotation_set->size_;
1646 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1647 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1648 if (result.Get() == nullptr) {
1649 return nullptr;
1650 }
1651
1652 uint32_t dest_index = 0;
1653 for (uint32_t i = 0; i < size; ++i) {
1654 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1655 if (annotation_item->visibility_ != visibility) {
1656 continue;
1657 }
1658 const uint8_t* annotation = annotation_item->annotation_;
1659 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1660 if (annotation_obj != nullptr) {
1661 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1662 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001663 } else if (self->IsExceptionPending()) {
1664 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001665 }
1666 }
1667
1668 if (dest_index == size) {
1669 return result.Get();
1670 }
1671
1672 mirror::ObjectArray<mirror::Object>* trimmed_result =
1673 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001674 if (trimmed_result == nullptr) {
1675 return nullptr;
1676 }
1677
Jeff Hao13e748b2015-08-25 20:44:19 +00001678 for (uint32_t i = 0; i < dest_index; ++i) {
1679 mirror::Object* obj = result->GetWithoutChecks(i);
1680 trimmed_result->SetWithoutChecks<false>(i, obj);
1681 }
1682
1683 return trimmed_result;
1684}
1685
1686mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1687 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1688 Thread* self = Thread::Current();
1689 ScopedObjectAccessUnchecked soa(self);
1690 StackHandleScope<1> hs(self);
1691 mirror::Class* annotation_array_class =
1692 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1693 mirror::Class* annotation_array_array_class =
1694 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001695 if (annotation_array_array_class == nullptr) {
1696 return nullptr;
1697 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001698 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1699 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1700 if (annotation_array_array.Get() == nullptr) {
1701 LOG(ERROR) << "Annotation set ref array allocation failed";
1702 return nullptr;
1703 }
1704 for (uint32_t index = 0; index < size; ++index) {
1705 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1706 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1707 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1708 if (annotation_set == nullptr) {
1709 return nullptr;
1710 }
1711 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1712 }
1713 return annotation_array_array.Get();
1714}
1715
1716bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1717 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1718 DexFile::AnnotationResultStyle result_style) const {
1719 Thread* self = Thread::Current();
1720 mirror::Object* element_object = nullptr;
1721 bool set_object = false;
1722 Primitive::Type primitive_type = Primitive::kPrimVoid;
1723 const uint8_t* annotation = *annotation_ptr;
1724 uint8_t header_byte = *(annotation++);
1725 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1726 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1727 int32_t width = value_arg + 1;
1728 annotation_value->type_ = value_type;
1729
1730 switch (value_type) {
1731 case kDexAnnotationByte:
1732 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1733 primitive_type = Primitive::kPrimByte;
1734 break;
1735 case kDexAnnotationShort:
1736 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1737 primitive_type = Primitive::kPrimShort;
1738 break;
1739 case kDexAnnotationChar:
1740 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1741 false)));
1742 primitive_type = Primitive::kPrimChar;
1743 break;
1744 case kDexAnnotationInt:
1745 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1746 primitive_type = Primitive::kPrimInt;
1747 break;
1748 case kDexAnnotationLong:
1749 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1750 primitive_type = Primitive::kPrimLong;
1751 break;
1752 case kDexAnnotationFloat:
1753 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1754 primitive_type = Primitive::kPrimFloat;
1755 break;
1756 case kDexAnnotationDouble:
1757 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1758 primitive_type = Primitive::kPrimDouble;
1759 break;
1760 case kDexAnnotationBoolean:
1761 annotation_value->value_.SetZ(value_arg != 0);
1762 primitive_type = Primitive::kPrimBoolean;
1763 width = 0;
1764 break;
1765 case kDexAnnotationString: {
1766 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1767 if (result_style == kAllRaw) {
1768 annotation_value->value_.SetI(index);
1769 } else {
1770 StackHandleScope<1> hs(self);
1771 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1772 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1773 klass->GetDexFile(), index, dex_cache);
1774 set_object = true;
1775 if (element_object == nullptr) {
1776 return false;
1777 }
1778 }
1779 break;
1780 }
1781 case kDexAnnotationType: {
1782 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1783 if (result_style == kAllRaw) {
1784 annotation_value->value_.SetI(index);
1785 } else {
1786 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1787 klass->GetDexFile(), index, klass.Get());
1788 set_object = true;
1789 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001790 CHECK(self->IsExceptionPending());
1791 if (result_style == kAllObjects) {
1792 const char* msg = StringByTypeIdx(index);
1793 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1794 element_object = self->GetException();
1795 self->ClearException();
1796 } else {
1797 return false;
1798 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001799 }
1800 }
1801 break;
1802 }
1803 case kDexAnnotationMethod: {
1804 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1805 if (result_style == kAllRaw) {
1806 annotation_value->value_.SetI(index);
1807 } else {
1808 StackHandleScope<2> hs(self);
1809 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1810 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1811 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1812 klass->GetDexFile(), index, dex_cache, class_loader);
1813 if (method == nullptr) {
1814 return false;
1815 }
1816 set_object = true;
1817 if (method->IsConstructor()) {
1818 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1819 } else {
1820 element_object = mirror::Method::CreateFromArtMethod(self, method);
1821 }
1822 if (element_object == nullptr) {
1823 return false;
1824 }
1825 }
1826 break;
1827 }
1828 case kDexAnnotationField: {
1829 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1830 if (result_style == kAllRaw) {
1831 annotation_value->value_.SetI(index);
1832 } else {
1833 StackHandleScope<2> hs(self);
1834 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1835 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1836 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1837 klass->GetDexFile(), index, dex_cache, class_loader);
1838 if (field == nullptr) {
1839 return false;
1840 }
1841 set_object = true;
1842 element_object = mirror::Field::CreateFromArtField(self, field, true);
1843 if (element_object == nullptr) {
1844 return false;
1845 }
1846 }
1847 break;
1848 }
1849 case kDexAnnotationEnum: {
1850 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1851 if (result_style == kAllRaw) {
1852 annotation_value->value_.SetI(index);
1853 } else {
1854 StackHandleScope<3> hs(self);
1855 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1856 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1857 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1858 klass->GetDexFile(), index, dex_cache, class_loader, true);
1859 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1860 if (enum_field == nullptr) {
1861 return false;
1862 } else {
1863 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1864 element_object = enum_field->GetObject(field_class.Get());
1865 set_object = true;
1866 }
1867 }
1868 break;
1869 }
1870 case kDexAnnotationArray:
1871 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1872 return false;
1873 } else {
1874 ScopedObjectAccessUnchecked soa(self);
1875 StackHandleScope<2> hs(self);
1876 uint32_t size = DecodeUnsignedLeb128(&annotation);
1877 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1878 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1879 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1880 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1881 if (new_array.Get() == nullptr) {
1882 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1883 return false;
1884 }
1885 AnnotationValue new_annotation_value;
1886 for (uint32_t i = 0; i < size; ++i) {
1887 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1888 kPrimitivesOrObjects)) {
1889 return false;
1890 }
1891 if (!component_type->IsPrimitive()) {
1892 mirror::Object* obj = new_annotation_value.value_.GetL();
1893 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1894 } else {
1895 switch (new_annotation_value.type_) {
1896 case kDexAnnotationByte:
1897 new_array->AsByteArray()->SetWithoutChecks<false>(
1898 i, new_annotation_value.value_.GetB());
1899 break;
1900 case kDexAnnotationShort:
1901 new_array->AsShortArray()->SetWithoutChecks<false>(
1902 i, new_annotation_value.value_.GetS());
1903 break;
1904 case kDexAnnotationChar:
1905 new_array->AsCharArray()->SetWithoutChecks<false>(
1906 i, new_annotation_value.value_.GetC());
1907 break;
1908 case kDexAnnotationInt:
1909 new_array->AsIntArray()->SetWithoutChecks<false>(
1910 i, new_annotation_value.value_.GetI());
1911 break;
1912 case kDexAnnotationLong:
1913 new_array->AsLongArray()->SetWithoutChecks<false>(
1914 i, new_annotation_value.value_.GetJ());
1915 break;
1916 case kDexAnnotationFloat:
1917 new_array->AsFloatArray()->SetWithoutChecks<false>(
1918 i, new_annotation_value.value_.GetF());
1919 break;
1920 case kDexAnnotationDouble:
1921 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1922 i, new_annotation_value.value_.GetD());
1923 break;
1924 case kDexAnnotationBoolean:
1925 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1926 i, new_annotation_value.value_.GetZ());
1927 break;
1928 default:
1929 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1930 return false;
1931 }
1932 }
1933 }
1934 element_object = new_array.Get();
1935 set_object = true;
1936 width = 0;
1937 }
1938 break;
1939 case kDexAnnotationAnnotation:
1940 if (result_style == kAllRaw) {
1941 return false;
1942 }
1943 element_object = ProcessEncodedAnnotation(klass, &annotation);
1944 if (element_object == nullptr) {
1945 return false;
1946 }
1947 set_object = true;
1948 width = 0;
1949 break;
1950 case kDexAnnotationNull:
1951 if (result_style == kAllRaw) {
1952 annotation_value->value_.SetI(0);
1953 } else {
1954 CHECK(element_object == nullptr);
1955 set_object = true;
1956 }
1957 width = 0;
1958 break;
1959 default:
1960 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1961 return false;
1962 }
1963
1964 annotation += width;
1965 *annotation_ptr = annotation;
1966
1967 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1968 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1969 set_object = true;
1970 }
1971
1972 if (set_object) {
1973 annotation_value->value_.SetL(element_object);
1974 }
1975
1976 return true;
1977}
1978
1979mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1980 const uint8_t** annotation) const {
1981 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1982 uint32_t size = DecodeUnsignedLeb128(annotation);
1983
1984 Thread* self = Thread::Current();
1985 ScopedObjectAccessUnchecked soa(self);
1986 StackHandleScope<2> hs(self);
1987 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1988 Handle<mirror::Class> annotation_class(hs.NewHandle(
1989 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1990 if (annotation_class.Get() == nullptr) {
1991 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1992 << type_index;
1993 DCHECK(Thread::Current()->IsExceptionPending());
1994 Thread::Current()->ClearException();
1995 return nullptr;
1996 }
1997
1998 mirror::Class* annotation_member_class =
1999 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2000 mirror::Class* annotation_member_array_class =
2001 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002002 if (annotation_member_array_class == nullptr) {
2003 return nullptr;
2004 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002005 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002006 if (size > 0) {
2007 element_array =
2008 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2009 if (element_array == nullptr) {
2010 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2011 return nullptr;
2012 }
2013 }
2014
2015 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2016 for (uint32_t i = 0; i < size; ++i) {
2017 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2018 if (new_member == nullptr) {
2019 return nullptr;
2020 }
2021 h_element_array->SetWithoutChecks<false>(i, new_member);
2022 }
2023
2024 JValue result;
2025 ArtMethod* create_annotation_method =
2026 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2027 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2028 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2029 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2030 if (self->IsExceptionPending()) {
2031 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2032 return nullptr;
2033 }
2034
2035 return result.GetL();
2036}
2037
2038const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2039 const char* descriptor, uint32_t visibility) const {
2040 const AnnotationItem* result = nullptr;
2041 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2042 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2043 if (annotation_item->visibility_ != visibility) {
2044 continue;
2045 }
2046 const uint8_t* annotation = annotation_item->annotation_;
2047 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2048
2049 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2050 result = annotation_item;
2051 break;
2052 }
2053 }
2054 return result;
2055}
2056
2057const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2058 DecodeUnsignedLeb128(&annotation); // unused type_index
2059 uint32_t size = DecodeUnsignedLeb128(&annotation);
2060
2061 while (size != 0) {
2062 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2063 const char* element_name = GetStringData(GetStringId(element_name_index));
2064 if (strcmp(name, element_name) == 0) {
2065 return annotation;
2066 }
2067 SkipAnnotationValue(&annotation);
2068 size--;
2069 }
2070 return nullptr;
2071}
2072
2073bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2074 const uint8_t* annotation = *annotation_ptr;
2075 uint8_t header_byte = *(annotation++);
2076 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2077 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2078 int32_t width = value_arg + 1;
2079
2080 switch (value_type) {
2081 case kDexAnnotationByte:
2082 case kDexAnnotationShort:
2083 case kDexAnnotationChar:
2084 case kDexAnnotationInt:
2085 case kDexAnnotationLong:
2086 case kDexAnnotationFloat:
2087 case kDexAnnotationDouble:
2088 case kDexAnnotationString:
2089 case kDexAnnotationType:
2090 case kDexAnnotationMethod:
2091 case kDexAnnotationField:
2092 case kDexAnnotationEnum:
2093 break;
2094 case kDexAnnotationArray:
2095 {
2096 uint32_t size = DecodeUnsignedLeb128(&annotation);
2097 while (size--) {
2098 if (!SkipAnnotationValue(&annotation)) {
2099 return false;
2100 }
2101 }
2102 width = 0;
2103 break;
2104 }
2105 case kDexAnnotationAnnotation:
2106 {
2107 DecodeUnsignedLeb128(&annotation); // unused type_index
2108 uint32_t size = DecodeUnsignedLeb128(&annotation);
2109 while (size--) {
2110 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2111 if (!SkipAnnotationValue(&annotation)) {
2112 return false;
2113 }
2114 }
2115 width = 0;
2116 break;
2117 }
2118 case kDexAnnotationBoolean:
2119 case kDexAnnotationNull:
2120 width = 0;
2121 break;
2122 default:
2123 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2124 return false;
2125 }
2126
2127 annotation += width;
2128 *annotation_ptr = annotation;
2129 return true;
2130}
2131
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002132std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2133 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2134 dex_file.GetLocation().c_str(),
2135 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2136 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2137 return os;
2138}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002139
Ian Rogersd91d6d62013-09-25 20:26:14 -07002140std::string Signature::ToString() const {
2141 if (dex_file_ == nullptr) {
2142 CHECK(proto_id_ == nullptr);
2143 return "<no signature>";
2144 }
2145 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2146 std::string result;
2147 if (params == nullptr) {
2148 result += "()";
2149 } else {
2150 result += "(";
2151 for (uint32_t i = 0; i < params->Size(); ++i) {
2152 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2153 }
2154 result += ")";
2155 }
2156 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2157 return result;
2158}
2159
Vladimir Markod9cffea2013-11-25 15:08:02 +00002160bool Signature::operator==(const StringPiece& rhs) const {
2161 if (dex_file_ == nullptr) {
2162 return false;
2163 }
2164 StringPiece tail(rhs);
2165 if (!tail.starts_with("(")) {
2166 return false; // Invalid signature
2167 }
2168 tail.remove_prefix(1); // "(";
2169 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2170 if (params != nullptr) {
2171 for (uint32_t i = 0; i < params->Size(); ++i) {
2172 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2173 if (!tail.starts_with(param)) {
2174 return false;
2175 }
2176 tail.remove_prefix(param.length());
2177 }
2178 }
2179 if (!tail.starts_with(")")) {
2180 return false;
2181 }
2182 tail.remove_prefix(1); // ")";
2183 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2184}
2185
Ian Rogersd91d6d62013-09-25 20:26:14 -07002186std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2187 return os << sig.ToString();
2188}
2189
Ian Rogers0571d352011-11-03 19:51:38 -07002190// Decodes the header section from the class data bytes.
2191void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002192 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002193 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2194 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2195 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2196 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2197}
2198
2199void ClassDataItemIterator::ReadClassDataField() {
2200 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2201 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002202 // The user of the iterator is responsible for checking if there
2203 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002204}
2205
2206void ClassDataItemIterator::ReadClassDataMethod() {
2207 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2208 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2209 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002210 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002211 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002212 }
Ian Rogers0571d352011-11-03 19:51:38 -07002213}
2214
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002215EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2216 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2217 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2218 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002219 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2220 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002221 DCHECK(dex_cache != nullptr);
2222 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002223 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002224 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002225 array_size_ = 0;
2226 } else {
2227 array_size_ = DecodeUnsignedLeb128(&ptr_);
2228 }
2229 if (array_size_ > 0) {
2230 Next();
2231 }
2232}
2233
2234void EncodedStaticFieldValueIterator::Next() {
2235 pos_++;
2236 if (pos_ >= array_size_) {
2237 return;
2238 }
Ian Rogers13735952014-10-08 12:43:28 -07002239 uint8_t value_type = *ptr_++;
2240 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002241 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002242 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002243 switch (type_) {
2244 case kBoolean:
2245 jval_.i = (value_arg != 0) ? 1 : 0;
2246 width = 0;
2247 break;
2248 case kByte:
2249 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002250 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002251 break;
2252 case kShort:
2253 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002254 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002255 break;
2256 case kChar:
2257 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002258 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002259 break;
2260 case kInt:
2261 jval_.i = ReadSignedInt(ptr_, value_arg);
2262 break;
2263 case kLong:
2264 jval_.j = ReadSignedLong(ptr_, value_arg);
2265 break;
2266 case kFloat:
2267 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2268 break;
2269 case kDouble:
2270 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2271 break;
2272 case kString:
2273 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002274 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2275 break;
2276 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002277 case kMethod:
2278 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002279 case kArray:
2280 case kAnnotation:
2281 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002282 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002283 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002284 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002285 width = 0;
2286 break;
2287 default:
2288 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002289 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002290 }
2291 ptr_ += width;
2292}
2293
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002294template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002295void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002296 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002297 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2298 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002299 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2300 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2301 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2302 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2303 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2304 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2305 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002306 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002307 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002309 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002310 break;
2311 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002312 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002313 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2314 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002315 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002316 break;
2317 }
Ian Rogers0571d352011-11-03 19:51:38 -07002318 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2319 }
2320}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002321template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2322template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002323
2324CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2325 handler_.address_ = -1;
2326 int32_t offset = -1;
2327
2328 // Short-circuit the overwhelmingly common cases.
2329 switch (code_item.tries_size_) {
2330 case 0:
2331 break;
2332 case 1: {
2333 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2334 uint32_t start = tries->start_addr_;
2335 if (address >= start) {
2336 uint32_t end = start + tries->insn_count_;
2337 if (address < end) {
2338 offset = tries->handler_off_;
2339 }
2340 }
2341 break;
2342 }
2343 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002344 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002345 }
Logan Chien736df022012-04-27 16:25:57 +08002346 Init(code_item, offset);
2347}
2348
2349CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2350 const DexFile::TryItem& try_item) {
2351 handler_.address_ = -1;
2352 Init(code_item, try_item.handler_off_);
2353}
2354
2355void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2356 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002357 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002358 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002359 } else {
2360 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002361 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002362 remaining_count_ = -1;
2363 catch_all_ = false;
2364 DCHECK(!HasNext());
2365 }
2366}
2367
Ian Rogers13735952014-10-08 12:43:28 -07002368void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002369 current_data_ = handler_data;
2370 remaining_count_ = DecodeSignedLeb128(&current_data_);
2371
2372 // If remaining_count_ is non-positive, then it is the negative of
2373 // the number of catch types, and the catches are followed by a
2374 // catch-all handler.
2375 if (remaining_count_ <= 0) {
2376 catch_all_ = true;
2377 remaining_count_ = -remaining_count_;
2378 } else {
2379 catch_all_ = false;
2380 }
2381 Next();
2382}
2383
2384void CatchHandlerIterator::Next() {
2385 if (remaining_count_ > 0) {
2386 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2387 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2388 remaining_count_--;
2389 return;
2390 }
2391
2392 if (catch_all_) {
2393 handler_.type_idx_ = DexFile::kDexNoIndex16;
2394 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2395 catch_all_ = false;
2396 return;
2397 }
2398
2399 // no more handler
2400 remaining_count_ = -1;
2401}
2402
Carl Shapiro1fb86202011-06-27 17:43:13 -07002403} // namespace art