blob: 30d921afe63ef836541f3ace30b306cc3b1b25c5 [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);
TDYa127c8dc1012012-04-19 07:03:33 -0700770 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700772 return context.line_num_;
773}
774
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700775int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700776 // Note: Signed type is important for max and min.
777 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700778 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700779
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700780 while (min <= max) {
781 int32_t mid = min + ((max - min) / 2);
782
783 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
784 uint32_t start = ti->start_addr_;
785 uint32_t end = start + ti->insn_count_;
786
Ian Rogers0571d352011-11-03 19:51:38 -0700787 if (address < start) {
788 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700789 } else if (address >= end) {
790 min = mid + 1;
791 } else { // We have a winner!
792 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700793 }
794 }
795 // No match.
796 return -1;
797}
798
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700799int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
800 int32_t try_item = FindTryItem(code_item, address);
801 if (try_item == -1) {
802 return -1;
803 } else {
804 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
805 }
806}
807
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800808void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800809 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700810 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
811 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700812 uint32_t line = DecodeUnsignedLeb128(&stream);
813 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
814 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
815 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700816 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700817
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800818 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700819 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800820 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700821 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800822 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700823 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700824 local_in_reg[arg_reg].start_address_ = 0;
825 local_in_reg[arg_reg].is_live_ = true;
826 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700827 arg_reg++;
828 }
829
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800830 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700831 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700832 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700833 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800834 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700835 return;
836 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800837 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700838 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800839 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700840 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700841 local_in_reg[arg_reg].name_ = name;
842 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700843 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700844 local_in_reg[arg_reg].start_address_ = address;
845 local_in_reg[arg_reg].is_live_ = true;
846 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700847 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700848 case 'D':
849 case 'J':
850 arg_reg += 2;
851 break;
852 default:
853 arg_reg += 1;
854 break;
855 }
856 }
857
Ian Rogers0571d352011-11-03 19:51:38 -0700858 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800859 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
860 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700861 return;
862 }
863
864 for (;;) {
865 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700866 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800867 uint32_t name_idx;
868 uint32_t descriptor_idx;
869 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700870
Shih-wei Liao195487c2011-08-20 13:29:04 -0700871 switch (opcode) {
872 case DBG_END_SEQUENCE:
873 return;
874
875 case DBG_ADVANCE_PC:
876 address += DecodeUnsignedLeb128(&stream);
877 break;
878
879 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700880 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 break;
882
883 case DBG_START_LOCAL:
884 case DBG_START_LOCAL_EXTENDED:
885 reg = DecodeUnsignedLeb128(&stream);
886 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700887 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800888 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700889 return;
890 }
891
jeffhaof8728872011-10-28 19:11:13 -0700892 name_idx = DecodeUnsignedLeb128P1(&stream);
893 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
894 if (opcode == DBG_START_LOCAL_EXTENDED) {
895 signature_idx = DecodeUnsignedLeb128P1(&stream);
896 }
897
Shih-wei Liao195487c2011-08-20 13:29:04 -0700898 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700899 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800900 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700901
Ian Rogers0571d352011-11-03 19:51:38 -0700902 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
903 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700904 local_in_reg[reg].signature_ =
905 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
906 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700907 local_in_reg[reg].start_address_ = address;
908 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700909 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910 break;
911
912 case DBG_END_LOCAL:
913 reg = DecodeUnsignedLeb128(&stream);
914 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700915 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800916 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700917 return;
918 }
919
Elliott Hughes30646832011-10-13 16:59:46 -0700920 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800921 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700922 local_in_reg[reg].is_live_ = false;
923 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 break;
925
926 case DBG_RESTART_LOCAL:
927 reg = DecodeUnsignedLeb128(&stream);
928 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700929 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800930 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700931 return;
932 }
933
Elliott Hughes30646832011-10-13 16:59:46 -0700934 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700935 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800936 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700937 return;
938 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700939
Elliott Hughes30646832011-10-13 16:59:46 -0700940 // If the register is live, the "restart" is superfluous,
941 // and we don't want to mess with the existing start address.
942 if (!local_in_reg[reg].is_live_) {
943 local_in_reg[reg].start_address_ = address;
944 local_in_reg[reg].is_live_ = true;
945 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700946 }
947 break;
948
949 case DBG_SET_PROLOGUE_END:
950 case DBG_SET_EPILOGUE_BEGIN:
951 case DBG_SET_FILE:
952 break;
953
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700954 default: {
955 int adjopcode = opcode - DBG_FIRST_SPECIAL;
956
Shih-wei Liao195487c2011-08-20 13:29:04 -0700957 address += adjopcode / DBG_LINE_RANGE;
958 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
959
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700960 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800961 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700962 // early exit
963 return;
964 }
965 }
966 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700967 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700968 }
969 }
970}
971
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800972void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800973 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
974 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100975 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700976 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700977 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700978 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700979 nullptr);
980 if (stream != nullptr) {
981 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
982 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700983 }
984 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700985 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
986 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700987 }
988}
989
Elliott Hughes2435a572012-02-17 16:07:41 -0800990bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
991 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700992
993 // We know that this callback will be called in
994 // ascending address order, so keep going until we find
995 // a match or we've just gone past it.
996 if (address > context->address_) {
997 // The line number from the previous positions callback
998 // wil be the final result.
999 return true;
1000 } else {
1001 context->line_num_ = line_num;
1002 return address == context->address_;
1003 }
1004}
1005
Andreas Gampe833a4852014-05-21 18:46:59 -07001006bool DexFile::IsMultiDexLocation(const char* location) {
1007 return strrchr(location, kMultiDexSeparator) != nullptr;
1008}
1009
Andreas Gampe90e34042015-04-27 20:01:52 -07001010std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1011 if (index == 0) {
1012 return "classes.dex";
1013 } else {
1014 return StringPrintf("classes%zu.dex", index + 1);
1015 }
1016}
1017
1018std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1019 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001020 return dex_location;
1021 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001022 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001023 }
1024}
1025
1026std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1027 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001028 std::string base_location = GetBaseLocation(dex_location);
1029 const char* suffix = dex_location + base_location.size();
1030 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1031 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1032 if (path != nullptr && path.get() != base_location) {
1033 return std::string(path.get()) + suffix;
1034 } else if (suffix[0] == 0) {
1035 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001036 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001037 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001038 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001039}
1040
Jeff Hao13e748b2015-08-25 20:44:19 +00001041// Read a signed integer. "zwidth" is the zero-based byte count.
1042static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1043 int32_t val = 0;
1044 for (int i = zwidth; i >= 0; --i) {
1045 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1046 }
1047 val >>= (3 - zwidth) * 8;
1048 return val;
1049}
1050
1051// Read an unsigned integer. "zwidth" is the zero-based byte count,
1052// "fill_on_right" indicates which side we want to zero-fill from.
1053static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1054 uint32_t val = 0;
1055 for (int i = zwidth; i >= 0; --i) {
1056 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1057 }
1058 if (!fill_on_right) {
1059 val >>= (3 - zwidth) * 8;
1060 }
1061 return val;
1062}
1063
1064// Read a signed long. "zwidth" is the zero-based byte count.
1065static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1066 int64_t val = 0;
1067 for (int i = zwidth; i >= 0; --i) {
1068 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1069 }
1070 val >>= (7 - zwidth) * 8;
1071 return val;
1072}
1073
1074// Read an unsigned long. "zwidth" is the zero-based byte count,
1075// "fill_on_right" indicates which side we want to zero-fill from.
1076static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1077 uint64_t val = 0;
1078 for (int i = zwidth; i >= 0; --i) {
1079 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1080 }
1081 if (!fill_on_right) {
1082 val >>= (7 - zwidth) * 8;
1083 }
1084 return val;
1085}
1086
1087const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1088 mirror::Class* klass = field->GetDeclaringClass();
1089 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1090 if (annotations_dir == nullptr) {
1091 return nullptr;
1092 }
1093 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1094 if (field_annotations == nullptr) {
1095 return nullptr;
1096 }
1097 uint32_t field_index = field->GetDexFieldIndex();
1098 uint32_t field_count = annotations_dir->fields_size_;
1099 for (uint32_t i = 0; i < field_count; ++i) {
1100 if (field_annotations[i].field_idx_ == field_index) {
1101 return GetFieldAnnotationSetItem(field_annotations[i]);
1102 }
1103 }
1104 return nullptr;
1105}
1106
1107mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1108 Handle<mirror::Class> annotation_class) const {
1109 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1110 if (annotation_set == nullptr) {
1111 return nullptr;
1112 }
1113 StackHandleScope<1> hs(Thread::Current());
1114 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1115 return GetAnnotationObjectFromAnnotationSet(
1116 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1117}
1118
1119mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1120 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1121 StackHandleScope<1> hs(Thread::Current());
1122 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1123 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1124}
1125
Jeff Hao2a5892f2015-08-31 15:00:40 -07001126mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001127 const {
1128 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1129 if (annotation_set == nullptr) {
1130 return nullptr;
1131 }
1132 StackHandleScope<1> hs(Thread::Current());
1133 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1134 return GetSignatureValue(field_class, annotation_set);
1135}
1136
1137bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1138 const {
1139 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1140 if (annotation_set == nullptr) {
1141 return false;
1142 }
1143 StackHandleScope<1> hs(Thread::Current());
1144 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1145 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1146 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1147 return annotation_item != nullptr;
1148}
1149
1150const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1151 mirror::Class* klass = method->GetDeclaringClass();
1152 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1153 if (annotations_dir == nullptr) {
1154 return nullptr;
1155 }
1156 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1157 if (method_annotations == nullptr) {
1158 return nullptr;
1159 }
1160 uint32_t method_index = method->GetDexMethodIndex();
1161 uint32_t method_count = annotations_dir->methods_size_;
1162 for (uint32_t i = 0; i < method_count; ++i) {
1163 if (method_annotations[i].method_idx_ == method_index) {
1164 return GetMethodAnnotationSetItem(method_annotations[i]);
1165 }
1166 }
1167 return nullptr;
1168}
1169
1170const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1171 const {
1172 mirror::Class* klass = method->GetDeclaringClass();
1173 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1174 if (annotations_dir == nullptr) {
1175 return nullptr;
1176 }
1177 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1178 if (parameter_annotations == nullptr) {
1179 return nullptr;
1180 }
1181 uint32_t method_index = method->GetDexMethodIndex();
1182 uint32_t parameter_count = annotations_dir->parameters_size_;
1183 for (uint32_t i = 0; i < parameter_count; ++i) {
1184 if (parameter_annotations[i].method_idx_ == method_index) {
1185 return &parameter_annotations[i];
1186 }
1187 }
1188 return nullptr;
1189}
1190
1191mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1192 mirror::Class* klass = method->GetDeclaringClass();
1193 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1194 if (annotations_dir == nullptr) {
1195 return nullptr;
1196 }
1197 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1198 if (annotation_set == nullptr) {
1199 return nullptr;
1200 }
1201 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1202 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1203 if (annotation_item == nullptr) {
1204 return nullptr;
1205 }
1206 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1207 if (annotation == nullptr) {
1208 return nullptr;
1209 }
1210 uint8_t header_byte = *(annotation++);
1211 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1212 return nullptr;
1213 }
1214 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1215 if (annotation == nullptr) {
1216 return nullptr;
1217 }
1218 AnnotationValue annotation_value;
1219 StackHandleScope<2> hs(Thread::Current());
1220 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001221 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1222 Handle<mirror::Class> return_type(hs.NewHandle(
1223 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001224 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1225 return nullptr;
1226 }
1227 return annotation_value.value_.GetL();
1228}
1229
1230mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1231 Handle<mirror::Class> annotation_class) const {
1232 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1233 if (annotation_set == nullptr) {
1234 return nullptr;
1235 }
1236 StackHandleScope<1> hs(Thread::Current());
1237 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1238 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1239 kDexVisibilityRuntime, annotation_class);
1240}
1241
1242mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1243 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1244 StackHandleScope<1> hs(Thread::Current());
1245 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1246 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1247}
1248
Jeff Hao2a5892f2015-08-31 15:00:40 -07001249mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001250 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1251 if (annotation_set == nullptr) {
1252 return nullptr;
1253 }
1254 StackHandleScope<1> hs(Thread::Current());
1255 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1256 return GetThrowsValue(method_class, annotation_set);
1257}
1258
1259mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1260 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1261 if (parameter_annotations == nullptr) {
1262 return nullptr;
1263 }
1264 const AnnotationSetRefList* set_ref_list =
1265 GetParameterAnnotationSetRefList(parameter_annotations);
1266 if (set_ref_list == nullptr) {
1267 return nullptr;
1268 }
1269 uint32_t size = set_ref_list->size_;
1270 StackHandleScope<1> hs(Thread::Current());
1271 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1272 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1273}
1274
1275bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1276 const {
1277 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1278 if (annotation_set == nullptr) {
1279 return false;
1280 }
1281 StackHandleScope<1> hs(Thread::Current());
1282 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1283 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1284 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001285 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001286}
1287
1288const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1289 const {
1290 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1291 if (annotations_dir == nullptr) {
1292 return nullptr;
1293 }
1294 return GetClassAnnotationSet(annotations_dir);
1295}
1296
1297mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1298 Handle<mirror::Class> annotation_class) const {
1299 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1300 if (annotation_set == nullptr) {
1301 return nullptr;
1302 }
1303 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1304 annotation_class);
1305}
1306
1307mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1308 const {
1309 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1310 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1311}
1312
Jeff Hao2a5892f2015-08-31 15:00:40 -07001313mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1314 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1315 if (annotation_set == nullptr) {
1316 return nullptr;
1317 }
1318 const AnnotationItem* annotation_item = SearchAnnotationSet(
1319 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1320 if (annotation_item == nullptr) {
1321 return nullptr;
1322 }
1323 StackHandleScope<1> hs(Thread::Current());
1324 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1325 Handle<mirror::Class> class_array_class(hs.NewHandle(
1326 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1327 if (class_array_class.Get() == nullptr) {
1328 return nullptr;
1329 }
1330 mirror::Object* obj = GetAnnotationValue(
1331 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1332 if (obj == nullptr) {
1333 return nullptr;
1334 }
1335 return obj->AsObjectArray<mirror::Class>();
1336}
1337
1338mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1339 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1340 if (annotation_set == nullptr) {
1341 return nullptr;
1342 }
1343 const AnnotationItem* annotation_item = SearchAnnotationSet(
1344 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1345 if (annotation_item == nullptr) {
1346 return nullptr;
1347 }
1348 mirror::Object* obj = GetAnnotationValue(
1349 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1350 if (obj == nullptr) {
1351 return nullptr;
1352 }
1353 return obj->AsClass();
1354}
1355
1356mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1357 mirror::Class* declaring_class = GetDeclaringClass(klass);
1358 if (declaring_class != nullptr) {
1359 return declaring_class;
1360 }
1361 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1362 if (annotation_set == nullptr) {
1363 return nullptr;
1364 }
1365 const AnnotationItem* annotation_item = SearchAnnotationSet(
1366 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1367 if (annotation_item == nullptr) {
1368 return nullptr;
1369 }
1370 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1371 if (annotation == nullptr) {
1372 return nullptr;
1373 }
1374 AnnotationValue annotation_value;
1375 if (!ProcessAnnotationValue(
1376 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1377 return nullptr;
1378 }
1379 if (annotation_value.type_ != kDexAnnotationMethod) {
1380 return nullptr;
1381 }
1382 StackHandleScope<2> hs(Thread::Current());
1383 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1384 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1385 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1386 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1387 if (method == nullptr) {
1388 return nullptr;
1389 }
1390 return method->GetDeclaringClass();
1391}
1392
1393mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1394 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1395 if (annotation_set == nullptr) {
1396 return nullptr;
1397 }
1398 const AnnotationItem* annotation_item = SearchAnnotationSet(
1399 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1400 if (annotation_item == nullptr) {
1401 return nullptr;
1402 }
1403 return GetAnnotationValue(
1404 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1405}
1406
1407bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1408 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1409 if (annotation_set == nullptr) {
1410 return false;
1411 }
1412 const AnnotationItem* annotation_item = SearchAnnotationSet(
1413 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1414 if (annotation_item == nullptr) {
1415 return false;
1416 }
1417 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1418 if (annotation == nullptr) {
1419 return false;
1420 }
1421 AnnotationValue annotation_value;
1422 if (!ProcessAnnotationValue(
1423 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1424 return false;
1425 }
1426 if (annotation_value.type_ != kDexAnnotationNull &&
1427 annotation_value.type_ != kDexAnnotationString) {
1428 return false;
1429 }
1430 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1431 return true;
1432}
1433
1434bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1435 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1436 if (annotation_set == nullptr) {
1437 return false;
1438 }
1439 const AnnotationItem* annotation_item = SearchAnnotationSet(
1440 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1441 if (annotation_item == nullptr) {
1442 return false;
1443 }
1444 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1445 if (annotation == nullptr) {
1446 return false;
1447 }
1448 AnnotationValue annotation_value;
1449 if (!ProcessAnnotationValue(
1450 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1451 return false;
1452 }
1453 if (annotation_value.type_ != kDexAnnotationInt) {
1454 return false;
1455 }
1456 *flags = annotation_value.value_.GetI();
1457 return true;
1458}
1459
Jeff Hao13e748b2015-08-25 20:44:19 +00001460bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1461 Handle<mirror::Class> annotation_class) const {
1462 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1463 if (annotation_set == nullptr) {
1464 return false;
1465 }
1466 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1467 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001468 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001469}
1470
1471mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1472 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1473 Thread* self = Thread::Current();
1474 ScopedObjectAccessUnchecked soa(self);
1475 StackHandleScope<5> hs(self);
1476 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1477 const char* name = StringDataByIdx(element_name_index);
1478 Handle<mirror::String> string_name(
1479 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1480
1481 ArtMethod* annotation_method =
1482 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1483 if (annotation_method == nullptr) {
1484 return nullptr;
1485 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001486 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1487 Handle<mirror::Class> method_return(hs.NewHandle(
1488 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001489
1490 AnnotationValue annotation_value;
1491 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1492 return nullptr;
1493 }
1494 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1495
1496 mirror::Class* annotation_member_class =
1497 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1498 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1499 Handle<mirror::Method> method_object(
1500 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1501
1502 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1503 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1504 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1505 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1506 return nullptr;
1507 }
1508
1509 JValue result;
1510 ArtMethod* annotation_member_init =
1511 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1512 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1513 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1514 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1515 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1516 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1517 };
1518 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1519 if (self->IsExceptionPending()) {
1520 LOG(INFO) << "Exception in AnnotationMember.<init>";
1521 return nullptr;
1522 }
1523
1524 return new_member.Get();
1525}
1526
1527const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1528 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1529 Handle<mirror::Class> annotation_class) const {
1530 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1531 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1532 if (annotation_item->visibility_ != visibility) {
1533 continue;
1534 }
1535 const uint8_t* annotation = annotation_item->annotation_;
1536 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1537 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1538 klass->GetDexFile(), type_index, klass.Get());
1539 if (resolved_class == nullptr) {
1540 std::string temp;
1541 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1542 klass->GetDescriptor(&temp), type_index);
1543 CHECK(Thread::Current()->IsExceptionPending());
1544 Thread::Current()->ClearException();
1545 continue;
1546 }
1547 if (resolved_class == annotation_class.Get()) {
1548 return annotation_item;
1549 }
1550 }
1551
1552 return nullptr;
1553}
1554
1555mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1556 const AnnotationSetItem* annotation_set, uint32_t visibility,
1557 Handle<mirror::Class> annotation_class) const {
1558 const AnnotationItem* annotation_item =
1559 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1560 if (annotation_item == nullptr) {
1561 return nullptr;
1562 }
1563 const uint8_t* annotation = annotation_item->annotation_;
1564 return ProcessEncodedAnnotation(klass, &annotation);
1565}
1566
1567mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1568 const AnnotationItem* annotation_item, const char* annotation_name,
1569 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1570 const uint8_t* annotation =
1571 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1572 if (annotation == nullptr) {
1573 return nullptr;
1574 }
1575 AnnotationValue annotation_value;
1576 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1577 return nullptr;
1578 }
1579 if (annotation_value.type_ != expected_type) {
1580 return nullptr;
1581 }
1582 return annotation_value.value_.GetL();
1583}
1584
Jeff Hao2a5892f2015-08-31 15:00:40 -07001585mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001586 const AnnotationSetItem* annotation_set) const {
1587 StackHandleScope<1> hs(Thread::Current());
1588 const AnnotationItem* annotation_item =
1589 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1590 if (annotation_item == nullptr) {
1591 return nullptr;
1592 }
1593 mirror::Class* string_class = mirror::String::GetJavaLangString();
1594 Handle<mirror::Class> string_array_class(hs.NewHandle(
1595 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001596 if (string_array_class.Get() == nullptr) {
1597 return nullptr;
1598 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001599 mirror::Object* obj =
1600 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1601 if (obj == nullptr) {
1602 return nullptr;
1603 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001604 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001605}
1606
Jeff Hao2a5892f2015-08-31 15:00:40 -07001607mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001608 const AnnotationSetItem* annotation_set) const {
1609 StackHandleScope<1> hs(Thread::Current());
1610 const AnnotationItem* annotation_item =
1611 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1612 if (annotation_item == nullptr) {
1613 return nullptr;
1614 }
1615 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1616 Handle<mirror::Class> class_array_class(hs.NewHandle(
1617 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001618 if (class_array_class.Get() == nullptr) {
1619 return nullptr;
1620 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001621 mirror::Object* obj =
1622 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1623 if (obj == nullptr) {
1624 return nullptr;
1625 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001626 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001627}
1628
1629mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1630 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1631 Thread* self = Thread::Current();
1632 ScopedObjectAccessUnchecked soa(self);
1633 StackHandleScope<2> hs(self);
1634 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1635 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1636 if (annotation_set == nullptr) {
1637 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1638 }
1639
1640 uint32_t size = annotation_set->size_;
1641 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1642 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1643 if (result.Get() == nullptr) {
1644 return nullptr;
1645 }
1646
1647 uint32_t dest_index = 0;
1648 for (uint32_t i = 0; i < size; ++i) {
1649 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1650 if (annotation_item->visibility_ != visibility) {
1651 continue;
1652 }
1653 const uint8_t* annotation = annotation_item->annotation_;
1654 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1655 if (annotation_obj != nullptr) {
1656 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1657 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001658 } else if (self->IsExceptionPending()) {
1659 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001660 }
1661 }
1662
1663 if (dest_index == size) {
1664 return result.Get();
1665 }
1666
1667 mirror::ObjectArray<mirror::Object>* trimmed_result =
1668 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001669 if (trimmed_result == nullptr) {
1670 return nullptr;
1671 }
1672
Jeff Hao13e748b2015-08-25 20:44:19 +00001673 for (uint32_t i = 0; i < dest_index; ++i) {
1674 mirror::Object* obj = result->GetWithoutChecks(i);
1675 trimmed_result->SetWithoutChecks<false>(i, obj);
1676 }
1677
1678 return trimmed_result;
1679}
1680
1681mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1682 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1683 Thread* self = Thread::Current();
1684 ScopedObjectAccessUnchecked soa(self);
1685 StackHandleScope<1> hs(self);
1686 mirror::Class* annotation_array_class =
1687 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1688 mirror::Class* annotation_array_array_class =
1689 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001690 if (annotation_array_array_class == nullptr) {
1691 return nullptr;
1692 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001693 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1694 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1695 if (annotation_array_array.Get() == nullptr) {
1696 LOG(ERROR) << "Annotation set ref array allocation failed";
1697 return nullptr;
1698 }
1699 for (uint32_t index = 0; index < size; ++index) {
1700 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1701 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1702 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1703 if (annotation_set == nullptr) {
1704 return nullptr;
1705 }
1706 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1707 }
1708 return annotation_array_array.Get();
1709}
1710
1711bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1712 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1713 DexFile::AnnotationResultStyle result_style) const {
1714 Thread* self = Thread::Current();
1715 mirror::Object* element_object = nullptr;
1716 bool set_object = false;
1717 Primitive::Type primitive_type = Primitive::kPrimVoid;
1718 const uint8_t* annotation = *annotation_ptr;
1719 uint8_t header_byte = *(annotation++);
1720 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1721 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1722 int32_t width = value_arg + 1;
1723 annotation_value->type_ = value_type;
1724
1725 switch (value_type) {
1726 case kDexAnnotationByte:
1727 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1728 primitive_type = Primitive::kPrimByte;
1729 break;
1730 case kDexAnnotationShort:
1731 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1732 primitive_type = Primitive::kPrimShort;
1733 break;
1734 case kDexAnnotationChar:
1735 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1736 false)));
1737 primitive_type = Primitive::kPrimChar;
1738 break;
1739 case kDexAnnotationInt:
1740 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1741 primitive_type = Primitive::kPrimInt;
1742 break;
1743 case kDexAnnotationLong:
1744 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1745 primitive_type = Primitive::kPrimLong;
1746 break;
1747 case kDexAnnotationFloat:
1748 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1749 primitive_type = Primitive::kPrimFloat;
1750 break;
1751 case kDexAnnotationDouble:
1752 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1753 primitive_type = Primitive::kPrimDouble;
1754 break;
1755 case kDexAnnotationBoolean:
1756 annotation_value->value_.SetZ(value_arg != 0);
1757 primitive_type = Primitive::kPrimBoolean;
1758 width = 0;
1759 break;
1760 case kDexAnnotationString: {
1761 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1762 if (result_style == kAllRaw) {
1763 annotation_value->value_.SetI(index);
1764 } else {
1765 StackHandleScope<1> hs(self);
1766 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1767 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1768 klass->GetDexFile(), index, dex_cache);
1769 set_object = true;
1770 if (element_object == nullptr) {
1771 return false;
1772 }
1773 }
1774 break;
1775 }
1776 case kDexAnnotationType: {
1777 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1778 if (result_style == kAllRaw) {
1779 annotation_value->value_.SetI(index);
1780 } else {
1781 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1782 klass->GetDexFile(), index, klass.Get());
1783 set_object = true;
1784 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001785 CHECK(self->IsExceptionPending());
1786 if (result_style == kAllObjects) {
1787 const char* msg = StringByTypeIdx(index);
1788 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1789 element_object = self->GetException();
1790 self->ClearException();
1791 } else {
1792 return false;
1793 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001794 }
1795 }
1796 break;
1797 }
1798 case kDexAnnotationMethod: {
1799 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1800 if (result_style == kAllRaw) {
1801 annotation_value->value_.SetI(index);
1802 } else {
1803 StackHandleScope<2> hs(self);
1804 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1805 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1806 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1807 klass->GetDexFile(), index, dex_cache, class_loader);
1808 if (method == nullptr) {
1809 return false;
1810 }
1811 set_object = true;
1812 if (method->IsConstructor()) {
1813 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1814 } else {
1815 element_object = mirror::Method::CreateFromArtMethod(self, method);
1816 }
1817 if (element_object == nullptr) {
1818 return false;
1819 }
1820 }
1821 break;
1822 }
1823 case kDexAnnotationField: {
1824 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1825 if (result_style == kAllRaw) {
1826 annotation_value->value_.SetI(index);
1827 } else {
1828 StackHandleScope<2> hs(self);
1829 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1830 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1831 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1832 klass->GetDexFile(), index, dex_cache, class_loader);
1833 if (field == nullptr) {
1834 return false;
1835 }
1836 set_object = true;
1837 element_object = mirror::Field::CreateFromArtField(self, field, true);
1838 if (element_object == nullptr) {
1839 return false;
1840 }
1841 }
1842 break;
1843 }
1844 case kDexAnnotationEnum: {
1845 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1846 if (result_style == kAllRaw) {
1847 annotation_value->value_.SetI(index);
1848 } else {
1849 StackHandleScope<3> hs(self);
1850 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1851 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1852 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1853 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001854 if (enum_field == nullptr) {
1855 return false;
1856 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001857 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001858 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1859 element_object = enum_field->GetObject(field_class.Get());
1860 set_object = true;
1861 }
1862 }
1863 break;
1864 }
1865 case kDexAnnotationArray:
1866 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1867 return false;
1868 } else {
1869 ScopedObjectAccessUnchecked soa(self);
1870 StackHandleScope<2> hs(self);
1871 uint32_t size = DecodeUnsignedLeb128(&annotation);
1872 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1873 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1874 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1875 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1876 if (new_array.Get() == nullptr) {
1877 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1878 return false;
1879 }
1880 AnnotationValue new_annotation_value;
1881 for (uint32_t i = 0; i < size; ++i) {
1882 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1883 kPrimitivesOrObjects)) {
1884 return false;
1885 }
1886 if (!component_type->IsPrimitive()) {
1887 mirror::Object* obj = new_annotation_value.value_.GetL();
1888 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1889 } else {
1890 switch (new_annotation_value.type_) {
1891 case kDexAnnotationByte:
1892 new_array->AsByteArray()->SetWithoutChecks<false>(
1893 i, new_annotation_value.value_.GetB());
1894 break;
1895 case kDexAnnotationShort:
1896 new_array->AsShortArray()->SetWithoutChecks<false>(
1897 i, new_annotation_value.value_.GetS());
1898 break;
1899 case kDexAnnotationChar:
1900 new_array->AsCharArray()->SetWithoutChecks<false>(
1901 i, new_annotation_value.value_.GetC());
1902 break;
1903 case kDexAnnotationInt:
1904 new_array->AsIntArray()->SetWithoutChecks<false>(
1905 i, new_annotation_value.value_.GetI());
1906 break;
1907 case kDexAnnotationLong:
1908 new_array->AsLongArray()->SetWithoutChecks<false>(
1909 i, new_annotation_value.value_.GetJ());
1910 break;
1911 case kDexAnnotationFloat:
1912 new_array->AsFloatArray()->SetWithoutChecks<false>(
1913 i, new_annotation_value.value_.GetF());
1914 break;
1915 case kDexAnnotationDouble:
1916 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1917 i, new_annotation_value.value_.GetD());
1918 break;
1919 case kDexAnnotationBoolean:
1920 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1921 i, new_annotation_value.value_.GetZ());
1922 break;
1923 default:
1924 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1925 return false;
1926 }
1927 }
1928 }
1929 element_object = new_array.Get();
1930 set_object = true;
1931 width = 0;
1932 }
1933 break;
1934 case kDexAnnotationAnnotation:
1935 if (result_style == kAllRaw) {
1936 return false;
1937 }
1938 element_object = ProcessEncodedAnnotation(klass, &annotation);
1939 if (element_object == nullptr) {
1940 return false;
1941 }
1942 set_object = true;
1943 width = 0;
1944 break;
1945 case kDexAnnotationNull:
1946 if (result_style == kAllRaw) {
1947 annotation_value->value_.SetI(0);
1948 } else {
1949 CHECK(element_object == nullptr);
1950 set_object = true;
1951 }
1952 width = 0;
1953 break;
1954 default:
1955 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1956 return false;
1957 }
1958
1959 annotation += width;
1960 *annotation_ptr = annotation;
1961
1962 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1963 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1964 set_object = true;
1965 }
1966
1967 if (set_object) {
1968 annotation_value->value_.SetL(element_object);
1969 }
1970
1971 return true;
1972}
1973
1974mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1975 const uint8_t** annotation) const {
1976 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1977 uint32_t size = DecodeUnsignedLeb128(annotation);
1978
1979 Thread* self = Thread::Current();
1980 ScopedObjectAccessUnchecked soa(self);
1981 StackHandleScope<2> hs(self);
1982 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1983 Handle<mirror::Class> annotation_class(hs.NewHandle(
1984 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1985 if (annotation_class.Get() == nullptr) {
1986 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1987 << type_index;
1988 DCHECK(Thread::Current()->IsExceptionPending());
1989 Thread::Current()->ClearException();
1990 return nullptr;
1991 }
1992
1993 mirror::Class* annotation_member_class =
1994 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
1995 mirror::Class* annotation_member_array_class =
1996 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001997 if (annotation_member_array_class == nullptr) {
1998 return nullptr;
1999 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002000 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002001 if (size > 0) {
2002 element_array =
2003 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2004 if (element_array == nullptr) {
2005 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2006 return nullptr;
2007 }
2008 }
2009
2010 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2011 for (uint32_t i = 0; i < size; ++i) {
2012 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2013 if (new_member == nullptr) {
2014 return nullptr;
2015 }
2016 h_element_array->SetWithoutChecks<false>(i, new_member);
2017 }
2018
2019 JValue result;
2020 ArtMethod* create_annotation_method =
2021 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2022 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2023 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2024 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2025 if (self->IsExceptionPending()) {
2026 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2027 return nullptr;
2028 }
2029
2030 return result.GetL();
2031}
2032
2033const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2034 const char* descriptor, uint32_t visibility) const {
2035 const AnnotationItem* result = nullptr;
2036 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2037 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2038 if (annotation_item->visibility_ != visibility) {
2039 continue;
2040 }
2041 const uint8_t* annotation = annotation_item->annotation_;
2042 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2043
2044 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2045 result = annotation_item;
2046 break;
2047 }
2048 }
2049 return result;
2050}
2051
2052const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2053 DecodeUnsignedLeb128(&annotation); // unused type_index
2054 uint32_t size = DecodeUnsignedLeb128(&annotation);
2055
2056 while (size != 0) {
2057 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2058 const char* element_name = GetStringData(GetStringId(element_name_index));
2059 if (strcmp(name, element_name) == 0) {
2060 return annotation;
2061 }
2062 SkipAnnotationValue(&annotation);
2063 size--;
2064 }
2065 return nullptr;
2066}
2067
2068bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2069 const uint8_t* annotation = *annotation_ptr;
2070 uint8_t header_byte = *(annotation++);
2071 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2072 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2073 int32_t width = value_arg + 1;
2074
2075 switch (value_type) {
2076 case kDexAnnotationByte:
2077 case kDexAnnotationShort:
2078 case kDexAnnotationChar:
2079 case kDexAnnotationInt:
2080 case kDexAnnotationLong:
2081 case kDexAnnotationFloat:
2082 case kDexAnnotationDouble:
2083 case kDexAnnotationString:
2084 case kDexAnnotationType:
2085 case kDexAnnotationMethod:
2086 case kDexAnnotationField:
2087 case kDexAnnotationEnum:
2088 break;
2089 case kDexAnnotationArray:
2090 {
2091 uint32_t size = DecodeUnsignedLeb128(&annotation);
2092 while (size--) {
2093 if (!SkipAnnotationValue(&annotation)) {
2094 return false;
2095 }
2096 }
2097 width = 0;
2098 break;
2099 }
2100 case kDexAnnotationAnnotation:
2101 {
2102 DecodeUnsignedLeb128(&annotation); // unused type_index
2103 uint32_t size = DecodeUnsignedLeb128(&annotation);
2104 while (size--) {
2105 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2106 if (!SkipAnnotationValue(&annotation)) {
2107 return false;
2108 }
2109 }
2110 width = 0;
2111 break;
2112 }
2113 case kDexAnnotationBoolean:
2114 case kDexAnnotationNull:
2115 width = 0;
2116 break;
2117 default:
2118 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2119 return false;
2120 }
2121
2122 annotation += width;
2123 *annotation_ptr = annotation;
2124 return true;
2125}
2126
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002127std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2128 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2129 dex_file.GetLocation().c_str(),
2130 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2131 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2132 return os;
2133}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002134
Ian Rogersd91d6d62013-09-25 20:26:14 -07002135std::string Signature::ToString() const {
2136 if (dex_file_ == nullptr) {
2137 CHECK(proto_id_ == nullptr);
2138 return "<no signature>";
2139 }
2140 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2141 std::string result;
2142 if (params == nullptr) {
2143 result += "()";
2144 } else {
2145 result += "(";
2146 for (uint32_t i = 0; i < params->Size(); ++i) {
2147 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2148 }
2149 result += ")";
2150 }
2151 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2152 return result;
2153}
2154
Vladimir Markod9cffea2013-11-25 15:08:02 +00002155bool Signature::operator==(const StringPiece& rhs) const {
2156 if (dex_file_ == nullptr) {
2157 return false;
2158 }
2159 StringPiece tail(rhs);
2160 if (!tail.starts_with("(")) {
2161 return false; // Invalid signature
2162 }
2163 tail.remove_prefix(1); // "(";
2164 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2165 if (params != nullptr) {
2166 for (uint32_t i = 0; i < params->Size(); ++i) {
2167 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2168 if (!tail.starts_with(param)) {
2169 return false;
2170 }
2171 tail.remove_prefix(param.length());
2172 }
2173 }
2174 if (!tail.starts_with(")")) {
2175 return false;
2176 }
2177 tail.remove_prefix(1); // ")";
2178 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2179}
2180
Ian Rogersd91d6d62013-09-25 20:26:14 -07002181std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2182 return os << sig.ToString();
2183}
2184
Ian Rogers0571d352011-11-03 19:51:38 -07002185// Decodes the header section from the class data bytes.
2186void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002187 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002188 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2189 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2190 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2191 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2192}
2193
2194void ClassDataItemIterator::ReadClassDataField() {
2195 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2196 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002197 // The user of the iterator is responsible for checking if there
2198 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002199}
2200
2201void ClassDataItemIterator::ReadClassDataMethod() {
2202 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2203 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2204 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002205 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002206 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002207 }
Ian Rogers0571d352011-11-03 19:51:38 -07002208}
2209
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002210EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2211 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2212 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2213 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002214 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2215 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 DCHECK(dex_cache != nullptr);
2217 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002218 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002219 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002220 array_size_ = 0;
2221 } else {
2222 array_size_ = DecodeUnsignedLeb128(&ptr_);
2223 }
2224 if (array_size_ > 0) {
2225 Next();
2226 }
2227}
2228
2229void EncodedStaticFieldValueIterator::Next() {
2230 pos_++;
2231 if (pos_ >= array_size_) {
2232 return;
2233 }
Ian Rogers13735952014-10-08 12:43:28 -07002234 uint8_t value_type = *ptr_++;
2235 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002236 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002237 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002238 switch (type_) {
2239 case kBoolean:
2240 jval_.i = (value_arg != 0) ? 1 : 0;
2241 width = 0;
2242 break;
2243 case kByte:
2244 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002245 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002246 break;
2247 case kShort:
2248 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002249 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002250 break;
2251 case kChar:
2252 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002253 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002254 break;
2255 case kInt:
2256 jval_.i = ReadSignedInt(ptr_, value_arg);
2257 break;
2258 case kLong:
2259 jval_.j = ReadSignedLong(ptr_, value_arg);
2260 break;
2261 case kFloat:
2262 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2263 break;
2264 case kDouble:
2265 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2266 break;
2267 case kString:
2268 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002269 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2270 break;
2271 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002272 case kMethod:
2273 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002274 case kArray:
2275 case kAnnotation:
2276 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002277 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002278 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002279 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002280 width = 0;
2281 break;
2282 default:
2283 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002284 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002285 }
2286 ptr_ += width;
2287}
2288
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002289template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002290void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002291 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002292 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2293 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002294 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2295 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2296 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2297 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2298 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2299 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2300 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002301 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002302 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002303 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002304 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002305 break;
2306 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002307 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2309 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002310 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002311 break;
2312 }
Ian Rogers0571d352011-11-03 19:51:38 -07002313 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2314 }
2315}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002316template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2317template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002318
2319CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2320 handler_.address_ = -1;
2321 int32_t offset = -1;
2322
2323 // Short-circuit the overwhelmingly common cases.
2324 switch (code_item.tries_size_) {
2325 case 0:
2326 break;
2327 case 1: {
2328 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2329 uint32_t start = tries->start_addr_;
2330 if (address >= start) {
2331 uint32_t end = start + tries->insn_count_;
2332 if (address < end) {
2333 offset = tries->handler_off_;
2334 }
2335 }
2336 break;
2337 }
2338 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002339 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002340 }
Logan Chien736df022012-04-27 16:25:57 +08002341 Init(code_item, offset);
2342}
2343
2344CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2345 const DexFile::TryItem& try_item) {
2346 handler_.address_ = -1;
2347 Init(code_item, try_item.handler_off_);
2348}
2349
2350void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2351 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002352 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002353 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002354 } else {
2355 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002356 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002357 remaining_count_ = -1;
2358 catch_all_ = false;
2359 DCHECK(!HasNext());
2360 }
2361}
2362
Ian Rogers13735952014-10-08 12:43:28 -07002363void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002364 current_data_ = handler_data;
2365 remaining_count_ = DecodeSignedLeb128(&current_data_);
2366
2367 // If remaining_count_ is non-positive, then it is the negative of
2368 // the number of catch types, and the catches are followed by a
2369 // catch-all handler.
2370 if (remaining_count_ <= 0) {
2371 catch_all_ = true;
2372 remaining_count_ = -remaining_count_;
2373 } else {
2374 catch_all_ = false;
2375 }
2376 Next();
2377}
2378
2379void CatchHandlerIterator::Next() {
2380 if (remaining_count_ > 0) {
2381 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2382 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2383 remaining_count_--;
2384 return;
2385 }
2386
2387 if (catch_all_) {
2388 handler_.type_idx_ = DexFile::kDexNoIndex16;
2389 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2390 catch_all_ = false;
2391 return;
2392 }
2393
2394 // no more handler
2395 remaining_count_ = -1;
2396}
2397
Carl Shapiro1fb86202011-06-27 17:43:13 -07002398} // namespace art