blob: e62aa04d0092a29f811351e00c044cee9c26a7c9 [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
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300690void DexFile::CreateTypeLookupTable() const {
691 lookup_table_.reset(TypeLookupTable::Create(*this));
692}
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 }
1386 mirror::Object* obj = GetAnnotationValue(
1387 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1388 if (obj == nullptr) {
1389 return nullptr;
1390 }
1391 return obj->AsClass();
1392}
1393
1394mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1395 mirror::Class* declaring_class = GetDeclaringClass(klass);
1396 if (declaring_class != nullptr) {
1397 return declaring_class;
1398 }
1399 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1400 if (annotation_set == nullptr) {
1401 return nullptr;
1402 }
1403 const AnnotationItem* annotation_item = SearchAnnotationSet(
1404 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1405 if (annotation_item == nullptr) {
1406 return nullptr;
1407 }
1408 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1409 if (annotation == nullptr) {
1410 return nullptr;
1411 }
1412 AnnotationValue annotation_value;
1413 if (!ProcessAnnotationValue(
1414 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1415 return nullptr;
1416 }
1417 if (annotation_value.type_ != kDexAnnotationMethod) {
1418 return nullptr;
1419 }
1420 StackHandleScope<2> hs(Thread::Current());
1421 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1422 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1423 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1424 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1425 if (method == nullptr) {
1426 return nullptr;
1427 }
1428 return method->GetDeclaringClass();
1429}
1430
1431mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1432 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1433 if (annotation_set == nullptr) {
1434 return nullptr;
1435 }
1436 const AnnotationItem* annotation_item = SearchAnnotationSet(
1437 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1438 if (annotation_item == nullptr) {
1439 return nullptr;
1440 }
1441 return GetAnnotationValue(
1442 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1443}
1444
1445bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1446 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1447 if (annotation_set == nullptr) {
1448 return false;
1449 }
1450 const AnnotationItem* annotation_item = SearchAnnotationSet(
1451 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1452 if (annotation_item == nullptr) {
1453 return false;
1454 }
1455 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1456 if (annotation == nullptr) {
1457 return false;
1458 }
1459 AnnotationValue annotation_value;
1460 if (!ProcessAnnotationValue(
1461 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1462 return false;
1463 }
1464 if (annotation_value.type_ != kDexAnnotationNull &&
1465 annotation_value.type_ != kDexAnnotationString) {
1466 return false;
1467 }
1468 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1469 return true;
1470}
1471
1472bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1473 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1474 if (annotation_set == nullptr) {
1475 return false;
1476 }
1477 const AnnotationItem* annotation_item = SearchAnnotationSet(
1478 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1479 if (annotation_item == nullptr) {
1480 return false;
1481 }
1482 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1483 if (annotation == nullptr) {
1484 return false;
1485 }
1486 AnnotationValue annotation_value;
1487 if (!ProcessAnnotationValue(
1488 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1489 return false;
1490 }
1491 if (annotation_value.type_ != kDexAnnotationInt) {
1492 return false;
1493 }
1494 *flags = annotation_value.value_.GetI();
1495 return true;
1496}
1497
Jeff Hao13e748b2015-08-25 20:44:19 +00001498bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1499 Handle<mirror::Class> annotation_class) const {
1500 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1501 if (annotation_set == nullptr) {
1502 return false;
1503 }
1504 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1505 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001506 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001507}
1508
1509mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1510 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1511 Thread* self = Thread::Current();
1512 ScopedObjectAccessUnchecked soa(self);
1513 StackHandleScope<5> hs(self);
1514 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1515 const char* name = StringDataByIdx(element_name_index);
1516 Handle<mirror::String> string_name(
1517 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1518
1519 ArtMethod* annotation_method =
1520 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1521 if (annotation_method == nullptr) {
1522 return nullptr;
1523 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001524 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1525 Handle<mirror::Class> method_return(hs.NewHandle(
1526 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001527
1528 AnnotationValue annotation_value;
1529 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1530 return nullptr;
1531 }
1532 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1533
1534 mirror::Class* annotation_member_class =
1535 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1536 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1537 Handle<mirror::Method> method_object(
1538 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1539
1540 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1541 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1542 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1543 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1544 return nullptr;
1545 }
1546
1547 JValue result;
1548 ArtMethod* annotation_member_init =
1549 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1550 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1551 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1552 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1553 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1554 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1555 };
1556 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1557 if (self->IsExceptionPending()) {
1558 LOG(INFO) << "Exception in AnnotationMember.<init>";
1559 return nullptr;
1560 }
1561
1562 return new_member.Get();
1563}
1564
1565const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1566 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1567 Handle<mirror::Class> annotation_class) const {
1568 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1569 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1570 if (annotation_item->visibility_ != visibility) {
1571 continue;
1572 }
1573 const uint8_t* annotation = annotation_item->annotation_;
1574 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1575 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1576 klass->GetDexFile(), type_index, klass.Get());
1577 if (resolved_class == nullptr) {
1578 std::string temp;
1579 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1580 klass->GetDescriptor(&temp), type_index);
1581 CHECK(Thread::Current()->IsExceptionPending());
1582 Thread::Current()->ClearException();
1583 continue;
1584 }
1585 if (resolved_class == annotation_class.Get()) {
1586 return annotation_item;
1587 }
1588 }
1589
1590 return nullptr;
1591}
1592
1593mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1594 const AnnotationSetItem* annotation_set, uint32_t visibility,
1595 Handle<mirror::Class> annotation_class) const {
1596 const AnnotationItem* annotation_item =
1597 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1598 if (annotation_item == nullptr) {
1599 return nullptr;
1600 }
1601 const uint8_t* annotation = annotation_item->annotation_;
1602 return ProcessEncodedAnnotation(klass, &annotation);
1603}
1604
1605mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1606 const AnnotationItem* annotation_item, const char* annotation_name,
1607 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1608 const uint8_t* annotation =
1609 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1610 if (annotation == nullptr) {
1611 return nullptr;
1612 }
1613 AnnotationValue annotation_value;
1614 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1615 return nullptr;
1616 }
1617 if (annotation_value.type_ != expected_type) {
1618 return nullptr;
1619 }
1620 return annotation_value.value_.GetL();
1621}
1622
Jeff Hao2a5892f2015-08-31 15:00:40 -07001623mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001624 const AnnotationSetItem* annotation_set) const {
1625 StackHandleScope<1> hs(Thread::Current());
1626 const AnnotationItem* annotation_item =
1627 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1628 if (annotation_item == nullptr) {
1629 return nullptr;
1630 }
1631 mirror::Class* string_class = mirror::String::GetJavaLangString();
1632 Handle<mirror::Class> string_array_class(hs.NewHandle(
1633 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001634 if (string_array_class.Get() == nullptr) {
1635 return nullptr;
1636 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001637 mirror::Object* obj =
1638 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1639 if (obj == nullptr) {
1640 return nullptr;
1641 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001642 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001643}
1644
Jeff Hao2a5892f2015-08-31 15:00:40 -07001645mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001646 const AnnotationSetItem* annotation_set) const {
1647 StackHandleScope<1> hs(Thread::Current());
1648 const AnnotationItem* annotation_item =
1649 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1650 if (annotation_item == nullptr) {
1651 return nullptr;
1652 }
1653 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1654 Handle<mirror::Class> class_array_class(hs.NewHandle(
1655 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001656 if (class_array_class.Get() == nullptr) {
1657 return nullptr;
1658 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001659 mirror::Object* obj =
1660 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1661 if (obj == nullptr) {
1662 return nullptr;
1663 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001664 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001665}
1666
1667mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1668 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1669 Thread* self = Thread::Current();
1670 ScopedObjectAccessUnchecked soa(self);
1671 StackHandleScope<2> hs(self);
1672 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1673 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1674 if (annotation_set == nullptr) {
1675 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1676 }
1677
1678 uint32_t size = annotation_set->size_;
1679 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1680 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1681 if (result.Get() == nullptr) {
1682 return nullptr;
1683 }
1684
1685 uint32_t dest_index = 0;
1686 for (uint32_t i = 0; i < size; ++i) {
1687 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1688 if (annotation_item->visibility_ != visibility) {
1689 continue;
1690 }
1691 const uint8_t* annotation = annotation_item->annotation_;
1692 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1693 if (annotation_obj != nullptr) {
1694 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1695 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001696 } else if (self->IsExceptionPending()) {
1697 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001698 }
1699 }
1700
1701 if (dest_index == size) {
1702 return result.Get();
1703 }
1704
1705 mirror::ObjectArray<mirror::Object>* trimmed_result =
1706 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001707 if (trimmed_result == nullptr) {
1708 return nullptr;
1709 }
1710
Jeff Hao13e748b2015-08-25 20:44:19 +00001711 for (uint32_t i = 0; i < dest_index; ++i) {
1712 mirror::Object* obj = result->GetWithoutChecks(i);
1713 trimmed_result->SetWithoutChecks<false>(i, obj);
1714 }
1715
1716 return trimmed_result;
1717}
1718
1719mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1720 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1721 Thread* self = Thread::Current();
1722 ScopedObjectAccessUnchecked soa(self);
1723 StackHandleScope<1> hs(self);
1724 mirror::Class* annotation_array_class =
1725 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1726 mirror::Class* annotation_array_array_class =
1727 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001728 if (annotation_array_array_class == nullptr) {
1729 return nullptr;
1730 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001731 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1732 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1733 if (annotation_array_array.Get() == nullptr) {
1734 LOG(ERROR) << "Annotation set ref array allocation failed";
1735 return nullptr;
1736 }
1737 for (uint32_t index = 0; index < size; ++index) {
1738 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1739 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1740 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1741 if (annotation_set == nullptr) {
1742 return nullptr;
1743 }
1744 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1745 }
1746 return annotation_array_array.Get();
1747}
1748
1749bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1750 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1751 DexFile::AnnotationResultStyle result_style) const {
1752 Thread* self = Thread::Current();
1753 mirror::Object* element_object = nullptr;
1754 bool set_object = false;
1755 Primitive::Type primitive_type = Primitive::kPrimVoid;
1756 const uint8_t* annotation = *annotation_ptr;
1757 uint8_t header_byte = *(annotation++);
1758 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1759 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1760 int32_t width = value_arg + 1;
1761 annotation_value->type_ = value_type;
1762
1763 switch (value_type) {
1764 case kDexAnnotationByte:
1765 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1766 primitive_type = Primitive::kPrimByte;
1767 break;
1768 case kDexAnnotationShort:
1769 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1770 primitive_type = Primitive::kPrimShort;
1771 break;
1772 case kDexAnnotationChar:
1773 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1774 false)));
1775 primitive_type = Primitive::kPrimChar;
1776 break;
1777 case kDexAnnotationInt:
1778 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1779 primitive_type = Primitive::kPrimInt;
1780 break;
1781 case kDexAnnotationLong:
1782 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1783 primitive_type = Primitive::kPrimLong;
1784 break;
1785 case kDexAnnotationFloat:
1786 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1787 primitive_type = Primitive::kPrimFloat;
1788 break;
1789 case kDexAnnotationDouble:
1790 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1791 primitive_type = Primitive::kPrimDouble;
1792 break;
1793 case kDexAnnotationBoolean:
1794 annotation_value->value_.SetZ(value_arg != 0);
1795 primitive_type = Primitive::kPrimBoolean;
1796 width = 0;
1797 break;
1798 case kDexAnnotationString: {
1799 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1800 if (result_style == kAllRaw) {
1801 annotation_value->value_.SetI(index);
1802 } else {
1803 StackHandleScope<1> hs(self);
1804 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1805 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1806 klass->GetDexFile(), index, dex_cache);
1807 set_object = true;
1808 if (element_object == nullptr) {
1809 return false;
1810 }
1811 }
1812 break;
1813 }
1814 case kDexAnnotationType: {
1815 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1816 if (result_style == kAllRaw) {
1817 annotation_value->value_.SetI(index);
1818 } else {
1819 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1820 klass->GetDexFile(), index, klass.Get());
1821 set_object = true;
1822 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001823 CHECK(self->IsExceptionPending());
1824 if (result_style == kAllObjects) {
1825 const char* msg = StringByTypeIdx(index);
1826 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1827 element_object = self->GetException();
1828 self->ClearException();
1829 } else {
1830 return false;
1831 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001832 }
1833 }
1834 break;
1835 }
1836 case kDexAnnotationMethod: {
1837 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1838 if (result_style == kAllRaw) {
1839 annotation_value->value_.SetI(index);
1840 } else {
1841 StackHandleScope<2> hs(self);
1842 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1843 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1844 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1845 klass->GetDexFile(), index, dex_cache, class_loader);
1846 if (method == nullptr) {
1847 return false;
1848 }
1849 set_object = true;
1850 if (method->IsConstructor()) {
1851 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1852 } else {
1853 element_object = mirror::Method::CreateFromArtMethod(self, method);
1854 }
1855 if (element_object == nullptr) {
1856 return false;
1857 }
1858 }
1859 break;
1860 }
1861 case kDexAnnotationField: {
1862 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1863 if (result_style == kAllRaw) {
1864 annotation_value->value_.SetI(index);
1865 } else {
1866 StackHandleScope<2> hs(self);
1867 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1868 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1869 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1870 klass->GetDexFile(), index, dex_cache, class_loader);
1871 if (field == nullptr) {
1872 return false;
1873 }
1874 set_object = true;
1875 element_object = mirror::Field::CreateFromArtField(self, field, true);
1876 if (element_object == nullptr) {
1877 return false;
1878 }
1879 }
1880 break;
1881 }
1882 case kDexAnnotationEnum: {
1883 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1884 if (result_style == kAllRaw) {
1885 annotation_value->value_.SetI(index);
1886 } else {
1887 StackHandleScope<3> hs(self);
1888 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1889 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1890 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1891 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001892 if (enum_field == nullptr) {
1893 return false;
1894 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001895 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001896 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1897 element_object = enum_field->GetObject(field_class.Get());
1898 set_object = true;
1899 }
1900 }
1901 break;
1902 }
1903 case kDexAnnotationArray:
1904 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1905 return false;
1906 } else {
1907 ScopedObjectAccessUnchecked soa(self);
1908 StackHandleScope<2> hs(self);
1909 uint32_t size = DecodeUnsignedLeb128(&annotation);
1910 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1911 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1912 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1913 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1914 if (new_array.Get() == nullptr) {
1915 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1916 return false;
1917 }
1918 AnnotationValue new_annotation_value;
1919 for (uint32_t i = 0; i < size; ++i) {
1920 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1921 kPrimitivesOrObjects)) {
1922 return false;
1923 }
1924 if (!component_type->IsPrimitive()) {
1925 mirror::Object* obj = new_annotation_value.value_.GetL();
1926 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1927 } else {
1928 switch (new_annotation_value.type_) {
1929 case kDexAnnotationByte:
1930 new_array->AsByteArray()->SetWithoutChecks<false>(
1931 i, new_annotation_value.value_.GetB());
1932 break;
1933 case kDexAnnotationShort:
1934 new_array->AsShortArray()->SetWithoutChecks<false>(
1935 i, new_annotation_value.value_.GetS());
1936 break;
1937 case kDexAnnotationChar:
1938 new_array->AsCharArray()->SetWithoutChecks<false>(
1939 i, new_annotation_value.value_.GetC());
1940 break;
1941 case kDexAnnotationInt:
1942 new_array->AsIntArray()->SetWithoutChecks<false>(
1943 i, new_annotation_value.value_.GetI());
1944 break;
1945 case kDexAnnotationLong:
1946 new_array->AsLongArray()->SetWithoutChecks<false>(
1947 i, new_annotation_value.value_.GetJ());
1948 break;
1949 case kDexAnnotationFloat:
1950 new_array->AsFloatArray()->SetWithoutChecks<false>(
1951 i, new_annotation_value.value_.GetF());
1952 break;
1953 case kDexAnnotationDouble:
1954 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1955 i, new_annotation_value.value_.GetD());
1956 break;
1957 case kDexAnnotationBoolean:
1958 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1959 i, new_annotation_value.value_.GetZ());
1960 break;
1961 default:
1962 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1963 return false;
1964 }
1965 }
1966 }
1967 element_object = new_array.Get();
1968 set_object = true;
1969 width = 0;
1970 }
1971 break;
1972 case kDexAnnotationAnnotation:
1973 if (result_style == kAllRaw) {
1974 return false;
1975 }
1976 element_object = ProcessEncodedAnnotation(klass, &annotation);
1977 if (element_object == nullptr) {
1978 return false;
1979 }
1980 set_object = true;
1981 width = 0;
1982 break;
1983 case kDexAnnotationNull:
1984 if (result_style == kAllRaw) {
1985 annotation_value->value_.SetI(0);
1986 } else {
1987 CHECK(element_object == nullptr);
1988 set_object = true;
1989 }
1990 width = 0;
1991 break;
1992 default:
1993 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1994 return false;
1995 }
1996
1997 annotation += width;
1998 *annotation_ptr = annotation;
1999
2000 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2001 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2002 set_object = true;
2003 }
2004
2005 if (set_object) {
2006 annotation_value->value_.SetL(element_object);
2007 }
2008
2009 return true;
2010}
2011
2012mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2013 const uint8_t** annotation) const {
2014 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2015 uint32_t size = DecodeUnsignedLeb128(annotation);
2016
2017 Thread* self = Thread::Current();
2018 ScopedObjectAccessUnchecked soa(self);
2019 StackHandleScope<2> hs(self);
2020 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2021 Handle<mirror::Class> annotation_class(hs.NewHandle(
2022 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2023 if (annotation_class.Get() == nullptr) {
2024 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2025 << type_index;
2026 DCHECK(Thread::Current()->IsExceptionPending());
2027 Thread::Current()->ClearException();
2028 return nullptr;
2029 }
2030
2031 mirror::Class* annotation_member_class =
2032 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2033 mirror::Class* annotation_member_array_class =
2034 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002035 if (annotation_member_array_class == nullptr) {
2036 return nullptr;
2037 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002038 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002039 if (size > 0) {
2040 element_array =
2041 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2042 if (element_array == nullptr) {
2043 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2044 return nullptr;
2045 }
2046 }
2047
2048 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2049 for (uint32_t i = 0; i < size; ++i) {
2050 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2051 if (new_member == nullptr) {
2052 return nullptr;
2053 }
2054 h_element_array->SetWithoutChecks<false>(i, new_member);
2055 }
2056
2057 JValue result;
2058 ArtMethod* create_annotation_method =
2059 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2060 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2061 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2062 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2063 if (self->IsExceptionPending()) {
2064 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2065 return nullptr;
2066 }
2067
2068 return result.GetL();
2069}
2070
2071const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2072 const char* descriptor, uint32_t visibility) const {
2073 const AnnotationItem* result = nullptr;
2074 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2075 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2076 if (annotation_item->visibility_ != visibility) {
2077 continue;
2078 }
2079 const uint8_t* annotation = annotation_item->annotation_;
2080 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2081
2082 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2083 result = annotation_item;
2084 break;
2085 }
2086 }
2087 return result;
2088}
2089
2090const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2091 DecodeUnsignedLeb128(&annotation); // unused type_index
2092 uint32_t size = DecodeUnsignedLeb128(&annotation);
2093
2094 while (size != 0) {
2095 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2096 const char* element_name = GetStringData(GetStringId(element_name_index));
2097 if (strcmp(name, element_name) == 0) {
2098 return annotation;
2099 }
2100 SkipAnnotationValue(&annotation);
2101 size--;
2102 }
2103 return nullptr;
2104}
2105
2106bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2107 const uint8_t* annotation = *annotation_ptr;
2108 uint8_t header_byte = *(annotation++);
2109 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2110 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2111 int32_t width = value_arg + 1;
2112
2113 switch (value_type) {
2114 case kDexAnnotationByte:
2115 case kDexAnnotationShort:
2116 case kDexAnnotationChar:
2117 case kDexAnnotationInt:
2118 case kDexAnnotationLong:
2119 case kDexAnnotationFloat:
2120 case kDexAnnotationDouble:
2121 case kDexAnnotationString:
2122 case kDexAnnotationType:
2123 case kDexAnnotationMethod:
2124 case kDexAnnotationField:
2125 case kDexAnnotationEnum:
2126 break;
2127 case kDexAnnotationArray:
2128 {
2129 uint32_t size = DecodeUnsignedLeb128(&annotation);
2130 while (size--) {
2131 if (!SkipAnnotationValue(&annotation)) {
2132 return false;
2133 }
2134 }
2135 width = 0;
2136 break;
2137 }
2138 case kDexAnnotationAnnotation:
2139 {
2140 DecodeUnsignedLeb128(&annotation); // unused type_index
2141 uint32_t size = DecodeUnsignedLeb128(&annotation);
2142 while (size--) {
2143 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2144 if (!SkipAnnotationValue(&annotation)) {
2145 return false;
2146 }
2147 }
2148 width = 0;
2149 break;
2150 }
2151 case kDexAnnotationBoolean:
2152 case kDexAnnotationNull:
2153 width = 0;
2154 break;
2155 default:
2156 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2157 return false;
2158 }
2159
2160 annotation += width;
2161 *annotation_ptr = annotation;
2162 return true;
2163}
2164
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002165std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2166 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2167 dex_file.GetLocation().c_str(),
2168 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2169 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2170 return os;
2171}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002172
Ian Rogersd91d6d62013-09-25 20:26:14 -07002173std::string Signature::ToString() const {
2174 if (dex_file_ == nullptr) {
2175 CHECK(proto_id_ == nullptr);
2176 return "<no signature>";
2177 }
2178 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2179 std::string result;
2180 if (params == nullptr) {
2181 result += "()";
2182 } else {
2183 result += "(";
2184 for (uint32_t i = 0; i < params->Size(); ++i) {
2185 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2186 }
2187 result += ")";
2188 }
2189 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2190 return result;
2191}
2192
Vladimir Markod9cffea2013-11-25 15:08:02 +00002193bool Signature::operator==(const StringPiece& rhs) const {
2194 if (dex_file_ == nullptr) {
2195 return false;
2196 }
2197 StringPiece tail(rhs);
2198 if (!tail.starts_with("(")) {
2199 return false; // Invalid signature
2200 }
2201 tail.remove_prefix(1); // "(";
2202 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2203 if (params != nullptr) {
2204 for (uint32_t i = 0; i < params->Size(); ++i) {
2205 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2206 if (!tail.starts_with(param)) {
2207 return false;
2208 }
2209 tail.remove_prefix(param.length());
2210 }
2211 }
2212 if (!tail.starts_with(")")) {
2213 return false;
2214 }
2215 tail.remove_prefix(1); // ")";
2216 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2217}
2218
Ian Rogersd91d6d62013-09-25 20:26:14 -07002219std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2220 return os << sig.ToString();
2221}
2222
Ian Rogers0571d352011-11-03 19:51:38 -07002223// Decodes the header section from the class data bytes.
2224void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002225 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002226 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2227 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2228 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2229 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2230}
2231
2232void ClassDataItemIterator::ReadClassDataField() {
2233 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2234 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002235 // The user of the iterator is responsible for checking if there
2236 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002237}
2238
2239void ClassDataItemIterator::ReadClassDataMethod() {
2240 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2241 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2242 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002243 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002244 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002245 }
Ian Rogers0571d352011-11-03 19:51:38 -07002246}
2247
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002248EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2249 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2250 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2251 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002252 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2253 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002254 DCHECK(dex_cache != nullptr);
2255 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002256 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002257 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002258 array_size_ = 0;
2259 } else {
2260 array_size_ = DecodeUnsignedLeb128(&ptr_);
2261 }
2262 if (array_size_ > 0) {
2263 Next();
2264 }
2265}
2266
2267void EncodedStaticFieldValueIterator::Next() {
2268 pos_++;
2269 if (pos_ >= array_size_) {
2270 return;
2271 }
Ian Rogers13735952014-10-08 12:43:28 -07002272 uint8_t value_type = *ptr_++;
2273 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002274 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002275 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002276 switch (type_) {
2277 case kBoolean:
2278 jval_.i = (value_arg != 0) ? 1 : 0;
2279 width = 0;
2280 break;
2281 case kByte:
2282 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002283 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002284 break;
2285 case kShort:
2286 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002287 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002288 break;
2289 case kChar:
2290 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002291 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002292 break;
2293 case kInt:
2294 jval_.i = ReadSignedInt(ptr_, value_arg);
2295 break;
2296 case kLong:
2297 jval_.j = ReadSignedLong(ptr_, value_arg);
2298 break;
2299 case kFloat:
2300 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2301 break;
2302 case kDouble:
2303 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2304 break;
2305 case kString:
2306 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002307 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2308 break;
2309 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002310 case kMethod:
2311 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002312 case kArray:
2313 case kAnnotation:
2314 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002315 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002316 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002317 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002318 width = 0;
2319 break;
2320 default:
2321 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002322 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002323 }
2324 ptr_ += width;
2325}
2326
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002327template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002328void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002329 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002330 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2331 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002332 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2333 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2334 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2335 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2336 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2337 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2338 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002339 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002340 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002341 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002342 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002343 break;
2344 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002345 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2347 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002348 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002349 break;
2350 }
Ian Rogers0571d352011-11-03 19:51:38 -07002351 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2352 }
2353}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002354template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2355template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002356
2357CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2358 handler_.address_ = -1;
2359 int32_t offset = -1;
2360
2361 // Short-circuit the overwhelmingly common cases.
2362 switch (code_item.tries_size_) {
2363 case 0:
2364 break;
2365 case 1: {
2366 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2367 uint32_t start = tries->start_addr_;
2368 if (address >= start) {
2369 uint32_t end = start + tries->insn_count_;
2370 if (address < end) {
2371 offset = tries->handler_off_;
2372 }
2373 }
2374 break;
2375 }
2376 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002377 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002378 }
Logan Chien736df022012-04-27 16:25:57 +08002379 Init(code_item, offset);
2380}
2381
2382CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2383 const DexFile::TryItem& try_item) {
2384 handler_.address_ = -1;
2385 Init(code_item, try_item.handler_off_);
2386}
2387
2388void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2389 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002390 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002391 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002392 } else {
2393 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002394 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002395 remaining_count_ = -1;
2396 catch_all_ = false;
2397 DCHECK(!HasNext());
2398 }
2399}
2400
Ian Rogers13735952014-10-08 12:43:28 -07002401void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002402 current_data_ = handler_data;
2403 remaining_count_ = DecodeSignedLeb128(&current_data_);
2404
2405 // If remaining_count_ is non-positive, then it is the negative of
2406 // the number of catch types, and the catches are followed by a
2407 // catch-all handler.
2408 if (remaining_count_ <= 0) {
2409 catch_all_ = true;
2410 remaining_count_ = -remaining_count_;
2411 } else {
2412 catch_all_ = false;
2413 }
2414 Next();
2415}
2416
2417void CatchHandlerIterator::Next() {
2418 if (remaining_count_ > 0) {
2419 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2420 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2421 remaining_count_--;
2422 return;
2423 }
2424
2425 if (catch_all_) {
2426 handler_.type_idx_ = DexFile::kDexNoIndex16;
2427 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2428 catch_all_ = false;
2429 return;
2430 }
2431
2432 // no more handler
2433 remaining_count_ = -1;
2434}
2435
Carl Shapiro1fb86202011-06-27 17:43:13 -07002436} // namespace art