blob: b3ca6ac131aebb3436cf71094e99b49dc725fbba [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;
234 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
235 if (map.get() == nullptr) {
236 DCHECK(!error_msg->empty());
237 return nullptr;
238 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700239 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800240
241 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700242 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800243 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700244 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800245 }
246
247 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
248
Andreas Gampe928f72b2014-09-09 19:53:48 -0700249 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
250 error_msg));
251 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700252 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
253 error_msg->c_str());
254 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800255 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800256
Andreas Gampe928f72b2014-09-09 19:53:48 -0700257 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
258 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800260 }
261
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800262 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700263}
264
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700265const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700266
Andreas Gampe833a4852014-05-21 18:46:59 -0700267bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800268 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700269 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700270 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 if (zip_archive.get() == nullptr) {
272 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700274 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700275 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800276}
277
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800278std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
279 uint32_t location_checksum,
280 MemMap* mem_map,
281 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800282 return OpenMemory(mem_map->Begin(),
283 mem_map->Size(),
284 location,
285 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700286 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800287 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700288 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800289}
290
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800291std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
292 const std::string& location, std::string* error_msg,
293 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800294 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700296 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700298 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700299 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700300 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700301 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700302 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700304 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700306 }
Ian Rogers700a4022014-05-19 16:49:03 -0700307 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 error_msg));
309 if (dex_file.get() == nullptr) {
310 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
311 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700312 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700313 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800314 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700315 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700318 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700319 }
320 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700321 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
322 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700324 return nullptr;
325 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700326 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800327 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700328}
329
Andreas Gampe90e34042015-04-27 20:01:52 -0700330// Technically we do not have a limitation with respect to the number of dex files that can be in a
331// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
332// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
333// seems an excessive number.
334static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
335
Andreas Gampe833a4852014-05-21 18:46:59 -0700336bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800337 std::string* error_msg,
338 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700339 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 ZipOpenErrorCode error_code;
341 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
342 &error_code));
343 if (dex_file.get() == nullptr) {
344 return false;
345 } else {
346 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800347 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700348
349 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700350
351 // We could try to avoid std::string allocations by working on a char array directly. As we
352 // do not expect a lot of iterations, this seems too involved and brittle.
353
Andreas Gampe90e34042015-04-27 20:01:52 -0700354 for (size_t i = 1; ; ++i) {
355 std::string name = GetMultiDexClassesDexName(i);
356 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700357 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
358 error_msg, &error_code));
359 if (next_dex_file.get() == nullptr) {
360 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
361 LOG(WARNING) << error_msg;
362 }
363 break;
364 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800365 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 }
367
Andreas Gampe90e34042015-04-27 20:01:52 -0700368 if (i == kWarnOnManyDexFilesThreshold) {
369 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
370 << " dex files. Please consider coalescing and shrinking the number to "
371 " avoid runtime overhead.";
372 }
373
374 if (i == std::numeric_limits<size_t>::max()) {
375 LOG(ERROR) << "Overflow in number of dex files!";
376 break;
377 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700378 }
379
380 return true;
381 }
382}
383
384
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800385std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
386 size_t size,
387 const std::string& location,
388 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800389 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700390 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800391 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700392 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800393 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700394 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800396 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700397 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800398 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700399}
400
Ian Rogers13735952014-10-08 12:43:28 -0700401DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800402 const std::string& location,
403 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800404 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700405 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800406 : begin_(base),
407 size_(size),
408 location_(location),
409 location_checksum_(location_checksum),
410 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800411 header_(reinterpret_cast<const Header*>(base)),
412 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
413 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
414 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
415 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
416 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700417 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800420 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300421 const uint8_t* lookup_data = (oat_dex_file != nullptr)
422 ? oat_dex_file->GetLookupTableData()
423 : nullptr;
424 if (lookup_data != nullptr) {
425 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
426 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
427 } else {
428 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
429 }
430 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800431}
432
Jesse Wilson6bf19152011-09-29 13:12:33 -0400433DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700434 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
435 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
436 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
437 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400438}
439
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700440bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700442 return false;
443 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700444 return true;
445}
446
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800448 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700449 std::ostringstream oss;
450 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800451 << " " << header_->magic_[0]
452 << " " << header_->magic_[1]
453 << " " << header_->magic_[2]
454 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700455 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700456 return false;
457 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800458 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700459 std::ostringstream oss;
460 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800461 << " " << header_->magic_[4]
462 << " " << header_->magic_[5]
463 << " " << header_->magic_[6]
464 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700465 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700466 return false;
467 }
468 return true;
469}
470
Ian Rogers13735952014-10-08 12:43:28 -0700471bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800472 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
473}
474
Ian Rogers13735952014-10-08 12:43:28 -0700475bool DexFile::IsVersionValid(const uint8_t* magic) {
476 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800477 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
478}
479
Ian Rogersd81871c2011-10-03 13:57:23 -0700480uint32_t DexFile::GetVersion() const {
481 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
482 return atoi(version);
483}
484
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800485const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
486 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300487 if (LIKELY(lookup_table_ != nullptr)) {
488 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
489 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700490 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300491
Ian Rogers68b56852014-08-29 20:19:11 -0700492 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300493 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700494 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700495 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700496 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300497 const TypeId* type_id = FindTypeId(descriptor);
498 if (type_id != nullptr) {
499 uint16_t type_idx = GetIndexForTypeId(*type_id);
500 for (size_t i = 0; i < num_class_defs; ++i) {
501 const ClassDef& class_def = GetClassDef(i);
502 if (class_def.class_idx_ == type_idx) {
503 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700504 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700505 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700506 }
Ian Rogers68b56852014-08-29 20:19:11 -0700507 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700508}
509
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700510const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
511 size_t num_class_defs = NumClassDefs();
512 for (size_t i = 0; i < num_class_defs; ++i) {
513 const ClassDef& class_def = GetClassDef(i);
514 if (class_def.class_idx_ == type_idx) {
515 return &class_def;
516 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700517 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700518 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700519}
520
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800521const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
522 const DexFile::StringId& name,
523 const DexFile::TypeId& type) const {
524 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
525 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
526 const uint32_t name_idx = GetIndexForStringId(name);
527 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700528 int32_t lo = 0;
529 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800530 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700531 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800532 const DexFile::FieldId& field = GetFieldId(mid);
533 if (class_idx > field.class_idx_) {
534 lo = mid + 1;
535 } else if (class_idx < field.class_idx_) {
536 hi = mid - 1;
537 } else {
538 if (name_idx > field.name_idx_) {
539 lo = mid + 1;
540 } else if (name_idx < field.name_idx_) {
541 hi = mid - 1;
542 } else {
543 if (type_idx > field.type_idx_) {
544 lo = mid + 1;
545 } else if (type_idx < field.type_idx_) {
546 hi = mid - 1;
547 } else {
548 return &field;
549 }
550 }
551 }
552 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700553 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800554}
555
556const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700557 const DexFile::StringId& name,
558 const DexFile::ProtoId& signature) const {
559 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800560 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700561 const uint32_t name_idx = GetIndexForStringId(name);
562 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700563 int32_t lo = 0;
564 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700565 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700566 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700567 const DexFile::MethodId& method = GetMethodId(mid);
568 if (class_idx > method.class_idx_) {
569 lo = mid + 1;
570 } else if (class_idx < method.class_idx_) {
571 hi = mid - 1;
572 } else {
573 if (name_idx > method.name_idx_) {
574 lo = mid + 1;
575 } else if (name_idx < method.name_idx_) {
576 hi = mid - 1;
577 } else {
578 if (proto_idx > method.proto_idx_) {
579 lo = mid + 1;
580 } else if (proto_idx < method.proto_idx_) {
581 hi = mid - 1;
582 } else {
583 return &method;
584 }
585 }
586 }
587 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700588 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700589}
590
Ian Rogers637c65b2013-05-31 11:46:00 -0700591const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t lo = 0;
593 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700594 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700595 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700596 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700597 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700598 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
599 if (compare > 0) {
600 lo = mid + 1;
601 } else if (compare < 0) {
602 hi = mid - 1;
603 } else {
604 return &str_id;
605 }
606 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700608}
609
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300610const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
611 int32_t lo = 0;
612 int32_t hi = NumTypeIds() - 1;
613 while (hi >= lo) {
614 int32_t mid = (hi + lo) / 2;
615 const TypeId& type_id = GetTypeId(mid);
616 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
617 const char* str = GetStringData(str_id);
618 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
619 if (compare > 0) {
620 lo = mid + 1;
621 } else if (compare < 0) {
622 hi = mid - 1;
623 } else {
624 return &type_id;
625 }
626 }
627 return nullptr;
628}
629
Vladimir Markoa48aef42014-12-03 17:53:53 +0000630const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700631 int32_t lo = 0;
632 int32_t hi = NumStringIds() - 1;
633 while (hi >= lo) {
634 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700635 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700636 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000637 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700638 if (compare > 0) {
639 lo = mid + 1;
640 } else if (compare < 0) {
641 hi = mid - 1;
642 } else {
643 return &str_id;
644 }
645 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700647}
648
649const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700650 int32_t lo = 0;
651 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700652 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700653 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700654 const TypeId& type_id = GetTypeId(mid);
655 if (string_idx > type_id.descriptor_idx_) {
656 lo = mid + 1;
657 } else if (string_idx < type_id.descriptor_idx_) {
658 hi = mid - 1;
659 } else {
660 return &type_id;
661 }
662 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700663 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700664}
665
666const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000667 const uint16_t* signature_type_idxs,
668 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t lo = 0;
670 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700671 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700672 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700673 const DexFile::ProtoId& proto = GetProtoId(mid);
674 int compare = return_type_idx - proto.return_type_idx_;
675 if (compare == 0) {
676 DexFileParameterIterator it(*this, proto);
677 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000678 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800679 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700680 it.Next();
681 i++;
682 }
683 if (compare == 0) {
684 if (it.HasNext()) {
685 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000686 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700687 compare = 1;
688 }
689 }
690 }
691 if (compare > 0) {
692 lo = mid + 1;
693 } else if (compare < 0) {
694 hi = mid - 1;
695 } else {
696 return &proto;
697 }
698 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700699 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700700}
701
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300702void DexFile::CreateTypeLookupTable() const {
703 lookup_table_.reset(TypeLookupTable::Create(*this));
704}
705
Ian Rogers0571d352011-11-03 19:51:38 -0700706// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700707bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
708 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700709 if (signature[0] != '(') {
710 return false;
711 }
712 size_t offset = 1;
713 size_t end = signature.size();
714 bool process_return = false;
715 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000716 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700717 char c = signature[offset];
718 offset++;
719 if (c == ')') {
720 process_return = true;
721 continue;
722 }
Ian Rogers0571d352011-11-03 19:51:38 -0700723 while (c == '[') { // process array prefix
724 if (offset >= end) { // expect some descriptor following [
725 return false;
726 }
727 c = signature[offset];
728 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700729 }
730 if (c == 'L') { // process type descriptors
731 do {
732 if (offset >= end) { // unexpected early termination of descriptor
733 return false;
734 }
735 c = signature[offset];
736 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700737 } while (c != ';');
738 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000739 // TODO: avoid creating a std::string just to get a 0-terminated char array
740 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Ian Rogers637c65b2013-05-31 11:46:00 -0700741 const DexFile::StringId* string_id = FindStringId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700742 if (string_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700743 return false;
744 }
745 const DexFile::TypeId* type_id = FindTypeId(GetIndexForStringId(*string_id));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700747 return false;
748 }
749 uint16_t type_idx = GetIndexForTypeId(*type_id);
750 if (!process_return) {
751 param_type_idxs->push_back(type_idx);
752 } else {
753 *return_type_idx = type_idx;
754 return offset == end; // return true if the signature had reached a sensible end
755 }
756 }
757 return false; // failed to correctly parse return type
758}
759
Ian Rogersd91d6d62013-09-25 20:26:14 -0700760const Signature DexFile::CreateSignature(const StringPiece& signature) const {
761 uint16_t return_type_idx;
762 std::vector<uint16_t> param_type_indices;
763 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
764 if (!success) {
765 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700766 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700767 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700768 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700769 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700770 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700771 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700772}
773
Mathieu Chartiere401d142015-04-22 13:56:20 -0700774int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700775 // For native method, lineno should be -2 to indicate it is native. Note that
776 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700778 return -2;
779 }
780
TDYa127c8dc1012012-04-19 07:03:33 -0700781 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700782 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700783
784 // A method with no line number info should return -1
785 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700786 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700787 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700788 return context.line_num_;
789}
790
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700791int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700792 // Note: Signed type is important for max and min.
793 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700794 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700795
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700796 while (min <= max) {
797 int32_t mid = min + ((max - min) / 2);
798
799 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
800 uint32_t start = ti->start_addr_;
801 uint32_t end = start + ti->insn_count_;
802
Ian Rogers0571d352011-11-03 19:51:38 -0700803 if (address < start) {
804 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700805 } else if (address >= end) {
806 min = mid + 1;
807 } else { // We have a winner!
808 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700809 }
810 }
811 // No match.
812 return -1;
813}
814
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700815int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
816 int32_t try_item = FindTryItem(code_item, address);
817 if (try_item == -1) {
818 return -1;
819 } else {
820 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
821 }
822}
823
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800824void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800825 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700826 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
827 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700828 uint32_t line = DecodeUnsignedLeb128(&stream);
829 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
830 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
831 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700832 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700833
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800834 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700835 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800836 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700837 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800838 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700840 local_in_reg[arg_reg].start_address_ = 0;
841 local_in_reg[arg_reg].is_live_ = true;
842 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700843 arg_reg++;
844 }
845
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700847 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700848 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700849 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800850 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700851 return;
852 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800853 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700854 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800855 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700856 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700857 local_in_reg[arg_reg].name_ = name;
858 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700859 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700860 local_in_reg[arg_reg].start_address_ = address;
861 local_in_reg[arg_reg].is_live_ = true;
862 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700863 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700864 case 'D':
865 case 'J':
866 arg_reg += 2;
867 break;
868 default:
869 arg_reg += 1;
870 break;
871 }
872 }
873
Ian Rogers0571d352011-11-03 19:51:38 -0700874 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800875 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
876 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700877 return;
878 }
879
880 for (;;) {
881 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700882 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800883 uint32_t name_idx;
884 uint32_t descriptor_idx;
885 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700886
Shih-wei Liao195487c2011-08-20 13:29:04 -0700887 switch (opcode) {
888 case DBG_END_SEQUENCE:
889 return;
890
891 case DBG_ADVANCE_PC:
892 address += DecodeUnsignedLeb128(&stream);
893 break;
894
895 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700896 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700897 break;
898
899 case DBG_START_LOCAL:
900 case DBG_START_LOCAL_EXTENDED:
901 reg = DecodeUnsignedLeb128(&stream);
902 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700903 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800904 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700905 return;
906 }
907
jeffhaof8728872011-10-28 19:11:13 -0700908 name_idx = DecodeUnsignedLeb128P1(&stream);
909 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
910 if (opcode == DBG_START_LOCAL_EXTENDED) {
911 signature_idx = DecodeUnsignedLeb128P1(&stream);
912 }
913
Shih-wei Liao195487c2011-08-20 13:29:04 -0700914 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700915 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800916 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700917
Ian Rogers0571d352011-11-03 19:51:38 -0700918 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
919 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700920 local_in_reg[reg].signature_ =
921 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
922 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700923 local_in_reg[reg].start_address_ = address;
924 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 break;
927
928 case DBG_END_LOCAL:
929 reg = DecodeUnsignedLeb128(&stream);
930 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700931 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800932 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700933 return;
934 }
935
Elliott Hughes30646832011-10-13 16:59:46 -0700936 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800937 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700938 local_in_reg[reg].is_live_ = false;
939 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700940 break;
941
942 case DBG_RESTART_LOCAL:
943 reg = DecodeUnsignedLeb128(&stream);
944 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700945 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800946 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700947 return;
948 }
949
Elliott Hughes30646832011-10-13 16:59:46 -0700950 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700951 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800952 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700953 return;
954 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700955
Elliott Hughes30646832011-10-13 16:59:46 -0700956 // If the register is live, the "restart" is superfluous,
957 // and we don't want to mess with the existing start address.
958 if (!local_in_reg[reg].is_live_) {
959 local_in_reg[reg].start_address_ = address;
960 local_in_reg[reg].is_live_ = true;
961 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700962 }
963 break;
964
965 case DBG_SET_PROLOGUE_END:
966 case DBG_SET_EPILOGUE_BEGIN:
967 case DBG_SET_FILE:
968 break;
969
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700970 default: {
971 int adjopcode = opcode - DBG_FIRST_SPECIAL;
972
Shih-wei Liao195487c2011-08-20 13:29:04 -0700973 address += adjopcode / DBG_LINE_RANGE;
974 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
975
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700976 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800977 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700978 // early exit
979 return;
980 }
981 }
982 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700983 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700984 }
985 }
986}
987
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800988void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800989 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
990 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100991 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700992 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700993 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700994 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700995 nullptr);
996 if (stream != nullptr) {
997 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
998 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700999 }
1000 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001001 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
1002 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -07001003 }
1004}
1005
Elliott Hughes2435a572012-02-17 16:07:41 -08001006bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1007 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001008
1009 // We know that this callback will be called in
1010 // ascending address order, so keep going until we find
1011 // a match or we've just gone past it.
1012 if (address > context->address_) {
1013 // The line number from the previous positions callback
1014 // wil be the final result.
1015 return true;
1016 } else {
1017 context->line_num_ = line_num;
1018 return address == context->address_;
1019 }
1020}
1021
Andreas Gampe833a4852014-05-21 18:46:59 -07001022bool DexFile::IsMultiDexLocation(const char* location) {
1023 return strrchr(location, kMultiDexSeparator) != nullptr;
1024}
1025
Andreas Gampe90e34042015-04-27 20:01:52 -07001026std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1027 if (index == 0) {
1028 return "classes.dex";
1029 } else {
1030 return StringPrintf("classes%zu.dex", index + 1);
1031 }
1032}
1033
1034std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1035 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001036 return dex_location;
1037 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001038 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001039 }
1040}
1041
1042std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1043 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001044 std::string base_location = GetBaseLocation(dex_location);
1045 const char* suffix = dex_location + base_location.size();
1046 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1047 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1048 if (path != nullptr && path.get() != base_location) {
1049 return std::string(path.get()) + suffix;
1050 } else if (suffix[0] == 0) {
1051 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001052 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001053 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001054 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001055}
1056
Jeff Hao13e748b2015-08-25 20:44:19 +00001057// Read a signed integer. "zwidth" is the zero-based byte count.
1058static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1059 int32_t val = 0;
1060 for (int i = zwidth; i >= 0; --i) {
1061 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1062 }
1063 val >>= (3 - zwidth) * 8;
1064 return val;
1065}
1066
1067// Read an unsigned integer. "zwidth" is the zero-based byte count,
1068// "fill_on_right" indicates which side we want to zero-fill from.
1069static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1070 uint32_t val = 0;
1071 for (int i = zwidth; i >= 0; --i) {
1072 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1073 }
1074 if (!fill_on_right) {
1075 val >>= (3 - zwidth) * 8;
1076 }
1077 return val;
1078}
1079
1080// Read a signed long. "zwidth" is the zero-based byte count.
1081static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1082 int64_t val = 0;
1083 for (int i = zwidth; i >= 0; --i) {
1084 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1085 }
1086 val >>= (7 - zwidth) * 8;
1087 return val;
1088}
1089
1090// Read an unsigned long. "zwidth" is the zero-based byte count,
1091// "fill_on_right" indicates which side we want to zero-fill from.
1092static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1093 uint64_t val = 0;
1094 for (int i = zwidth; i >= 0; --i) {
1095 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1096 }
1097 if (!fill_on_right) {
1098 val >>= (7 - zwidth) * 8;
1099 }
1100 return val;
1101}
1102
1103const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1104 mirror::Class* klass = field->GetDeclaringClass();
1105 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1106 if (annotations_dir == nullptr) {
1107 return nullptr;
1108 }
1109 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1110 if (field_annotations == nullptr) {
1111 return nullptr;
1112 }
1113 uint32_t field_index = field->GetDexFieldIndex();
1114 uint32_t field_count = annotations_dir->fields_size_;
1115 for (uint32_t i = 0; i < field_count; ++i) {
1116 if (field_annotations[i].field_idx_ == field_index) {
1117 return GetFieldAnnotationSetItem(field_annotations[i]);
1118 }
1119 }
1120 return nullptr;
1121}
1122
1123mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1124 Handle<mirror::Class> annotation_class) const {
1125 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1126 if (annotation_set == nullptr) {
1127 return nullptr;
1128 }
1129 StackHandleScope<1> hs(Thread::Current());
1130 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1131 return GetAnnotationObjectFromAnnotationSet(
1132 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1133}
1134
1135mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1136 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1137 StackHandleScope<1> hs(Thread::Current());
1138 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1139 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1140}
1141
Jeff Hao2a5892f2015-08-31 15:00:40 -07001142mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001143 const {
1144 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1145 if (annotation_set == nullptr) {
1146 return nullptr;
1147 }
1148 StackHandleScope<1> hs(Thread::Current());
1149 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1150 return GetSignatureValue(field_class, annotation_set);
1151}
1152
1153bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1154 const {
1155 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1156 if (annotation_set == nullptr) {
1157 return false;
1158 }
1159 StackHandleScope<1> hs(Thread::Current());
1160 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1161 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1162 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1163 return annotation_item != nullptr;
1164}
1165
1166const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1167 mirror::Class* klass = method->GetDeclaringClass();
1168 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1169 if (annotations_dir == nullptr) {
1170 return nullptr;
1171 }
1172 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1173 if (method_annotations == nullptr) {
1174 return nullptr;
1175 }
1176 uint32_t method_index = method->GetDexMethodIndex();
1177 uint32_t method_count = annotations_dir->methods_size_;
1178 for (uint32_t i = 0; i < method_count; ++i) {
1179 if (method_annotations[i].method_idx_ == method_index) {
1180 return GetMethodAnnotationSetItem(method_annotations[i]);
1181 }
1182 }
1183 return nullptr;
1184}
1185
1186const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1187 const {
1188 mirror::Class* klass = method->GetDeclaringClass();
1189 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1190 if (annotations_dir == nullptr) {
1191 return nullptr;
1192 }
1193 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1194 if (parameter_annotations == nullptr) {
1195 return nullptr;
1196 }
1197 uint32_t method_index = method->GetDexMethodIndex();
1198 uint32_t parameter_count = annotations_dir->parameters_size_;
1199 for (uint32_t i = 0; i < parameter_count; ++i) {
1200 if (parameter_annotations[i].method_idx_ == method_index) {
1201 return &parameter_annotations[i];
1202 }
1203 }
1204 return nullptr;
1205}
1206
1207mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1208 mirror::Class* klass = method->GetDeclaringClass();
1209 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1210 if (annotations_dir == nullptr) {
1211 return nullptr;
1212 }
1213 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1214 if (annotation_set == nullptr) {
1215 return nullptr;
1216 }
1217 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1218 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1219 if (annotation_item == nullptr) {
1220 return nullptr;
1221 }
1222 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1223 if (annotation == nullptr) {
1224 return nullptr;
1225 }
1226 uint8_t header_byte = *(annotation++);
1227 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1228 return nullptr;
1229 }
1230 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1231 if (annotation == nullptr) {
1232 return nullptr;
1233 }
1234 AnnotationValue annotation_value;
1235 StackHandleScope<2> hs(Thread::Current());
1236 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001237 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1238 Handle<mirror::Class> return_type(hs.NewHandle(
1239 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001240 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1241 return nullptr;
1242 }
1243 return annotation_value.value_.GetL();
1244}
1245
1246mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1247 Handle<mirror::Class> annotation_class) const {
1248 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1249 if (annotation_set == nullptr) {
1250 return nullptr;
1251 }
1252 StackHandleScope<1> hs(Thread::Current());
1253 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1254 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1255 kDexVisibilityRuntime, annotation_class);
1256}
1257
1258mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1259 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1260 StackHandleScope<1> hs(Thread::Current());
1261 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1262 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1263}
1264
Jeff Hao2a5892f2015-08-31 15:00:40 -07001265mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001266 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1267 if (annotation_set == nullptr) {
1268 return nullptr;
1269 }
1270 StackHandleScope<1> hs(Thread::Current());
1271 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1272 return GetThrowsValue(method_class, annotation_set);
1273}
1274
1275mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1276 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1277 if (parameter_annotations == nullptr) {
1278 return nullptr;
1279 }
1280 const AnnotationSetRefList* set_ref_list =
1281 GetParameterAnnotationSetRefList(parameter_annotations);
1282 if (set_ref_list == nullptr) {
1283 return nullptr;
1284 }
1285 uint32_t size = set_ref_list->size_;
1286 StackHandleScope<1> hs(Thread::Current());
1287 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1288 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1289}
1290
1291bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1292 const {
1293 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1294 if (annotation_set == nullptr) {
1295 return false;
1296 }
1297 StackHandleScope<1> hs(Thread::Current());
1298 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1299 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1300 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001301 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001302}
1303
1304const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1305 const {
1306 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1307 if (annotations_dir == nullptr) {
1308 return nullptr;
1309 }
1310 return GetClassAnnotationSet(annotations_dir);
1311}
1312
1313mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1314 Handle<mirror::Class> annotation_class) const {
1315 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1316 if (annotation_set == nullptr) {
1317 return nullptr;
1318 }
1319 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1320 annotation_class);
1321}
1322
1323mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1324 const {
1325 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1326 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1327}
1328
Jeff Hao2a5892f2015-08-31 15:00:40 -07001329mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1330 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1331 if (annotation_set == nullptr) {
1332 return nullptr;
1333 }
1334 const AnnotationItem* annotation_item = SearchAnnotationSet(
1335 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1336 if (annotation_item == nullptr) {
1337 return nullptr;
1338 }
1339 StackHandleScope<1> hs(Thread::Current());
1340 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1341 Handle<mirror::Class> class_array_class(hs.NewHandle(
1342 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1343 if (class_array_class.Get() == nullptr) {
1344 return nullptr;
1345 }
1346 mirror::Object* obj = GetAnnotationValue(
1347 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1348 if (obj == nullptr) {
1349 return nullptr;
1350 }
1351 return obj->AsObjectArray<mirror::Class>();
1352}
1353
1354mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1355 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1356 if (annotation_set == nullptr) {
1357 return nullptr;
1358 }
1359 const AnnotationItem* annotation_item = SearchAnnotationSet(
1360 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1361 if (annotation_item == nullptr) {
1362 return nullptr;
1363 }
1364 mirror::Object* obj = GetAnnotationValue(
1365 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1366 if (obj == nullptr) {
1367 return nullptr;
1368 }
1369 return obj->AsClass();
1370}
1371
1372mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1373 mirror::Class* declaring_class = GetDeclaringClass(klass);
1374 if (declaring_class != nullptr) {
1375 return declaring_class;
1376 }
1377 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1378 if (annotation_set == nullptr) {
1379 return nullptr;
1380 }
1381 const AnnotationItem* annotation_item = SearchAnnotationSet(
1382 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1383 if (annotation_item == nullptr) {
1384 return nullptr;
1385 }
1386 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1387 if (annotation == nullptr) {
1388 return nullptr;
1389 }
1390 AnnotationValue annotation_value;
1391 if (!ProcessAnnotationValue(
1392 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1393 return nullptr;
1394 }
1395 if (annotation_value.type_ != kDexAnnotationMethod) {
1396 return nullptr;
1397 }
1398 StackHandleScope<2> hs(Thread::Current());
1399 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1400 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1401 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1402 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1403 if (method == nullptr) {
1404 return nullptr;
1405 }
1406 return method->GetDeclaringClass();
1407}
1408
1409mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1410 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1411 if (annotation_set == nullptr) {
1412 return nullptr;
1413 }
1414 const AnnotationItem* annotation_item = SearchAnnotationSet(
1415 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1416 if (annotation_item == nullptr) {
1417 return nullptr;
1418 }
1419 return GetAnnotationValue(
1420 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1421}
1422
1423bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1424 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1425 if (annotation_set == nullptr) {
1426 return false;
1427 }
1428 const AnnotationItem* annotation_item = SearchAnnotationSet(
1429 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1430 if (annotation_item == nullptr) {
1431 return false;
1432 }
1433 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1434 if (annotation == nullptr) {
1435 return false;
1436 }
1437 AnnotationValue annotation_value;
1438 if (!ProcessAnnotationValue(
1439 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1440 return false;
1441 }
1442 if (annotation_value.type_ != kDexAnnotationNull &&
1443 annotation_value.type_ != kDexAnnotationString) {
1444 return false;
1445 }
1446 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1447 return true;
1448}
1449
1450bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1451 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1452 if (annotation_set == nullptr) {
1453 return false;
1454 }
1455 const AnnotationItem* annotation_item = SearchAnnotationSet(
1456 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1457 if (annotation_item == nullptr) {
1458 return false;
1459 }
1460 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1461 if (annotation == nullptr) {
1462 return false;
1463 }
1464 AnnotationValue annotation_value;
1465 if (!ProcessAnnotationValue(
1466 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1467 return false;
1468 }
1469 if (annotation_value.type_ != kDexAnnotationInt) {
1470 return false;
1471 }
1472 *flags = annotation_value.value_.GetI();
1473 return true;
1474}
1475
Jeff Hao13e748b2015-08-25 20:44:19 +00001476bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1477 Handle<mirror::Class> annotation_class) const {
1478 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1479 if (annotation_set == nullptr) {
1480 return false;
1481 }
1482 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1483 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001484 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001485}
1486
1487mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1488 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1489 Thread* self = Thread::Current();
1490 ScopedObjectAccessUnchecked soa(self);
1491 StackHandleScope<5> hs(self);
1492 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1493 const char* name = StringDataByIdx(element_name_index);
1494 Handle<mirror::String> string_name(
1495 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1496
1497 ArtMethod* annotation_method =
1498 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1499 if (annotation_method == nullptr) {
1500 return nullptr;
1501 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001502 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1503 Handle<mirror::Class> method_return(hs.NewHandle(
1504 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001505
1506 AnnotationValue annotation_value;
1507 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1508 return nullptr;
1509 }
1510 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1511
1512 mirror::Class* annotation_member_class =
1513 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1514 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1515 Handle<mirror::Method> method_object(
1516 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1517
1518 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1519 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1520 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1521 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1522 return nullptr;
1523 }
1524
1525 JValue result;
1526 ArtMethod* annotation_member_init =
1527 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1528 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1529 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1530 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1531 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1532 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1533 };
1534 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1535 if (self->IsExceptionPending()) {
1536 LOG(INFO) << "Exception in AnnotationMember.<init>";
1537 return nullptr;
1538 }
1539
1540 return new_member.Get();
1541}
1542
1543const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1544 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1545 Handle<mirror::Class> annotation_class) const {
1546 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1547 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1548 if (annotation_item->visibility_ != visibility) {
1549 continue;
1550 }
1551 const uint8_t* annotation = annotation_item->annotation_;
1552 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1553 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1554 klass->GetDexFile(), type_index, klass.Get());
1555 if (resolved_class == nullptr) {
1556 std::string temp;
1557 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1558 klass->GetDescriptor(&temp), type_index);
1559 CHECK(Thread::Current()->IsExceptionPending());
1560 Thread::Current()->ClearException();
1561 continue;
1562 }
1563 if (resolved_class == annotation_class.Get()) {
1564 return annotation_item;
1565 }
1566 }
1567
1568 return nullptr;
1569}
1570
1571mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1572 const AnnotationSetItem* annotation_set, uint32_t visibility,
1573 Handle<mirror::Class> annotation_class) const {
1574 const AnnotationItem* annotation_item =
1575 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1576 if (annotation_item == nullptr) {
1577 return nullptr;
1578 }
1579 const uint8_t* annotation = annotation_item->annotation_;
1580 return ProcessEncodedAnnotation(klass, &annotation);
1581}
1582
1583mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1584 const AnnotationItem* annotation_item, const char* annotation_name,
1585 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1586 const uint8_t* annotation =
1587 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1588 if (annotation == nullptr) {
1589 return nullptr;
1590 }
1591 AnnotationValue annotation_value;
1592 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1593 return nullptr;
1594 }
1595 if (annotation_value.type_ != expected_type) {
1596 return nullptr;
1597 }
1598 return annotation_value.value_.GetL();
1599}
1600
Jeff Hao2a5892f2015-08-31 15:00:40 -07001601mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001602 const AnnotationSetItem* annotation_set) const {
1603 StackHandleScope<1> hs(Thread::Current());
1604 const AnnotationItem* annotation_item =
1605 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1606 if (annotation_item == nullptr) {
1607 return nullptr;
1608 }
1609 mirror::Class* string_class = mirror::String::GetJavaLangString();
1610 Handle<mirror::Class> string_array_class(hs.NewHandle(
1611 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001612 if (string_array_class.Get() == nullptr) {
1613 return nullptr;
1614 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001615 mirror::Object* obj =
1616 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1617 if (obj == nullptr) {
1618 return nullptr;
1619 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001620 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001621}
1622
Jeff Hao2a5892f2015-08-31 15:00:40 -07001623mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001624 const AnnotationSetItem* annotation_set) const {
1625 StackHandleScope<1> hs(Thread::Current());
1626 const AnnotationItem* annotation_item =
1627 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1628 if (annotation_item == nullptr) {
1629 return nullptr;
1630 }
1631 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1632 Handle<mirror::Class> class_array_class(hs.NewHandle(
1633 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001634 if (class_array_class.Get() == nullptr) {
1635 return nullptr;
1636 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001637 mirror::Object* obj =
1638 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1639 if (obj == nullptr) {
1640 return nullptr;
1641 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001642 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001643}
1644
1645mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1646 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1647 Thread* self = Thread::Current();
1648 ScopedObjectAccessUnchecked soa(self);
1649 StackHandleScope<2> hs(self);
1650 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1651 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1652 if (annotation_set == nullptr) {
1653 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1654 }
1655
1656 uint32_t size = annotation_set->size_;
1657 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1658 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1659 if (result.Get() == nullptr) {
1660 return nullptr;
1661 }
1662
1663 uint32_t dest_index = 0;
1664 for (uint32_t i = 0; i < size; ++i) {
1665 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1666 if (annotation_item->visibility_ != visibility) {
1667 continue;
1668 }
1669 const uint8_t* annotation = annotation_item->annotation_;
1670 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1671 if (annotation_obj != nullptr) {
1672 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1673 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001674 } else if (self->IsExceptionPending()) {
1675 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001676 }
1677 }
1678
1679 if (dest_index == size) {
1680 return result.Get();
1681 }
1682
1683 mirror::ObjectArray<mirror::Object>* trimmed_result =
1684 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001685 if (trimmed_result == nullptr) {
1686 return nullptr;
1687 }
1688
Jeff Hao13e748b2015-08-25 20:44:19 +00001689 for (uint32_t i = 0; i < dest_index; ++i) {
1690 mirror::Object* obj = result->GetWithoutChecks(i);
1691 trimmed_result->SetWithoutChecks<false>(i, obj);
1692 }
1693
1694 return trimmed_result;
1695}
1696
1697mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1698 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1699 Thread* self = Thread::Current();
1700 ScopedObjectAccessUnchecked soa(self);
1701 StackHandleScope<1> hs(self);
1702 mirror::Class* annotation_array_class =
1703 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1704 mirror::Class* annotation_array_array_class =
1705 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001706 if (annotation_array_array_class == nullptr) {
1707 return nullptr;
1708 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001709 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1710 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1711 if (annotation_array_array.Get() == nullptr) {
1712 LOG(ERROR) << "Annotation set ref array allocation failed";
1713 return nullptr;
1714 }
1715 for (uint32_t index = 0; index < size; ++index) {
1716 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1717 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1718 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1719 if (annotation_set == nullptr) {
1720 return nullptr;
1721 }
1722 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1723 }
1724 return annotation_array_array.Get();
1725}
1726
1727bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1728 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1729 DexFile::AnnotationResultStyle result_style) const {
1730 Thread* self = Thread::Current();
1731 mirror::Object* element_object = nullptr;
1732 bool set_object = false;
1733 Primitive::Type primitive_type = Primitive::kPrimVoid;
1734 const uint8_t* annotation = *annotation_ptr;
1735 uint8_t header_byte = *(annotation++);
1736 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1737 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1738 int32_t width = value_arg + 1;
1739 annotation_value->type_ = value_type;
1740
1741 switch (value_type) {
1742 case kDexAnnotationByte:
1743 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1744 primitive_type = Primitive::kPrimByte;
1745 break;
1746 case kDexAnnotationShort:
1747 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1748 primitive_type = Primitive::kPrimShort;
1749 break;
1750 case kDexAnnotationChar:
1751 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1752 false)));
1753 primitive_type = Primitive::kPrimChar;
1754 break;
1755 case kDexAnnotationInt:
1756 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1757 primitive_type = Primitive::kPrimInt;
1758 break;
1759 case kDexAnnotationLong:
1760 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1761 primitive_type = Primitive::kPrimLong;
1762 break;
1763 case kDexAnnotationFloat:
1764 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1765 primitive_type = Primitive::kPrimFloat;
1766 break;
1767 case kDexAnnotationDouble:
1768 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1769 primitive_type = Primitive::kPrimDouble;
1770 break;
1771 case kDexAnnotationBoolean:
1772 annotation_value->value_.SetZ(value_arg != 0);
1773 primitive_type = Primitive::kPrimBoolean;
1774 width = 0;
1775 break;
1776 case kDexAnnotationString: {
1777 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1778 if (result_style == kAllRaw) {
1779 annotation_value->value_.SetI(index);
1780 } else {
1781 StackHandleScope<1> hs(self);
1782 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1783 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1784 klass->GetDexFile(), index, dex_cache);
1785 set_object = true;
1786 if (element_object == nullptr) {
1787 return false;
1788 }
1789 }
1790 break;
1791 }
1792 case kDexAnnotationType: {
1793 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1794 if (result_style == kAllRaw) {
1795 annotation_value->value_.SetI(index);
1796 } else {
1797 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1798 klass->GetDexFile(), index, klass.Get());
1799 set_object = true;
1800 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001801 CHECK(self->IsExceptionPending());
1802 if (result_style == kAllObjects) {
1803 const char* msg = StringByTypeIdx(index);
1804 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1805 element_object = self->GetException();
1806 self->ClearException();
1807 } else {
1808 return false;
1809 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001810 }
1811 }
1812 break;
1813 }
1814 case kDexAnnotationMethod: {
1815 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1816 if (result_style == kAllRaw) {
1817 annotation_value->value_.SetI(index);
1818 } else {
1819 StackHandleScope<2> hs(self);
1820 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1821 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1822 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1823 klass->GetDexFile(), index, dex_cache, class_loader);
1824 if (method == nullptr) {
1825 return false;
1826 }
1827 set_object = true;
1828 if (method->IsConstructor()) {
1829 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1830 } else {
1831 element_object = mirror::Method::CreateFromArtMethod(self, method);
1832 }
1833 if (element_object == nullptr) {
1834 return false;
1835 }
1836 }
1837 break;
1838 }
1839 case kDexAnnotationField: {
1840 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1841 if (result_style == kAllRaw) {
1842 annotation_value->value_.SetI(index);
1843 } else {
1844 StackHandleScope<2> hs(self);
1845 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1846 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1847 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1848 klass->GetDexFile(), index, dex_cache, class_loader);
1849 if (field == nullptr) {
1850 return false;
1851 }
1852 set_object = true;
1853 element_object = mirror::Field::CreateFromArtField(self, field, true);
1854 if (element_object == nullptr) {
1855 return false;
1856 }
1857 }
1858 break;
1859 }
1860 case kDexAnnotationEnum: {
1861 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1862 if (result_style == kAllRaw) {
1863 annotation_value->value_.SetI(index);
1864 } else {
1865 StackHandleScope<3> hs(self);
1866 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1867 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1868 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1869 klass->GetDexFile(), index, dex_cache, class_loader, true);
1870 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1871 if (enum_field == nullptr) {
1872 return false;
1873 } else {
1874 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1875 element_object = enum_field->GetObject(field_class.Get());
1876 set_object = true;
1877 }
1878 }
1879 break;
1880 }
1881 case kDexAnnotationArray:
1882 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1883 return false;
1884 } else {
1885 ScopedObjectAccessUnchecked soa(self);
1886 StackHandleScope<2> hs(self);
1887 uint32_t size = DecodeUnsignedLeb128(&annotation);
1888 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1889 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1890 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1891 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1892 if (new_array.Get() == nullptr) {
1893 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1894 return false;
1895 }
1896 AnnotationValue new_annotation_value;
1897 for (uint32_t i = 0; i < size; ++i) {
1898 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1899 kPrimitivesOrObjects)) {
1900 return false;
1901 }
1902 if (!component_type->IsPrimitive()) {
1903 mirror::Object* obj = new_annotation_value.value_.GetL();
1904 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1905 } else {
1906 switch (new_annotation_value.type_) {
1907 case kDexAnnotationByte:
1908 new_array->AsByteArray()->SetWithoutChecks<false>(
1909 i, new_annotation_value.value_.GetB());
1910 break;
1911 case kDexAnnotationShort:
1912 new_array->AsShortArray()->SetWithoutChecks<false>(
1913 i, new_annotation_value.value_.GetS());
1914 break;
1915 case kDexAnnotationChar:
1916 new_array->AsCharArray()->SetWithoutChecks<false>(
1917 i, new_annotation_value.value_.GetC());
1918 break;
1919 case kDexAnnotationInt:
1920 new_array->AsIntArray()->SetWithoutChecks<false>(
1921 i, new_annotation_value.value_.GetI());
1922 break;
1923 case kDexAnnotationLong:
1924 new_array->AsLongArray()->SetWithoutChecks<false>(
1925 i, new_annotation_value.value_.GetJ());
1926 break;
1927 case kDexAnnotationFloat:
1928 new_array->AsFloatArray()->SetWithoutChecks<false>(
1929 i, new_annotation_value.value_.GetF());
1930 break;
1931 case kDexAnnotationDouble:
1932 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1933 i, new_annotation_value.value_.GetD());
1934 break;
1935 case kDexAnnotationBoolean:
1936 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1937 i, new_annotation_value.value_.GetZ());
1938 break;
1939 default:
1940 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1941 return false;
1942 }
1943 }
1944 }
1945 element_object = new_array.Get();
1946 set_object = true;
1947 width = 0;
1948 }
1949 break;
1950 case kDexAnnotationAnnotation:
1951 if (result_style == kAllRaw) {
1952 return false;
1953 }
1954 element_object = ProcessEncodedAnnotation(klass, &annotation);
1955 if (element_object == nullptr) {
1956 return false;
1957 }
1958 set_object = true;
1959 width = 0;
1960 break;
1961 case kDexAnnotationNull:
1962 if (result_style == kAllRaw) {
1963 annotation_value->value_.SetI(0);
1964 } else {
1965 CHECK(element_object == nullptr);
1966 set_object = true;
1967 }
1968 width = 0;
1969 break;
1970 default:
1971 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1972 return false;
1973 }
1974
1975 annotation += width;
1976 *annotation_ptr = annotation;
1977
1978 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1979 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1980 set_object = true;
1981 }
1982
1983 if (set_object) {
1984 annotation_value->value_.SetL(element_object);
1985 }
1986
1987 return true;
1988}
1989
1990mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1991 const uint8_t** annotation) const {
1992 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1993 uint32_t size = DecodeUnsignedLeb128(annotation);
1994
1995 Thread* self = Thread::Current();
1996 ScopedObjectAccessUnchecked soa(self);
1997 StackHandleScope<2> hs(self);
1998 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1999 Handle<mirror::Class> annotation_class(hs.NewHandle(
2000 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2001 if (annotation_class.Get() == nullptr) {
2002 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2003 << type_index;
2004 DCHECK(Thread::Current()->IsExceptionPending());
2005 Thread::Current()->ClearException();
2006 return nullptr;
2007 }
2008
2009 mirror::Class* annotation_member_class =
2010 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2011 mirror::Class* annotation_member_array_class =
2012 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002013 if (annotation_member_array_class == nullptr) {
2014 return nullptr;
2015 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002016 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002017 if (size > 0) {
2018 element_array =
2019 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2020 if (element_array == nullptr) {
2021 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2022 return nullptr;
2023 }
2024 }
2025
2026 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2027 for (uint32_t i = 0; i < size; ++i) {
2028 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2029 if (new_member == nullptr) {
2030 return nullptr;
2031 }
2032 h_element_array->SetWithoutChecks<false>(i, new_member);
2033 }
2034
2035 JValue result;
2036 ArtMethod* create_annotation_method =
2037 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2038 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2039 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2040 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2041 if (self->IsExceptionPending()) {
2042 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2043 return nullptr;
2044 }
2045
2046 return result.GetL();
2047}
2048
2049const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2050 const char* descriptor, uint32_t visibility) const {
2051 const AnnotationItem* result = nullptr;
2052 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2053 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2054 if (annotation_item->visibility_ != visibility) {
2055 continue;
2056 }
2057 const uint8_t* annotation = annotation_item->annotation_;
2058 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2059
2060 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2061 result = annotation_item;
2062 break;
2063 }
2064 }
2065 return result;
2066}
2067
2068const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2069 DecodeUnsignedLeb128(&annotation); // unused type_index
2070 uint32_t size = DecodeUnsignedLeb128(&annotation);
2071
2072 while (size != 0) {
2073 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2074 const char* element_name = GetStringData(GetStringId(element_name_index));
2075 if (strcmp(name, element_name) == 0) {
2076 return annotation;
2077 }
2078 SkipAnnotationValue(&annotation);
2079 size--;
2080 }
2081 return nullptr;
2082}
2083
2084bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2085 const uint8_t* annotation = *annotation_ptr;
2086 uint8_t header_byte = *(annotation++);
2087 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2088 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2089 int32_t width = value_arg + 1;
2090
2091 switch (value_type) {
2092 case kDexAnnotationByte:
2093 case kDexAnnotationShort:
2094 case kDexAnnotationChar:
2095 case kDexAnnotationInt:
2096 case kDexAnnotationLong:
2097 case kDexAnnotationFloat:
2098 case kDexAnnotationDouble:
2099 case kDexAnnotationString:
2100 case kDexAnnotationType:
2101 case kDexAnnotationMethod:
2102 case kDexAnnotationField:
2103 case kDexAnnotationEnum:
2104 break;
2105 case kDexAnnotationArray:
2106 {
2107 uint32_t size = DecodeUnsignedLeb128(&annotation);
2108 while (size--) {
2109 if (!SkipAnnotationValue(&annotation)) {
2110 return false;
2111 }
2112 }
2113 width = 0;
2114 break;
2115 }
2116 case kDexAnnotationAnnotation:
2117 {
2118 DecodeUnsignedLeb128(&annotation); // unused type_index
2119 uint32_t size = DecodeUnsignedLeb128(&annotation);
2120 while (size--) {
2121 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2122 if (!SkipAnnotationValue(&annotation)) {
2123 return false;
2124 }
2125 }
2126 width = 0;
2127 break;
2128 }
2129 case kDexAnnotationBoolean:
2130 case kDexAnnotationNull:
2131 width = 0;
2132 break;
2133 default:
2134 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2135 return false;
2136 }
2137
2138 annotation += width;
2139 *annotation_ptr = annotation;
2140 return true;
2141}
2142
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002143std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2144 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2145 dex_file.GetLocation().c_str(),
2146 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2147 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2148 return os;
2149}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002150
Ian Rogersd91d6d62013-09-25 20:26:14 -07002151std::string Signature::ToString() const {
2152 if (dex_file_ == nullptr) {
2153 CHECK(proto_id_ == nullptr);
2154 return "<no signature>";
2155 }
2156 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2157 std::string result;
2158 if (params == nullptr) {
2159 result += "()";
2160 } else {
2161 result += "(";
2162 for (uint32_t i = 0; i < params->Size(); ++i) {
2163 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2164 }
2165 result += ")";
2166 }
2167 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2168 return result;
2169}
2170
Vladimir Markod9cffea2013-11-25 15:08:02 +00002171bool Signature::operator==(const StringPiece& rhs) const {
2172 if (dex_file_ == nullptr) {
2173 return false;
2174 }
2175 StringPiece tail(rhs);
2176 if (!tail.starts_with("(")) {
2177 return false; // Invalid signature
2178 }
2179 tail.remove_prefix(1); // "(";
2180 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2181 if (params != nullptr) {
2182 for (uint32_t i = 0; i < params->Size(); ++i) {
2183 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2184 if (!tail.starts_with(param)) {
2185 return false;
2186 }
2187 tail.remove_prefix(param.length());
2188 }
2189 }
2190 if (!tail.starts_with(")")) {
2191 return false;
2192 }
2193 tail.remove_prefix(1); // ")";
2194 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2195}
2196
Ian Rogersd91d6d62013-09-25 20:26:14 -07002197std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2198 return os << sig.ToString();
2199}
2200
Ian Rogers0571d352011-11-03 19:51:38 -07002201// Decodes the header section from the class data bytes.
2202void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002203 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002204 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2205 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2206 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2207 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2208}
2209
2210void ClassDataItemIterator::ReadClassDataField() {
2211 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2212 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002213 // The user of the iterator is responsible for checking if there
2214 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002215}
2216
2217void ClassDataItemIterator::ReadClassDataMethod() {
2218 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2219 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2220 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002221 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002222 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002223 }
Ian Rogers0571d352011-11-03 19:51:38 -07002224}
2225
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002226EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2227 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2228 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2229 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002230 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2231 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002232 DCHECK(dex_cache != nullptr);
2233 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002234 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002235 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002236 array_size_ = 0;
2237 } else {
2238 array_size_ = DecodeUnsignedLeb128(&ptr_);
2239 }
2240 if (array_size_ > 0) {
2241 Next();
2242 }
2243}
2244
2245void EncodedStaticFieldValueIterator::Next() {
2246 pos_++;
2247 if (pos_ >= array_size_) {
2248 return;
2249 }
Ian Rogers13735952014-10-08 12:43:28 -07002250 uint8_t value_type = *ptr_++;
2251 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002252 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002253 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002254 switch (type_) {
2255 case kBoolean:
2256 jval_.i = (value_arg != 0) ? 1 : 0;
2257 width = 0;
2258 break;
2259 case kByte:
2260 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002261 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002262 break;
2263 case kShort:
2264 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002265 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002266 break;
2267 case kChar:
2268 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002269 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002270 break;
2271 case kInt:
2272 jval_.i = ReadSignedInt(ptr_, value_arg);
2273 break;
2274 case kLong:
2275 jval_.j = ReadSignedLong(ptr_, value_arg);
2276 break;
2277 case kFloat:
2278 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2279 break;
2280 case kDouble:
2281 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2282 break;
2283 case kString:
2284 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002285 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2286 break;
2287 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002288 case kMethod:
2289 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002290 case kArray:
2291 case kAnnotation:
2292 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002293 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002294 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002295 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002296 width = 0;
2297 break;
2298 default:
2299 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002300 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002301 }
2302 ptr_ += width;
2303}
2304
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002305template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002306void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002307 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002308 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2309 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002310 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2311 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2312 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2313 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2314 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2315 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2316 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002317 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002318 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002319 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002320 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002321 break;
2322 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002323 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002324 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2325 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002326 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002327 break;
2328 }
Ian Rogers0571d352011-11-03 19:51:38 -07002329 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2330 }
2331}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002332template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2333template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002334
2335CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2336 handler_.address_ = -1;
2337 int32_t offset = -1;
2338
2339 // Short-circuit the overwhelmingly common cases.
2340 switch (code_item.tries_size_) {
2341 case 0:
2342 break;
2343 case 1: {
2344 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2345 uint32_t start = tries->start_addr_;
2346 if (address >= start) {
2347 uint32_t end = start + tries->insn_count_;
2348 if (address < end) {
2349 offset = tries->handler_off_;
2350 }
2351 }
2352 break;
2353 }
2354 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002355 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002356 }
Logan Chien736df022012-04-27 16:25:57 +08002357 Init(code_item, offset);
2358}
2359
2360CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2361 const DexFile::TryItem& try_item) {
2362 handler_.address_ = -1;
2363 Init(code_item, try_item.handler_off_);
2364}
2365
2366void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2367 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002368 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002369 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002370 } else {
2371 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002372 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002373 remaining_count_ = -1;
2374 catch_all_ = false;
2375 DCHECK(!HasNext());
2376 }
2377}
2378
Ian Rogers13735952014-10-08 12:43:28 -07002379void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002380 current_data_ = handler_data;
2381 remaining_count_ = DecodeSignedLeb128(&current_data_);
2382
2383 // If remaining_count_ is non-positive, then it is the negative of
2384 // the number of catch types, and the catches are followed by a
2385 // catch-all handler.
2386 if (remaining_count_ <= 0) {
2387 catch_all_ = true;
2388 remaining_count_ = -remaining_count_;
2389 } else {
2390 catch_all_ = false;
2391 }
2392 Next();
2393}
2394
2395void CatchHandlerIterator::Next() {
2396 if (remaining_count_ > 0) {
2397 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2398 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2399 remaining_count_--;
2400 return;
2401 }
2402
2403 if (catch_all_) {
2404 handler_.type_idx_ = DexFile::kDexNoIndex16;
2405 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2406 catch_all_ = false;
2407 return;
2408 }
2409
2410 // no more handler
2411 remaining_count_ = -1;
2412}
2413
Carl Shapiro1fb86202011-06-27 17:43:13 -07002414} // namespace art