blob: 62065be9a061110f88f2a7feeac4eb2377b4ae31 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010034#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080035#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000036#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080038#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070039#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030040#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070041#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000042#include "mirror/field.h"
43#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070045#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000046#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070047#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070048#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030049#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070050#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070051#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070052#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070053#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070054
Andreas Gampe277ccbd2014-11-03 21:36:10 -080055#pragma GCC diagnostic push
56#pragma GCC diagnostic ignored "-Wshadow"
57#include "ScopedFd.h"
58#pragma GCC diagnostic pop
59
Carl Shapiro1fb86202011-06-27 17:43:13 -070060namespace art {
61
Ian Rogers13735952014-10-08 12:43:28 -070062const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
63const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070064
Ian Rogers8d31bbd2013-10-13 10:44:14 -070065static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070066 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000067 ScopedFd fd(open(filename, O_RDONLY, 0));
68 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070070 return -1;
71 }
Vladimir Markofd995762013-11-06 16:36:36 +000072 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070073 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070074 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070075 return -1;
76 }
Vladimir Markofd995762013-11-06 16:36:36 +000077 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070078 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
79 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070080 return -1;
81 }
Vladimir Markofd995762013-11-06 16:36:36 +000082 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070083}
84
Ian Rogers8d31bbd2013-10-13 10:44:14 -070085bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070086 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070087 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070088
89 // Strip ":...", which is the location
90 const char* zip_entry_name = kClassesDex;
91 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010092 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070093
Vladimir Markoaa4497d2014-09-05 14:01:17 +010094 if (DexFile::IsMultiDexLocation(filename)) {
95 file_part_storage = GetBaseLocation(filename);
96 file_part = file_part_storage.c_str();
97 zip_entry_name = filename + file_part_storage.size() + 1;
98 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070099 }
100
101 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000102 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700103 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 return false;
105 }
106 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700107 std::unique_ptr<ZipArchive> zip_archive(
108 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
109 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800110 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
111 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700113 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700114 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700115 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700116 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
117 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 return false;
119 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700120 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700122 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700123 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 std::unique_ptr<const DexFile> dex_file(
125 DexFile::OpenFile(fd.release(), filename, false, error_msg));
126 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800127 return false;
128 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800130 return true;
131 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800133 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700134}
135
Andreas Gampe833a4852014-05-21 18:46:59 -0700136bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800137 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700138 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000140 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
141 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700142 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700144 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700145 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700146 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700147 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700148 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700149 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
150 error_msg));
151 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800152 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700153 return true;
154 } else {
155 return false;
156 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700157 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700158 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400159 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700160}
161
Andreas Gampe0cba0042015-04-29 20:47:16 -0700162static bool ContainsClassesDex(int fd, const char* filename) {
163 std::string error_msg;
164 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
165 if (zip_archive.get() == nullptr) {
166 return false;
167 }
168 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
169 return (zip_entry.get() != nullptr);
170}
171
172bool DexFile::MaybeDex(const char* filename) {
173 uint32_t magic;
174 std::string error_msg;
175 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
176 if (fd.get() == -1) {
177 return false;
178 }
179 if (IsZipMagic(magic)) {
180 return ContainsClassesDex(fd.release(), filename);
181 } else if (IsDexMagic(magic)) {
182 return true;
183 }
184 return false;
185}
186
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800187int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700188 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800189 return 0;
190 } else {
191 return mem_map_->GetProtect();
192 }
193}
194
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195bool DexFile::IsReadOnly() const {
196 return GetPermissions() == PROT_READ;
197}
198
Brian Carlstrome0948e12013-08-29 09:36:15 -0700199bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 return false;
203 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700204 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 }
206}
207
Brian Carlstrome0948e12013-08-29 09:36:15 -0700208bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200209 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700210 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200211 return false;
212 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700213 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200214 }
215}
216
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800217std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
218 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700219 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700220 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000221 {
222 ScopedFd delayed_close(fd);
223 struct stat sbuf;
224 memset(&sbuf, 0, sizeof(sbuf));
225 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800226 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000227 return nullptr;
228 }
229 if (S_ISDIR(sbuf.st_mode)) {
230 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
231 return nullptr;
232 }
233 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800234 map.reset(MemMap::MapFile(length,
235 PROT_READ,
236 MAP_PRIVATE,
237 fd,
238 0,
239 /*low_4gb*/false,
240 location,
241 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000242 if (map.get() == nullptr) {
243 DCHECK(!error_msg->empty());
244 return nullptr;
245 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700246 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800247
248 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700249 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800250 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700251 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800252 }
253
254 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
255
Andreas Gampe928f72b2014-09-09 19:53:48 -0700256 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
257 error_msg));
258 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
260 error_msg->c_str());
261 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800262 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800263
Andreas Gampe928f72b2014-09-09 19:53:48 -0700264 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
265 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700266 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800267 }
268
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800269 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700270}
271
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700272const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700273
Andreas Gampe833a4852014-05-21 18:46:59 -0700274bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800275 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700276 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700277 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700278 if (zip_archive.get() == nullptr) {
279 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700280 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700281 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700282 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800283}
284
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800285std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
286 uint32_t location_checksum,
287 MemMap* mem_map,
288 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800289 return OpenMemory(mem_map->Begin(),
290 mem_map->Size(),
291 location,
292 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800294 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700295 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800296}
297
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800298std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
299 const std::string& location, std::string* error_msg,
300 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800301 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700302 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700304 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700306 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700307 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700308 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700309 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700311 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700312 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700313 }
Ian Rogers700a4022014-05-19 16:49:03 -0700314 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700315 error_msg));
316 if (dex_file.get() == nullptr) {
317 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
318 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700319 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800321 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700322 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700323 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700324 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700325 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700326 }
327 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700328 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
329 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700330 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700331 return nullptr;
332 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700333 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800334 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700335}
336
Andreas Gampe90e34042015-04-27 20:01:52 -0700337// Technically we do not have a limitation with respect to the number of dex files that can be in a
338// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
339// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
340// seems an excessive number.
341static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
342
Andreas Gampe833a4852014-05-21 18:46:59 -0700343bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800344 std::string* error_msg,
345 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700346 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700347 ZipOpenErrorCode error_code;
348 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
349 &error_code));
350 if (dex_file.get() == nullptr) {
351 return false;
352 } else {
353 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800354 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700355
356 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700357
358 // We could try to avoid std::string allocations by working on a char array directly. As we
359 // do not expect a lot of iterations, this seems too involved and brittle.
360
Andreas Gampe90e34042015-04-27 20:01:52 -0700361 for (size_t i = 1; ; ++i) {
362 std::string name = GetMultiDexClassesDexName(i);
363 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
365 error_msg, &error_code));
366 if (next_dex_file.get() == nullptr) {
367 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
368 LOG(WARNING) << error_msg;
369 }
370 break;
371 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800372 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700373 }
374
Andreas Gampe90e34042015-04-27 20:01:52 -0700375 if (i == kWarnOnManyDexFilesThreshold) {
376 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
377 << " dex files. Please consider coalescing and shrinking the number to "
378 " avoid runtime overhead.";
379 }
380
381 if (i == std::numeric_limits<size_t>::max()) {
382 LOG(ERROR) << "Overflow in number of dex files!";
383 break;
384 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700385 }
386
387 return true;
388 }
389}
390
391
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800392std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
393 size_t size,
394 const std::string& location,
395 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800396 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700397 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800398 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700399 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800400 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700401 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700402 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800403 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700404 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800405 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700406}
407
Ian Rogers13735952014-10-08 12:43:28 -0700408DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800409 const std::string& location,
410 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800411 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700412 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800413 : begin_(base),
414 size_(size),
415 location_(location),
416 location_checksum_(location_checksum),
417 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800418 header_(reinterpret_cast<const Header*>(base)),
419 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
420 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
421 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
422 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
423 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700424 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700425 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700426 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800427 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300428 const uint8_t* lookup_data = (oat_dex_file != nullptr)
429 ? oat_dex_file->GetLookupTableData()
430 : nullptr;
431 if (lookup_data != nullptr) {
432 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
433 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
434 } else {
435 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
436 }
437 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800438}
439
Jesse Wilson6bf19152011-09-29 13:12:33 -0400440DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700441 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
442 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
443 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
444 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400445}
446
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700448 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700449 return false;
450 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700451 return true;
452}
453
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700454bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800455 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700456 std::ostringstream oss;
457 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800458 << " " << header_->magic_[0]
459 << " " << header_->magic_[1]
460 << " " << header_->magic_[2]
461 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700462 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700463 return false;
464 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800465 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700466 std::ostringstream oss;
467 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800468 << " " << header_->magic_[4]
469 << " " << header_->magic_[5]
470 << " " << header_->magic_[6]
471 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700472 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700473 return false;
474 }
475 return true;
476}
477
Ian Rogers13735952014-10-08 12:43:28 -0700478bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800479 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
480}
481
Ian Rogers13735952014-10-08 12:43:28 -0700482bool DexFile::IsVersionValid(const uint8_t* magic) {
483 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800484 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
485}
486
Ian Rogersd81871c2011-10-03 13:57:23 -0700487uint32_t DexFile::GetVersion() const {
488 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
489 return atoi(version);
490}
491
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800492const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
493 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300494 if (LIKELY(lookup_table_ != nullptr)) {
495 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
496 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700497 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300498
Ian Rogers68b56852014-08-29 20:19:11 -0700499 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300500 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700501 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700502 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700503 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300504 const TypeId* type_id = FindTypeId(descriptor);
505 if (type_id != nullptr) {
506 uint16_t type_idx = GetIndexForTypeId(*type_id);
507 for (size_t i = 0; i < num_class_defs; ++i) {
508 const ClassDef& class_def = GetClassDef(i);
509 if (class_def.class_idx_ == type_idx) {
510 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700511 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700512 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700513 }
Ian Rogers68b56852014-08-29 20:19:11 -0700514 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700515}
516
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700517const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
518 size_t num_class_defs = NumClassDefs();
519 for (size_t i = 0; i < num_class_defs; ++i) {
520 const ClassDef& class_def = GetClassDef(i);
521 if (class_def.class_idx_ == type_idx) {
522 return &class_def;
523 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700524 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700525 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700526}
527
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800528const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
529 const DexFile::StringId& name,
530 const DexFile::TypeId& type) const {
531 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
532 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
533 const uint32_t name_idx = GetIndexForStringId(name);
534 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700535 int32_t lo = 0;
536 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800537 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700538 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800539 const DexFile::FieldId& field = GetFieldId(mid);
540 if (class_idx > field.class_idx_) {
541 lo = mid + 1;
542 } else if (class_idx < field.class_idx_) {
543 hi = mid - 1;
544 } else {
545 if (name_idx > field.name_idx_) {
546 lo = mid + 1;
547 } else if (name_idx < field.name_idx_) {
548 hi = mid - 1;
549 } else {
550 if (type_idx > field.type_idx_) {
551 lo = mid + 1;
552 } else if (type_idx < field.type_idx_) {
553 hi = mid - 1;
554 } else {
555 return &field;
556 }
557 }
558 }
559 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700560 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800561}
562
563const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700564 const DexFile::StringId& name,
565 const DexFile::ProtoId& signature) const {
566 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800567 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700568 const uint32_t name_idx = GetIndexForStringId(name);
569 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700570 int32_t lo = 0;
571 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700572 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700573 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700574 const DexFile::MethodId& method = GetMethodId(mid);
575 if (class_idx > method.class_idx_) {
576 lo = mid + 1;
577 } else if (class_idx < method.class_idx_) {
578 hi = mid - 1;
579 } else {
580 if (name_idx > method.name_idx_) {
581 lo = mid + 1;
582 } else if (name_idx < method.name_idx_) {
583 hi = mid - 1;
584 } else {
585 if (proto_idx > method.proto_idx_) {
586 lo = mid + 1;
587 } else if (proto_idx < method.proto_idx_) {
588 hi = mid - 1;
589 } else {
590 return &method;
591 }
592 }
593 }
594 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700595 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700596}
597
Ian Rogers637c65b2013-05-31 11:46:00 -0700598const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700599 int32_t lo = 0;
600 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700601 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700602 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700603 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700604 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700605 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
606 if (compare > 0) {
607 lo = mid + 1;
608 } else if (compare < 0) {
609 hi = mid - 1;
610 } else {
611 return &str_id;
612 }
613 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700614 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700615}
616
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300617const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
618 int32_t lo = 0;
619 int32_t hi = NumTypeIds() - 1;
620 while (hi >= lo) {
621 int32_t mid = (hi + lo) / 2;
622 const TypeId& type_id = GetTypeId(mid);
623 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
624 const char* str = GetStringData(str_id);
625 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
626 if (compare > 0) {
627 lo = mid + 1;
628 } else if (compare < 0) {
629 hi = mid - 1;
630 } else {
631 return &type_id;
632 }
633 }
634 return nullptr;
635}
636
Vladimir Markoa48aef42014-12-03 17:53:53 +0000637const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700638 int32_t lo = 0;
639 int32_t hi = NumStringIds() - 1;
640 while (hi >= lo) {
641 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700642 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700643 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000644 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700645 if (compare > 0) {
646 lo = mid + 1;
647 } else if (compare < 0) {
648 hi = mid - 1;
649 } else {
650 return &str_id;
651 }
652 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700653 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700654}
655
656const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700657 int32_t lo = 0;
658 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700659 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700660 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700661 const TypeId& type_id = GetTypeId(mid);
662 if (string_idx > type_id.descriptor_idx_) {
663 lo = mid + 1;
664 } else if (string_idx < type_id.descriptor_idx_) {
665 hi = mid - 1;
666 } else {
667 return &type_id;
668 }
669 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700670 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700671}
672
673const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000674 const uint16_t* signature_type_idxs,
675 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700676 int32_t lo = 0;
677 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700678 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700679 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700680 const DexFile::ProtoId& proto = GetProtoId(mid);
681 int compare = return_type_idx - proto.return_type_idx_;
682 if (compare == 0) {
683 DexFileParameterIterator it(*this, proto);
684 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000685 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800686 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700687 it.Next();
688 i++;
689 }
690 if (compare == 0) {
691 if (it.HasNext()) {
692 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000693 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700694 compare = 1;
695 }
696 }
697 }
698 if (compare > 0) {
699 lo = mid + 1;
700 } else if (compare < 0) {
701 hi = mid - 1;
702 } else {
703 return &proto;
704 }
705 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700706 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700707}
708
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300709void DexFile::CreateTypeLookupTable() const {
710 lookup_table_.reset(TypeLookupTable::Create(*this));
711}
712
Ian Rogers0571d352011-11-03 19:51:38 -0700713// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700714bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
715 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700716 if (signature[0] != '(') {
717 return false;
718 }
719 size_t offset = 1;
720 size_t end = signature.size();
721 bool process_return = false;
722 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000723 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700724 char c = signature[offset];
725 offset++;
726 if (c == ')') {
727 process_return = true;
728 continue;
729 }
Ian Rogers0571d352011-11-03 19:51:38 -0700730 while (c == '[') { // process array prefix
731 if (offset >= end) { // expect some descriptor following [
732 return false;
733 }
734 c = signature[offset];
735 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700736 }
737 if (c == 'L') { // process type descriptors
738 do {
739 if (offset >= end) { // unexpected early termination of descriptor
740 return false;
741 }
742 c = signature[offset];
743 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700744 } while (c != ';');
745 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000746 // TODO: avoid creating a std::string just to get a 0-terminated char array
747 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700748 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700749 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700750 return false;
751 }
752 uint16_t type_idx = GetIndexForTypeId(*type_id);
753 if (!process_return) {
754 param_type_idxs->push_back(type_idx);
755 } else {
756 *return_type_idx = type_idx;
757 return offset == end; // return true if the signature had reached a sensible end
758 }
759 }
760 return false; // failed to correctly parse return type
761}
762
Ian Rogersd91d6d62013-09-25 20:26:14 -0700763const Signature DexFile::CreateSignature(const StringPiece& signature) const {
764 uint16_t return_type_idx;
765 std::vector<uint16_t> param_type_indices;
766 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
767 if (!success) {
768 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700769 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700770 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700772 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700773 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700774 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700775}
776
Mathieu Chartiere401d142015-04-22 13:56:20 -0700777int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700778 // For native method, lineno should be -2 to indicate it is native. Note that
779 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700780 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700781 return -2;
782 }
783
TDYa127c8dc1012012-04-19 07:03:33 -0700784 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700785 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700786
787 // A method with no line number info should return -1
788 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700789 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700791 return context.line_num_;
792}
793
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700794int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700795 // Note: Signed type is important for max and min.
796 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700797 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700798
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700799 while (min <= max) {
800 int32_t mid = min + ((max - min) / 2);
801
802 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
803 uint32_t start = ti->start_addr_;
804 uint32_t end = start + ti->insn_count_;
805
Ian Rogers0571d352011-11-03 19:51:38 -0700806 if (address < start) {
807 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700808 } else if (address >= end) {
809 min = mid + 1;
810 } else { // We have a winner!
811 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700812 }
813 }
814 // No match.
815 return -1;
816}
817
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700818int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
819 int32_t try_item = FindTryItem(code_item, address);
820 if (try_item == -1) {
821 return -1;
822 } else {
823 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
824 }
825}
826
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800828 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700829 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
830 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700831 uint32_t line = DecodeUnsignedLeb128(&stream);
832 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
833 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
834 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700835 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700836
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800837 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700838 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800839 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700840 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800841 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700842 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700843 local_in_reg[arg_reg].start_address_ = 0;
844 local_in_reg[arg_reg].is_live_ = true;
845 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700846 arg_reg++;
847 }
848
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800849 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700850 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700851 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700852 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800853 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700854 return;
855 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800856 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700857 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800858 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700859 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700860 local_in_reg[arg_reg].name_ = name;
861 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700862 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700863 local_in_reg[arg_reg].start_address_ = address;
864 local_in_reg[arg_reg].is_live_ = true;
865 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700866 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700867 case 'D':
868 case 'J':
869 arg_reg += 2;
870 break;
871 default:
872 arg_reg += 1;
873 break;
874 }
875 }
876
Ian Rogers0571d352011-11-03 19:51:38 -0700877 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800878 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
879 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700880 return;
881 }
882
883 for (;;) {
884 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700885 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800886 uint32_t name_idx;
887 uint32_t descriptor_idx;
888 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700889
Shih-wei Liao195487c2011-08-20 13:29:04 -0700890 switch (opcode) {
891 case DBG_END_SEQUENCE:
892 return;
893
894 case DBG_ADVANCE_PC:
895 address += DecodeUnsignedLeb128(&stream);
896 break;
897
898 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700899 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700900 break;
901
902 case DBG_START_LOCAL:
903 case DBG_START_LOCAL_EXTENDED:
904 reg = DecodeUnsignedLeb128(&stream);
905 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700906 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800907 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700908 return;
909 }
910
jeffhaof8728872011-10-28 19:11:13 -0700911 name_idx = DecodeUnsignedLeb128P1(&stream);
912 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
913 if (opcode == DBG_START_LOCAL_EXTENDED) {
914 signature_idx = DecodeUnsignedLeb128P1(&stream);
915 }
916
Shih-wei Liao195487c2011-08-20 13:29:04 -0700917 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700918 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800919 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700920
Ian Rogers0571d352011-11-03 19:51:38 -0700921 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
922 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700923 local_in_reg[reg].signature_ =
924 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
925 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700926 local_in_reg[reg].start_address_ = address;
927 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700928 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 break;
930
931 case DBG_END_LOCAL:
932 reg = DecodeUnsignedLeb128(&stream);
933 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700934 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800935 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700936 return;
937 }
938
Elliott Hughes30646832011-10-13 16:59:46 -0700939 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800940 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700941 local_in_reg[reg].is_live_ = false;
942 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943 break;
944
945 case DBG_RESTART_LOCAL:
946 reg = DecodeUnsignedLeb128(&stream);
947 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700948 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800949 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700950 return;
951 }
952
Elliott Hughes30646832011-10-13 16:59:46 -0700953 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700954 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800955 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700956 return;
957 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700958
Elliott Hughes30646832011-10-13 16:59:46 -0700959 // If the register is live, the "restart" is superfluous,
960 // and we don't want to mess with the existing start address.
961 if (!local_in_reg[reg].is_live_) {
962 local_in_reg[reg].start_address_ = address;
963 local_in_reg[reg].is_live_ = true;
964 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700965 }
966 break;
967
968 case DBG_SET_PROLOGUE_END:
969 case DBG_SET_EPILOGUE_BEGIN:
970 case DBG_SET_FILE:
971 break;
972
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700973 default: {
974 int adjopcode = opcode - DBG_FIRST_SPECIAL;
975
Shih-wei Liao195487c2011-08-20 13:29:04 -0700976 address += adjopcode / DBG_LINE_RANGE;
977 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
978
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700979 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800980 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700981 // early exit
982 return;
983 }
984 }
985 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700986 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700987 }
988 }
989}
990
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800991void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800992 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
993 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100994 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700995 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700996 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700997 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700998 nullptr);
999 if (stream != nullptr) {
1000 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
1001 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -07001002 }
1003 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001004 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
1005 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -07001006 }
1007}
1008
Elliott Hughes2435a572012-02-17 16:07:41 -08001009bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1010 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001011
1012 // We know that this callback will be called in
1013 // ascending address order, so keep going until we find
1014 // a match or we've just gone past it.
1015 if (address > context->address_) {
1016 // The line number from the previous positions callback
1017 // wil be the final result.
1018 return true;
1019 } else {
1020 context->line_num_ = line_num;
1021 return address == context->address_;
1022 }
1023}
1024
Andreas Gampe833a4852014-05-21 18:46:59 -07001025bool DexFile::IsMultiDexLocation(const char* location) {
1026 return strrchr(location, kMultiDexSeparator) != nullptr;
1027}
1028
Andreas Gampe90e34042015-04-27 20:01:52 -07001029std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1030 if (index == 0) {
1031 return "classes.dex";
1032 } else {
1033 return StringPrintf("classes%zu.dex", index + 1);
1034 }
1035}
1036
1037std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1038 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001039 return dex_location;
1040 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001041 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001042 }
1043}
1044
1045std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1046 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001047 std::string base_location = GetBaseLocation(dex_location);
1048 const char* suffix = dex_location + base_location.size();
1049 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1050 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1051 if (path != nullptr && path.get() != base_location) {
1052 return std::string(path.get()) + suffix;
1053 } else if (suffix[0] == 0) {
1054 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001055 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001056 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001057 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001058}
1059
Jeff Hao13e748b2015-08-25 20:44:19 +00001060// Read a signed integer. "zwidth" is the zero-based byte count.
1061static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1062 int32_t val = 0;
1063 for (int i = zwidth; i >= 0; --i) {
1064 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1065 }
1066 val >>= (3 - zwidth) * 8;
1067 return val;
1068}
1069
1070// Read an unsigned integer. "zwidth" is the zero-based byte count,
1071// "fill_on_right" indicates which side we want to zero-fill from.
1072static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1073 uint32_t val = 0;
1074 for (int i = zwidth; i >= 0; --i) {
1075 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1076 }
1077 if (!fill_on_right) {
1078 val >>= (3 - zwidth) * 8;
1079 }
1080 return val;
1081}
1082
1083// Read a signed long. "zwidth" is the zero-based byte count.
1084static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1085 int64_t val = 0;
1086 for (int i = zwidth; i >= 0; --i) {
1087 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1088 }
1089 val >>= (7 - zwidth) * 8;
1090 return val;
1091}
1092
1093// Read an unsigned long. "zwidth" is the zero-based byte count,
1094// "fill_on_right" indicates which side we want to zero-fill from.
1095static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1096 uint64_t val = 0;
1097 for (int i = zwidth; i >= 0; --i) {
1098 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1099 }
1100 if (!fill_on_right) {
1101 val >>= (7 - zwidth) * 8;
1102 }
1103 return val;
1104}
1105
1106const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1107 mirror::Class* klass = field->GetDeclaringClass();
1108 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1109 if (annotations_dir == nullptr) {
1110 return nullptr;
1111 }
1112 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1113 if (field_annotations == nullptr) {
1114 return nullptr;
1115 }
1116 uint32_t field_index = field->GetDexFieldIndex();
1117 uint32_t field_count = annotations_dir->fields_size_;
1118 for (uint32_t i = 0; i < field_count; ++i) {
1119 if (field_annotations[i].field_idx_ == field_index) {
1120 return GetFieldAnnotationSetItem(field_annotations[i]);
1121 }
1122 }
1123 return nullptr;
1124}
1125
1126mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1127 Handle<mirror::Class> annotation_class) const {
1128 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1129 if (annotation_set == nullptr) {
1130 return nullptr;
1131 }
1132 StackHandleScope<1> hs(Thread::Current());
1133 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1134 return GetAnnotationObjectFromAnnotationSet(
1135 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1136}
1137
1138mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1139 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1140 StackHandleScope<1> hs(Thread::Current());
1141 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1142 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1143}
1144
Jeff Hao2a5892f2015-08-31 15:00:40 -07001145mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001146 const {
1147 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1148 if (annotation_set == nullptr) {
1149 return nullptr;
1150 }
1151 StackHandleScope<1> hs(Thread::Current());
1152 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1153 return GetSignatureValue(field_class, annotation_set);
1154}
1155
1156bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1157 const {
1158 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1159 if (annotation_set == nullptr) {
1160 return false;
1161 }
1162 StackHandleScope<1> hs(Thread::Current());
1163 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1164 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1165 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1166 return annotation_item != nullptr;
1167}
1168
1169const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1170 mirror::Class* klass = method->GetDeclaringClass();
1171 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1172 if (annotations_dir == nullptr) {
1173 return nullptr;
1174 }
1175 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1176 if (method_annotations == nullptr) {
1177 return nullptr;
1178 }
1179 uint32_t method_index = method->GetDexMethodIndex();
1180 uint32_t method_count = annotations_dir->methods_size_;
1181 for (uint32_t i = 0; i < method_count; ++i) {
1182 if (method_annotations[i].method_idx_ == method_index) {
1183 return GetMethodAnnotationSetItem(method_annotations[i]);
1184 }
1185 }
1186 return nullptr;
1187}
1188
1189const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1190 const {
1191 mirror::Class* klass = method->GetDeclaringClass();
1192 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1193 if (annotations_dir == nullptr) {
1194 return nullptr;
1195 }
1196 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1197 if (parameter_annotations == nullptr) {
1198 return nullptr;
1199 }
1200 uint32_t method_index = method->GetDexMethodIndex();
1201 uint32_t parameter_count = annotations_dir->parameters_size_;
1202 for (uint32_t i = 0; i < parameter_count; ++i) {
1203 if (parameter_annotations[i].method_idx_ == method_index) {
1204 return &parameter_annotations[i];
1205 }
1206 }
1207 return nullptr;
1208}
1209
1210mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1211 mirror::Class* klass = method->GetDeclaringClass();
1212 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1213 if (annotations_dir == nullptr) {
1214 return nullptr;
1215 }
1216 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1217 if (annotation_set == nullptr) {
1218 return nullptr;
1219 }
1220 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1221 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1222 if (annotation_item == nullptr) {
1223 return nullptr;
1224 }
1225 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1226 if (annotation == nullptr) {
1227 return nullptr;
1228 }
1229 uint8_t header_byte = *(annotation++);
1230 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1231 return nullptr;
1232 }
1233 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1234 if (annotation == nullptr) {
1235 return nullptr;
1236 }
1237 AnnotationValue annotation_value;
1238 StackHandleScope<2> hs(Thread::Current());
1239 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001240 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1241 Handle<mirror::Class> return_type(hs.NewHandle(
1242 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001243 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1244 return nullptr;
1245 }
1246 return annotation_value.value_.GetL();
1247}
1248
1249mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1250 Handle<mirror::Class> annotation_class) const {
1251 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1252 if (annotation_set == nullptr) {
1253 return nullptr;
1254 }
1255 StackHandleScope<1> hs(Thread::Current());
1256 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1257 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1258 kDexVisibilityRuntime, annotation_class);
1259}
1260
1261mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1262 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1263 StackHandleScope<1> hs(Thread::Current());
1264 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1265 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1266}
1267
Jeff Hao2a5892f2015-08-31 15:00:40 -07001268mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001269 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1270 if (annotation_set == nullptr) {
1271 return nullptr;
1272 }
1273 StackHandleScope<1> hs(Thread::Current());
1274 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1275 return GetThrowsValue(method_class, annotation_set);
1276}
1277
1278mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1279 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1280 if (parameter_annotations == nullptr) {
1281 return nullptr;
1282 }
1283 const AnnotationSetRefList* set_ref_list =
1284 GetParameterAnnotationSetRefList(parameter_annotations);
1285 if (set_ref_list == nullptr) {
1286 return nullptr;
1287 }
1288 uint32_t size = set_ref_list->size_;
1289 StackHandleScope<1> hs(Thread::Current());
1290 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1291 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1292}
1293
1294bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1295 const {
1296 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1297 if (annotation_set == nullptr) {
1298 return false;
1299 }
1300 StackHandleScope<1> hs(Thread::Current());
1301 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1302 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1303 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001304 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001305}
1306
1307const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1308 const {
1309 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1310 if (annotations_dir == nullptr) {
1311 return nullptr;
1312 }
1313 return GetClassAnnotationSet(annotations_dir);
1314}
1315
1316mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1317 Handle<mirror::Class> annotation_class) const {
1318 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1319 if (annotation_set == nullptr) {
1320 return nullptr;
1321 }
1322 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1323 annotation_class);
1324}
1325
1326mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1327 const {
1328 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1329 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1330}
1331
Jeff Hao2a5892f2015-08-31 15:00:40 -07001332mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1333 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1334 if (annotation_set == nullptr) {
1335 return nullptr;
1336 }
1337 const AnnotationItem* annotation_item = SearchAnnotationSet(
1338 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1339 if (annotation_item == nullptr) {
1340 return nullptr;
1341 }
1342 StackHandleScope<1> hs(Thread::Current());
1343 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1344 Handle<mirror::Class> class_array_class(hs.NewHandle(
1345 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1346 if (class_array_class.Get() == nullptr) {
1347 return nullptr;
1348 }
1349 mirror::Object* obj = GetAnnotationValue(
1350 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1351 if (obj == nullptr) {
1352 return nullptr;
1353 }
1354 return obj->AsObjectArray<mirror::Class>();
1355}
1356
1357mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1358 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1359 if (annotation_set == nullptr) {
1360 return nullptr;
1361 }
1362 const AnnotationItem* annotation_item = SearchAnnotationSet(
1363 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1364 if (annotation_item == nullptr) {
1365 return nullptr;
1366 }
1367 mirror::Object* obj = GetAnnotationValue(
1368 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1369 if (obj == nullptr) {
1370 return nullptr;
1371 }
1372 return obj->AsClass();
1373}
1374
1375mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1376 mirror::Class* declaring_class = GetDeclaringClass(klass);
1377 if (declaring_class != nullptr) {
1378 return declaring_class;
1379 }
1380 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1381 if (annotation_set == nullptr) {
1382 return nullptr;
1383 }
1384 const AnnotationItem* annotation_item = SearchAnnotationSet(
1385 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1386 if (annotation_item == nullptr) {
1387 return nullptr;
1388 }
1389 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1390 if (annotation == nullptr) {
1391 return nullptr;
1392 }
1393 AnnotationValue annotation_value;
1394 if (!ProcessAnnotationValue(
1395 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1396 return nullptr;
1397 }
1398 if (annotation_value.type_ != kDexAnnotationMethod) {
1399 return nullptr;
1400 }
1401 StackHandleScope<2> hs(Thread::Current());
1402 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1403 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1404 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1405 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1406 if (method == nullptr) {
1407 return nullptr;
1408 }
1409 return method->GetDeclaringClass();
1410}
1411
1412mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1413 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1414 if (annotation_set == nullptr) {
1415 return nullptr;
1416 }
1417 const AnnotationItem* annotation_item = SearchAnnotationSet(
1418 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1419 if (annotation_item == nullptr) {
1420 return nullptr;
1421 }
1422 return GetAnnotationValue(
1423 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1424}
1425
1426bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1427 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1428 if (annotation_set == nullptr) {
1429 return false;
1430 }
1431 const AnnotationItem* annotation_item = SearchAnnotationSet(
1432 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1433 if (annotation_item == nullptr) {
1434 return false;
1435 }
1436 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1437 if (annotation == nullptr) {
1438 return false;
1439 }
1440 AnnotationValue annotation_value;
1441 if (!ProcessAnnotationValue(
1442 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1443 return false;
1444 }
1445 if (annotation_value.type_ != kDexAnnotationNull &&
1446 annotation_value.type_ != kDexAnnotationString) {
1447 return false;
1448 }
1449 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1450 return true;
1451}
1452
1453bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1454 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1455 if (annotation_set == nullptr) {
1456 return false;
1457 }
1458 const AnnotationItem* annotation_item = SearchAnnotationSet(
1459 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1460 if (annotation_item == nullptr) {
1461 return false;
1462 }
1463 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1464 if (annotation == nullptr) {
1465 return false;
1466 }
1467 AnnotationValue annotation_value;
1468 if (!ProcessAnnotationValue(
1469 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1470 return false;
1471 }
1472 if (annotation_value.type_ != kDexAnnotationInt) {
1473 return false;
1474 }
1475 *flags = annotation_value.value_.GetI();
1476 return true;
1477}
1478
Jeff Hao13e748b2015-08-25 20:44:19 +00001479bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1480 Handle<mirror::Class> annotation_class) const {
1481 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1482 if (annotation_set == nullptr) {
1483 return false;
1484 }
1485 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1486 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001487 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001488}
1489
1490mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1491 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1492 Thread* self = Thread::Current();
1493 ScopedObjectAccessUnchecked soa(self);
1494 StackHandleScope<5> hs(self);
1495 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1496 const char* name = StringDataByIdx(element_name_index);
1497 Handle<mirror::String> string_name(
1498 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1499
1500 ArtMethod* annotation_method =
1501 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1502 if (annotation_method == nullptr) {
1503 return nullptr;
1504 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001505 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1506 Handle<mirror::Class> method_return(hs.NewHandle(
1507 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001508
1509 AnnotationValue annotation_value;
1510 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1511 return nullptr;
1512 }
1513 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1514
1515 mirror::Class* annotation_member_class =
1516 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1517 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1518 Handle<mirror::Method> method_object(
1519 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1520
1521 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1522 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1523 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1524 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1525 return nullptr;
1526 }
1527
1528 JValue result;
1529 ArtMethod* annotation_member_init =
1530 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1531 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1532 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1533 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1534 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1535 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1536 };
1537 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1538 if (self->IsExceptionPending()) {
1539 LOG(INFO) << "Exception in AnnotationMember.<init>";
1540 return nullptr;
1541 }
1542
1543 return new_member.Get();
1544}
1545
1546const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1547 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1548 Handle<mirror::Class> annotation_class) const {
1549 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1550 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1551 if (annotation_item->visibility_ != visibility) {
1552 continue;
1553 }
1554 const uint8_t* annotation = annotation_item->annotation_;
1555 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1556 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1557 klass->GetDexFile(), type_index, klass.Get());
1558 if (resolved_class == nullptr) {
1559 std::string temp;
1560 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1561 klass->GetDescriptor(&temp), type_index);
1562 CHECK(Thread::Current()->IsExceptionPending());
1563 Thread::Current()->ClearException();
1564 continue;
1565 }
1566 if (resolved_class == annotation_class.Get()) {
1567 return annotation_item;
1568 }
1569 }
1570
1571 return nullptr;
1572}
1573
1574mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1575 const AnnotationSetItem* annotation_set, uint32_t visibility,
1576 Handle<mirror::Class> annotation_class) const {
1577 const AnnotationItem* annotation_item =
1578 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1579 if (annotation_item == nullptr) {
1580 return nullptr;
1581 }
1582 const uint8_t* annotation = annotation_item->annotation_;
1583 return ProcessEncodedAnnotation(klass, &annotation);
1584}
1585
1586mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1587 const AnnotationItem* annotation_item, const char* annotation_name,
1588 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1589 const uint8_t* annotation =
1590 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1591 if (annotation == nullptr) {
1592 return nullptr;
1593 }
1594 AnnotationValue annotation_value;
1595 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1596 return nullptr;
1597 }
1598 if (annotation_value.type_ != expected_type) {
1599 return nullptr;
1600 }
1601 return annotation_value.value_.GetL();
1602}
1603
Jeff Hao2a5892f2015-08-31 15:00:40 -07001604mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001605 const AnnotationSetItem* annotation_set) const {
1606 StackHandleScope<1> hs(Thread::Current());
1607 const AnnotationItem* annotation_item =
1608 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1609 if (annotation_item == nullptr) {
1610 return nullptr;
1611 }
1612 mirror::Class* string_class = mirror::String::GetJavaLangString();
1613 Handle<mirror::Class> string_array_class(hs.NewHandle(
1614 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001615 if (string_array_class.Get() == nullptr) {
1616 return nullptr;
1617 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001618 mirror::Object* obj =
1619 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1620 if (obj == nullptr) {
1621 return nullptr;
1622 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001623 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001624}
1625
Jeff Hao2a5892f2015-08-31 15:00:40 -07001626mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001627 const AnnotationSetItem* annotation_set) const {
1628 StackHandleScope<1> hs(Thread::Current());
1629 const AnnotationItem* annotation_item =
1630 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1631 if (annotation_item == nullptr) {
1632 return nullptr;
1633 }
1634 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1635 Handle<mirror::Class> class_array_class(hs.NewHandle(
1636 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001637 if (class_array_class.Get() == nullptr) {
1638 return nullptr;
1639 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001640 mirror::Object* obj =
1641 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1642 if (obj == nullptr) {
1643 return nullptr;
1644 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001645 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001646}
1647
1648mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1649 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1650 Thread* self = Thread::Current();
1651 ScopedObjectAccessUnchecked soa(self);
1652 StackHandleScope<2> hs(self);
1653 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1654 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1655 if (annotation_set == nullptr) {
1656 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1657 }
1658
1659 uint32_t size = annotation_set->size_;
1660 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1661 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1662 if (result.Get() == nullptr) {
1663 return nullptr;
1664 }
1665
1666 uint32_t dest_index = 0;
1667 for (uint32_t i = 0; i < size; ++i) {
1668 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1669 if (annotation_item->visibility_ != visibility) {
1670 continue;
1671 }
1672 const uint8_t* annotation = annotation_item->annotation_;
1673 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1674 if (annotation_obj != nullptr) {
1675 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1676 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001677 } else if (self->IsExceptionPending()) {
1678 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001679 }
1680 }
1681
1682 if (dest_index == size) {
1683 return result.Get();
1684 }
1685
1686 mirror::ObjectArray<mirror::Object>* trimmed_result =
1687 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001688 if (trimmed_result == nullptr) {
1689 return nullptr;
1690 }
1691
Jeff Hao13e748b2015-08-25 20:44:19 +00001692 for (uint32_t i = 0; i < dest_index; ++i) {
1693 mirror::Object* obj = result->GetWithoutChecks(i);
1694 trimmed_result->SetWithoutChecks<false>(i, obj);
1695 }
1696
1697 return trimmed_result;
1698}
1699
1700mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1701 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1702 Thread* self = Thread::Current();
1703 ScopedObjectAccessUnchecked soa(self);
1704 StackHandleScope<1> hs(self);
1705 mirror::Class* annotation_array_class =
1706 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1707 mirror::Class* annotation_array_array_class =
1708 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001709 if (annotation_array_array_class == nullptr) {
1710 return nullptr;
1711 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001712 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1713 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1714 if (annotation_array_array.Get() == nullptr) {
1715 LOG(ERROR) << "Annotation set ref array allocation failed";
1716 return nullptr;
1717 }
1718 for (uint32_t index = 0; index < size; ++index) {
1719 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1720 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1721 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1722 if (annotation_set == nullptr) {
1723 return nullptr;
1724 }
1725 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1726 }
1727 return annotation_array_array.Get();
1728}
1729
1730bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1731 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1732 DexFile::AnnotationResultStyle result_style) const {
1733 Thread* self = Thread::Current();
1734 mirror::Object* element_object = nullptr;
1735 bool set_object = false;
1736 Primitive::Type primitive_type = Primitive::kPrimVoid;
1737 const uint8_t* annotation = *annotation_ptr;
1738 uint8_t header_byte = *(annotation++);
1739 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1740 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1741 int32_t width = value_arg + 1;
1742 annotation_value->type_ = value_type;
1743
1744 switch (value_type) {
1745 case kDexAnnotationByte:
1746 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1747 primitive_type = Primitive::kPrimByte;
1748 break;
1749 case kDexAnnotationShort:
1750 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1751 primitive_type = Primitive::kPrimShort;
1752 break;
1753 case kDexAnnotationChar:
1754 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1755 false)));
1756 primitive_type = Primitive::kPrimChar;
1757 break;
1758 case kDexAnnotationInt:
1759 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1760 primitive_type = Primitive::kPrimInt;
1761 break;
1762 case kDexAnnotationLong:
1763 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1764 primitive_type = Primitive::kPrimLong;
1765 break;
1766 case kDexAnnotationFloat:
1767 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1768 primitive_type = Primitive::kPrimFloat;
1769 break;
1770 case kDexAnnotationDouble:
1771 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1772 primitive_type = Primitive::kPrimDouble;
1773 break;
1774 case kDexAnnotationBoolean:
1775 annotation_value->value_.SetZ(value_arg != 0);
1776 primitive_type = Primitive::kPrimBoolean;
1777 width = 0;
1778 break;
1779 case kDexAnnotationString: {
1780 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1781 if (result_style == kAllRaw) {
1782 annotation_value->value_.SetI(index);
1783 } else {
1784 StackHandleScope<1> hs(self);
1785 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1786 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1787 klass->GetDexFile(), index, dex_cache);
1788 set_object = true;
1789 if (element_object == nullptr) {
1790 return false;
1791 }
1792 }
1793 break;
1794 }
1795 case kDexAnnotationType: {
1796 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1797 if (result_style == kAllRaw) {
1798 annotation_value->value_.SetI(index);
1799 } else {
1800 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1801 klass->GetDexFile(), index, klass.Get());
1802 set_object = true;
1803 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001804 CHECK(self->IsExceptionPending());
1805 if (result_style == kAllObjects) {
1806 const char* msg = StringByTypeIdx(index);
1807 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1808 element_object = self->GetException();
1809 self->ClearException();
1810 } else {
1811 return false;
1812 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001813 }
1814 }
1815 break;
1816 }
1817 case kDexAnnotationMethod: {
1818 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1819 if (result_style == kAllRaw) {
1820 annotation_value->value_.SetI(index);
1821 } else {
1822 StackHandleScope<2> hs(self);
1823 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1824 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1825 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1826 klass->GetDexFile(), index, dex_cache, class_loader);
1827 if (method == nullptr) {
1828 return false;
1829 }
1830 set_object = true;
1831 if (method->IsConstructor()) {
1832 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1833 } else {
1834 element_object = mirror::Method::CreateFromArtMethod(self, method);
1835 }
1836 if (element_object == nullptr) {
1837 return false;
1838 }
1839 }
1840 break;
1841 }
1842 case kDexAnnotationField: {
1843 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1844 if (result_style == kAllRaw) {
1845 annotation_value->value_.SetI(index);
1846 } else {
1847 StackHandleScope<2> hs(self);
1848 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1849 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1850 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1851 klass->GetDexFile(), index, dex_cache, class_loader);
1852 if (field == nullptr) {
1853 return false;
1854 }
1855 set_object = true;
1856 element_object = mirror::Field::CreateFromArtField(self, field, true);
1857 if (element_object == nullptr) {
1858 return false;
1859 }
1860 }
1861 break;
1862 }
1863 case kDexAnnotationEnum: {
1864 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1865 if (result_style == kAllRaw) {
1866 annotation_value->value_.SetI(index);
1867 } else {
1868 StackHandleScope<3> hs(self);
1869 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1870 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1871 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1872 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001873 if (enum_field == nullptr) {
1874 return false;
1875 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001876 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001877 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1878 element_object = enum_field->GetObject(field_class.Get());
1879 set_object = true;
1880 }
1881 }
1882 break;
1883 }
1884 case kDexAnnotationArray:
1885 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1886 return false;
1887 } else {
1888 ScopedObjectAccessUnchecked soa(self);
1889 StackHandleScope<2> hs(self);
1890 uint32_t size = DecodeUnsignedLeb128(&annotation);
1891 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1892 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1893 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1894 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1895 if (new_array.Get() == nullptr) {
1896 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1897 return false;
1898 }
1899 AnnotationValue new_annotation_value;
1900 for (uint32_t i = 0; i < size; ++i) {
1901 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1902 kPrimitivesOrObjects)) {
1903 return false;
1904 }
1905 if (!component_type->IsPrimitive()) {
1906 mirror::Object* obj = new_annotation_value.value_.GetL();
1907 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1908 } else {
1909 switch (new_annotation_value.type_) {
1910 case kDexAnnotationByte:
1911 new_array->AsByteArray()->SetWithoutChecks<false>(
1912 i, new_annotation_value.value_.GetB());
1913 break;
1914 case kDexAnnotationShort:
1915 new_array->AsShortArray()->SetWithoutChecks<false>(
1916 i, new_annotation_value.value_.GetS());
1917 break;
1918 case kDexAnnotationChar:
1919 new_array->AsCharArray()->SetWithoutChecks<false>(
1920 i, new_annotation_value.value_.GetC());
1921 break;
1922 case kDexAnnotationInt:
1923 new_array->AsIntArray()->SetWithoutChecks<false>(
1924 i, new_annotation_value.value_.GetI());
1925 break;
1926 case kDexAnnotationLong:
1927 new_array->AsLongArray()->SetWithoutChecks<false>(
1928 i, new_annotation_value.value_.GetJ());
1929 break;
1930 case kDexAnnotationFloat:
1931 new_array->AsFloatArray()->SetWithoutChecks<false>(
1932 i, new_annotation_value.value_.GetF());
1933 break;
1934 case kDexAnnotationDouble:
1935 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1936 i, new_annotation_value.value_.GetD());
1937 break;
1938 case kDexAnnotationBoolean:
1939 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1940 i, new_annotation_value.value_.GetZ());
1941 break;
1942 default:
1943 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1944 return false;
1945 }
1946 }
1947 }
1948 element_object = new_array.Get();
1949 set_object = true;
1950 width = 0;
1951 }
1952 break;
1953 case kDexAnnotationAnnotation:
1954 if (result_style == kAllRaw) {
1955 return false;
1956 }
1957 element_object = ProcessEncodedAnnotation(klass, &annotation);
1958 if (element_object == nullptr) {
1959 return false;
1960 }
1961 set_object = true;
1962 width = 0;
1963 break;
1964 case kDexAnnotationNull:
1965 if (result_style == kAllRaw) {
1966 annotation_value->value_.SetI(0);
1967 } else {
1968 CHECK(element_object == nullptr);
1969 set_object = true;
1970 }
1971 width = 0;
1972 break;
1973 default:
1974 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1975 return false;
1976 }
1977
1978 annotation += width;
1979 *annotation_ptr = annotation;
1980
1981 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1982 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1983 set_object = true;
1984 }
1985
1986 if (set_object) {
1987 annotation_value->value_.SetL(element_object);
1988 }
1989
1990 return true;
1991}
1992
1993mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1994 const uint8_t** annotation) const {
1995 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1996 uint32_t size = DecodeUnsignedLeb128(annotation);
1997
1998 Thread* self = Thread::Current();
1999 ScopedObjectAccessUnchecked soa(self);
2000 StackHandleScope<2> hs(self);
2001 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2002 Handle<mirror::Class> annotation_class(hs.NewHandle(
2003 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2004 if (annotation_class.Get() == nullptr) {
2005 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2006 << type_index;
2007 DCHECK(Thread::Current()->IsExceptionPending());
2008 Thread::Current()->ClearException();
2009 return nullptr;
2010 }
2011
2012 mirror::Class* annotation_member_class =
2013 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2014 mirror::Class* annotation_member_array_class =
2015 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002016 if (annotation_member_array_class == nullptr) {
2017 return nullptr;
2018 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002019 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002020 if (size > 0) {
2021 element_array =
2022 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2023 if (element_array == nullptr) {
2024 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2025 return nullptr;
2026 }
2027 }
2028
2029 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2030 for (uint32_t i = 0; i < size; ++i) {
2031 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2032 if (new_member == nullptr) {
2033 return nullptr;
2034 }
2035 h_element_array->SetWithoutChecks<false>(i, new_member);
2036 }
2037
2038 JValue result;
2039 ArtMethod* create_annotation_method =
2040 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2041 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2042 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2043 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2044 if (self->IsExceptionPending()) {
2045 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2046 return nullptr;
2047 }
2048
2049 return result.GetL();
2050}
2051
2052const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2053 const char* descriptor, uint32_t visibility) const {
2054 const AnnotationItem* result = nullptr;
2055 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2056 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2057 if (annotation_item->visibility_ != visibility) {
2058 continue;
2059 }
2060 const uint8_t* annotation = annotation_item->annotation_;
2061 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2062
2063 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2064 result = annotation_item;
2065 break;
2066 }
2067 }
2068 return result;
2069}
2070
2071const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2072 DecodeUnsignedLeb128(&annotation); // unused type_index
2073 uint32_t size = DecodeUnsignedLeb128(&annotation);
2074
2075 while (size != 0) {
2076 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2077 const char* element_name = GetStringData(GetStringId(element_name_index));
2078 if (strcmp(name, element_name) == 0) {
2079 return annotation;
2080 }
2081 SkipAnnotationValue(&annotation);
2082 size--;
2083 }
2084 return nullptr;
2085}
2086
2087bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2088 const uint8_t* annotation = *annotation_ptr;
2089 uint8_t header_byte = *(annotation++);
2090 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2091 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2092 int32_t width = value_arg + 1;
2093
2094 switch (value_type) {
2095 case kDexAnnotationByte:
2096 case kDexAnnotationShort:
2097 case kDexAnnotationChar:
2098 case kDexAnnotationInt:
2099 case kDexAnnotationLong:
2100 case kDexAnnotationFloat:
2101 case kDexAnnotationDouble:
2102 case kDexAnnotationString:
2103 case kDexAnnotationType:
2104 case kDexAnnotationMethod:
2105 case kDexAnnotationField:
2106 case kDexAnnotationEnum:
2107 break;
2108 case kDexAnnotationArray:
2109 {
2110 uint32_t size = DecodeUnsignedLeb128(&annotation);
2111 while (size--) {
2112 if (!SkipAnnotationValue(&annotation)) {
2113 return false;
2114 }
2115 }
2116 width = 0;
2117 break;
2118 }
2119 case kDexAnnotationAnnotation:
2120 {
2121 DecodeUnsignedLeb128(&annotation); // unused type_index
2122 uint32_t size = DecodeUnsignedLeb128(&annotation);
2123 while (size--) {
2124 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2125 if (!SkipAnnotationValue(&annotation)) {
2126 return false;
2127 }
2128 }
2129 width = 0;
2130 break;
2131 }
2132 case kDexAnnotationBoolean:
2133 case kDexAnnotationNull:
2134 width = 0;
2135 break;
2136 default:
2137 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2138 return false;
2139 }
2140
2141 annotation += width;
2142 *annotation_ptr = annotation;
2143 return true;
2144}
2145
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002146std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2147 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2148 dex_file.GetLocation().c_str(),
2149 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2150 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2151 return os;
2152}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002153
Ian Rogersd91d6d62013-09-25 20:26:14 -07002154std::string Signature::ToString() const {
2155 if (dex_file_ == nullptr) {
2156 CHECK(proto_id_ == nullptr);
2157 return "<no signature>";
2158 }
2159 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2160 std::string result;
2161 if (params == nullptr) {
2162 result += "()";
2163 } else {
2164 result += "(";
2165 for (uint32_t i = 0; i < params->Size(); ++i) {
2166 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2167 }
2168 result += ")";
2169 }
2170 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2171 return result;
2172}
2173
Vladimir Markod9cffea2013-11-25 15:08:02 +00002174bool Signature::operator==(const StringPiece& rhs) const {
2175 if (dex_file_ == nullptr) {
2176 return false;
2177 }
2178 StringPiece tail(rhs);
2179 if (!tail.starts_with("(")) {
2180 return false; // Invalid signature
2181 }
2182 tail.remove_prefix(1); // "(";
2183 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2184 if (params != nullptr) {
2185 for (uint32_t i = 0; i < params->Size(); ++i) {
2186 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2187 if (!tail.starts_with(param)) {
2188 return false;
2189 }
2190 tail.remove_prefix(param.length());
2191 }
2192 }
2193 if (!tail.starts_with(")")) {
2194 return false;
2195 }
2196 tail.remove_prefix(1); // ")";
2197 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2198}
2199
Ian Rogersd91d6d62013-09-25 20:26:14 -07002200std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2201 return os << sig.ToString();
2202}
2203
Ian Rogers0571d352011-11-03 19:51:38 -07002204// Decodes the header section from the class data bytes.
2205void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002206 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002207 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2208 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2209 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2210 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2211}
2212
2213void ClassDataItemIterator::ReadClassDataField() {
2214 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2215 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002216 // The user of the iterator is responsible for checking if there
2217 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002218}
2219
2220void ClassDataItemIterator::ReadClassDataMethod() {
2221 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2222 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2223 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002224 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002225 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002226 }
Ian Rogers0571d352011-11-03 19:51:38 -07002227}
2228
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002229EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002230 const DexFile& dex_file,
2231 const DexFile::ClassDef& class_def)
2232 : EncodedStaticFieldValueIterator(dex_file, nullptr, nullptr,
2233 nullptr, class_def) {
2234}
2235
2236EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002237 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2238 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2239 const DexFile::ClassDef& class_def)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002240 : dex_file_(dex_file),
2241 dex_cache_(dex_cache),
2242 class_loader_(class_loader),
2243 linker_(linker),
2244 array_size_(),
2245 pos_(-1),
2246 type_(kByte) {
2247 ptr_ = dex_file_.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002248 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002249 array_size_ = 0;
2250 } else {
2251 array_size_ = DecodeUnsignedLeb128(&ptr_);
2252 }
2253 if (array_size_ > 0) {
2254 Next();
2255 }
2256}
2257
2258void EncodedStaticFieldValueIterator::Next() {
2259 pos_++;
2260 if (pos_ >= array_size_) {
2261 return;
2262 }
Ian Rogers13735952014-10-08 12:43:28 -07002263 uint8_t value_type = *ptr_++;
2264 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002265 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002266 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002267 switch (type_) {
2268 case kBoolean:
2269 jval_.i = (value_arg != 0) ? 1 : 0;
2270 width = 0;
2271 break;
2272 case kByte:
2273 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002274 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002275 break;
2276 case kShort:
2277 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002278 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002279 break;
2280 case kChar:
2281 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002282 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002283 break;
2284 case kInt:
2285 jval_.i = ReadSignedInt(ptr_, value_arg);
2286 break;
2287 case kLong:
2288 jval_.j = ReadSignedLong(ptr_, value_arg);
2289 break;
2290 case kFloat:
2291 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2292 break;
2293 case kDouble:
2294 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2295 break;
2296 case kString:
2297 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002298 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2299 break;
2300 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002301 case kMethod:
2302 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002303 case kArray:
2304 case kAnnotation:
2305 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002306 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002307 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002308 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002309 width = 0;
2310 break;
2311 default:
2312 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002313 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002314 }
2315 ptr_ += width;
2316}
2317
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002318template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002319void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002320 DCHECK(dex_cache_ != nullptr);
2321 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002322 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002323 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2324 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002325 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2326 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2327 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2328 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2329 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2330 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2331 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002332 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002333 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002334 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002335 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002336 break;
2337 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002338 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002339 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2340 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002341 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002342 break;
2343 }
Ian Rogers0571d352011-11-03 19:51:38 -07002344 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2345 }
2346}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002347template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2348template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002349
2350CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2351 handler_.address_ = -1;
2352 int32_t offset = -1;
2353
2354 // Short-circuit the overwhelmingly common cases.
2355 switch (code_item.tries_size_) {
2356 case 0:
2357 break;
2358 case 1: {
2359 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2360 uint32_t start = tries->start_addr_;
2361 if (address >= start) {
2362 uint32_t end = start + tries->insn_count_;
2363 if (address < end) {
2364 offset = tries->handler_off_;
2365 }
2366 }
2367 break;
2368 }
2369 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002370 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002371 }
Logan Chien736df022012-04-27 16:25:57 +08002372 Init(code_item, offset);
2373}
2374
2375CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2376 const DexFile::TryItem& try_item) {
2377 handler_.address_ = -1;
2378 Init(code_item, try_item.handler_off_);
2379}
2380
2381void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2382 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002383 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002384 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002385 } else {
2386 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002387 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002388 remaining_count_ = -1;
2389 catch_all_ = false;
2390 DCHECK(!HasNext());
2391 }
2392}
2393
Ian Rogers13735952014-10-08 12:43:28 -07002394void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002395 current_data_ = handler_data;
2396 remaining_count_ = DecodeSignedLeb128(&current_data_);
2397
2398 // If remaining_count_ is non-positive, then it is the negative of
2399 // the number of catch types, and the catches are followed by a
2400 // catch-all handler.
2401 if (remaining_count_ <= 0) {
2402 catch_all_ = true;
2403 remaining_count_ = -remaining_count_;
2404 } else {
2405 catch_all_ = false;
2406 }
2407 Next();
2408}
2409
2410void CatchHandlerIterator::Next() {
2411 if (remaining_count_ > 0) {
2412 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2413 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2414 remaining_count_--;
2415 return;
2416 }
2417
2418 if (catch_all_) {
2419 handler_.type_idx_ = DexFile::kDexNoIndex16;
2420 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2421 catch_all_ = false;
2422 return;
2423 }
2424
2425 // no more handler
2426 remaining_count_ = -1;
2427}
2428
Carl Shapiro1fb86202011-06-27 17:43:13 -07002429} // namespace art