blob: 9b93c131df0fa6d2b765bbd8144810f9ab02d83c [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "dex_file.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070018
19#include <fcntl.h>
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include <limits.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <stdio.h>
Ian Rogersd81871c2011-10-03 13:57:23 -070022#include <stdlib.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070023#include <string.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070024#include <sys/file.h>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070025#include <sys/stat.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070026
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070029
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000032#include "base/file_magic.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070033#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080034#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010035#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080036#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000037#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070038#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080039#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070040#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070042#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000043#include "mirror/field.h"
44#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070046#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000047#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070048#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070049#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030050#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070051#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070052#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070054#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070055
Andreas Gampe277ccbd2014-11-03 21:36:10 -080056#pragma GCC diagnostic push
57#pragma GCC diagnostic ignored "-Wshadow"
58#include "ScopedFd.h"
59#pragma GCC diagnostic pop
60
Carl Shapiro1fb86202011-06-27 17:43:13 -070061namespace art {
62
Ian Rogers13735952014-10-08 12:43:28 -070063const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
64const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070065
Ian Rogers8d31bbd2013-10-13 10:44:14 -070066bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070067 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070068 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070069
70 // Strip ":...", which is the location
71 const char* zip_entry_name = kClassesDex;
72 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010073 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070074
Vladimir Markoaa4497d2014-09-05 14:01:17 +010075 if (DexFile::IsMultiDexLocation(filename)) {
76 file_part_storage = GetBaseLocation(filename);
77 file_part = file_part_storage.c_str();
78 zip_entry_name = filename + file_part_storage.size() + 1;
79 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070080 }
81
82 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000083 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070084 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070085 return false;
86 }
87 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 std::unique_ptr<ZipArchive> zip_archive(
89 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
90 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080091 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
92 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080093 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070094 }
Andreas Gampe833a4852014-05-21 18:46:59 -070095 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -070097 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
98 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
100 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700101 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700103 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700105 std::unique_ptr<const DexFile> dex_file(
106 DexFile::OpenFile(fd.release(), filename, false, error_msg));
107 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return false;
109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800111 return true;
112 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700113 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700115}
116
Andreas Gampe833a4852014-05-21 18:46:59 -0700117bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800118 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700120 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000121 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
122 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700123 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700124 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700125 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700126 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700127 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700128 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700130 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
131 error_msg));
132 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800133 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return true;
135 } else {
136 return false;
137 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700138 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400140 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700141}
142
Andreas Gampe0cba0042015-04-29 20:47:16 -0700143static bool ContainsClassesDex(int fd, const char* filename) {
144 std::string error_msg;
145 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
146 if (zip_archive.get() == nullptr) {
147 return false;
148 }
149 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
150 return (zip_entry.get() != nullptr);
151}
152
153bool DexFile::MaybeDex(const char* filename) {
154 uint32_t magic;
155 std::string error_msg;
156 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
157 if (fd.get() == -1) {
158 return false;
159 }
160 if (IsZipMagic(magic)) {
161 return ContainsClassesDex(fd.release(), filename);
162 } else if (IsDexMagic(magic)) {
163 return true;
164 }
165 return false;
166}
167
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800168int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700169 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800170 return 0;
171 } else {
172 return mem_map_->GetProtect();
173 }
174}
175
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200176bool DexFile::IsReadOnly() const {
177 return GetPermissions() == PROT_READ;
178}
179
Brian Carlstrome0948e12013-08-29 09:36:15 -0700180bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200181 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183 return false;
184 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700185 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200186 }
187}
188
Brian Carlstrome0948e12013-08-29 09:36:15 -0700189bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200190 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700191 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200192 return false;
193 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700194 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195 }
196}
197
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800198std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
199 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700200 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700201 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000202 {
203 ScopedFd delayed_close(fd);
204 struct stat sbuf;
205 memset(&sbuf, 0, sizeof(sbuf));
206 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800207 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000208 return nullptr;
209 }
210 if (S_ISDIR(sbuf.st_mode)) {
211 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
212 return nullptr;
213 }
214 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800215 map.reset(MemMap::MapFile(length,
216 PROT_READ,
217 MAP_PRIVATE,
218 fd,
219 0,
220 /*low_4gb*/false,
221 location,
222 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000223 if (map.get() == nullptr) {
224 DCHECK(!error_msg->empty());
225 return nullptr;
226 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700227 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800228
229 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800231 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700232 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800233 }
234
235 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
236
Andreas Gampe928f72b2014-09-09 19:53:48 -0700237 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
238 error_msg));
239 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
241 error_msg->c_str());
242 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800243 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800244
Andreas Gampe928f72b2014-09-09 19:53:48 -0700245 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
246 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700247 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800248 }
249
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800250 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700251}
252
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700253const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700254
Andreas Gampe833a4852014-05-21 18:46:59 -0700255bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800256 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700257 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700258 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 if (zip_archive.get() == nullptr) {
260 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700261 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700262 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700263 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800264}
265
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800266std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
267 uint32_t location_checksum,
268 MemMap* mem_map,
269 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800270 return OpenMemory(mem_map->Begin(),
271 mem_map->Size(),
272 location,
273 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700274 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800275 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700276 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277}
278
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800279std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
280 const std::string& location, std::string* error_msg,
281 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800282 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700283 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700284 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700285 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700286 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700287 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700288 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700289 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700290 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700291 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700292 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700294 }
Ian Rogers700a4022014-05-19 16:49:03 -0700295 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700296 error_msg));
297 if (dex_file.get() == nullptr) {
298 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
299 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700300 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700301 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800302 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700303 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700304 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700305 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700306 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700307 }
308 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700309 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
310 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700311 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700312 return nullptr;
313 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700314 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800315 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700316}
317
Andreas Gampe90e34042015-04-27 20:01:52 -0700318// Technically we do not have a limitation with respect to the number of dex files that can be in a
319// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
320// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
321// seems an excessive number.
322static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
323
Andreas Gampe833a4852014-05-21 18:46:59 -0700324bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325 std::string* error_msg,
326 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700327 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700328 ZipOpenErrorCode error_code;
329 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
330 &error_code));
331 if (dex_file.get() == nullptr) {
332 return false;
333 } else {
334 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800335 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700336
337 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700338
339 // We could try to avoid std::string allocations by working on a char array directly. As we
340 // do not expect a lot of iterations, this seems too involved and brittle.
341
Andreas Gampe90e34042015-04-27 20:01:52 -0700342 for (size_t i = 1; ; ++i) {
343 std::string name = GetMultiDexClassesDexName(i);
344 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700345 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
346 error_msg, &error_code));
347 if (next_dex_file.get() == nullptr) {
348 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
349 LOG(WARNING) << error_msg;
350 }
351 break;
352 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800353 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700354 }
355
Andreas Gampe90e34042015-04-27 20:01:52 -0700356 if (i == kWarnOnManyDexFilesThreshold) {
357 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
358 << " dex files. Please consider coalescing and shrinking the number to "
359 " avoid runtime overhead.";
360 }
361
362 if (i == std::numeric_limits<size_t>::max()) {
363 LOG(ERROR) << "Overflow in number of dex files!";
364 break;
365 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 }
367
368 return true;
369 }
370}
371
372
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800373std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
374 size_t size,
375 const std::string& location,
376 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800377 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700378 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800379 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700380 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800381 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700382 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700383 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800384 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700385 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800386 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700387}
388
Ian Rogers13735952014-10-08 12:43:28 -0700389DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800390 const std::string& location,
391 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800392 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700393 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800394 : begin_(base),
395 size_(size),
396 location_(location),
397 location_checksum_(location_checksum),
398 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800399 header_(reinterpret_cast<const Header*>(base)),
400 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
401 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
402 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
403 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
404 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700405 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700406 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700407 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800408 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300409 const uint8_t* lookup_data = (oat_dex_file != nullptr)
410 ? oat_dex_file->GetLookupTableData()
411 : nullptr;
412 if (lookup_data != nullptr) {
413 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
414 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
415 } else {
416 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
417 }
418 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800419}
420
Jesse Wilson6bf19152011-09-29 13:12:33 -0400421DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700422 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
423 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
424 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
425 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400426}
427
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700428bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700430 return false;
431 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700432 return true;
433}
434
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700435bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800436 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700437 std::ostringstream oss;
438 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800439 << " " << header_->magic_[0]
440 << " " << header_->magic_[1]
441 << " " << header_->magic_[2]
442 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700443 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700444 return false;
445 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800446 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 std::ostringstream oss;
448 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800449 << " " << header_->magic_[4]
450 << " " << header_->magic_[5]
451 << " " << header_->magic_[6]
452 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700453 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700454 return false;
455 }
456 return true;
457}
458
Ian Rogers13735952014-10-08 12:43:28 -0700459bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800460 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
461}
462
Ian Rogers13735952014-10-08 12:43:28 -0700463bool DexFile::IsVersionValid(const uint8_t* magic) {
464 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800465 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
466}
467
Ian Rogersd81871c2011-10-03 13:57:23 -0700468uint32_t DexFile::GetVersion() const {
469 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
470 return atoi(version);
471}
472
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800473const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
474 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300475 if (LIKELY(lookup_table_ != nullptr)) {
476 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
477 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700478 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300479
Ian Rogers68b56852014-08-29 20:19:11 -0700480 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300481 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700482 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700483 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700484 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300485 const TypeId* type_id = FindTypeId(descriptor);
486 if (type_id != nullptr) {
487 uint16_t type_idx = GetIndexForTypeId(*type_id);
488 for (size_t i = 0; i < num_class_defs; ++i) {
489 const ClassDef& class_def = GetClassDef(i);
490 if (class_def.class_idx_ == type_idx) {
491 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700492 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700493 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700494 }
Ian Rogers68b56852014-08-29 20:19:11 -0700495 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700496}
497
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700498const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
499 size_t num_class_defs = NumClassDefs();
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;
504 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700505 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700506 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700507}
508
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800509const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
510 const DexFile::StringId& name,
511 const DexFile::TypeId& type) const {
512 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
513 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
514 const uint32_t name_idx = GetIndexForStringId(name);
515 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700516 int32_t lo = 0;
517 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800518 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700519 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800520 const DexFile::FieldId& field = GetFieldId(mid);
521 if (class_idx > field.class_idx_) {
522 lo = mid + 1;
523 } else if (class_idx < field.class_idx_) {
524 hi = mid - 1;
525 } else {
526 if (name_idx > field.name_idx_) {
527 lo = mid + 1;
528 } else if (name_idx < field.name_idx_) {
529 hi = mid - 1;
530 } else {
531 if (type_idx > field.type_idx_) {
532 lo = mid + 1;
533 } else if (type_idx < field.type_idx_) {
534 hi = mid - 1;
535 } else {
536 return &field;
537 }
538 }
539 }
540 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700541 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800542}
543
544const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700545 const DexFile::StringId& name,
546 const DexFile::ProtoId& signature) const {
547 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800548 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700549 const uint32_t name_idx = GetIndexForStringId(name);
550 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700551 int32_t lo = 0;
552 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700553 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700554 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700555 const DexFile::MethodId& method = GetMethodId(mid);
556 if (class_idx > method.class_idx_) {
557 lo = mid + 1;
558 } else if (class_idx < method.class_idx_) {
559 hi = mid - 1;
560 } else {
561 if (name_idx > method.name_idx_) {
562 lo = mid + 1;
563 } else if (name_idx < method.name_idx_) {
564 hi = mid - 1;
565 } else {
566 if (proto_idx > method.proto_idx_) {
567 lo = mid + 1;
568 } else if (proto_idx < method.proto_idx_) {
569 hi = mid - 1;
570 } else {
571 return &method;
572 }
573 }
574 }
575 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700576 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700577}
578
Ian Rogers637c65b2013-05-31 11:46:00 -0700579const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700580 int32_t lo = 0;
581 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700582 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700583 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700584 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700585 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700586 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
587 if (compare > 0) {
588 lo = mid + 1;
589 } else if (compare < 0) {
590 hi = mid - 1;
591 } else {
592 return &str_id;
593 }
594 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700595 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700596}
597
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300598const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
599 int32_t lo = 0;
600 int32_t hi = NumTypeIds() - 1;
601 while (hi >= lo) {
602 int32_t mid = (hi + lo) / 2;
603 const TypeId& type_id = GetTypeId(mid);
604 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
605 const char* str = GetStringData(str_id);
606 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
607 if (compare > 0) {
608 lo = mid + 1;
609 } else if (compare < 0) {
610 hi = mid - 1;
611 } else {
612 return &type_id;
613 }
614 }
615 return nullptr;
616}
617
Vladimir Markoa48aef42014-12-03 17:53:53 +0000618const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700619 int32_t lo = 0;
620 int32_t hi = NumStringIds() - 1;
621 while (hi >= lo) {
622 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700623 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700624 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000625 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700626 if (compare > 0) {
627 lo = mid + 1;
628 } else if (compare < 0) {
629 hi = mid - 1;
630 } else {
631 return &str_id;
632 }
633 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700634 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700635}
636
637const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700638 int32_t lo = 0;
639 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700640 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700641 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700642 const TypeId& type_id = GetTypeId(mid);
643 if (string_idx > type_id.descriptor_idx_) {
644 lo = mid + 1;
645 } else if (string_idx < type_id.descriptor_idx_) {
646 hi = mid - 1;
647 } else {
648 return &type_id;
649 }
650 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700651 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700652}
653
654const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000655 const uint16_t* signature_type_idxs,
656 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700657 int32_t lo = 0;
658 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700659 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700660 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700661 const DexFile::ProtoId& proto = GetProtoId(mid);
662 int compare = return_type_idx - proto.return_type_idx_;
663 if (compare == 0) {
664 DexFileParameterIterator it(*this, proto);
665 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000666 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800667 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700668 it.Next();
669 i++;
670 }
671 if (compare == 0) {
672 if (it.HasNext()) {
673 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000674 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700675 compare = 1;
676 }
677 }
678 }
679 if (compare > 0) {
680 lo = mid + 1;
681 } else if (compare < 0) {
682 hi = mid - 1;
683 } else {
684 return &proto;
685 }
686 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700687 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700688}
689
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000690void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
691 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300692}
693
Ian Rogers0571d352011-11-03 19:51:38 -0700694// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700695bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
696 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700697 if (signature[0] != '(') {
698 return false;
699 }
700 size_t offset = 1;
701 size_t end = signature.size();
702 bool process_return = false;
703 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000704 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700705 char c = signature[offset];
706 offset++;
707 if (c == ')') {
708 process_return = true;
709 continue;
710 }
Ian Rogers0571d352011-11-03 19:51:38 -0700711 while (c == '[') { // process array prefix
712 if (offset >= end) { // expect some descriptor following [
713 return false;
714 }
715 c = signature[offset];
716 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700717 }
718 if (c == 'L') { // process type descriptors
719 do {
720 if (offset >= end) { // unexpected early termination of descriptor
721 return false;
722 }
723 c = signature[offset];
724 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700725 } while (c != ';');
726 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000727 // TODO: avoid creating a std::string just to get a 0-terminated char array
728 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700729 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700730 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700731 return false;
732 }
733 uint16_t type_idx = GetIndexForTypeId(*type_id);
734 if (!process_return) {
735 param_type_idxs->push_back(type_idx);
736 } else {
737 *return_type_idx = type_idx;
738 return offset == end; // return true if the signature had reached a sensible end
739 }
740 }
741 return false; // failed to correctly parse return type
742}
743
Ian Rogersd91d6d62013-09-25 20:26:14 -0700744const Signature DexFile::CreateSignature(const StringPiece& signature) const {
745 uint16_t return_type_idx;
746 std::vector<uint16_t> param_type_indices;
747 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
748 if (!success) {
749 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700750 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700751 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700752 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700753 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700754 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700755 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700756}
757
Mathieu Chartiere401d142015-04-22 13:56:20 -0700758int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700759 // For native method, lineno should be -2 to indicate it is native. Note that
760 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700761 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700762 return -2;
763 }
764
TDYa127c8dc1012012-04-19 07:03:33 -0700765 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700766 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700767
768 // A method with no line number info should return -1
769 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000770 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700771 return context.line_num_;
772}
773
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700774int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700775 // Note: Signed type is important for max and min.
776 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700777 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700778
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700779 while (min <= max) {
780 int32_t mid = min + ((max - min) / 2);
781
782 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
783 uint32_t start = ti->start_addr_;
784 uint32_t end = start + ti->insn_count_;
785
Ian Rogers0571d352011-11-03 19:51:38 -0700786 if (address < start) {
787 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700788 } else if (address >= end) {
789 min = mid + 1;
790 } else { // We have a winner!
791 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700792 }
793 }
794 // No match.
795 return -1;
796}
797
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700798int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
799 int32_t try_item = FindTryItem(code_item, address);
800 if (try_item == -1) {
801 return -1;
802 } else {
803 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
804 }
805}
806
David Srbeckyb06e28e2015-12-10 13:15:00 +0000807bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
808 DexDebugNewLocalCb local_cb, void* context) const {
809 DCHECK(local_cb != nullptr);
810 if (code_item == nullptr) {
811 return false;
812 }
813 const uint8_t* stream = GetDebugInfoStream(code_item);
814 if (stream == nullptr) {
815 return false;
816 }
817 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700818
David Srbeckyb06e28e2015-12-10 13:15:00 +0000819 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800820 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000821 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
822 local_in_reg[arg_reg].name_ = "this";
823 local_in_reg[arg_reg].descriptor_ = descriptor;
824 local_in_reg[arg_reg].signature_ = nullptr;
825 local_in_reg[arg_reg].start_address_ = 0;
826 local_in_reg[arg_reg].reg_ = arg_reg;
827 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700828 arg_reg++;
829 }
830
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800831 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000832 DecodeUnsignedLeb128(&stream); // Line.
833 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
834 uint32_t i;
835 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700836 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700837 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800838 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000839 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700840 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000841 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700842 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000843 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
844 local_in_reg[arg_reg].descriptor_ = descriptor;
845 local_in_reg[arg_reg].signature_ = nullptr;
846 local_in_reg[arg_reg].start_address_ = 0;
847 local_in_reg[arg_reg].reg_ = arg_reg;
848 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700849 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700850 case 'D':
851 case 'J':
852 arg_reg += 2;
853 break;
854 default:
855 arg_reg += 1;
856 break;
857 }
858 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000859 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800860 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
861 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000862 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700863 }
864
David Srbeckyb06e28e2015-12-10 13:15:00 +0000865 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700866 for (;;) {
867 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700868 switch (opcode) {
869 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000870 // Emit all variables which are still alive at the end of the method.
871 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
872 if (local_in_reg[reg].is_live_) {
873 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
874 local_cb(context, local_in_reg[reg]);
875 }
876 }
877 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700878 case DBG_ADVANCE_PC:
879 address += DecodeUnsignedLeb128(&stream);
880 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700883 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700884 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000885 case DBG_START_LOCAL_EXTENDED: {
886 uint16_t reg = DecodeUnsignedLeb128(&stream);
887 if (reg >= code_item->registers_size_) {
888 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800889 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000890 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 }
892
David Srbeckyb06e28e2015-12-10 13:15:00 +0000893 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
894 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
895 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700896 if (opcode == DBG_START_LOCAL_EXTENDED) {
897 signature_idx = DecodeUnsignedLeb128P1(&stream);
898 }
899
Shih-wei Liao195487c2011-08-20 13:29:04 -0700900 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000901 if (local_in_reg[reg].is_live_) {
902 local_in_reg[reg].end_address_ = address;
903 local_cb(context, local_in_reg[reg]);
904 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700905
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
907 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
908 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
909 local_in_reg[reg].start_address_ = address;
910 local_in_reg[reg].reg_ = reg;
911 local_in_reg[reg].is_live_ = true;
912 break;
913 }
914 case DBG_END_LOCAL: {
915 uint16_t reg = DecodeUnsignedLeb128(&stream);
916 if (reg >= code_item->registers_size_) {
917 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
918 << code_item->registers_size_ << ") in " << GetLocation();
919 return false;
920 }
921 if (!local_in_reg[reg].is_live_) {
922 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
923 return false;
924 }
925 local_in_reg[reg].end_address_ = address;
926 local_cb(context, local_in_reg[reg]);
927 local_in_reg[reg].is_live_ = false;
928 break;
929 }
930 case DBG_RESTART_LOCAL: {
931 uint16_t reg = DecodeUnsignedLeb128(&stream);
932 if (reg >= code_item->registers_size_) {
933 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
934 << code_item->registers_size_ << ") in " << GetLocation();
935 return false;
936 }
937 // If the register is live, the "restart" is superfluous,
938 // and we don't want to mess with the existing start address.
939 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700940 local_in_reg[reg].start_address_ = address;
941 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700942 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000944 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700945 case DBG_SET_PROLOGUE_END:
946 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700947 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000948 case DBG_SET_FILE:
949 DecodeUnsignedLeb128P1(&stream); // name.
950 break;
951 default:
952 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
953 break;
954 }
955 }
956}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700957
David Srbeckyb06e28e2015-12-10 13:15:00 +0000958bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
959 void* context) const {
960 DCHECK(position_cb != nullptr);
961 if (code_item == nullptr) {
962 return false;
963 }
964 const uint8_t* stream = GetDebugInfoStream(code_item);
965 if (stream == nullptr) {
966 return false;
967 }
968
969 PositionInfo entry = PositionInfo();
970 entry.line_ = DecodeUnsignedLeb128(&stream);
971 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
972 for (uint32_t i = 0; i < parameters_size; ++i) {
973 DecodeUnsignedLeb128P1(&stream); // Parameter name.
974 }
975
976 for (;;) {
977 uint8_t opcode = *stream++;
978 switch (opcode) {
979 case DBG_END_SEQUENCE:
980 return true; // end of stream.
981 case DBG_ADVANCE_PC:
982 entry.address_ += DecodeUnsignedLeb128(&stream);
983 break;
984 case DBG_ADVANCE_LINE:
985 entry.line_ += DecodeSignedLeb128(&stream);
986 break;
987 case DBG_START_LOCAL:
988 DecodeUnsignedLeb128(&stream); // reg.
989 DecodeUnsignedLeb128P1(&stream); // name.
990 DecodeUnsignedLeb128P1(&stream); // descriptor.
991 break;
992 case DBG_START_LOCAL_EXTENDED:
993 DecodeUnsignedLeb128(&stream); // reg.
994 DecodeUnsignedLeb128P1(&stream); // name.
995 DecodeUnsignedLeb128P1(&stream); // descriptor.
996 DecodeUnsignedLeb128P1(&stream); // signature.
997 break;
998 case DBG_END_LOCAL:
999 case DBG_RESTART_LOCAL:
1000 DecodeUnsignedLeb128(&stream); // reg.
1001 break;
1002 case DBG_SET_PROLOGUE_END:
1003 entry.prologue_end_ = true;
1004 break;
1005 case DBG_SET_EPILOGUE_BEGIN:
1006 entry.epilogue_begin_ = true;
1007 break;
1008 case DBG_SET_FILE: {
1009 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1010 entry.source_file_ = StringDataByIdx(name_idx);
1011 break;
1012 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001013 default: {
1014 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001015 entry.address_ += adjopcode / DBG_LINE_RANGE;
1016 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1017 if (position_cb(context, entry)) {
1018 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001019 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001020 entry.prologue_end_ = false;
1021 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001022 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001023 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001024 }
1025 }
1026}
1027
David Srbeckyb06e28e2015-12-10 13:15:00 +00001028bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001029 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001030
1031 // We know that this callback will be called in
1032 // ascending address order, so keep going until we find
1033 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001034 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001035 // The line number from the previous positions callback
1036 // wil be the final result.
1037 return true;
1038 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001039 context->line_num_ = entry.line_;
1040 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001041 }
1042}
1043
Andreas Gampe833a4852014-05-21 18:46:59 -07001044bool DexFile::IsMultiDexLocation(const char* location) {
1045 return strrchr(location, kMultiDexSeparator) != nullptr;
1046}
1047
Andreas Gampe90e34042015-04-27 20:01:52 -07001048std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1049 if (index == 0) {
1050 return "classes.dex";
1051 } else {
1052 return StringPrintf("classes%zu.dex", index + 1);
1053 }
1054}
1055
1056std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1057 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001058 return dex_location;
1059 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001060 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001061 }
1062}
1063
1064std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1065 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001066 std::string base_location = GetBaseLocation(dex_location);
1067 const char* suffix = dex_location + base_location.size();
1068 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1069 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1070 if (path != nullptr && path.get() != base_location) {
1071 return std::string(path.get()) + suffix;
1072 } else if (suffix[0] == 0) {
1073 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001074 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001075 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001076 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001077}
1078
Jeff Hao13e748b2015-08-25 20:44:19 +00001079// Read a signed integer. "zwidth" is the zero-based byte count.
1080static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1081 int32_t val = 0;
1082 for (int i = zwidth; i >= 0; --i) {
1083 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1084 }
1085 val >>= (3 - zwidth) * 8;
1086 return val;
1087}
1088
1089// Read an unsigned integer. "zwidth" is the zero-based byte count,
1090// "fill_on_right" indicates which side we want to zero-fill from.
1091static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1092 uint32_t val = 0;
1093 for (int i = zwidth; i >= 0; --i) {
1094 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1095 }
1096 if (!fill_on_right) {
1097 val >>= (3 - zwidth) * 8;
1098 }
1099 return val;
1100}
1101
1102// Read a signed long. "zwidth" is the zero-based byte count.
1103static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1104 int64_t val = 0;
1105 for (int i = zwidth; i >= 0; --i) {
1106 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1107 }
1108 val >>= (7 - zwidth) * 8;
1109 return val;
1110}
1111
1112// Read an unsigned long. "zwidth" is the zero-based byte count,
1113// "fill_on_right" indicates which side we want to zero-fill from.
1114static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1115 uint64_t val = 0;
1116 for (int i = zwidth; i >= 0; --i) {
1117 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1118 }
1119 if (!fill_on_right) {
1120 val >>= (7 - zwidth) * 8;
1121 }
1122 return val;
1123}
1124
1125const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1126 mirror::Class* klass = field->GetDeclaringClass();
1127 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1128 if (annotations_dir == nullptr) {
1129 return nullptr;
1130 }
1131 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1132 if (field_annotations == nullptr) {
1133 return nullptr;
1134 }
1135 uint32_t field_index = field->GetDexFieldIndex();
1136 uint32_t field_count = annotations_dir->fields_size_;
1137 for (uint32_t i = 0; i < field_count; ++i) {
1138 if (field_annotations[i].field_idx_ == field_index) {
1139 return GetFieldAnnotationSetItem(field_annotations[i]);
1140 }
1141 }
1142 return nullptr;
1143}
1144
1145mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1146 Handle<mirror::Class> annotation_class) const {
1147 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1148 if (annotation_set == nullptr) {
1149 return nullptr;
1150 }
1151 StackHandleScope<1> hs(Thread::Current());
1152 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1153 return GetAnnotationObjectFromAnnotationSet(
1154 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1155}
1156
1157mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1158 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1159 StackHandleScope<1> hs(Thread::Current());
1160 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1161 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1162}
1163
Jeff Hao2a5892f2015-08-31 15:00:40 -07001164mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001165 const {
1166 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1167 if (annotation_set == nullptr) {
1168 return nullptr;
1169 }
1170 StackHandleScope<1> hs(Thread::Current());
1171 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1172 return GetSignatureValue(field_class, annotation_set);
1173}
1174
1175bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1176 const {
1177 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1178 if (annotation_set == nullptr) {
1179 return false;
1180 }
1181 StackHandleScope<1> hs(Thread::Current());
1182 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1183 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1184 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1185 return annotation_item != nullptr;
1186}
1187
1188const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1189 mirror::Class* klass = method->GetDeclaringClass();
1190 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1191 if (annotations_dir == nullptr) {
1192 return nullptr;
1193 }
1194 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1195 if (method_annotations == nullptr) {
1196 return nullptr;
1197 }
1198 uint32_t method_index = method->GetDexMethodIndex();
1199 uint32_t method_count = annotations_dir->methods_size_;
1200 for (uint32_t i = 0; i < method_count; ++i) {
1201 if (method_annotations[i].method_idx_ == method_index) {
1202 return GetMethodAnnotationSetItem(method_annotations[i]);
1203 }
1204 }
1205 return nullptr;
1206}
1207
1208const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1209 const {
1210 mirror::Class* klass = method->GetDeclaringClass();
1211 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1212 if (annotations_dir == nullptr) {
1213 return nullptr;
1214 }
1215 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1216 if (parameter_annotations == nullptr) {
1217 return nullptr;
1218 }
1219 uint32_t method_index = method->GetDexMethodIndex();
1220 uint32_t parameter_count = annotations_dir->parameters_size_;
1221 for (uint32_t i = 0; i < parameter_count; ++i) {
1222 if (parameter_annotations[i].method_idx_ == method_index) {
1223 return &parameter_annotations[i];
1224 }
1225 }
1226 return nullptr;
1227}
1228
1229mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1230 mirror::Class* klass = method->GetDeclaringClass();
1231 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1232 if (annotations_dir == nullptr) {
1233 return nullptr;
1234 }
1235 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1236 if (annotation_set == nullptr) {
1237 return nullptr;
1238 }
1239 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1240 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1241 if (annotation_item == nullptr) {
1242 return nullptr;
1243 }
1244 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1245 if (annotation == nullptr) {
1246 return nullptr;
1247 }
1248 uint8_t header_byte = *(annotation++);
1249 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1250 return nullptr;
1251 }
1252 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1253 if (annotation == nullptr) {
1254 return nullptr;
1255 }
1256 AnnotationValue annotation_value;
1257 StackHandleScope<2> hs(Thread::Current());
1258 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001259 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1260 Handle<mirror::Class> return_type(hs.NewHandle(
1261 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001262 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1263 return nullptr;
1264 }
1265 return annotation_value.value_.GetL();
1266}
1267
1268mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1269 Handle<mirror::Class> annotation_class) const {
1270 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1271 if (annotation_set == nullptr) {
1272 return nullptr;
1273 }
1274 StackHandleScope<1> hs(Thread::Current());
1275 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1276 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1277 kDexVisibilityRuntime, annotation_class);
1278}
1279
1280mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1281 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1282 StackHandleScope<1> hs(Thread::Current());
1283 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1284 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1285}
1286
Jeff Hao2a5892f2015-08-31 15:00:40 -07001287mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001288 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1289 if (annotation_set == nullptr) {
1290 return nullptr;
1291 }
1292 StackHandleScope<1> hs(Thread::Current());
1293 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1294 return GetThrowsValue(method_class, annotation_set);
1295}
1296
1297mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1298 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1299 if (parameter_annotations == nullptr) {
1300 return nullptr;
1301 }
1302 const AnnotationSetRefList* set_ref_list =
1303 GetParameterAnnotationSetRefList(parameter_annotations);
1304 if (set_ref_list == nullptr) {
1305 return nullptr;
1306 }
1307 uint32_t size = set_ref_list->size_;
1308 StackHandleScope<1> hs(Thread::Current());
1309 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1310 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1311}
1312
1313bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1314 const {
1315 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1316 if (annotation_set == nullptr) {
1317 return false;
1318 }
1319 StackHandleScope<1> hs(Thread::Current());
1320 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1321 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1322 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001323 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001324}
1325
1326const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1327 const {
1328 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1329 if (annotations_dir == nullptr) {
1330 return nullptr;
1331 }
1332 return GetClassAnnotationSet(annotations_dir);
1333}
1334
1335mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1336 Handle<mirror::Class> annotation_class) const {
1337 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1338 if (annotation_set == nullptr) {
1339 return nullptr;
1340 }
1341 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1342 annotation_class);
1343}
1344
1345mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1346 const {
1347 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1348 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1349}
1350
Jeff Hao2a5892f2015-08-31 15:00:40 -07001351mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1352 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1353 if (annotation_set == nullptr) {
1354 return nullptr;
1355 }
1356 const AnnotationItem* annotation_item = SearchAnnotationSet(
1357 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1358 if (annotation_item == nullptr) {
1359 return nullptr;
1360 }
1361 StackHandleScope<1> hs(Thread::Current());
1362 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1363 Handle<mirror::Class> class_array_class(hs.NewHandle(
1364 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1365 if (class_array_class.Get() == nullptr) {
1366 return nullptr;
1367 }
1368 mirror::Object* obj = GetAnnotationValue(
1369 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1370 if (obj == nullptr) {
1371 return nullptr;
1372 }
1373 return obj->AsObjectArray<mirror::Class>();
1374}
1375
1376mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
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/EnclosingClass;", kDexVisibilitySystem);
1383 if (annotation_item == nullptr) {
1384 return nullptr;
1385 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001386 mirror::Object* obj = GetAnnotationValue(klass,
1387 annotation_item,
1388 "value",
1389 ScopedNullHandle<mirror::Class>(),
1390 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001391 if (obj == nullptr) {
1392 return nullptr;
1393 }
1394 return obj->AsClass();
1395}
1396
1397mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1398 mirror::Class* declaring_class = GetDeclaringClass(klass);
1399 if (declaring_class != nullptr) {
1400 return declaring_class;
1401 }
1402 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1403 if (annotation_set == nullptr) {
1404 return nullptr;
1405 }
1406 const AnnotationItem* annotation_item = SearchAnnotationSet(
1407 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1408 if (annotation_item == nullptr) {
1409 return nullptr;
1410 }
1411 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1412 if (annotation == nullptr) {
1413 return nullptr;
1414 }
1415 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001416 if (!ProcessAnnotationValue(klass,
1417 &annotation,
1418 &annotation_value,
1419 ScopedNullHandle<mirror::Class>(),
1420 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001421 return nullptr;
1422 }
1423 if (annotation_value.type_ != kDexAnnotationMethod) {
1424 return nullptr;
1425 }
1426 StackHandleScope<2> hs(Thread::Current());
1427 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1428 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1429 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1430 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1431 if (method == nullptr) {
1432 return nullptr;
1433 }
1434 return method->GetDeclaringClass();
1435}
1436
1437mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1438 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1439 if (annotation_set == nullptr) {
1440 return nullptr;
1441 }
1442 const AnnotationItem* annotation_item = SearchAnnotationSet(
1443 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1444 if (annotation_item == nullptr) {
1445 return nullptr;
1446 }
1447 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001448 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001449}
1450
1451bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1452 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1453 if (annotation_set == nullptr) {
1454 return false;
1455 }
1456 const AnnotationItem* annotation_item = SearchAnnotationSet(
1457 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1458 if (annotation_item == nullptr) {
1459 return false;
1460 }
1461 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1462 if (annotation == nullptr) {
1463 return false;
1464 }
1465 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001466 if (!ProcessAnnotationValue(klass,
1467 &annotation,
1468 &annotation_value,
1469 ScopedNullHandle<mirror::Class>(),
1470 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001471 return false;
1472 }
1473 if (annotation_value.type_ != kDexAnnotationNull &&
1474 annotation_value.type_ != kDexAnnotationString) {
1475 return false;
1476 }
1477 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1478 return true;
1479}
1480
1481bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1482 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1483 if (annotation_set == nullptr) {
1484 return false;
1485 }
1486 const AnnotationItem* annotation_item = SearchAnnotationSet(
1487 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1488 if (annotation_item == nullptr) {
1489 return false;
1490 }
1491 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1492 if (annotation == nullptr) {
1493 return false;
1494 }
1495 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001496 if (!ProcessAnnotationValue(klass,
1497 &annotation,
1498 &annotation_value,
1499 ScopedNullHandle<mirror::Class>(),
1500 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001501 return false;
1502 }
1503 if (annotation_value.type_ != kDexAnnotationInt) {
1504 return false;
1505 }
1506 *flags = annotation_value.value_.GetI();
1507 return true;
1508}
1509
Jeff Hao13e748b2015-08-25 20:44:19 +00001510bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1511 Handle<mirror::Class> annotation_class) const {
1512 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1513 if (annotation_set == nullptr) {
1514 return false;
1515 }
1516 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1517 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001518 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001519}
1520
1521mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1522 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1523 Thread* self = Thread::Current();
1524 ScopedObjectAccessUnchecked soa(self);
1525 StackHandleScope<5> hs(self);
1526 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1527 const char* name = StringDataByIdx(element_name_index);
1528 Handle<mirror::String> string_name(
1529 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1530
1531 ArtMethod* annotation_method =
1532 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1533 if (annotation_method == nullptr) {
1534 return nullptr;
1535 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001536 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1537 Handle<mirror::Class> method_return(hs.NewHandle(
1538 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001539
1540 AnnotationValue annotation_value;
1541 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1542 return nullptr;
1543 }
1544 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1545
1546 mirror::Class* annotation_member_class =
1547 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1548 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1549 Handle<mirror::Method> method_object(
1550 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1551
1552 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1553 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1554 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1555 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1556 return nullptr;
1557 }
1558
1559 JValue result;
1560 ArtMethod* annotation_member_init =
1561 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1562 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1563 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1564 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1565 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1566 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1567 };
1568 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1569 if (self->IsExceptionPending()) {
1570 LOG(INFO) << "Exception in AnnotationMember.<init>";
1571 return nullptr;
1572 }
1573
1574 return new_member.Get();
1575}
1576
1577const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1578 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1579 Handle<mirror::Class> annotation_class) const {
1580 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1581 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1582 if (annotation_item->visibility_ != visibility) {
1583 continue;
1584 }
1585 const uint8_t* annotation = annotation_item->annotation_;
1586 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1587 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1588 klass->GetDexFile(), type_index, klass.Get());
1589 if (resolved_class == nullptr) {
1590 std::string temp;
1591 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1592 klass->GetDescriptor(&temp), type_index);
1593 CHECK(Thread::Current()->IsExceptionPending());
1594 Thread::Current()->ClearException();
1595 continue;
1596 }
1597 if (resolved_class == annotation_class.Get()) {
1598 return annotation_item;
1599 }
1600 }
1601
1602 return nullptr;
1603}
1604
1605mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1606 const AnnotationSetItem* annotation_set, uint32_t visibility,
1607 Handle<mirror::Class> annotation_class) const {
1608 const AnnotationItem* annotation_item =
1609 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1610 if (annotation_item == nullptr) {
1611 return nullptr;
1612 }
1613 const uint8_t* annotation = annotation_item->annotation_;
1614 return ProcessEncodedAnnotation(klass, &annotation);
1615}
1616
1617mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1618 const AnnotationItem* annotation_item, const char* annotation_name,
1619 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1620 const uint8_t* annotation =
1621 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1622 if (annotation == nullptr) {
1623 return nullptr;
1624 }
1625 AnnotationValue annotation_value;
1626 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1627 return nullptr;
1628 }
1629 if (annotation_value.type_ != expected_type) {
1630 return nullptr;
1631 }
1632 return annotation_value.value_.GetL();
1633}
1634
Jeff Hao2a5892f2015-08-31 15:00:40 -07001635mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001636 const AnnotationSetItem* annotation_set) const {
1637 StackHandleScope<1> hs(Thread::Current());
1638 const AnnotationItem* annotation_item =
1639 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1640 if (annotation_item == nullptr) {
1641 return nullptr;
1642 }
1643 mirror::Class* string_class = mirror::String::GetJavaLangString();
1644 Handle<mirror::Class> string_array_class(hs.NewHandle(
1645 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001646 if (string_array_class.Get() == nullptr) {
1647 return nullptr;
1648 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001649 mirror::Object* obj =
1650 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1651 if (obj == nullptr) {
1652 return nullptr;
1653 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001654 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001655}
1656
Jeff Hao2a5892f2015-08-31 15:00:40 -07001657mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001658 const AnnotationSetItem* annotation_set) const {
1659 StackHandleScope<1> hs(Thread::Current());
1660 const AnnotationItem* annotation_item =
1661 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1662 if (annotation_item == nullptr) {
1663 return nullptr;
1664 }
1665 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1666 Handle<mirror::Class> class_array_class(hs.NewHandle(
1667 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001668 if (class_array_class.Get() == nullptr) {
1669 return nullptr;
1670 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001671 mirror::Object* obj =
1672 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1673 if (obj == nullptr) {
1674 return nullptr;
1675 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001676 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001677}
1678
1679mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1680 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1681 Thread* self = Thread::Current();
1682 ScopedObjectAccessUnchecked soa(self);
1683 StackHandleScope<2> hs(self);
1684 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1685 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1686 if (annotation_set == nullptr) {
1687 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1688 }
1689
1690 uint32_t size = annotation_set->size_;
1691 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1692 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1693 if (result.Get() == nullptr) {
1694 return nullptr;
1695 }
1696
1697 uint32_t dest_index = 0;
1698 for (uint32_t i = 0; i < size; ++i) {
1699 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1700 if (annotation_item->visibility_ != visibility) {
1701 continue;
1702 }
1703 const uint8_t* annotation = annotation_item->annotation_;
1704 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1705 if (annotation_obj != nullptr) {
1706 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1707 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001708 } else if (self->IsExceptionPending()) {
1709 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001710 }
1711 }
1712
1713 if (dest_index == size) {
1714 return result.Get();
1715 }
1716
1717 mirror::ObjectArray<mirror::Object>* trimmed_result =
1718 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001719 if (trimmed_result == nullptr) {
1720 return nullptr;
1721 }
1722
Jeff Hao13e748b2015-08-25 20:44:19 +00001723 for (uint32_t i = 0; i < dest_index; ++i) {
1724 mirror::Object* obj = result->GetWithoutChecks(i);
1725 trimmed_result->SetWithoutChecks<false>(i, obj);
1726 }
1727
1728 return trimmed_result;
1729}
1730
1731mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1732 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1733 Thread* self = Thread::Current();
1734 ScopedObjectAccessUnchecked soa(self);
1735 StackHandleScope<1> hs(self);
1736 mirror::Class* annotation_array_class =
1737 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1738 mirror::Class* annotation_array_array_class =
1739 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001740 if (annotation_array_array_class == nullptr) {
1741 return nullptr;
1742 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001743 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1744 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1745 if (annotation_array_array.Get() == nullptr) {
1746 LOG(ERROR) << "Annotation set ref array allocation failed";
1747 return nullptr;
1748 }
1749 for (uint32_t index = 0; index < size; ++index) {
1750 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1751 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1752 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1753 if (annotation_set == nullptr) {
1754 return nullptr;
1755 }
1756 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1757 }
1758 return annotation_array_array.Get();
1759}
1760
1761bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1762 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1763 DexFile::AnnotationResultStyle result_style) const {
1764 Thread* self = Thread::Current();
1765 mirror::Object* element_object = nullptr;
1766 bool set_object = false;
1767 Primitive::Type primitive_type = Primitive::kPrimVoid;
1768 const uint8_t* annotation = *annotation_ptr;
1769 uint8_t header_byte = *(annotation++);
1770 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1771 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1772 int32_t width = value_arg + 1;
1773 annotation_value->type_ = value_type;
1774
1775 switch (value_type) {
1776 case kDexAnnotationByte:
1777 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1778 primitive_type = Primitive::kPrimByte;
1779 break;
1780 case kDexAnnotationShort:
1781 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1782 primitive_type = Primitive::kPrimShort;
1783 break;
1784 case kDexAnnotationChar:
1785 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1786 false)));
1787 primitive_type = Primitive::kPrimChar;
1788 break;
1789 case kDexAnnotationInt:
1790 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1791 primitive_type = Primitive::kPrimInt;
1792 break;
1793 case kDexAnnotationLong:
1794 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1795 primitive_type = Primitive::kPrimLong;
1796 break;
1797 case kDexAnnotationFloat:
1798 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1799 primitive_type = Primitive::kPrimFloat;
1800 break;
1801 case kDexAnnotationDouble:
1802 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1803 primitive_type = Primitive::kPrimDouble;
1804 break;
1805 case kDexAnnotationBoolean:
1806 annotation_value->value_.SetZ(value_arg != 0);
1807 primitive_type = Primitive::kPrimBoolean;
1808 width = 0;
1809 break;
1810 case kDexAnnotationString: {
1811 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1812 if (result_style == kAllRaw) {
1813 annotation_value->value_.SetI(index);
1814 } else {
1815 StackHandleScope<1> hs(self);
1816 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1817 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1818 klass->GetDexFile(), index, dex_cache);
1819 set_object = true;
1820 if (element_object == nullptr) {
1821 return false;
1822 }
1823 }
1824 break;
1825 }
1826 case kDexAnnotationType: {
1827 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1828 if (result_style == kAllRaw) {
1829 annotation_value->value_.SetI(index);
1830 } else {
1831 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1832 klass->GetDexFile(), index, klass.Get());
1833 set_object = true;
1834 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001835 CHECK(self->IsExceptionPending());
1836 if (result_style == kAllObjects) {
1837 const char* msg = StringByTypeIdx(index);
1838 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1839 element_object = self->GetException();
1840 self->ClearException();
1841 } else {
1842 return false;
1843 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001844 }
1845 }
1846 break;
1847 }
1848 case kDexAnnotationMethod: {
1849 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1850 if (result_style == kAllRaw) {
1851 annotation_value->value_.SetI(index);
1852 } else {
1853 StackHandleScope<2> hs(self);
1854 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1855 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1856 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1857 klass->GetDexFile(), index, dex_cache, class_loader);
1858 if (method == nullptr) {
1859 return false;
1860 }
1861 set_object = true;
1862 if (method->IsConstructor()) {
1863 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1864 } else {
1865 element_object = mirror::Method::CreateFromArtMethod(self, method);
1866 }
1867 if (element_object == nullptr) {
1868 return false;
1869 }
1870 }
1871 break;
1872 }
1873 case kDexAnnotationField: {
1874 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1875 if (result_style == kAllRaw) {
1876 annotation_value->value_.SetI(index);
1877 } else {
1878 StackHandleScope<2> hs(self);
1879 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1880 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1881 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1882 klass->GetDexFile(), index, dex_cache, class_loader);
1883 if (field == nullptr) {
1884 return false;
1885 }
1886 set_object = true;
1887 element_object = mirror::Field::CreateFromArtField(self, field, true);
1888 if (element_object == nullptr) {
1889 return false;
1890 }
1891 }
1892 break;
1893 }
1894 case kDexAnnotationEnum: {
1895 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1896 if (result_style == kAllRaw) {
1897 annotation_value->value_.SetI(index);
1898 } else {
1899 StackHandleScope<3> hs(self);
1900 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1901 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1902 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1903 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001904 if (enum_field == nullptr) {
1905 return false;
1906 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001907 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001908 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1909 element_object = enum_field->GetObject(field_class.Get());
1910 set_object = true;
1911 }
1912 }
1913 break;
1914 }
1915 case kDexAnnotationArray:
1916 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1917 return false;
1918 } else {
1919 ScopedObjectAccessUnchecked soa(self);
1920 StackHandleScope<2> hs(self);
1921 uint32_t size = DecodeUnsignedLeb128(&annotation);
1922 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1923 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1924 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1925 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1926 if (new_array.Get() == nullptr) {
1927 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1928 return false;
1929 }
1930 AnnotationValue new_annotation_value;
1931 for (uint32_t i = 0; i < size; ++i) {
1932 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1933 kPrimitivesOrObjects)) {
1934 return false;
1935 }
1936 if (!component_type->IsPrimitive()) {
1937 mirror::Object* obj = new_annotation_value.value_.GetL();
1938 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1939 } else {
1940 switch (new_annotation_value.type_) {
1941 case kDexAnnotationByte:
1942 new_array->AsByteArray()->SetWithoutChecks<false>(
1943 i, new_annotation_value.value_.GetB());
1944 break;
1945 case kDexAnnotationShort:
1946 new_array->AsShortArray()->SetWithoutChecks<false>(
1947 i, new_annotation_value.value_.GetS());
1948 break;
1949 case kDexAnnotationChar:
1950 new_array->AsCharArray()->SetWithoutChecks<false>(
1951 i, new_annotation_value.value_.GetC());
1952 break;
1953 case kDexAnnotationInt:
1954 new_array->AsIntArray()->SetWithoutChecks<false>(
1955 i, new_annotation_value.value_.GetI());
1956 break;
1957 case kDexAnnotationLong:
1958 new_array->AsLongArray()->SetWithoutChecks<false>(
1959 i, new_annotation_value.value_.GetJ());
1960 break;
1961 case kDexAnnotationFloat:
1962 new_array->AsFloatArray()->SetWithoutChecks<false>(
1963 i, new_annotation_value.value_.GetF());
1964 break;
1965 case kDexAnnotationDouble:
1966 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1967 i, new_annotation_value.value_.GetD());
1968 break;
1969 case kDexAnnotationBoolean:
1970 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1971 i, new_annotation_value.value_.GetZ());
1972 break;
1973 default:
1974 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1975 return false;
1976 }
1977 }
1978 }
1979 element_object = new_array.Get();
1980 set_object = true;
1981 width = 0;
1982 }
1983 break;
1984 case kDexAnnotationAnnotation:
1985 if (result_style == kAllRaw) {
1986 return false;
1987 }
1988 element_object = ProcessEncodedAnnotation(klass, &annotation);
1989 if (element_object == nullptr) {
1990 return false;
1991 }
1992 set_object = true;
1993 width = 0;
1994 break;
1995 case kDexAnnotationNull:
1996 if (result_style == kAllRaw) {
1997 annotation_value->value_.SetI(0);
1998 } else {
1999 CHECK(element_object == nullptr);
2000 set_object = true;
2001 }
2002 width = 0;
2003 break;
2004 default:
2005 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2006 return false;
2007 }
2008
2009 annotation += width;
2010 *annotation_ptr = annotation;
2011
2012 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2013 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2014 set_object = true;
2015 }
2016
2017 if (set_object) {
2018 annotation_value->value_.SetL(element_object);
2019 }
2020
2021 return true;
2022}
2023
2024mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2025 const uint8_t** annotation) const {
2026 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2027 uint32_t size = DecodeUnsignedLeb128(annotation);
2028
2029 Thread* self = Thread::Current();
2030 ScopedObjectAccessUnchecked soa(self);
2031 StackHandleScope<2> hs(self);
2032 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2033 Handle<mirror::Class> annotation_class(hs.NewHandle(
2034 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2035 if (annotation_class.Get() == nullptr) {
2036 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2037 << type_index;
2038 DCHECK(Thread::Current()->IsExceptionPending());
2039 Thread::Current()->ClearException();
2040 return nullptr;
2041 }
2042
2043 mirror::Class* annotation_member_class =
2044 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2045 mirror::Class* annotation_member_array_class =
2046 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002047 if (annotation_member_array_class == nullptr) {
2048 return nullptr;
2049 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002050 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002051 if (size > 0) {
2052 element_array =
2053 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2054 if (element_array == nullptr) {
2055 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2056 return nullptr;
2057 }
2058 }
2059
2060 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2061 for (uint32_t i = 0; i < size; ++i) {
2062 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2063 if (new_member == nullptr) {
2064 return nullptr;
2065 }
2066 h_element_array->SetWithoutChecks<false>(i, new_member);
2067 }
2068
2069 JValue result;
2070 ArtMethod* create_annotation_method =
2071 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2072 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2073 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2074 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2075 if (self->IsExceptionPending()) {
2076 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2077 return nullptr;
2078 }
2079
2080 return result.GetL();
2081}
2082
2083const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2084 const char* descriptor, uint32_t visibility) const {
2085 const AnnotationItem* result = nullptr;
2086 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2087 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2088 if (annotation_item->visibility_ != visibility) {
2089 continue;
2090 }
2091 const uint8_t* annotation = annotation_item->annotation_;
2092 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2093
2094 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2095 result = annotation_item;
2096 break;
2097 }
2098 }
2099 return result;
2100}
2101
2102const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2103 DecodeUnsignedLeb128(&annotation); // unused type_index
2104 uint32_t size = DecodeUnsignedLeb128(&annotation);
2105
2106 while (size != 0) {
2107 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2108 const char* element_name = GetStringData(GetStringId(element_name_index));
2109 if (strcmp(name, element_name) == 0) {
2110 return annotation;
2111 }
2112 SkipAnnotationValue(&annotation);
2113 size--;
2114 }
2115 return nullptr;
2116}
2117
2118bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2119 const uint8_t* annotation = *annotation_ptr;
2120 uint8_t header_byte = *(annotation++);
2121 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2122 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2123 int32_t width = value_arg + 1;
2124
2125 switch (value_type) {
2126 case kDexAnnotationByte:
2127 case kDexAnnotationShort:
2128 case kDexAnnotationChar:
2129 case kDexAnnotationInt:
2130 case kDexAnnotationLong:
2131 case kDexAnnotationFloat:
2132 case kDexAnnotationDouble:
2133 case kDexAnnotationString:
2134 case kDexAnnotationType:
2135 case kDexAnnotationMethod:
2136 case kDexAnnotationField:
2137 case kDexAnnotationEnum:
2138 break;
2139 case kDexAnnotationArray:
2140 {
2141 uint32_t size = DecodeUnsignedLeb128(&annotation);
2142 while (size--) {
2143 if (!SkipAnnotationValue(&annotation)) {
2144 return false;
2145 }
2146 }
2147 width = 0;
2148 break;
2149 }
2150 case kDexAnnotationAnnotation:
2151 {
2152 DecodeUnsignedLeb128(&annotation); // unused type_index
2153 uint32_t size = DecodeUnsignedLeb128(&annotation);
2154 while (size--) {
2155 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2156 if (!SkipAnnotationValue(&annotation)) {
2157 return false;
2158 }
2159 }
2160 width = 0;
2161 break;
2162 }
2163 case kDexAnnotationBoolean:
2164 case kDexAnnotationNull:
2165 width = 0;
2166 break;
2167 default:
2168 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2169 return false;
2170 }
2171
2172 annotation += width;
2173 *annotation_ptr = annotation;
2174 return true;
2175}
2176
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002177std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2178 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2179 dex_file.GetLocation().c_str(),
2180 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2181 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2182 return os;
2183}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002184
Ian Rogersd91d6d62013-09-25 20:26:14 -07002185std::string Signature::ToString() const {
2186 if (dex_file_ == nullptr) {
2187 CHECK(proto_id_ == nullptr);
2188 return "<no signature>";
2189 }
2190 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2191 std::string result;
2192 if (params == nullptr) {
2193 result += "()";
2194 } else {
2195 result += "(";
2196 for (uint32_t i = 0; i < params->Size(); ++i) {
2197 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2198 }
2199 result += ")";
2200 }
2201 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2202 return result;
2203}
2204
Vladimir Markod9cffea2013-11-25 15:08:02 +00002205bool Signature::operator==(const StringPiece& rhs) const {
2206 if (dex_file_ == nullptr) {
2207 return false;
2208 }
2209 StringPiece tail(rhs);
2210 if (!tail.starts_with("(")) {
2211 return false; // Invalid signature
2212 }
2213 tail.remove_prefix(1); // "(";
2214 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2215 if (params != nullptr) {
2216 for (uint32_t i = 0; i < params->Size(); ++i) {
2217 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2218 if (!tail.starts_with(param)) {
2219 return false;
2220 }
2221 tail.remove_prefix(param.length());
2222 }
2223 }
2224 if (!tail.starts_with(")")) {
2225 return false;
2226 }
2227 tail.remove_prefix(1); // ")";
2228 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2229}
2230
Ian Rogersd91d6d62013-09-25 20:26:14 -07002231std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2232 return os << sig.ToString();
2233}
2234
Ian Rogers0571d352011-11-03 19:51:38 -07002235// Decodes the header section from the class data bytes.
2236void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002237 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002238 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2239 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2240 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2241 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2242}
2243
2244void ClassDataItemIterator::ReadClassDataField() {
2245 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2246 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002247 // The user of the iterator is responsible for checking if there
2248 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002249}
2250
2251void ClassDataItemIterator::ReadClassDataMethod() {
2252 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2253 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2254 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002255 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002256 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002257 }
Ian Rogers0571d352011-11-03 19:51:38 -07002258}
2259
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002260EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002261 const DexFile& dex_file,
2262 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002263 : EncodedStaticFieldValueIterator(dex_file,
2264 nullptr,
2265 nullptr,
2266 nullptr,
2267 class_def,
2268 -1,
2269 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002270}
2271
2272EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002273 const DexFile& dex_file,
2274 Handle<mirror::DexCache>* dex_cache,
2275 Handle<mirror::ClassLoader>* class_loader,
2276 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002277 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002278 : EncodedStaticFieldValueIterator(dex_file,
2279 dex_cache, class_loader,
2280 linker,
2281 class_def,
2282 -1,
2283 kByte) {
2284 DCHECK(dex_cache_ != nullptr);
2285 DCHECK(class_loader_ != nullptr);
2286}
2287
2288EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2289 const DexFile& dex_file,
2290 Handle<mirror::DexCache>* dex_cache,
2291 Handle<mirror::ClassLoader>* class_loader,
2292 ClassLinker* linker,
2293 const DexFile::ClassDef& class_def,
2294 size_t pos,
2295 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002296 : dex_file_(dex_file),
2297 dex_cache_(dex_cache),
2298 class_loader_(class_loader),
2299 linker_(linker),
2300 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002301 pos_(pos),
2302 type_(type) {
2303 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002304 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002305 array_size_ = 0;
2306 } else {
2307 array_size_ = DecodeUnsignedLeb128(&ptr_);
2308 }
2309 if (array_size_ > 0) {
2310 Next();
2311 }
2312}
2313
2314void EncodedStaticFieldValueIterator::Next() {
2315 pos_++;
2316 if (pos_ >= array_size_) {
2317 return;
2318 }
Ian Rogers13735952014-10-08 12:43:28 -07002319 uint8_t value_type = *ptr_++;
2320 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002321 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002322 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002323 switch (type_) {
2324 case kBoolean:
2325 jval_.i = (value_arg != 0) ? 1 : 0;
2326 width = 0;
2327 break;
2328 case kByte:
2329 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002330 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002331 break;
2332 case kShort:
2333 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002334 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002335 break;
2336 case kChar:
2337 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002338 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002339 break;
2340 case kInt:
2341 jval_.i = ReadSignedInt(ptr_, value_arg);
2342 break;
2343 case kLong:
2344 jval_.j = ReadSignedLong(ptr_, value_arg);
2345 break;
2346 case kFloat:
2347 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2348 break;
2349 case kDouble:
2350 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2351 break;
2352 case kString:
2353 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002354 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2355 break;
2356 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002357 case kMethod:
2358 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002359 case kArray:
2360 case kAnnotation:
2361 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002362 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002363 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002364 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002365 width = 0;
2366 break;
2367 default:
2368 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002369 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002370 }
2371 ptr_ += width;
2372}
2373
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002374template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002375void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002376 DCHECK(dex_cache_ != nullptr);
2377 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002378 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002379 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2380 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002381 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2382 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2383 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2384 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2385 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2386 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2387 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002388 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002389 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002390 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002391 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002392 break;
2393 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002394 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002395 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2396 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002397 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002398 break;
2399 }
Ian Rogers0571d352011-11-03 19:51:38 -07002400 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2401 }
2402}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002403template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2404template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002405
2406CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2407 handler_.address_ = -1;
2408 int32_t offset = -1;
2409
2410 // Short-circuit the overwhelmingly common cases.
2411 switch (code_item.tries_size_) {
2412 case 0:
2413 break;
2414 case 1: {
2415 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2416 uint32_t start = tries->start_addr_;
2417 if (address >= start) {
2418 uint32_t end = start + tries->insn_count_;
2419 if (address < end) {
2420 offset = tries->handler_off_;
2421 }
2422 }
2423 break;
2424 }
2425 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002426 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002427 }
Logan Chien736df022012-04-27 16:25:57 +08002428 Init(code_item, offset);
2429}
2430
2431CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2432 const DexFile::TryItem& try_item) {
2433 handler_.address_ = -1;
2434 Init(code_item, try_item.handler_off_);
2435}
2436
2437void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2438 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002439 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002440 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002441 } else {
2442 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002443 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002444 remaining_count_ = -1;
2445 catch_all_ = false;
2446 DCHECK(!HasNext());
2447 }
2448}
2449
Ian Rogers13735952014-10-08 12:43:28 -07002450void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002451 current_data_ = handler_data;
2452 remaining_count_ = DecodeSignedLeb128(&current_data_);
2453
2454 // If remaining_count_ is non-positive, then it is the negative of
2455 // the number of catch types, and the catches are followed by a
2456 // catch-all handler.
2457 if (remaining_count_ <= 0) {
2458 catch_all_ = true;
2459 remaining_count_ = -remaining_count_;
2460 } else {
2461 catch_all_ = false;
2462 }
2463 Next();
2464}
2465
2466void CatchHandlerIterator::Next() {
2467 if (remaining_count_ > 0) {
2468 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2469 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2470 remaining_count_--;
2471 return;
2472 }
2473
2474 if (catch_all_) {
2475 handler_.type_idx_ = DexFile::kDexNoIndex16;
2476 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2477 catch_all_ = false;
2478 return;
2479 }
2480
2481 // no more handler
2482 remaining_count_ = -1;
2483}
2484
Carl Shapiro1fb86202011-06-27 17:43:13 -07002485} // namespace art