blob: 81a3e4b08c247a3e0ad8ba175e1f606bb3e7b874 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000032#include "base/file_magic.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070033#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080034#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010035#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080036#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000037#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070038#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080039#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070040#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070042#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000043#include "mirror/field.h"
44#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070046#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000047#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070048#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070049#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030050#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070051#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070052#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070054#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070055
Andreas Gampe277ccbd2014-11-03 21:36:10 -080056#pragma GCC diagnostic push
57#pragma GCC diagnostic ignored "-Wshadow"
58#include "ScopedFd.h"
59#pragma GCC diagnostic pop
60
Carl Shapiro1fb86202011-06-27 17:43:13 -070061namespace art {
62
Ian Rogers13735952014-10-08 12:43:28 -070063const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
64const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070065
Ian Rogers8d31bbd2013-10-13 10:44:14 -070066bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070067 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070069
70 // Strip ":...", which is the location
71 const char* zip_entry_name = kClassesDex;
72 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010073 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070074
Vladimir Markoaa4497d2014-09-05 14:01:17 +010075 if (DexFile::IsMultiDexLocation(filename)) {
76 file_part_storage = GetBaseLocation(filename);
77 file_part = file_part_storage.c_str();
78 zip_entry_name = filename + file_part_storage.size() + 1;
79 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070080 }
81
82 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000083 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070084 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085 return false;
86 }
87 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 std::unique_ptr<ZipArchive> zip_archive(
89 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
90 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080091 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
92 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080093 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070094 }
Andreas Gampe833a4852014-05-21 18:46:59 -070095 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -070097 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
98 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
100 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700101 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700103 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700105 std::unique_ptr<const DexFile> dex_file(
106 DexFile::OpenFile(fd.release(), filename, false, error_msg));
107 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return false;
109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return true;
112 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700113 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700115}
116
Andreas Gampe833a4852014-05-21 18:46:59 -0700117bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800118 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700120 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000121 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
122 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700123 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700124 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700125 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700126 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700127 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700128 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700130 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
131 error_msg));
132 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800133 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return true;
135 } else {
136 return false;
137 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700138 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400140 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700141}
142
Andreas Gampe0cba0042015-04-29 20:47:16 -0700143static bool ContainsClassesDex(int fd, const char* filename) {
144 std::string error_msg;
145 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
146 if (zip_archive.get() == nullptr) {
147 return false;
148 }
149 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
150 return (zip_entry.get() != nullptr);
151}
152
153bool DexFile::MaybeDex(const char* filename) {
154 uint32_t magic;
155 std::string error_msg;
156 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
157 if (fd.get() == -1) {
158 return false;
159 }
160 if (IsZipMagic(magic)) {
161 return ContainsClassesDex(fd.release(), filename);
162 } else if (IsDexMagic(magic)) {
163 return true;
164 }
165 return false;
166}
167
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800168int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700169 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800170 return 0;
171 } else {
172 return mem_map_->GetProtect();
173 }
174}
175
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200176bool DexFile::IsReadOnly() const {
177 return GetPermissions() == PROT_READ;
178}
179
Brian Carlstrome0948e12013-08-29 09:36:15 -0700180bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200181 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183 return false;
184 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700185 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200186 }
187}
188
Brian Carlstrome0948e12013-08-29 09:36:15 -0700189bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200190 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700191 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200192 return false;
193 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700194 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195 }
196}
197
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800198std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
199 const std::string& location,
200 uint32_t location_checksum,
201 const OatDexFile* oat_dex_file,
202 bool verify,
203 std::string* error_msg) {
204 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
205 size,
206 location,
207 location_checksum,
208 nullptr,
209 oat_dex_file,
210 error_msg);
211 if (verify && !DexFileVerifier::Verify(dex_file.get(),
212 dex_file->Begin(),
213 dex_file->Size(),
214 location.c_str(),
215 error_msg)) {
216 return nullptr;
217 }
218
219 return dex_file;
220}
221
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800222std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
223 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700224 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700225 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000226 {
227 ScopedFd delayed_close(fd);
228 struct stat sbuf;
229 memset(&sbuf, 0, sizeof(sbuf));
230 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800231 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000232 return nullptr;
233 }
234 if (S_ISDIR(sbuf.st_mode)) {
235 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
236 return nullptr;
237 }
238 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800239 map.reset(MemMap::MapFile(length,
240 PROT_READ,
241 MAP_PRIVATE,
242 fd,
243 0,
244 /*low_4gb*/false,
245 location,
246 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000247 if (map.get() == nullptr) {
248 DCHECK(!error_msg->empty());
249 return nullptr;
250 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700251 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800252
253 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700254 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800255 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700256 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800257 }
258
259 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
260
Andreas Gampe928f72b2014-09-09 19:53:48 -0700261 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
262 error_msg));
263 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700264 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
265 error_msg->c_str());
266 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800267 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800268
Andreas Gampe928f72b2014-09-09 19:53:48 -0700269 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
270 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800272 }
273
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800274 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700275}
276
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700277const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700278
Andreas Gampe833a4852014-05-21 18:46:59 -0700279bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800280 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700281 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700282 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 if (zip_archive.get() == nullptr) {
284 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700285 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700286 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700287 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800288}
289
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800290std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
291 uint32_t location_checksum,
292 MemMap* mem_map,
293 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800294 return OpenMemory(mem_map->Begin(),
295 mem_map->Size(),
296 location,
297 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700298 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800299 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700300 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800301}
302
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800303std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
304 const std::string& location, std::string* error_msg,
305 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800306 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700307 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700308 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700309 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700311 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700312 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700313 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700314 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700315 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700316 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700317 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700318 }
Ian Rogers700a4022014-05-19 16:49:03 -0700319 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320 error_msg));
321 if (dex_file.get() == nullptr) {
322 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
323 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700324 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700325 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800326 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700327 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700328 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700329 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700330 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700331 }
332 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700333 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
334 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700336 return nullptr;
337 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700338 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800339 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700340}
341
Andreas Gampe90e34042015-04-27 20:01:52 -0700342// Technically we do not have a limitation with respect to the number of dex files that can be in a
343// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
344// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
345// seems an excessive number.
346static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
347
Andreas Gampe833a4852014-05-21 18:46:59 -0700348bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800349 std::string* error_msg,
350 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700351 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700352 ZipOpenErrorCode error_code;
353 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
354 &error_code));
355 if (dex_file.get() == nullptr) {
356 return false;
357 } else {
358 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800359 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700360
361 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700362
363 // We could try to avoid std::string allocations by working on a char array directly. As we
364 // do not expect a lot of iterations, this seems too involved and brittle.
365
Andreas Gampe90e34042015-04-27 20:01:52 -0700366 for (size_t i = 1; ; ++i) {
367 std::string name = GetMultiDexClassesDexName(i);
368 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700369 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
370 error_msg, &error_code));
371 if (next_dex_file.get() == nullptr) {
372 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
373 LOG(WARNING) << error_msg;
374 }
375 break;
376 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800377 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700378 }
379
Andreas Gampe90e34042015-04-27 20:01:52 -0700380 if (i == kWarnOnManyDexFilesThreshold) {
381 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
382 << " dex files. Please consider coalescing and shrinking the number to "
383 " avoid runtime overhead.";
384 }
385
386 if (i == std::numeric_limits<size_t>::max()) {
387 LOG(ERROR) << "Overflow in number of dex files!";
388 break;
389 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700390 }
391
392 return true;
393 }
394}
395
396
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800397std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
398 size_t size,
399 const std::string& location,
400 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800401 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700402 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800403 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700404 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800405 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700406 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700407 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700409 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800410 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700411}
412
Ian Rogers13735952014-10-08 12:43:28 -0700413DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800414 const std::string& location,
415 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800416 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700417 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800418 : begin_(base),
419 size_(size),
420 location_(location),
421 location_checksum_(location_checksum),
422 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800423 header_(reinterpret_cast<const Header*>(base)),
424 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
425 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
426 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
427 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
428 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700429 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700430 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700431 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800432 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300433 const uint8_t* lookup_data = (oat_dex_file != nullptr)
434 ? oat_dex_file->GetLookupTableData()
435 : nullptr;
436 if (lookup_data != nullptr) {
437 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
438 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
439 } else {
440 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
441 }
442 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800443}
444
Jesse Wilson6bf19152011-09-29 13:12:33 -0400445DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700446 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
447 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
448 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
449 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400450}
451
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700452bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700453 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700454 return false;
455 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700456 return true;
457}
458
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700459bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800460 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700461 std::ostringstream oss;
462 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800463 << " " << header_->magic_[0]
464 << " " << header_->magic_[1]
465 << " " << header_->magic_[2]
466 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700467 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700468 return false;
469 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800470 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700471 std::ostringstream oss;
472 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800473 << " " << header_->magic_[4]
474 << " " << header_->magic_[5]
475 << " " << header_->magic_[6]
476 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700477 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700478 return false;
479 }
480 return true;
481}
482
Ian Rogers13735952014-10-08 12:43:28 -0700483bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800484 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
485}
486
Ian Rogers13735952014-10-08 12:43:28 -0700487bool DexFile::IsVersionValid(const uint8_t* magic) {
488 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800489 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
490}
491
Ian Rogersd81871c2011-10-03 13:57:23 -0700492uint32_t DexFile::GetVersion() const {
493 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
494 return atoi(version);
495}
496
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800497const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
498 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300499 if (LIKELY(lookup_table_ != nullptr)) {
500 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
501 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700502 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300503
Ian Rogers68b56852014-08-29 20:19:11 -0700504 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300505 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700506 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700507 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700508 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300509 const TypeId* type_id = FindTypeId(descriptor);
510 if (type_id != nullptr) {
511 uint16_t type_idx = GetIndexForTypeId(*type_id);
512 for (size_t i = 0; i < num_class_defs; ++i) {
513 const ClassDef& class_def = GetClassDef(i);
514 if (class_def.class_idx_ == type_idx) {
515 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700516 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700517 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700518 }
Ian Rogers68b56852014-08-29 20:19:11 -0700519 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700520}
521
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700522const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
523 size_t num_class_defs = NumClassDefs();
524 for (size_t i = 0; i < num_class_defs; ++i) {
525 const ClassDef& class_def = GetClassDef(i);
526 if (class_def.class_idx_ == type_idx) {
527 return &class_def;
528 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700529 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700530 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700531}
532
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800533const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
534 const DexFile::StringId& name,
535 const DexFile::TypeId& type) const {
536 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
537 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
538 const uint32_t name_idx = GetIndexForStringId(name);
539 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700540 int32_t lo = 0;
541 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800542 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700543 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800544 const DexFile::FieldId& field = GetFieldId(mid);
545 if (class_idx > field.class_idx_) {
546 lo = mid + 1;
547 } else if (class_idx < field.class_idx_) {
548 hi = mid - 1;
549 } else {
550 if (name_idx > field.name_idx_) {
551 lo = mid + 1;
552 } else if (name_idx < field.name_idx_) {
553 hi = mid - 1;
554 } else {
555 if (type_idx > field.type_idx_) {
556 lo = mid + 1;
557 } else if (type_idx < field.type_idx_) {
558 hi = mid - 1;
559 } else {
560 return &field;
561 }
562 }
563 }
564 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700565 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800566}
567
568const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700569 const DexFile::StringId& name,
570 const DexFile::ProtoId& signature) const {
571 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800572 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700573 const uint32_t name_idx = GetIndexForStringId(name);
574 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700575 int32_t lo = 0;
576 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700577 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700578 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700579 const DexFile::MethodId& method = GetMethodId(mid);
580 if (class_idx > method.class_idx_) {
581 lo = mid + 1;
582 } else if (class_idx < method.class_idx_) {
583 hi = mid - 1;
584 } else {
585 if (name_idx > method.name_idx_) {
586 lo = mid + 1;
587 } else if (name_idx < method.name_idx_) {
588 hi = mid - 1;
589 } else {
590 if (proto_idx > method.proto_idx_) {
591 lo = mid + 1;
592 } else if (proto_idx < method.proto_idx_) {
593 hi = mid - 1;
594 } else {
595 return &method;
596 }
597 }
598 }
599 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700600 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700601}
602
Ian Rogers637c65b2013-05-31 11:46:00 -0700603const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700604 int32_t lo = 0;
605 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700606 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700607 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700608 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700609 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700610 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
611 if (compare > 0) {
612 lo = mid + 1;
613 } else if (compare < 0) {
614 hi = mid - 1;
615 } else {
616 return &str_id;
617 }
618 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700619 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700620}
621
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300622const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
623 int32_t lo = 0;
624 int32_t hi = NumTypeIds() - 1;
625 while (hi >= lo) {
626 int32_t mid = (hi + lo) / 2;
627 const TypeId& type_id = GetTypeId(mid);
628 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
629 const char* str = GetStringData(str_id);
630 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
631 if (compare > 0) {
632 lo = mid + 1;
633 } else if (compare < 0) {
634 hi = mid - 1;
635 } else {
636 return &type_id;
637 }
638 }
639 return nullptr;
640}
641
Vladimir Markoa48aef42014-12-03 17:53:53 +0000642const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700643 int32_t lo = 0;
644 int32_t hi = NumStringIds() - 1;
645 while (hi >= lo) {
646 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700647 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700648 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000649 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700650 if (compare > 0) {
651 lo = mid + 1;
652 } else if (compare < 0) {
653 hi = mid - 1;
654 } else {
655 return &str_id;
656 }
657 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700658 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700659}
660
661const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700662 int32_t lo = 0;
663 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700664 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700665 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700666 const TypeId& type_id = GetTypeId(mid);
667 if (string_idx > type_id.descriptor_idx_) {
668 lo = mid + 1;
669 } else if (string_idx < type_id.descriptor_idx_) {
670 hi = mid - 1;
671 } else {
672 return &type_id;
673 }
674 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700675 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700676}
677
678const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000679 const uint16_t* signature_type_idxs,
680 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700681 int32_t lo = 0;
682 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700683 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700684 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700685 const DexFile::ProtoId& proto = GetProtoId(mid);
686 int compare = return_type_idx - proto.return_type_idx_;
687 if (compare == 0) {
688 DexFileParameterIterator it(*this, proto);
689 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000690 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800691 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700692 it.Next();
693 i++;
694 }
695 if (compare == 0) {
696 if (it.HasNext()) {
697 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000698 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700699 compare = 1;
700 }
701 }
702 }
703 if (compare > 0) {
704 lo = mid + 1;
705 } else if (compare < 0) {
706 hi = mid - 1;
707 } else {
708 return &proto;
709 }
710 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700711 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700712}
713
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000714void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
715 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300716}
717
Ian Rogers0571d352011-11-03 19:51:38 -0700718// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700719bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
720 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700721 if (signature[0] != '(') {
722 return false;
723 }
724 size_t offset = 1;
725 size_t end = signature.size();
726 bool process_return = false;
727 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000728 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700729 char c = signature[offset];
730 offset++;
731 if (c == ')') {
732 process_return = true;
733 continue;
734 }
Ian Rogers0571d352011-11-03 19:51:38 -0700735 while (c == '[') { // process array prefix
736 if (offset >= end) { // expect some descriptor following [
737 return false;
738 }
739 c = signature[offset];
740 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700741 }
742 if (c == 'L') { // process type descriptors
743 do {
744 if (offset >= end) { // unexpected early termination of descriptor
745 return false;
746 }
747 c = signature[offset];
748 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700749 } while (c != ';');
750 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000751 // TODO: avoid creating a std::string just to get a 0-terminated char array
752 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700753 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700754 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700755 return false;
756 }
757 uint16_t type_idx = GetIndexForTypeId(*type_id);
758 if (!process_return) {
759 param_type_idxs->push_back(type_idx);
760 } else {
761 *return_type_idx = type_idx;
762 return offset == end; // return true if the signature had reached a sensible end
763 }
764 }
765 return false; // failed to correctly parse return type
766}
767
Ian Rogersd91d6d62013-09-25 20:26:14 -0700768const Signature DexFile::CreateSignature(const StringPiece& signature) const {
769 uint16_t return_type_idx;
770 std::vector<uint16_t> param_type_indices;
771 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
772 if (!success) {
773 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700774 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700775 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700776 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700777 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700778 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700779 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700780}
781
Mathieu Chartiere401d142015-04-22 13:56:20 -0700782int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700783 // For native method, lineno should be -2 to indicate it is native. Note that
784 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700785 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700786 return -2;
787 }
788
TDYa127c8dc1012012-04-19 07:03:33 -0700789 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700791
792 // A method with no line number info should return -1
793 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000794 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700795 return context.line_num_;
796}
797
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700798int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700799 // Note: Signed type is important for max and min.
800 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700801 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700802
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700803 while (min <= max) {
804 int32_t mid = min + ((max - min) / 2);
805
806 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
807 uint32_t start = ti->start_addr_;
808 uint32_t end = start + ti->insn_count_;
809
Ian Rogers0571d352011-11-03 19:51:38 -0700810 if (address < start) {
811 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700812 } else if (address >= end) {
813 min = mid + 1;
814 } else { // We have a winner!
815 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700816 }
817 }
818 // No match.
819 return -1;
820}
821
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700822int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
823 int32_t try_item = FindTryItem(code_item, address);
824 if (try_item == -1) {
825 return -1;
826 } else {
827 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
828 }
829}
830
David Srbeckyb06e28e2015-12-10 13:15:00 +0000831bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
832 DexDebugNewLocalCb local_cb, void* context) const {
833 DCHECK(local_cb != nullptr);
834 if (code_item == nullptr) {
835 return false;
836 }
837 const uint8_t* stream = GetDebugInfoStream(code_item);
838 if (stream == nullptr) {
839 return false;
840 }
841 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700842
David Srbeckyb06e28e2015-12-10 13:15:00 +0000843 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800844 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000845 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
846 local_in_reg[arg_reg].name_ = "this";
847 local_in_reg[arg_reg].descriptor_ = descriptor;
848 local_in_reg[arg_reg].signature_ = nullptr;
849 local_in_reg[arg_reg].start_address_ = 0;
850 local_in_reg[arg_reg].reg_ = arg_reg;
851 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700852 arg_reg++;
853 }
854
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800855 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000856 DecodeUnsignedLeb128(&stream); // Line.
857 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
858 uint32_t i;
859 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700860 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700861 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800862 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000863 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700864 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000865 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700866 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000867 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
868 local_in_reg[arg_reg].descriptor_ = descriptor;
869 local_in_reg[arg_reg].signature_ = nullptr;
870 local_in_reg[arg_reg].start_address_ = 0;
871 local_in_reg[arg_reg].reg_ = arg_reg;
872 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700873 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700874 case 'D':
875 case 'J':
876 arg_reg += 2;
877 break;
878 default:
879 arg_reg += 1;
880 break;
881 }
882 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000883 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800884 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
885 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000886 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 }
888
David Srbeckyb06e28e2015-12-10 13:15:00 +0000889 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890 for (;;) {
891 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700892 switch (opcode) {
893 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000894 // Emit all variables which are still alive at the end of the method.
895 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
896 if (local_in_reg[reg].is_live_) {
897 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
898 local_cb(context, local_in_reg[reg]);
899 }
900 }
901 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700902 case DBG_ADVANCE_PC:
903 address += DecodeUnsignedLeb128(&stream);
904 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700905 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700908 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000909 case DBG_START_LOCAL_EXTENDED: {
910 uint16_t reg = DecodeUnsignedLeb128(&stream);
911 if (reg >= code_item->registers_size_) {
912 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800913 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000914 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700915 }
916
David Srbeckyb06e28e2015-12-10 13:15:00 +0000917 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
918 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
919 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700920 if (opcode == DBG_START_LOCAL_EXTENDED) {
921 signature_idx = DecodeUnsignedLeb128P1(&stream);
922 }
923
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000925 if (local_in_reg[reg].is_live_) {
926 local_in_reg[reg].end_address_ = address;
927 local_cb(context, local_in_reg[reg]);
928 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929
David Srbeckyb06e28e2015-12-10 13:15:00 +0000930 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
931 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
932 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
933 local_in_reg[reg].start_address_ = address;
934 local_in_reg[reg].reg_ = reg;
935 local_in_reg[reg].is_live_ = true;
936 break;
937 }
938 case DBG_END_LOCAL: {
939 uint16_t reg = DecodeUnsignedLeb128(&stream);
940 if (reg >= code_item->registers_size_) {
941 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
942 << code_item->registers_size_ << ") in " << GetLocation();
943 return false;
944 }
945 if (!local_in_reg[reg].is_live_) {
946 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
947 return false;
948 }
949 local_in_reg[reg].end_address_ = address;
950 local_cb(context, local_in_reg[reg]);
951 local_in_reg[reg].is_live_ = false;
952 break;
953 }
954 case DBG_RESTART_LOCAL: {
955 uint16_t reg = DecodeUnsignedLeb128(&stream);
956 if (reg >= code_item->registers_size_) {
957 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
958 << code_item->registers_size_ << ") in " << GetLocation();
959 return false;
960 }
961 // If the register is live, the "restart" is superfluous,
962 // and we don't want to mess with the existing start address.
963 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700964 local_in_reg[reg].start_address_ = address;
965 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700966 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700967 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000968 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969 case DBG_SET_PROLOGUE_END:
970 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700971 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000972 case DBG_SET_FILE:
973 DecodeUnsignedLeb128P1(&stream); // name.
974 break;
975 default:
976 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
977 break;
978 }
979 }
980}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981
David Srbeckyb06e28e2015-12-10 13:15:00 +0000982bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
983 void* context) const {
984 DCHECK(position_cb != nullptr);
985 if (code_item == nullptr) {
986 return false;
987 }
988 const uint8_t* stream = GetDebugInfoStream(code_item);
989 if (stream == nullptr) {
990 return false;
991 }
992
993 PositionInfo entry = PositionInfo();
994 entry.line_ = DecodeUnsignedLeb128(&stream);
995 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
996 for (uint32_t i = 0; i < parameters_size; ++i) {
997 DecodeUnsignedLeb128P1(&stream); // Parameter name.
998 }
999
1000 for (;;) {
1001 uint8_t opcode = *stream++;
1002 switch (opcode) {
1003 case DBG_END_SEQUENCE:
1004 return true; // end of stream.
1005 case DBG_ADVANCE_PC:
1006 entry.address_ += DecodeUnsignedLeb128(&stream);
1007 break;
1008 case DBG_ADVANCE_LINE:
1009 entry.line_ += DecodeSignedLeb128(&stream);
1010 break;
1011 case DBG_START_LOCAL:
1012 DecodeUnsignedLeb128(&stream); // reg.
1013 DecodeUnsignedLeb128P1(&stream); // name.
1014 DecodeUnsignedLeb128P1(&stream); // descriptor.
1015 break;
1016 case DBG_START_LOCAL_EXTENDED:
1017 DecodeUnsignedLeb128(&stream); // reg.
1018 DecodeUnsignedLeb128P1(&stream); // name.
1019 DecodeUnsignedLeb128P1(&stream); // descriptor.
1020 DecodeUnsignedLeb128P1(&stream); // signature.
1021 break;
1022 case DBG_END_LOCAL:
1023 case DBG_RESTART_LOCAL:
1024 DecodeUnsignedLeb128(&stream); // reg.
1025 break;
1026 case DBG_SET_PROLOGUE_END:
1027 entry.prologue_end_ = true;
1028 break;
1029 case DBG_SET_EPILOGUE_BEGIN:
1030 entry.epilogue_begin_ = true;
1031 break;
1032 case DBG_SET_FILE: {
1033 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1034 entry.source_file_ = StringDataByIdx(name_idx);
1035 break;
1036 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001037 default: {
1038 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001039 entry.address_ += adjopcode / DBG_LINE_RANGE;
1040 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1041 if (position_cb(context, entry)) {
1042 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001043 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001044 entry.prologue_end_ = false;
1045 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001046 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001047 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001048 }
1049 }
1050}
1051
David Srbeckyb06e28e2015-12-10 13:15:00 +00001052bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001053 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001054
1055 // We know that this callback will be called in
1056 // ascending address order, so keep going until we find
1057 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001058 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001059 // The line number from the previous positions callback
1060 // wil be the final result.
1061 return true;
1062 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001063 context->line_num_ = entry.line_;
1064 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001065 }
1066}
1067
Andreas Gampe833a4852014-05-21 18:46:59 -07001068bool DexFile::IsMultiDexLocation(const char* location) {
1069 return strrchr(location, kMultiDexSeparator) != nullptr;
1070}
1071
Andreas Gampe90e34042015-04-27 20:01:52 -07001072std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1073 if (index == 0) {
1074 return "classes.dex";
1075 } else {
1076 return StringPrintf("classes%zu.dex", index + 1);
1077 }
1078}
1079
1080std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1081 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001082 return dex_location;
1083 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001084 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001085 }
1086}
1087
1088std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1089 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001090 std::string base_location = GetBaseLocation(dex_location);
1091 const char* suffix = dex_location + base_location.size();
1092 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1093 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1094 if (path != nullptr && path.get() != base_location) {
1095 return std::string(path.get()) + suffix;
1096 } else if (suffix[0] == 0) {
1097 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001098 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001099 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001100 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001101}
1102
Jeff Hao13e748b2015-08-25 20:44:19 +00001103// Read a signed integer. "zwidth" is the zero-based byte count.
1104static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1105 int32_t val = 0;
1106 for (int i = zwidth; i >= 0; --i) {
1107 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1108 }
1109 val >>= (3 - zwidth) * 8;
1110 return val;
1111}
1112
1113// Read an unsigned integer. "zwidth" is the zero-based byte count,
1114// "fill_on_right" indicates which side we want to zero-fill from.
1115static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1116 uint32_t val = 0;
1117 for (int i = zwidth; i >= 0; --i) {
1118 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1119 }
1120 if (!fill_on_right) {
1121 val >>= (3 - zwidth) * 8;
1122 }
1123 return val;
1124}
1125
1126// Read a signed long. "zwidth" is the zero-based byte count.
1127static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1128 int64_t val = 0;
1129 for (int i = zwidth; i >= 0; --i) {
1130 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1131 }
1132 val >>= (7 - zwidth) * 8;
1133 return val;
1134}
1135
1136// Read an unsigned long. "zwidth" is the zero-based byte count,
1137// "fill_on_right" indicates which side we want to zero-fill from.
1138static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1139 uint64_t val = 0;
1140 for (int i = zwidth; i >= 0; --i) {
1141 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1142 }
1143 if (!fill_on_right) {
1144 val >>= (7 - zwidth) * 8;
1145 }
1146 return val;
1147}
1148
1149const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1150 mirror::Class* klass = field->GetDeclaringClass();
1151 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1152 if (annotations_dir == nullptr) {
1153 return nullptr;
1154 }
1155 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1156 if (field_annotations == nullptr) {
1157 return nullptr;
1158 }
1159 uint32_t field_index = field->GetDexFieldIndex();
1160 uint32_t field_count = annotations_dir->fields_size_;
1161 for (uint32_t i = 0; i < field_count; ++i) {
1162 if (field_annotations[i].field_idx_ == field_index) {
1163 return GetFieldAnnotationSetItem(field_annotations[i]);
1164 }
1165 }
1166 return nullptr;
1167}
1168
1169mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1170 Handle<mirror::Class> annotation_class) const {
1171 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1172 if (annotation_set == nullptr) {
1173 return nullptr;
1174 }
1175 StackHandleScope<1> hs(Thread::Current());
1176 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1177 return GetAnnotationObjectFromAnnotationSet(
1178 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1179}
1180
1181mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1182 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1183 StackHandleScope<1> hs(Thread::Current());
1184 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1185 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1186}
1187
Jeff Hao2a5892f2015-08-31 15:00:40 -07001188mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001189 const {
1190 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1191 if (annotation_set == nullptr) {
1192 return nullptr;
1193 }
1194 StackHandleScope<1> hs(Thread::Current());
1195 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1196 return GetSignatureValue(field_class, annotation_set);
1197}
1198
1199bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1200 const {
1201 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1202 if (annotation_set == nullptr) {
1203 return false;
1204 }
1205 StackHandleScope<1> hs(Thread::Current());
1206 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1207 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1208 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1209 return annotation_item != nullptr;
1210}
1211
1212const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1213 mirror::Class* klass = method->GetDeclaringClass();
1214 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1215 if (annotations_dir == nullptr) {
1216 return nullptr;
1217 }
1218 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1219 if (method_annotations == nullptr) {
1220 return nullptr;
1221 }
1222 uint32_t method_index = method->GetDexMethodIndex();
1223 uint32_t method_count = annotations_dir->methods_size_;
1224 for (uint32_t i = 0; i < method_count; ++i) {
1225 if (method_annotations[i].method_idx_ == method_index) {
1226 return GetMethodAnnotationSetItem(method_annotations[i]);
1227 }
1228 }
1229 return nullptr;
1230}
1231
1232const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1233 const {
1234 mirror::Class* klass = method->GetDeclaringClass();
1235 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1236 if (annotations_dir == nullptr) {
1237 return nullptr;
1238 }
1239 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1240 if (parameter_annotations == nullptr) {
1241 return nullptr;
1242 }
1243 uint32_t method_index = method->GetDexMethodIndex();
1244 uint32_t parameter_count = annotations_dir->parameters_size_;
1245 for (uint32_t i = 0; i < parameter_count; ++i) {
1246 if (parameter_annotations[i].method_idx_ == method_index) {
1247 return &parameter_annotations[i];
1248 }
1249 }
1250 return nullptr;
1251}
1252
1253mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1254 mirror::Class* klass = method->GetDeclaringClass();
1255 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1256 if (annotations_dir == nullptr) {
1257 return nullptr;
1258 }
1259 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1260 if (annotation_set == nullptr) {
1261 return nullptr;
1262 }
1263 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1264 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1265 if (annotation_item == nullptr) {
1266 return nullptr;
1267 }
1268 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1269 if (annotation == nullptr) {
1270 return nullptr;
1271 }
1272 uint8_t header_byte = *(annotation++);
1273 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1274 return nullptr;
1275 }
1276 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1277 if (annotation == nullptr) {
1278 return nullptr;
1279 }
1280 AnnotationValue annotation_value;
1281 StackHandleScope<2> hs(Thread::Current());
1282 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001283 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1284 Handle<mirror::Class> return_type(hs.NewHandle(
1285 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001286 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1287 return nullptr;
1288 }
1289 return annotation_value.value_.GetL();
1290}
1291
1292mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1293 Handle<mirror::Class> annotation_class) const {
1294 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1295 if (annotation_set == nullptr) {
1296 return nullptr;
1297 }
1298 StackHandleScope<1> hs(Thread::Current());
1299 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1300 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1301 kDexVisibilityRuntime, annotation_class);
1302}
1303
1304mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1305 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1306 StackHandleScope<1> hs(Thread::Current());
1307 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1308 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1309}
1310
Jeff Hao2a5892f2015-08-31 15:00:40 -07001311mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001312 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1313 if (annotation_set == nullptr) {
1314 return nullptr;
1315 }
1316 StackHandleScope<1> hs(Thread::Current());
1317 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1318 return GetThrowsValue(method_class, annotation_set);
1319}
1320
1321mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1322 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1323 if (parameter_annotations == nullptr) {
1324 return nullptr;
1325 }
1326 const AnnotationSetRefList* set_ref_list =
1327 GetParameterAnnotationSetRefList(parameter_annotations);
1328 if (set_ref_list == nullptr) {
1329 return nullptr;
1330 }
1331 uint32_t size = set_ref_list->size_;
1332 StackHandleScope<1> hs(Thread::Current());
1333 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1334 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1335}
1336
1337bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1338 const {
1339 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1340 if (annotation_set == nullptr) {
1341 return false;
1342 }
1343 StackHandleScope<1> hs(Thread::Current());
1344 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1345 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1346 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001347 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001348}
1349
1350const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1351 const {
1352 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1353 if (annotations_dir == nullptr) {
1354 return nullptr;
1355 }
1356 return GetClassAnnotationSet(annotations_dir);
1357}
1358
1359mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1360 Handle<mirror::Class> annotation_class) const {
1361 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1362 if (annotation_set == nullptr) {
1363 return nullptr;
1364 }
1365 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1366 annotation_class);
1367}
1368
1369mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1370 const {
1371 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1372 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1373}
1374
Jeff Hao2a5892f2015-08-31 15:00:40 -07001375mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1376 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1377 if (annotation_set == nullptr) {
1378 return nullptr;
1379 }
1380 const AnnotationItem* annotation_item = SearchAnnotationSet(
1381 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1382 if (annotation_item == nullptr) {
1383 return nullptr;
1384 }
1385 StackHandleScope<1> hs(Thread::Current());
1386 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1387 Handle<mirror::Class> class_array_class(hs.NewHandle(
1388 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1389 if (class_array_class.Get() == nullptr) {
1390 return nullptr;
1391 }
1392 mirror::Object* obj = GetAnnotationValue(
1393 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1394 if (obj == nullptr) {
1395 return nullptr;
1396 }
1397 return obj->AsObjectArray<mirror::Class>();
1398}
1399
1400mirror::Class* DexFile::GetDeclaringClass(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/EnclosingClass;", kDexVisibilitySystem);
1407 if (annotation_item == nullptr) {
1408 return nullptr;
1409 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001410 mirror::Object* obj = GetAnnotationValue(klass,
1411 annotation_item,
1412 "value",
1413 ScopedNullHandle<mirror::Class>(),
1414 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001415 if (obj == nullptr) {
1416 return nullptr;
1417 }
1418 return obj->AsClass();
1419}
1420
1421mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1422 mirror::Class* declaring_class = GetDeclaringClass(klass);
1423 if (declaring_class != nullptr) {
1424 return declaring_class;
1425 }
1426 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1427 if (annotation_set == nullptr) {
1428 return nullptr;
1429 }
1430 const AnnotationItem* annotation_item = SearchAnnotationSet(
1431 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1432 if (annotation_item == nullptr) {
1433 return nullptr;
1434 }
1435 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1436 if (annotation == nullptr) {
1437 return nullptr;
1438 }
1439 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001440 if (!ProcessAnnotationValue(klass,
1441 &annotation,
1442 &annotation_value,
1443 ScopedNullHandle<mirror::Class>(),
1444 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001445 return nullptr;
1446 }
1447 if (annotation_value.type_ != kDexAnnotationMethod) {
1448 return nullptr;
1449 }
1450 StackHandleScope<2> hs(Thread::Current());
1451 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1452 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1453 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1454 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1455 if (method == nullptr) {
1456 return nullptr;
1457 }
1458 return method->GetDeclaringClass();
1459}
1460
1461mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1462 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1463 if (annotation_set == nullptr) {
1464 return nullptr;
1465 }
1466 const AnnotationItem* annotation_item = SearchAnnotationSet(
1467 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1468 if (annotation_item == nullptr) {
1469 return nullptr;
1470 }
1471 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001472 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001473}
1474
1475bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1476 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1477 if (annotation_set == nullptr) {
1478 return false;
1479 }
1480 const AnnotationItem* annotation_item = SearchAnnotationSet(
1481 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1482 if (annotation_item == nullptr) {
1483 return false;
1484 }
1485 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1486 if (annotation == nullptr) {
1487 return false;
1488 }
1489 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001490 if (!ProcessAnnotationValue(klass,
1491 &annotation,
1492 &annotation_value,
1493 ScopedNullHandle<mirror::Class>(),
1494 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001495 return false;
1496 }
1497 if (annotation_value.type_ != kDexAnnotationNull &&
1498 annotation_value.type_ != kDexAnnotationString) {
1499 return false;
1500 }
1501 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1502 return true;
1503}
1504
1505bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1506 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1507 if (annotation_set == nullptr) {
1508 return false;
1509 }
1510 const AnnotationItem* annotation_item = SearchAnnotationSet(
1511 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1512 if (annotation_item == nullptr) {
1513 return false;
1514 }
1515 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1516 if (annotation == nullptr) {
1517 return false;
1518 }
1519 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001520 if (!ProcessAnnotationValue(klass,
1521 &annotation,
1522 &annotation_value,
1523 ScopedNullHandle<mirror::Class>(),
1524 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001525 return false;
1526 }
1527 if (annotation_value.type_ != kDexAnnotationInt) {
1528 return false;
1529 }
1530 *flags = annotation_value.value_.GetI();
1531 return true;
1532}
1533
Jeff Hao13e748b2015-08-25 20:44:19 +00001534bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1535 Handle<mirror::Class> annotation_class) const {
1536 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1537 if (annotation_set == nullptr) {
1538 return false;
1539 }
1540 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1541 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001542 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001543}
1544
1545mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1546 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1547 Thread* self = Thread::Current();
1548 ScopedObjectAccessUnchecked soa(self);
1549 StackHandleScope<5> hs(self);
1550 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1551 const char* name = StringDataByIdx(element_name_index);
1552 Handle<mirror::String> string_name(
1553 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1554
1555 ArtMethod* annotation_method =
1556 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1557 if (annotation_method == nullptr) {
1558 return nullptr;
1559 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001560 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1561 Handle<mirror::Class> method_return(hs.NewHandle(
1562 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001563
1564 AnnotationValue annotation_value;
1565 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1566 return nullptr;
1567 }
1568 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1569
1570 mirror::Class* annotation_member_class =
1571 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1572 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1573 Handle<mirror::Method> method_object(
1574 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1575
1576 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1577 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1578 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1579 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1580 return nullptr;
1581 }
1582
1583 JValue result;
1584 ArtMethod* annotation_member_init =
1585 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1586 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1587 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1588 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1589 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1590 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1591 };
1592 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1593 if (self->IsExceptionPending()) {
1594 LOG(INFO) << "Exception in AnnotationMember.<init>";
1595 return nullptr;
1596 }
1597
1598 return new_member.Get();
1599}
1600
1601const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1602 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1603 Handle<mirror::Class> annotation_class) const {
1604 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1605 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1606 if (annotation_item->visibility_ != visibility) {
1607 continue;
1608 }
1609 const uint8_t* annotation = annotation_item->annotation_;
1610 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1611 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1612 klass->GetDexFile(), type_index, klass.Get());
1613 if (resolved_class == nullptr) {
1614 std::string temp;
1615 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1616 klass->GetDescriptor(&temp), type_index);
1617 CHECK(Thread::Current()->IsExceptionPending());
1618 Thread::Current()->ClearException();
1619 continue;
1620 }
1621 if (resolved_class == annotation_class.Get()) {
1622 return annotation_item;
1623 }
1624 }
1625
1626 return nullptr;
1627}
1628
1629mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1630 const AnnotationSetItem* annotation_set, uint32_t visibility,
1631 Handle<mirror::Class> annotation_class) const {
1632 const AnnotationItem* annotation_item =
1633 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1634 if (annotation_item == nullptr) {
1635 return nullptr;
1636 }
1637 const uint8_t* annotation = annotation_item->annotation_;
1638 return ProcessEncodedAnnotation(klass, &annotation);
1639}
1640
1641mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1642 const AnnotationItem* annotation_item, const char* annotation_name,
1643 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1644 const uint8_t* annotation =
1645 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1646 if (annotation == nullptr) {
1647 return nullptr;
1648 }
1649 AnnotationValue annotation_value;
1650 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1651 return nullptr;
1652 }
1653 if (annotation_value.type_ != expected_type) {
1654 return nullptr;
1655 }
1656 return annotation_value.value_.GetL();
1657}
1658
Jeff Hao2a5892f2015-08-31 15:00:40 -07001659mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001660 const AnnotationSetItem* annotation_set) const {
1661 StackHandleScope<1> hs(Thread::Current());
1662 const AnnotationItem* annotation_item =
1663 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1664 if (annotation_item == nullptr) {
1665 return nullptr;
1666 }
1667 mirror::Class* string_class = mirror::String::GetJavaLangString();
1668 Handle<mirror::Class> string_array_class(hs.NewHandle(
1669 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001670 if (string_array_class.Get() == nullptr) {
1671 return nullptr;
1672 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001673 mirror::Object* obj =
1674 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1675 if (obj == nullptr) {
1676 return nullptr;
1677 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001678 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001679}
1680
Jeff Hao2a5892f2015-08-31 15:00:40 -07001681mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001682 const AnnotationSetItem* annotation_set) const {
1683 StackHandleScope<1> hs(Thread::Current());
1684 const AnnotationItem* annotation_item =
1685 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1686 if (annotation_item == nullptr) {
1687 return nullptr;
1688 }
1689 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1690 Handle<mirror::Class> class_array_class(hs.NewHandle(
1691 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001692 if (class_array_class.Get() == nullptr) {
1693 return nullptr;
1694 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001695 mirror::Object* obj =
1696 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1697 if (obj == nullptr) {
1698 return nullptr;
1699 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001700 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001701}
1702
1703mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1704 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1705 Thread* self = Thread::Current();
1706 ScopedObjectAccessUnchecked soa(self);
1707 StackHandleScope<2> hs(self);
1708 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1709 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1710 if (annotation_set == nullptr) {
1711 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1712 }
1713
1714 uint32_t size = annotation_set->size_;
1715 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1716 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1717 if (result.Get() == nullptr) {
1718 return nullptr;
1719 }
1720
1721 uint32_t dest_index = 0;
1722 for (uint32_t i = 0; i < size; ++i) {
1723 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1724 if (annotation_item->visibility_ != visibility) {
1725 continue;
1726 }
1727 const uint8_t* annotation = annotation_item->annotation_;
1728 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1729 if (annotation_obj != nullptr) {
1730 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1731 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001732 } else if (self->IsExceptionPending()) {
1733 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001734 }
1735 }
1736
1737 if (dest_index == size) {
1738 return result.Get();
1739 }
1740
1741 mirror::ObjectArray<mirror::Object>* trimmed_result =
1742 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001743 if (trimmed_result == nullptr) {
1744 return nullptr;
1745 }
1746
Jeff Hao13e748b2015-08-25 20:44:19 +00001747 for (uint32_t i = 0; i < dest_index; ++i) {
1748 mirror::Object* obj = result->GetWithoutChecks(i);
1749 trimmed_result->SetWithoutChecks<false>(i, obj);
1750 }
1751
1752 return trimmed_result;
1753}
1754
1755mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1756 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1757 Thread* self = Thread::Current();
1758 ScopedObjectAccessUnchecked soa(self);
1759 StackHandleScope<1> hs(self);
1760 mirror::Class* annotation_array_class =
1761 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1762 mirror::Class* annotation_array_array_class =
1763 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001764 if (annotation_array_array_class == nullptr) {
1765 return nullptr;
1766 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001767 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1768 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1769 if (annotation_array_array.Get() == nullptr) {
1770 LOG(ERROR) << "Annotation set ref array allocation failed";
1771 return nullptr;
1772 }
1773 for (uint32_t index = 0; index < size; ++index) {
1774 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1775 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1776 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1777 if (annotation_set == nullptr) {
1778 return nullptr;
1779 }
1780 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1781 }
1782 return annotation_array_array.Get();
1783}
1784
1785bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1786 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1787 DexFile::AnnotationResultStyle result_style) const {
1788 Thread* self = Thread::Current();
1789 mirror::Object* element_object = nullptr;
1790 bool set_object = false;
1791 Primitive::Type primitive_type = Primitive::kPrimVoid;
1792 const uint8_t* annotation = *annotation_ptr;
1793 uint8_t header_byte = *(annotation++);
1794 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1795 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1796 int32_t width = value_arg + 1;
1797 annotation_value->type_ = value_type;
1798
1799 switch (value_type) {
1800 case kDexAnnotationByte:
1801 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1802 primitive_type = Primitive::kPrimByte;
1803 break;
1804 case kDexAnnotationShort:
1805 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1806 primitive_type = Primitive::kPrimShort;
1807 break;
1808 case kDexAnnotationChar:
1809 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1810 false)));
1811 primitive_type = Primitive::kPrimChar;
1812 break;
1813 case kDexAnnotationInt:
1814 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1815 primitive_type = Primitive::kPrimInt;
1816 break;
1817 case kDexAnnotationLong:
1818 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1819 primitive_type = Primitive::kPrimLong;
1820 break;
1821 case kDexAnnotationFloat:
1822 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1823 primitive_type = Primitive::kPrimFloat;
1824 break;
1825 case kDexAnnotationDouble:
1826 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1827 primitive_type = Primitive::kPrimDouble;
1828 break;
1829 case kDexAnnotationBoolean:
1830 annotation_value->value_.SetZ(value_arg != 0);
1831 primitive_type = Primitive::kPrimBoolean;
1832 width = 0;
1833 break;
1834 case kDexAnnotationString: {
1835 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1836 if (result_style == kAllRaw) {
1837 annotation_value->value_.SetI(index);
1838 } else {
1839 StackHandleScope<1> hs(self);
1840 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1841 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1842 klass->GetDexFile(), index, dex_cache);
1843 set_object = true;
1844 if (element_object == nullptr) {
1845 return false;
1846 }
1847 }
1848 break;
1849 }
1850 case kDexAnnotationType: {
1851 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1852 if (result_style == kAllRaw) {
1853 annotation_value->value_.SetI(index);
1854 } else {
1855 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1856 klass->GetDexFile(), index, klass.Get());
1857 set_object = true;
1858 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001859 CHECK(self->IsExceptionPending());
1860 if (result_style == kAllObjects) {
1861 const char* msg = StringByTypeIdx(index);
1862 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1863 element_object = self->GetException();
1864 self->ClearException();
1865 } else {
1866 return false;
1867 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001868 }
1869 }
1870 break;
1871 }
1872 case kDexAnnotationMethod: {
1873 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1874 if (result_style == kAllRaw) {
1875 annotation_value->value_.SetI(index);
1876 } else {
1877 StackHandleScope<2> hs(self);
1878 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1879 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1880 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1881 klass->GetDexFile(), index, dex_cache, class_loader);
1882 if (method == nullptr) {
1883 return false;
1884 }
1885 set_object = true;
1886 if (method->IsConstructor()) {
1887 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1888 } else {
1889 element_object = mirror::Method::CreateFromArtMethod(self, method);
1890 }
1891 if (element_object == nullptr) {
1892 return false;
1893 }
1894 }
1895 break;
1896 }
1897 case kDexAnnotationField: {
1898 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1899 if (result_style == kAllRaw) {
1900 annotation_value->value_.SetI(index);
1901 } else {
1902 StackHandleScope<2> hs(self);
1903 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1904 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1905 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1906 klass->GetDexFile(), index, dex_cache, class_loader);
1907 if (field == nullptr) {
1908 return false;
1909 }
1910 set_object = true;
1911 element_object = mirror::Field::CreateFromArtField(self, field, true);
1912 if (element_object == nullptr) {
1913 return false;
1914 }
1915 }
1916 break;
1917 }
1918 case kDexAnnotationEnum: {
1919 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1920 if (result_style == kAllRaw) {
1921 annotation_value->value_.SetI(index);
1922 } else {
1923 StackHandleScope<3> hs(self);
1924 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1925 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1926 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1927 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001928 if (enum_field == nullptr) {
1929 return false;
1930 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001931 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001932 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1933 element_object = enum_field->GetObject(field_class.Get());
1934 set_object = true;
1935 }
1936 }
1937 break;
1938 }
1939 case kDexAnnotationArray:
1940 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1941 return false;
1942 } else {
1943 ScopedObjectAccessUnchecked soa(self);
1944 StackHandleScope<2> hs(self);
1945 uint32_t size = DecodeUnsignedLeb128(&annotation);
1946 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1947 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1948 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1949 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1950 if (new_array.Get() == nullptr) {
1951 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1952 return false;
1953 }
1954 AnnotationValue new_annotation_value;
1955 for (uint32_t i = 0; i < size; ++i) {
1956 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1957 kPrimitivesOrObjects)) {
1958 return false;
1959 }
1960 if (!component_type->IsPrimitive()) {
1961 mirror::Object* obj = new_annotation_value.value_.GetL();
1962 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1963 } else {
1964 switch (new_annotation_value.type_) {
1965 case kDexAnnotationByte:
1966 new_array->AsByteArray()->SetWithoutChecks<false>(
1967 i, new_annotation_value.value_.GetB());
1968 break;
1969 case kDexAnnotationShort:
1970 new_array->AsShortArray()->SetWithoutChecks<false>(
1971 i, new_annotation_value.value_.GetS());
1972 break;
1973 case kDexAnnotationChar:
1974 new_array->AsCharArray()->SetWithoutChecks<false>(
1975 i, new_annotation_value.value_.GetC());
1976 break;
1977 case kDexAnnotationInt:
1978 new_array->AsIntArray()->SetWithoutChecks<false>(
1979 i, new_annotation_value.value_.GetI());
1980 break;
1981 case kDexAnnotationLong:
1982 new_array->AsLongArray()->SetWithoutChecks<false>(
1983 i, new_annotation_value.value_.GetJ());
1984 break;
1985 case kDexAnnotationFloat:
1986 new_array->AsFloatArray()->SetWithoutChecks<false>(
1987 i, new_annotation_value.value_.GetF());
1988 break;
1989 case kDexAnnotationDouble:
1990 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1991 i, new_annotation_value.value_.GetD());
1992 break;
1993 case kDexAnnotationBoolean:
1994 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1995 i, new_annotation_value.value_.GetZ());
1996 break;
1997 default:
1998 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1999 return false;
2000 }
2001 }
2002 }
2003 element_object = new_array.Get();
2004 set_object = true;
2005 width = 0;
2006 }
2007 break;
2008 case kDexAnnotationAnnotation:
2009 if (result_style == kAllRaw) {
2010 return false;
2011 }
2012 element_object = ProcessEncodedAnnotation(klass, &annotation);
2013 if (element_object == nullptr) {
2014 return false;
2015 }
2016 set_object = true;
2017 width = 0;
2018 break;
2019 case kDexAnnotationNull:
2020 if (result_style == kAllRaw) {
2021 annotation_value->value_.SetI(0);
2022 } else {
2023 CHECK(element_object == nullptr);
2024 set_object = true;
2025 }
2026 width = 0;
2027 break;
2028 default:
2029 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2030 return false;
2031 }
2032
2033 annotation += width;
2034 *annotation_ptr = annotation;
2035
2036 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2037 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2038 set_object = true;
2039 }
2040
2041 if (set_object) {
2042 annotation_value->value_.SetL(element_object);
2043 }
2044
2045 return true;
2046}
2047
2048mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2049 const uint8_t** annotation) const {
2050 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2051 uint32_t size = DecodeUnsignedLeb128(annotation);
2052
2053 Thread* self = Thread::Current();
2054 ScopedObjectAccessUnchecked soa(self);
2055 StackHandleScope<2> hs(self);
2056 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2057 Handle<mirror::Class> annotation_class(hs.NewHandle(
2058 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2059 if (annotation_class.Get() == nullptr) {
2060 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2061 << type_index;
2062 DCHECK(Thread::Current()->IsExceptionPending());
2063 Thread::Current()->ClearException();
2064 return nullptr;
2065 }
2066
2067 mirror::Class* annotation_member_class =
2068 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2069 mirror::Class* annotation_member_array_class =
2070 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002071 if (annotation_member_array_class == nullptr) {
2072 return nullptr;
2073 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002074 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002075 if (size > 0) {
2076 element_array =
2077 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2078 if (element_array == nullptr) {
2079 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2080 return nullptr;
2081 }
2082 }
2083
2084 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2085 for (uint32_t i = 0; i < size; ++i) {
2086 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2087 if (new_member == nullptr) {
2088 return nullptr;
2089 }
2090 h_element_array->SetWithoutChecks<false>(i, new_member);
2091 }
2092
2093 JValue result;
2094 ArtMethod* create_annotation_method =
2095 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2096 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2097 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2098 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2099 if (self->IsExceptionPending()) {
2100 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2101 return nullptr;
2102 }
2103
2104 return result.GetL();
2105}
2106
2107const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2108 const char* descriptor, uint32_t visibility) const {
2109 const AnnotationItem* result = nullptr;
2110 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2111 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2112 if (annotation_item->visibility_ != visibility) {
2113 continue;
2114 }
2115 const uint8_t* annotation = annotation_item->annotation_;
2116 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2117
2118 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2119 result = annotation_item;
2120 break;
2121 }
2122 }
2123 return result;
2124}
2125
2126const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2127 DecodeUnsignedLeb128(&annotation); // unused type_index
2128 uint32_t size = DecodeUnsignedLeb128(&annotation);
2129
2130 while (size != 0) {
2131 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2132 const char* element_name = GetStringData(GetStringId(element_name_index));
2133 if (strcmp(name, element_name) == 0) {
2134 return annotation;
2135 }
2136 SkipAnnotationValue(&annotation);
2137 size--;
2138 }
2139 return nullptr;
2140}
2141
2142bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2143 const uint8_t* annotation = *annotation_ptr;
2144 uint8_t header_byte = *(annotation++);
2145 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2146 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2147 int32_t width = value_arg + 1;
2148
2149 switch (value_type) {
2150 case kDexAnnotationByte:
2151 case kDexAnnotationShort:
2152 case kDexAnnotationChar:
2153 case kDexAnnotationInt:
2154 case kDexAnnotationLong:
2155 case kDexAnnotationFloat:
2156 case kDexAnnotationDouble:
2157 case kDexAnnotationString:
2158 case kDexAnnotationType:
2159 case kDexAnnotationMethod:
2160 case kDexAnnotationField:
2161 case kDexAnnotationEnum:
2162 break;
2163 case kDexAnnotationArray:
2164 {
2165 uint32_t size = DecodeUnsignedLeb128(&annotation);
2166 while (size--) {
2167 if (!SkipAnnotationValue(&annotation)) {
2168 return false;
2169 }
2170 }
2171 width = 0;
2172 break;
2173 }
2174 case kDexAnnotationAnnotation:
2175 {
2176 DecodeUnsignedLeb128(&annotation); // unused type_index
2177 uint32_t size = DecodeUnsignedLeb128(&annotation);
2178 while (size--) {
2179 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2180 if (!SkipAnnotationValue(&annotation)) {
2181 return false;
2182 }
2183 }
2184 width = 0;
2185 break;
2186 }
2187 case kDexAnnotationBoolean:
2188 case kDexAnnotationNull:
2189 width = 0;
2190 break;
2191 default:
2192 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2193 return false;
2194 }
2195
2196 annotation += width;
2197 *annotation_ptr = annotation;
2198 return true;
2199}
2200
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002201std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2202 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2203 dex_file.GetLocation().c_str(),
2204 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2205 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2206 return os;
2207}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002208
Ian Rogersd91d6d62013-09-25 20:26:14 -07002209std::string Signature::ToString() const {
2210 if (dex_file_ == nullptr) {
2211 CHECK(proto_id_ == nullptr);
2212 return "<no signature>";
2213 }
2214 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2215 std::string result;
2216 if (params == nullptr) {
2217 result += "()";
2218 } else {
2219 result += "(";
2220 for (uint32_t i = 0; i < params->Size(); ++i) {
2221 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2222 }
2223 result += ")";
2224 }
2225 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2226 return result;
2227}
2228
Vladimir Markod9cffea2013-11-25 15:08:02 +00002229bool Signature::operator==(const StringPiece& rhs) const {
2230 if (dex_file_ == nullptr) {
2231 return false;
2232 }
2233 StringPiece tail(rhs);
2234 if (!tail.starts_with("(")) {
2235 return false; // Invalid signature
2236 }
2237 tail.remove_prefix(1); // "(";
2238 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2239 if (params != nullptr) {
2240 for (uint32_t i = 0; i < params->Size(); ++i) {
2241 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2242 if (!tail.starts_with(param)) {
2243 return false;
2244 }
2245 tail.remove_prefix(param.length());
2246 }
2247 }
2248 if (!tail.starts_with(")")) {
2249 return false;
2250 }
2251 tail.remove_prefix(1); // ")";
2252 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2253}
2254
Ian Rogersd91d6d62013-09-25 20:26:14 -07002255std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2256 return os << sig.ToString();
2257}
2258
Ian Rogers0571d352011-11-03 19:51:38 -07002259// Decodes the header section from the class data bytes.
2260void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002261 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002262 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2263 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2264 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2265 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2266}
2267
2268void ClassDataItemIterator::ReadClassDataField() {
2269 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2270 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002271 // The user of the iterator is responsible for checking if there
2272 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002273}
2274
2275void ClassDataItemIterator::ReadClassDataMethod() {
2276 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2277 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2278 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002279 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002280 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002281 }
Ian Rogers0571d352011-11-03 19:51:38 -07002282}
2283
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002284EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002285 const DexFile& dex_file,
2286 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002287 : EncodedStaticFieldValueIterator(dex_file,
2288 nullptr,
2289 nullptr,
2290 nullptr,
2291 class_def,
2292 -1,
2293 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002294}
2295
2296EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002297 const DexFile& dex_file,
2298 Handle<mirror::DexCache>* dex_cache,
2299 Handle<mirror::ClassLoader>* class_loader,
2300 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002301 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002302 : EncodedStaticFieldValueIterator(dex_file,
2303 dex_cache, class_loader,
2304 linker,
2305 class_def,
2306 -1,
2307 kByte) {
2308 DCHECK(dex_cache_ != nullptr);
2309 DCHECK(class_loader_ != nullptr);
2310}
2311
2312EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2313 const DexFile& dex_file,
2314 Handle<mirror::DexCache>* dex_cache,
2315 Handle<mirror::ClassLoader>* class_loader,
2316 ClassLinker* linker,
2317 const DexFile::ClassDef& class_def,
2318 size_t pos,
2319 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002320 : dex_file_(dex_file),
2321 dex_cache_(dex_cache),
2322 class_loader_(class_loader),
2323 linker_(linker),
2324 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002325 pos_(pos),
2326 type_(type) {
2327 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002328 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002329 array_size_ = 0;
2330 } else {
2331 array_size_ = DecodeUnsignedLeb128(&ptr_);
2332 }
2333 if (array_size_ > 0) {
2334 Next();
2335 }
2336}
2337
2338void EncodedStaticFieldValueIterator::Next() {
2339 pos_++;
2340 if (pos_ >= array_size_) {
2341 return;
2342 }
Ian Rogers13735952014-10-08 12:43:28 -07002343 uint8_t value_type = *ptr_++;
2344 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002345 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002346 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002347 switch (type_) {
2348 case kBoolean:
2349 jval_.i = (value_arg != 0) ? 1 : 0;
2350 width = 0;
2351 break;
2352 case kByte:
2353 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002354 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002355 break;
2356 case kShort:
2357 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002358 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002359 break;
2360 case kChar:
2361 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002362 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002363 break;
2364 case kInt:
2365 jval_.i = ReadSignedInt(ptr_, value_arg);
2366 break;
2367 case kLong:
2368 jval_.j = ReadSignedLong(ptr_, value_arg);
2369 break;
2370 case kFloat:
2371 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2372 break;
2373 case kDouble:
2374 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2375 break;
2376 case kString:
2377 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002378 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2379 break;
2380 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002381 case kMethod:
2382 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002383 case kArray:
2384 case kAnnotation:
2385 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002386 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002387 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002388 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002389 width = 0;
2390 break;
2391 default:
2392 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002393 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002394 }
2395 ptr_ += width;
2396}
2397
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002398template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002399void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002400 DCHECK(dex_cache_ != nullptr);
2401 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002402 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002403 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2404 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002405 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2406 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2407 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2408 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2409 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2410 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2411 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002412 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002413 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002414 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002415 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002416 break;
2417 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002418 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002419 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2420 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002421 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002422 break;
2423 }
Ian Rogers0571d352011-11-03 19:51:38 -07002424 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2425 }
2426}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002427template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2428template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002429
2430CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2431 handler_.address_ = -1;
2432 int32_t offset = -1;
2433
2434 // Short-circuit the overwhelmingly common cases.
2435 switch (code_item.tries_size_) {
2436 case 0:
2437 break;
2438 case 1: {
2439 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2440 uint32_t start = tries->start_addr_;
2441 if (address >= start) {
2442 uint32_t end = start + tries->insn_count_;
2443 if (address < end) {
2444 offset = tries->handler_off_;
2445 }
2446 }
2447 break;
2448 }
2449 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002450 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002451 }
Logan Chien736df022012-04-27 16:25:57 +08002452 Init(code_item, offset);
2453}
2454
2455CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2456 const DexFile::TryItem& try_item) {
2457 handler_.address_ = -1;
2458 Init(code_item, try_item.handler_off_);
2459}
2460
2461void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2462 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002463 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002464 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002465 } else {
2466 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002467 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002468 remaining_count_ = -1;
2469 catch_all_ = false;
2470 DCHECK(!HasNext());
2471 }
2472}
2473
Ian Rogers13735952014-10-08 12:43:28 -07002474void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002475 current_data_ = handler_data;
2476 remaining_count_ = DecodeSignedLeb128(&current_data_);
2477
2478 // If remaining_count_ is non-positive, then it is the negative of
2479 // the number of catch types, and the catches are followed by a
2480 // catch-all handler.
2481 if (remaining_count_ <= 0) {
2482 catch_all_ = true;
2483 remaining_count_ = -remaining_count_;
2484 } else {
2485 catch_all_ = false;
2486 }
2487 Next();
2488}
2489
2490void CatchHandlerIterator::Next() {
2491 if (remaining_count_ > 0) {
2492 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2493 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2494 remaining_count_--;
2495 return;
2496 }
2497
2498 if (catch_all_) {
2499 handler_.type_idx_ = DexFile::kDexNoIndex16;
2500 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2501 catch_all_ = false;
2502 return;
2503 }
2504
2505 // no more handler
2506 remaining_count_ = -1;
2507}
2508
Carl Shapiro1fb86202011-06-27 17:43:13 -07002509} // namespace art