blob: 2a2d2c09bc8c12d2f304cbb96f02f3e348818e9f [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"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070038#include "base/unix_file/fd_file.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000039#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070040#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080041#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070042#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030043#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070044#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000045#include "mirror/field.h"
46#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070048#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000049#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070050#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070051#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030052#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070053#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070054#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070056#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070057
58namespace art {
59
Ian Rogers13735952014-10-08 12:43:28 -070060const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070061const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
62 {'0', '3', '5', '\0'},
63 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
64 // files with that version number would erroneously be accepted and run.
65 {'0', '3', '7', '\0'}
66};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070067
Ian Rogers8d31bbd2013-10-13 10:44:14 -070068bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070069 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070070 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070071
72 // Strip ":...", which is the location
73 const char* zip_entry_name = kClassesDex;
74 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010075 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070076
Vladimir Markoaa4497d2014-09-05 14:01:17 +010077 if (DexFile::IsMultiDexLocation(filename)) {
78 file_part_storage = GetBaseLocation(filename);
79 file_part = file_part_storage.c_str();
80 zip_entry_name = filename + file_part_storage.size() + 1;
81 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070082 }
83
Andreas Gampe43e10b02016-07-15 17:17:34 -070084 File fd = OpenAndReadMagic(file_part, &magic, error_msg);
85 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070086 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070087 return false;
88 }
89 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070090 std::unique_ptr<ZipArchive> zip_archive(
Andreas Gampe43e10b02016-07-15 17:17:34 -070091 ZipArchive::OpenFromFd(fd.Release(), filename, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070092 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080093 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
94 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080095 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -070096 }
Andreas Gampe833a4852014-05-21 18:46:59 -070097 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -070098 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -070099 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
100 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800101 return false;
102 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700103 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800104 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700105 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700106 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700107 std::unique_ptr<const DexFile> dex_file(
Andreas Gampe43e10b02016-07-15 17:17:34 -0700108 DexFile::OpenFile(fd.Release(), filename, false, false, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800110 return false;
111 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700112 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800113 return true;
114 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700115 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800116 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700117}
118
Aart Bik37d6a3b2016-06-21 18:30:10 -0700119bool DexFile::Open(const char* filename,
120 const char* location,
121 bool verify_checksum,
122 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800123 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800124 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700125 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700126 uint32_t magic;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700127 File fd = OpenAndReadMagic(filename, &magic, error_msg);
128 if (fd.Fd() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700129 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700130 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700131 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700132 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700133 return DexFile::OpenZip(fd.Release(), location, verify_checksum, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700134 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700135 if (IsDexMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700136 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.Release(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700137 location,
138 /* verify */ true,
139 verify_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700140 error_msg));
141 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800142 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 return true;
144 } else {
145 return false;
146 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700147 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700148 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400149 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700150}
151
Andreas Gampe0cba0042015-04-29 20:47:16 -0700152static bool ContainsClassesDex(int fd, const char* filename) {
153 std::string error_msg;
154 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
155 if (zip_archive.get() == nullptr) {
156 return false;
157 }
158 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
159 return (zip_entry.get() != nullptr);
160}
161
162bool DexFile::MaybeDex(const char* filename) {
163 uint32_t magic;
164 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700165 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
166 if (fd.Fd() == -1) {
Andreas Gampe0cba0042015-04-29 20:47:16 -0700167 return false;
168 }
169 if (IsZipMagic(magic)) {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700170 return ContainsClassesDex(fd.Release(), filename);
Andreas Gampe0cba0042015-04-29 20:47:16 -0700171 } else if (IsDexMagic(magic)) {
172 return true;
173 }
174 return false;
175}
176
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800177int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700178 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800179 return 0;
180 } else {
181 return mem_map_->GetProtect();
182 }
183}
184
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200185bool DexFile::IsReadOnly() const {
186 return GetPermissions() == PROT_READ;
187}
188
Brian Carlstrome0948e12013-08-29 09:36:15 -0700189bool DexFile::EnableWrite() 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 | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195 }
196}
197
Brian Carlstrome0948e12013-08-29 09:36:15 -0700198bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700200 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200201 return false;
202 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700203 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200204 }
205}
206
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800207std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
208 const std::string& location,
209 uint32_t location_checksum,
210 const OatDexFile* oat_dex_file,
211 bool verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -0700212 bool verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800213 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800214 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800215 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
216 size,
217 location,
218 location_checksum,
219 nullptr,
220 oat_dex_file,
221 error_msg);
222 if (verify && !DexFileVerifier::Verify(dex_file.get(),
223 dex_file->Begin(),
224 dex_file->Size(),
225 location.c_str(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700226 verify_checksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800227 error_msg)) {
228 return nullptr;
229 }
230
231 return dex_file;
232}
233
Aart Bik37d6a3b2016-06-21 18:30:10 -0700234std::unique_ptr<const DexFile> DexFile::OpenFile(int fd,
235 const char* location,
236 bool verify,
237 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800238 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800239 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700241 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000242 {
Andreas Gampe43e10b02016-07-15 17:17:34 -0700243 File delayed_close(fd, /* check_usage */ false);
Vladimir Markofd995762013-11-06 16:36:36 +0000244 struct stat sbuf;
245 memset(&sbuf, 0, sizeof(sbuf));
246 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800247 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000248 return nullptr;
249 }
250 if (S_ISDIR(sbuf.st_mode)) {
251 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
252 return nullptr;
253 }
254 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800255 map.reset(MemMap::MapFile(length,
256 PROT_READ,
257 MAP_PRIVATE,
258 fd,
259 0,
260 /*low_4gb*/false,
261 location,
262 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000263 if (map.get() == nullptr) {
264 DCHECK(!error_msg->empty());
265 return nullptr;
266 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700267 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800268
269 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800271 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800273 }
274
275 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
276
Andreas Gampe928f72b2014-09-09 19:53:48 -0700277 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
278 error_msg));
279 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
281 error_msg->c_str());
282 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800283 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800284
Andreas Gampe928f72b2014-09-09 19:53:48 -0700285 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700286 location,
287 verify_checksum,
288 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700289 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800290 }
291
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800292 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700293}
294
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700295const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700296
Aart Bik37d6a3b2016-06-21 18:30:10 -0700297bool DexFile::OpenZip(int fd,
298 const std::string& location,
299 bool verify_checksum,
300 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800301 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800302 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700304 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 if (zip_archive.get() == nullptr) {
306 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700307 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700308 }
Aart Bik37d6a3b2016-06-21 18:30:10 -0700309 return DexFile::OpenFromZip(*zip_archive, location, verify_checksum, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800310}
311
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800312std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
313 uint32_t location_checksum,
314 MemMap* mem_map,
315 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800316 return OpenMemory(mem_map->Begin(),
317 mem_map->Size(),
318 location,
319 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700320 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800321 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700322 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800323}
324
Aart Bik37d6a3b2016-06-21 18:30:10 -0700325std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive,
326 const char* entry_name,
327 const std::string& location,
328 bool verify_checksum,
329 std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800330 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800331 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800332 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700333 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700334 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700337 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700338 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700339 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700341 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700342 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700343 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700344 }
Ian Rogers700a4022014-05-19 16:49:03 -0700345 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700346 error_msg));
347 if (dex_file.get() == nullptr) {
348 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
349 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700350 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700351 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800352 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700353 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700355 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700356 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700357 }
358 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700359 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
Aart Bik37d6a3b2016-06-21 18:30:10 -0700360 location.c_str(),
361 verify_checksum,
362 error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700363 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700364 return nullptr;
365 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800367 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700368}
369
Andreas Gampe90e34042015-04-27 20:01:52 -0700370// Technically we do not have a limitation with respect to the number of dex files that can be in a
371// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
372// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
373// seems an excessive number.
374static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
375
Aart Bik37d6a3b2016-06-21 18:30:10 -0700376bool DexFile::OpenFromZip(const ZipArchive& zip_archive,
377 const std::string& location,
378 bool verify_checksum,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800379 std::string* error_msg,
380 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800381 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700382 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700383 ZipOpenErrorCode error_code;
Aart Bik37d6a3b2016-06-21 18:30:10 -0700384 std::unique_ptr<const DexFile> dex_file(
385 Open(zip_archive, kClassesDex, location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700386 if (dex_file.get() == nullptr) {
387 return false;
388 } else {
389 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800390 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700391
392 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700393
394 // We could try to avoid std::string allocations by working on a char array directly. As we
395 // do not expect a lot of iterations, this seems too involved and brittle.
396
Andreas Gampe90e34042015-04-27 20:01:52 -0700397 for (size_t i = 1; ; ++i) {
398 std::string name = GetMultiDexClassesDexName(i);
399 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Aart Bik37d6a3b2016-06-21 18:30:10 -0700400 std::unique_ptr<const DexFile> next_dex_file(
401 Open(zip_archive, name.c_str(), fake_location, verify_checksum, error_msg, &error_code));
Andreas Gampe833a4852014-05-21 18:46:59 -0700402 if (next_dex_file.get() == nullptr) {
403 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
404 LOG(WARNING) << error_msg;
405 }
406 break;
407 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700409 }
410
Andreas Gampe90e34042015-04-27 20:01:52 -0700411 if (i == kWarnOnManyDexFilesThreshold) {
412 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
413 << " dex files. Please consider coalescing and shrinking the number to "
414 " avoid runtime overhead.";
415 }
416
417 if (i == std::numeric_limits<size_t>::max()) {
418 LOG(ERROR) << "Overflow in number of dex files!";
419 break;
420 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700421 }
422
423 return true;
424 }
425}
426
427
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800428std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
429 size_t size,
430 const std::string& location,
431 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800432 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700433 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800434 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700435 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800436 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700437 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700438 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800439 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700440 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800441 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700442}
443
Ian Rogers13735952014-10-08 12:43:28 -0700444DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800445 const std::string& location,
446 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800447 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700448 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800449 : begin_(base),
450 size_(size),
451 location_(location),
452 location_checksum_(location_checksum),
453 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800454 header_(reinterpret_cast<const Header*>(base)),
455 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
456 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
457 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
458 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
459 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700460 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700461 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700462 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800463 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300464 const uint8_t* lookup_data = (oat_dex_file != nullptr)
465 ? oat_dex_file->GetLookupTableData()
466 : nullptr;
467 if (lookup_data != nullptr) {
468 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
469 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
470 } else {
471 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
472 }
473 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800474}
475
Jesse Wilson6bf19152011-09-29 13:12:33 -0400476DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700477 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
478 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
479 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
480 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400481}
482
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700483bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700484 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700485 return false;
486 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700487 return true;
488}
489
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700490bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800491 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700492 std::ostringstream oss;
493 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800494 << " " << header_->magic_[0]
495 << " " << header_->magic_[1]
496 << " " << header_->magic_[2]
497 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700498 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700499 return false;
500 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800501 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502 std::ostringstream oss;
503 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800504 << " " << header_->magic_[4]
505 << " " << header_->magic_[5]
506 << " " << header_->magic_[6]
507 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700509 return false;
510 }
511 return true;
512}
513
Ian Rogers13735952014-10-08 12:43:28 -0700514bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800515 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
516}
517
Ian Rogers13735952014-10-08 12:43:28 -0700518bool DexFile::IsVersionValid(const uint8_t* magic) {
519 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700520 for (uint32_t i = 0; i < kNumDexVersions; i++) {
521 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
522 return true;
523 }
524 }
525 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800526}
527
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700528uint32_t DexFile::Header::GetVersion() const {
529 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700530 return atoi(version);
531}
532
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800533const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
534 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300535 if (LIKELY(lookup_table_ != nullptr)) {
536 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
537 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700538 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300539
Roland Levillainab880f42016-05-12 16:24:36 +0100540 // Fast path for rare no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300541 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700542 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700543 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700544 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300545 const TypeId* type_id = FindTypeId(descriptor);
546 if (type_id != nullptr) {
547 uint16_t type_idx = GetIndexForTypeId(*type_id);
548 for (size_t i = 0; i < num_class_defs; ++i) {
549 const ClassDef& class_def = GetClassDef(i);
550 if (class_def.class_idx_ == type_idx) {
551 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700552 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700553 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700554 }
Ian Rogers68b56852014-08-29 20:19:11 -0700555 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700556}
557
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700558const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
559 size_t num_class_defs = NumClassDefs();
560 for (size_t i = 0; i < num_class_defs; ++i) {
561 const ClassDef& class_def = GetClassDef(i);
562 if (class_def.class_idx_ == type_idx) {
563 return &class_def;
564 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700565 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700566 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700567}
568
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800569const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100570 const DexFile::StringId& name,
571 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800572 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
573 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
574 const uint32_t name_idx = GetIndexForStringId(name);
575 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700576 int32_t lo = 0;
577 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800578 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700579 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800580 const DexFile::FieldId& field = GetFieldId(mid);
581 if (class_idx > field.class_idx_) {
582 lo = mid + 1;
583 } else if (class_idx < field.class_idx_) {
584 hi = mid - 1;
585 } else {
586 if (name_idx > field.name_idx_) {
587 lo = mid + 1;
588 } else if (name_idx < field.name_idx_) {
589 hi = mid - 1;
590 } else {
591 if (type_idx > field.type_idx_) {
592 lo = mid + 1;
593 } else if (type_idx < field.type_idx_) {
594 hi = mid - 1;
595 } else {
596 return &field;
597 }
598 }
599 }
600 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700601 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800602}
603
604const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700605 const DexFile::StringId& name,
606 const DexFile::ProtoId& signature) const {
607 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800608 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700609 const uint32_t name_idx = GetIndexForStringId(name);
610 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700611 int32_t lo = 0;
612 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700613 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700614 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700615 const DexFile::MethodId& method = GetMethodId(mid);
616 if (class_idx > method.class_idx_) {
617 lo = mid + 1;
618 } else if (class_idx < method.class_idx_) {
619 hi = mid - 1;
620 } else {
621 if (name_idx > method.name_idx_) {
622 lo = mid + 1;
623 } else if (name_idx < method.name_idx_) {
624 hi = mid - 1;
625 } else {
626 if (proto_idx > method.proto_idx_) {
627 lo = mid + 1;
628 } else if (proto_idx < method.proto_idx_) {
629 hi = mid - 1;
630 } else {
631 return &method;
632 }
633 }
634 }
635 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700637}
638
Ian Rogers637c65b2013-05-31 11:46:00 -0700639const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700640 int32_t lo = 0;
641 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700642 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700643 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700644 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700645 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700646 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
647 if (compare > 0) {
648 lo = mid + 1;
649 } else if (compare < 0) {
650 hi = mid - 1;
651 } else {
652 return &str_id;
653 }
654 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700655 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700656}
657
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300658const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
659 int32_t lo = 0;
660 int32_t hi = NumTypeIds() - 1;
661 while (hi >= lo) {
662 int32_t mid = (hi + lo) / 2;
663 const TypeId& type_id = GetTypeId(mid);
664 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
665 const char* str = GetStringData(str_id);
666 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
667 if (compare > 0) {
668 lo = mid + 1;
669 } else if (compare < 0) {
670 hi = mid - 1;
671 } else {
672 return &type_id;
673 }
674 }
675 return nullptr;
676}
677
Vladimir Markoa48aef42014-12-03 17:53:53 +0000678const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700679 int32_t lo = 0;
680 int32_t hi = NumStringIds() - 1;
681 while (hi >= lo) {
682 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700683 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700684 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000685 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700686 if (compare > 0) {
687 lo = mid + 1;
688 } else if (compare < 0) {
689 hi = mid - 1;
690 } else {
691 return &str_id;
692 }
693 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700694 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700695}
696
697const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700698 int32_t lo = 0;
699 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700700 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700701 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700702 const TypeId& type_id = GetTypeId(mid);
703 if (string_idx > type_id.descriptor_idx_) {
704 lo = mid + 1;
705 } else if (string_idx < type_id.descriptor_idx_) {
706 hi = mid - 1;
707 } else {
708 return &type_id;
709 }
710 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700711 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700712}
713
714const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000715 const uint16_t* signature_type_idxs,
716 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700717 int32_t lo = 0;
718 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700719 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700720 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700721 const DexFile::ProtoId& proto = GetProtoId(mid);
722 int compare = return_type_idx - proto.return_type_idx_;
723 if (compare == 0) {
724 DexFileParameterIterator it(*this, proto);
725 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000726 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800727 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700728 it.Next();
729 i++;
730 }
731 if (compare == 0) {
732 if (it.HasNext()) {
733 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000734 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700735 compare = 1;
736 }
737 }
738 }
739 if (compare > 0) {
740 lo = mid + 1;
741 } else if (compare < 0) {
742 hi = mid - 1;
743 } else {
744 return &proto;
745 }
746 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700747 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700748}
749
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000750void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
751 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300752}
753
Ian Rogers0571d352011-11-03 19:51:38 -0700754// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700755bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
756 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700757 if (signature[0] != '(') {
758 return false;
759 }
760 size_t offset = 1;
761 size_t end = signature.size();
762 bool process_return = false;
763 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000764 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700765 char c = signature[offset];
766 offset++;
767 if (c == ')') {
768 process_return = true;
769 continue;
770 }
Ian Rogers0571d352011-11-03 19:51:38 -0700771 while (c == '[') { // process array prefix
772 if (offset >= end) { // expect some descriptor following [
773 return false;
774 }
775 c = signature[offset];
776 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700777 }
778 if (c == 'L') { // process type descriptors
779 do {
780 if (offset >= end) { // unexpected early termination of descriptor
781 return false;
782 }
783 c = signature[offset];
784 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700785 } while (c != ';');
786 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000787 // TODO: avoid creating a std::string just to get a 0-terminated char array
788 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700789 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700791 return false;
792 }
793 uint16_t type_idx = GetIndexForTypeId(*type_id);
794 if (!process_return) {
795 param_type_idxs->push_back(type_idx);
796 } else {
797 *return_type_idx = type_idx;
798 return offset == end; // return true if the signature had reached a sensible end
799 }
800 }
801 return false; // failed to correctly parse return type
802}
803
Ian Rogersd91d6d62013-09-25 20:26:14 -0700804const Signature DexFile::CreateSignature(const StringPiece& signature) const {
805 uint16_t return_type_idx;
806 std::vector<uint16_t> param_type_indices;
807 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
808 if (!success) {
809 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700810 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700811 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700812 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700813 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700814 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700815 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700816}
817
Mathieu Chartiere401d142015-04-22 13:56:20 -0700818int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700819 // For native method, lineno should be -2 to indicate it is native. Note that
820 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700821 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700822 return -2;
823 }
824
TDYa127c8dc1012012-04-19 07:03:33 -0700825 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700826 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700827
828 // A method with no line number info should return -1
829 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000830 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700831 return context.line_num_;
832}
833
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700834int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700835 // Note: Signed type is important for max and min.
836 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700837 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700838
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700839 while (min <= max) {
840 int32_t mid = min + ((max - min) / 2);
841
842 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
843 uint32_t start = ti->start_addr_;
844 uint32_t end = start + ti->insn_count_;
845
Ian Rogers0571d352011-11-03 19:51:38 -0700846 if (address < start) {
847 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700848 } else if (address >= end) {
849 min = mid + 1;
850 } else { // We have a winner!
851 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700852 }
853 }
854 // No match.
855 return -1;
856}
857
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700858int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
859 int32_t try_item = FindTryItem(code_item, address);
860 if (try_item == -1) {
861 return -1;
862 } else {
863 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
864 }
865}
866
David Srbeckyb06e28e2015-12-10 13:15:00 +0000867bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
868 DexDebugNewLocalCb local_cb, void* context) const {
869 DCHECK(local_cb != nullptr);
870 if (code_item == nullptr) {
871 return false;
872 }
873 const uint8_t* stream = GetDebugInfoStream(code_item);
874 if (stream == nullptr) {
875 return false;
876 }
877 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700878
David Srbeckyb06e28e2015-12-10 13:15:00 +0000879 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800880 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000881 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
882 local_in_reg[arg_reg].name_ = "this";
883 local_in_reg[arg_reg].descriptor_ = descriptor;
884 local_in_reg[arg_reg].signature_ = nullptr;
885 local_in_reg[arg_reg].start_address_ = 0;
886 local_in_reg[arg_reg].reg_ = arg_reg;
887 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700888 arg_reg++;
889 }
890
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800891 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000892 DecodeUnsignedLeb128(&stream); // Line.
893 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
894 uint32_t i;
895 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700896 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700897 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800898 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000899 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700900 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000901 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700902 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000903 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
904 local_in_reg[arg_reg].descriptor_ = descriptor;
905 local_in_reg[arg_reg].signature_ = nullptr;
906 local_in_reg[arg_reg].start_address_ = 0;
907 local_in_reg[arg_reg].reg_ = arg_reg;
908 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700909 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910 case 'D':
911 case 'J':
912 arg_reg += 2;
913 break;
914 default:
915 arg_reg += 1;
916 break;
917 }
918 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000919 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800920 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
921 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000922 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700923 }
924
David Srbeckyb06e28e2015-12-10 13:15:00 +0000925 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700926 for (;;) {
927 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700928 switch (opcode) {
929 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000930 // Emit all variables which are still alive at the end of the method.
931 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
932 if (local_in_reg[reg].is_live_) {
933 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
934 local_cb(context, local_in_reg[reg]);
935 }
936 }
937 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700938 case DBG_ADVANCE_PC:
939 address += DecodeUnsignedLeb128(&stream);
940 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000942 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700944 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000945 case DBG_START_LOCAL_EXTENDED: {
946 uint16_t reg = DecodeUnsignedLeb128(&stream);
947 if (reg >= code_item->registers_size_) {
948 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800949 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000950 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951 }
952
David Srbeckyb06e28e2015-12-10 13:15:00 +0000953 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
954 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
955 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700956 if (opcode == DBG_START_LOCAL_EXTENDED) {
957 signature_idx = DecodeUnsignedLeb128P1(&stream);
958 }
959
Shih-wei Liao195487c2011-08-20 13:29:04 -0700960 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000961 if (local_in_reg[reg].is_live_) {
962 local_in_reg[reg].end_address_ = address;
963 local_cb(context, local_in_reg[reg]);
964 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700965
David Srbeckyb06e28e2015-12-10 13:15:00 +0000966 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
967 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
968 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
969 local_in_reg[reg].start_address_ = address;
970 local_in_reg[reg].reg_ = reg;
971 local_in_reg[reg].is_live_ = true;
972 break;
973 }
974 case DBG_END_LOCAL: {
975 uint16_t reg = DecodeUnsignedLeb128(&stream);
976 if (reg >= code_item->registers_size_) {
977 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
978 << code_item->registers_size_ << ") in " << GetLocation();
979 return false;
980 }
981 if (!local_in_reg[reg].is_live_) {
982 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
983 return false;
984 }
985 local_in_reg[reg].end_address_ = address;
986 local_cb(context, local_in_reg[reg]);
987 local_in_reg[reg].is_live_ = false;
988 break;
989 }
990 case DBG_RESTART_LOCAL: {
991 uint16_t reg = DecodeUnsignedLeb128(&stream);
992 if (reg >= code_item->registers_size_) {
993 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
994 << code_item->registers_size_ << ") in " << GetLocation();
995 return false;
996 }
997 // If the register is live, the "restart" is superfluous,
998 // and we don't want to mess with the existing start address.
999 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -07001000 local_in_reg[reg].start_address_ = address;
1001 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001002 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001003 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001004 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001005 case DBG_SET_PROLOGUE_END:
1006 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -07001007 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001008 case DBG_SET_FILE:
1009 DecodeUnsignedLeb128P1(&stream); // name.
1010 break;
1011 default:
1012 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
1013 break;
1014 }
1015 }
1016}
Shih-wei Liao195487c2011-08-20 13:29:04 -07001017
David Srbeckyb06e28e2015-12-10 13:15:00 +00001018bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1019 void* context) const {
1020 DCHECK(position_cb != nullptr);
1021 if (code_item == nullptr) {
1022 return false;
1023 }
1024 const uint8_t* stream = GetDebugInfoStream(code_item);
1025 if (stream == nullptr) {
1026 return false;
1027 }
1028
1029 PositionInfo entry = PositionInfo();
1030 entry.line_ = DecodeUnsignedLeb128(&stream);
1031 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1032 for (uint32_t i = 0; i < parameters_size; ++i) {
1033 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1034 }
1035
1036 for (;;) {
1037 uint8_t opcode = *stream++;
1038 switch (opcode) {
1039 case DBG_END_SEQUENCE:
1040 return true; // end of stream.
1041 case DBG_ADVANCE_PC:
1042 entry.address_ += DecodeUnsignedLeb128(&stream);
1043 break;
1044 case DBG_ADVANCE_LINE:
1045 entry.line_ += DecodeSignedLeb128(&stream);
1046 break;
1047 case DBG_START_LOCAL:
1048 DecodeUnsignedLeb128(&stream); // reg.
1049 DecodeUnsignedLeb128P1(&stream); // name.
1050 DecodeUnsignedLeb128P1(&stream); // descriptor.
1051 break;
1052 case DBG_START_LOCAL_EXTENDED:
1053 DecodeUnsignedLeb128(&stream); // reg.
1054 DecodeUnsignedLeb128P1(&stream); // name.
1055 DecodeUnsignedLeb128P1(&stream); // descriptor.
1056 DecodeUnsignedLeb128P1(&stream); // signature.
1057 break;
1058 case DBG_END_LOCAL:
1059 case DBG_RESTART_LOCAL:
1060 DecodeUnsignedLeb128(&stream); // reg.
1061 break;
1062 case DBG_SET_PROLOGUE_END:
1063 entry.prologue_end_ = true;
1064 break;
1065 case DBG_SET_EPILOGUE_BEGIN:
1066 entry.epilogue_begin_ = true;
1067 break;
1068 case DBG_SET_FILE: {
1069 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1070 entry.source_file_ = StringDataByIdx(name_idx);
1071 break;
1072 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001073 default: {
1074 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001075 entry.address_ += adjopcode / DBG_LINE_RANGE;
1076 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1077 if (position_cb(context, entry)) {
1078 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001079 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001080 entry.prologue_end_ = false;
1081 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001082 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001083 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001084 }
1085 }
1086}
1087
David Srbeckyb06e28e2015-12-10 13:15:00 +00001088bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001089 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001090
1091 // We know that this callback will be called in
1092 // ascending address order, so keep going until we find
1093 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001094 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001095 // The line number from the previous positions callback
1096 // wil be the final result.
1097 return true;
1098 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001099 context->line_num_ = entry.line_;
1100 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001101 }
1102}
1103
Andreas Gampe833a4852014-05-21 18:46:59 -07001104bool DexFile::IsMultiDexLocation(const char* location) {
1105 return strrchr(location, kMultiDexSeparator) != nullptr;
1106}
1107
Andreas Gampe90e34042015-04-27 20:01:52 -07001108std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1109 if (index == 0) {
1110 return "classes.dex";
1111 } else {
1112 return StringPrintf("classes%zu.dex", index + 1);
1113 }
1114}
1115
1116std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1117 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001118 return dex_location;
1119 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001120 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001121 }
1122}
1123
1124std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1125 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001126 std::string base_location = GetBaseLocation(dex_location);
1127 const char* suffix = dex_location + base_location.size();
1128 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1129 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1130 if (path != nullptr && path.get() != base_location) {
1131 return std::string(path.get()) + suffix;
1132 } else if (suffix[0] == 0) {
1133 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001134 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001135 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001136 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001137}
1138
Jeff Hao13e748b2015-08-25 20:44:19 +00001139// Read a signed integer. "zwidth" is the zero-based byte count.
1140static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1141 int32_t val = 0;
1142 for (int i = zwidth; i >= 0; --i) {
1143 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1144 }
1145 val >>= (3 - zwidth) * 8;
1146 return val;
1147}
1148
1149// Read an unsigned integer. "zwidth" is the zero-based byte count,
1150// "fill_on_right" indicates which side we want to zero-fill from.
1151static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1152 uint32_t val = 0;
1153 for (int i = zwidth; i >= 0; --i) {
1154 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1155 }
1156 if (!fill_on_right) {
1157 val >>= (3 - zwidth) * 8;
1158 }
1159 return val;
1160}
1161
1162// Read a signed long. "zwidth" is the zero-based byte count.
1163static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1164 int64_t val = 0;
1165 for (int i = zwidth; i >= 0; --i) {
1166 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1167 }
1168 val >>= (7 - zwidth) * 8;
1169 return val;
1170}
1171
1172// Read an unsigned long. "zwidth" is the zero-based byte count,
1173// "fill_on_right" indicates which side we want to zero-fill from.
1174static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1175 uint64_t val = 0;
1176 for (int i = zwidth; i >= 0; --i) {
1177 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1178 }
1179 if (!fill_on_right) {
1180 val >>= (7 - zwidth) * 8;
1181 }
1182 return val;
1183}
1184
Jeff Hao3d080862016-05-26 18:39:17 -07001185// Checks that visibility is as expected. Includes special behavior for M and
1186// before to allow runtime and build visibility when expecting runtime.
1187static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1188 if (expected == DexFile::kDexVisibilityRuntime) {
1189 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1190 if (sdk_version > 0 && sdk_version <= 23) {
1191 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1192 }
1193 }
1194 return actual == expected;
1195}
1196
Jeff Hao13e748b2015-08-25 20:44:19 +00001197const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1198 mirror::Class* klass = field->GetDeclaringClass();
1199 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1200 if (annotations_dir == nullptr) {
1201 return nullptr;
1202 }
1203 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1204 if (field_annotations == nullptr) {
1205 return nullptr;
1206 }
1207 uint32_t field_index = field->GetDexFieldIndex();
1208 uint32_t field_count = annotations_dir->fields_size_;
1209 for (uint32_t i = 0; i < field_count; ++i) {
1210 if (field_annotations[i].field_idx_ == field_index) {
1211 return GetFieldAnnotationSetItem(field_annotations[i]);
1212 }
1213 }
1214 return nullptr;
1215}
1216
1217mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1218 Handle<mirror::Class> annotation_class) const {
1219 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1220 if (annotation_set == nullptr) {
1221 return nullptr;
1222 }
1223 StackHandleScope<1> hs(Thread::Current());
1224 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1225 return GetAnnotationObjectFromAnnotationSet(
1226 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1227}
1228
1229mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1230 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1231 StackHandleScope<1> hs(Thread::Current());
1232 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1233 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1234}
1235
Jeff Hao2a5892f2015-08-31 15:00:40 -07001236mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001237 const {
1238 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1239 if (annotation_set == nullptr) {
1240 return nullptr;
1241 }
1242 StackHandleScope<1> hs(Thread::Current());
1243 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1244 return GetSignatureValue(field_class, annotation_set);
1245}
1246
1247bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1248 const {
1249 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1250 if (annotation_set == nullptr) {
1251 return false;
1252 }
1253 StackHandleScope<1> hs(Thread::Current());
1254 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1255 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1256 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1257 return annotation_item != nullptr;
1258}
1259
1260const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1261 mirror::Class* klass = method->GetDeclaringClass();
1262 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1263 if (annotations_dir == nullptr) {
1264 return nullptr;
1265 }
1266 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1267 if (method_annotations == nullptr) {
1268 return nullptr;
1269 }
1270 uint32_t method_index = method->GetDexMethodIndex();
1271 uint32_t method_count = annotations_dir->methods_size_;
1272 for (uint32_t i = 0; i < method_count; ++i) {
1273 if (method_annotations[i].method_idx_ == method_index) {
1274 return GetMethodAnnotationSetItem(method_annotations[i]);
1275 }
1276 }
1277 return nullptr;
1278}
1279
1280const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1281 const {
1282 mirror::Class* klass = method->GetDeclaringClass();
1283 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1284 if (annotations_dir == nullptr) {
1285 return nullptr;
1286 }
1287 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1288 if (parameter_annotations == nullptr) {
1289 return nullptr;
1290 }
1291 uint32_t method_index = method->GetDexMethodIndex();
1292 uint32_t parameter_count = annotations_dir->parameters_size_;
1293 for (uint32_t i = 0; i < parameter_count; ++i) {
1294 if (parameter_annotations[i].method_idx_ == method_index) {
1295 return &parameter_annotations[i];
1296 }
1297 }
1298 return nullptr;
1299}
1300
1301mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1302 mirror::Class* klass = method->GetDeclaringClass();
1303 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1304 if (annotations_dir == nullptr) {
1305 return nullptr;
1306 }
1307 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1308 if (annotation_set == nullptr) {
1309 return nullptr;
1310 }
1311 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1312 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1313 if (annotation_item == nullptr) {
1314 return nullptr;
1315 }
1316 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1317 if (annotation == nullptr) {
1318 return nullptr;
1319 }
1320 uint8_t header_byte = *(annotation++);
1321 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1322 return nullptr;
1323 }
1324 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1325 if (annotation == nullptr) {
1326 return nullptr;
1327 }
1328 AnnotationValue annotation_value;
1329 StackHandleScope<2> hs(Thread::Current());
1330 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001331 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1332 Handle<mirror::Class> return_type(hs.NewHandle(
1333 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001334 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1335 return nullptr;
1336 }
1337 return annotation_value.value_.GetL();
1338}
1339
1340mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1341 Handle<mirror::Class> annotation_class) const {
1342 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1343 if (annotation_set == nullptr) {
1344 return nullptr;
1345 }
1346 StackHandleScope<1> hs(Thread::Current());
1347 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1348 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1349 kDexVisibilityRuntime, annotation_class);
1350}
1351
1352mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1353 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1354 StackHandleScope<1> hs(Thread::Current());
1355 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1356 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1357}
1358
Jeff Hao2a5892f2015-08-31 15:00:40 -07001359mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001360 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1361 if (annotation_set == nullptr) {
1362 return nullptr;
1363 }
1364 StackHandleScope<1> hs(Thread::Current());
1365 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1366 return GetThrowsValue(method_class, annotation_set);
1367}
1368
1369mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1370 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1371 if (parameter_annotations == nullptr) {
1372 return nullptr;
1373 }
1374 const AnnotationSetRefList* set_ref_list =
1375 GetParameterAnnotationSetRefList(parameter_annotations);
1376 if (set_ref_list == nullptr) {
1377 return nullptr;
1378 }
1379 uint32_t size = set_ref_list->size_;
1380 StackHandleScope<1> hs(Thread::Current());
1381 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1382 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1383}
1384
Jeff Hao1133db72016-04-04 19:50:14 -07001385mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1386 const {
1387 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1388 if (annotation_set == nullptr) {
1389 return nullptr;
1390 }
1391 StackHandleScope<1> hs(Thread::Current());
1392 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1393 return GetSignatureValue(method_class, annotation_set);
1394}
1395
Jeff Hao13e748b2015-08-25 20:44:19 +00001396bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1397 const {
1398 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1399 if (annotation_set == nullptr) {
1400 return false;
1401 }
1402 StackHandleScope<1> hs(Thread::Current());
1403 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1404 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1405 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001406 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001407}
1408
1409const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1410 const {
1411 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1412 if (annotations_dir == nullptr) {
1413 return nullptr;
1414 }
1415 return GetClassAnnotationSet(annotations_dir);
1416}
1417
1418mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1419 Handle<mirror::Class> annotation_class) const {
1420 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1421 if (annotation_set == nullptr) {
1422 return nullptr;
1423 }
1424 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1425 annotation_class);
1426}
1427
1428mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1429 const {
1430 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1431 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1432}
1433
Jeff Hao2a5892f2015-08-31 15:00:40 -07001434mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1435 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1436 if (annotation_set == nullptr) {
1437 return nullptr;
1438 }
1439 const AnnotationItem* annotation_item = SearchAnnotationSet(
1440 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1441 if (annotation_item == nullptr) {
1442 return nullptr;
1443 }
1444 StackHandleScope<1> hs(Thread::Current());
1445 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1446 Handle<mirror::Class> class_array_class(hs.NewHandle(
1447 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1448 if (class_array_class.Get() == nullptr) {
1449 return nullptr;
1450 }
1451 mirror::Object* obj = GetAnnotationValue(
1452 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1453 if (obj == nullptr) {
1454 return nullptr;
1455 }
1456 return obj->AsObjectArray<mirror::Class>();
1457}
1458
1459mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1460 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1461 if (annotation_set == nullptr) {
1462 return nullptr;
1463 }
1464 const AnnotationItem* annotation_item = SearchAnnotationSet(
1465 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1466 if (annotation_item == nullptr) {
1467 return nullptr;
1468 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001469 mirror::Object* obj = GetAnnotationValue(klass,
1470 annotation_item,
1471 "value",
1472 ScopedNullHandle<mirror::Class>(),
1473 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001474 if (obj == nullptr) {
1475 return nullptr;
1476 }
1477 return obj->AsClass();
1478}
1479
1480mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1481 mirror::Class* declaring_class = GetDeclaringClass(klass);
1482 if (declaring_class != nullptr) {
1483 return declaring_class;
1484 }
1485 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1486 if (annotation_set == nullptr) {
1487 return nullptr;
1488 }
1489 const AnnotationItem* annotation_item = SearchAnnotationSet(
1490 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1491 if (annotation_item == nullptr) {
1492 return nullptr;
1493 }
1494 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1495 if (annotation == nullptr) {
1496 return nullptr;
1497 }
1498 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001499 if (!ProcessAnnotationValue(klass,
1500 &annotation,
1501 &annotation_value,
1502 ScopedNullHandle<mirror::Class>(),
1503 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001504 return nullptr;
1505 }
1506 if (annotation_value.type_ != kDexAnnotationMethod) {
1507 return nullptr;
1508 }
1509 StackHandleScope<2> hs(Thread::Current());
1510 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1511 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1512 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1513 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1514 if (method == nullptr) {
1515 return nullptr;
1516 }
1517 return method->GetDeclaringClass();
1518}
1519
1520mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1521 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1522 if (annotation_set == nullptr) {
1523 return nullptr;
1524 }
1525 const AnnotationItem* annotation_item = SearchAnnotationSet(
1526 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1527 if (annotation_item == nullptr) {
1528 return nullptr;
1529 }
1530 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001531 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001532}
1533
1534bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1535 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1536 if (annotation_set == nullptr) {
1537 return false;
1538 }
1539 const AnnotationItem* annotation_item = SearchAnnotationSet(
1540 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1541 if (annotation_item == nullptr) {
1542 return false;
1543 }
1544 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1545 if (annotation == nullptr) {
1546 return false;
1547 }
1548 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001549 if (!ProcessAnnotationValue(klass,
1550 &annotation,
1551 &annotation_value,
1552 ScopedNullHandle<mirror::Class>(),
1553 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001554 return false;
1555 }
1556 if (annotation_value.type_ != kDexAnnotationNull &&
1557 annotation_value.type_ != kDexAnnotationString) {
1558 return false;
1559 }
1560 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1561 return true;
1562}
1563
1564bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1565 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1566 if (annotation_set == nullptr) {
1567 return false;
1568 }
1569 const AnnotationItem* annotation_item = SearchAnnotationSet(
1570 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1571 if (annotation_item == nullptr) {
1572 return false;
1573 }
1574 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1575 if (annotation == nullptr) {
1576 return false;
1577 }
1578 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001579 if (!ProcessAnnotationValue(klass,
1580 &annotation,
1581 &annotation_value,
1582 ScopedNullHandle<mirror::Class>(),
1583 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001584 return false;
1585 }
1586 if (annotation_value.type_ != kDexAnnotationInt) {
1587 return false;
1588 }
1589 *flags = annotation_value.value_.GetI();
1590 return true;
1591}
1592
Jeff Hao1133db72016-04-04 19:50:14 -07001593mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1594 Handle<mirror::Class> klass) const {
1595 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1596 if (annotation_set == nullptr) {
1597 return nullptr;
1598 }
1599 return GetSignatureValue(klass, annotation_set);
1600}
1601
Jeff Hao13e748b2015-08-25 20:44:19 +00001602bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1603 Handle<mirror::Class> annotation_class) const {
1604 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1605 if (annotation_set == nullptr) {
1606 return false;
1607 }
1608 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1609 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001610 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001611}
1612
1613mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1614 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1615 Thread* self = Thread::Current();
1616 ScopedObjectAccessUnchecked soa(self);
1617 StackHandleScope<5> hs(self);
1618 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1619 const char* name = StringDataByIdx(element_name_index);
1620 Handle<mirror::String> string_name(
1621 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1622
1623 ArtMethod* annotation_method =
1624 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1625 if (annotation_method == nullptr) {
1626 return nullptr;
1627 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001628 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1629 Handle<mirror::Class> method_return(hs.NewHandle(
1630 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001631
1632 AnnotationValue annotation_value;
1633 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1634 return nullptr;
1635 }
1636 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1637
1638 mirror::Class* annotation_member_class =
1639 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1640 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
Andreas Gampee01e3642016-07-25 13:06:04 -07001641 mirror::Method* method_obj_ptr;
1642 DCHECK(!Runtime::Current()->IsActiveTransaction());
1643 if (pointer_size == 8U) {
1644 method_obj_ptr = mirror::Method::CreateFromArtMethod<8U, false>(self, annotation_method);
1645 } else {
1646 DCHECK_EQ(pointer_size, 4U);
1647 method_obj_ptr = mirror::Method::CreateFromArtMethod<4U, false>(self, annotation_method);
1648 }
1649 Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
Jeff Hao13e748b2015-08-25 20:44:19 +00001650
1651 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1652 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1653 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1654 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1655 return nullptr;
1656 }
1657
1658 JValue result;
1659 ArtMethod* annotation_member_init =
1660 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1661 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1662 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1663 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1664 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1665 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1666 };
1667 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1668 if (self->IsExceptionPending()) {
1669 LOG(INFO) << "Exception in AnnotationMember.<init>";
1670 return nullptr;
1671 }
1672
1673 return new_member.Get();
1674}
1675
1676const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1677 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1678 Handle<mirror::Class> annotation_class) const {
1679 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1680 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001681 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001682 continue;
1683 }
1684 const uint8_t* annotation = annotation_item->annotation_;
1685 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1686 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1687 klass->GetDexFile(), type_index, klass.Get());
1688 if (resolved_class == nullptr) {
1689 std::string temp;
1690 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1691 klass->GetDescriptor(&temp), type_index);
1692 CHECK(Thread::Current()->IsExceptionPending());
1693 Thread::Current()->ClearException();
1694 continue;
1695 }
1696 if (resolved_class == annotation_class.Get()) {
1697 return annotation_item;
1698 }
1699 }
1700
1701 return nullptr;
1702}
1703
1704mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1705 const AnnotationSetItem* annotation_set, uint32_t visibility,
1706 Handle<mirror::Class> annotation_class) const {
1707 const AnnotationItem* annotation_item =
1708 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1709 if (annotation_item == nullptr) {
1710 return nullptr;
1711 }
1712 const uint8_t* annotation = annotation_item->annotation_;
1713 return ProcessEncodedAnnotation(klass, &annotation);
1714}
1715
1716mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1717 const AnnotationItem* annotation_item, const char* annotation_name,
1718 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1719 const uint8_t* annotation =
1720 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1721 if (annotation == nullptr) {
1722 return nullptr;
1723 }
1724 AnnotationValue annotation_value;
1725 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1726 return nullptr;
1727 }
1728 if (annotation_value.type_ != expected_type) {
1729 return nullptr;
1730 }
1731 return annotation_value.value_.GetL();
1732}
1733
Jeff Hao2a5892f2015-08-31 15:00:40 -07001734mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001735 const AnnotationSetItem* annotation_set) const {
1736 StackHandleScope<1> hs(Thread::Current());
1737 const AnnotationItem* annotation_item =
1738 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1739 if (annotation_item == nullptr) {
1740 return nullptr;
1741 }
1742 mirror::Class* string_class = mirror::String::GetJavaLangString();
1743 Handle<mirror::Class> string_array_class(hs.NewHandle(
1744 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001745 if (string_array_class.Get() == nullptr) {
1746 return nullptr;
1747 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001748 mirror::Object* obj =
1749 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1750 if (obj == nullptr) {
1751 return nullptr;
1752 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001753 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001754}
1755
Jeff Hao2a5892f2015-08-31 15:00:40 -07001756mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001757 const AnnotationSetItem* annotation_set) const {
1758 StackHandleScope<1> hs(Thread::Current());
1759 const AnnotationItem* annotation_item =
1760 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1761 if (annotation_item == nullptr) {
1762 return nullptr;
1763 }
1764 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1765 Handle<mirror::Class> class_array_class(hs.NewHandle(
1766 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001767 if (class_array_class.Get() == nullptr) {
1768 return nullptr;
1769 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001770 mirror::Object* obj =
1771 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1772 if (obj == nullptr) {
1773 return nullptr;
1774 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001775 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001776}
1777
1778mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1779 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1780 Thread* self = Thread::Current();
1781 ScopedObjectAccessUnchecked soa(self);
1782 StackHandleScope<2> hs(self);
1783 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1784 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1785 if (annotation_set == nullptr) {
1786 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1787 }
1788
1789 uint32_t size = annotation_set->size_;
1790 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1791 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1792 if (result.Get() == nullptr) {
1793 return nullptr;
1794 }
1795
1796 uint32_t dest_index = 0;
1797 for (uint32_t i = 0; i < size; ++i) {
1798 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07001799 // Note that we do not use IsVisibilityCompatible here because older code
1800 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001801 if (annotation_item->visibility_ != visibility) {
1802 continue;
1803 }
1804 const uint8_t* annotation = annotation_item->annotation_;
1805 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1806 if (annotation_obj != nullptr) {
1807 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1808 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001809 } else if (self->IsExceptionPending()) {
1810 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001811 }
1812 }
1813
1814 if (dest_index == size) {
1815 return result.Get();
1816 }
1817
1818 mirror::ObjectArray<mirror::Object>* trimmed_result =
1819 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001820 if (trimmed_result == nullptr) {
1821 return nullptr;
1822 }
1823
Jeff Hao13e748b2015-08-25 20:44:19 +00001824 for (uint32_t i = 0; i < dest_index; ++i) {
1825 mirror::Object* obj = result->GetWithoutChecks(i);
1826 trimmed_result->SetWithoutChecks<false>(i, obj);
1827 }
1828
1829 return trimmed_result;
1830}
1831
1832mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1833 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1834 Thread* self = Thread::Current();
1835 ScopedObjectAccessUnchecked soa(self);
1836 StackHandleScope<1> hs(self);
1837 mirror::Class* annotation_array_class =
1838 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1839 mirror::Class* annotation_array_array_class =
1840 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001841 if (annotation_array_array_class == nullptr) {
1842 return nullptr;
1843 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001844 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1845 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1846 if (annotation_array_array.Get() == nullptr) {
1847 LOG(ERROR) << "Annotation set ref array allocation failed";
1848 return nullptr;
1849 }
1850 for (uint32_t index = 0; index < size; ++index) {
1851 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1852 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1853 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1854 if (annotation_set == nullptr) {
1855 return nullptr;
1856 }
1857 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1858 }
1859 return annotation_array_array.Get();
1860}
1861
1862bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1863 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1864 DexFile::AnnotationResultStyle result_style) const {
1865 Thread* self = Thread::Current();
1866 mirror::Object* element_object = nullptr;
1867 bool set_object = false;
1868 Primitive::Type primitive_type = Primitive::kPrimVoid;
1869 const uint8_t* annotation = *annotation_ptr;
1870 uint8_t header_byte = *(annotation++);
1871 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1872 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1873 int32_t width = value_arg + 1;
1874 annotation_value->type_ = value_type;
1875
1876 switch (value_type) {
1877 case kDexAnnotationByte:
1878 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1879 primitive_type = Primitive::kPrimByte;
1880 break;
1881 case kDexAnnotationShort:
1882 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1883 primitive_type = Primitive::kPrimShort;
1884 break;
1885 case kDexAnnotationChar:
1886 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1887 false)));
1888 primitive_type = Primitive::kPrimChar;
1889 break;
1890 case kDexAnnotationInt:
1891 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1892 primitive_type = Primitive::kPrimInt;
1893 break;
1894 case kDexAnnotationLong:
1895 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1896 primitive_type = Primitive::kPrimLong;
1897 break;
1898 case kDexAnnotationFloat:
1899 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1900 primitive_type = Primitive::kPrimFloat;
1901 break;
1902 case kDexAnnotationDouble:
1903 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1904 primitive_type = Primitive::kPrimDouble;
1905 break;
1906 case kDexAnnotationBoolean:
1907 annotation_value->value_.SetZ(value_arg != 0);
1908 primitive_type = Primitive::kPrimBoolean;
1909 width = 0;
1910 break;
1911 case kDexAnnotationString: {
1912 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1913 if (result_style == kAllRaw) {
1914 annotation_value->value_.SetI(index);
1915 } else {
1916 StackHandleScope<1> hs(self);
1917 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1918 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1919 klass->GetDexFile(), index, dex_cache);
1920 set_object = true;
1921 if (element_object == nullptr) {
1922 return false;
1923 }
1924 }
1925 break;
1926 }
1927 case kDexAnnotationType: {
1928 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1929 if (result_style == kAllRaw) {
1930 annotation_value->value_.SetI(index);
1931 } else {
1932 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1933 klass->GetDexFile(), index, klass.Get());
1934 set_object = true;
1935 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001936 CHECK(self->IsExceptionPending());
1937 if (result_style == kAllObjects) {
1938 const char* msg = StringByTypeIdx(index);
1939 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1940 element_object = self->GetException();
1941 self->ClearException();
1942 } else {
1943 return false;
1944 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001945 }
1946 }
1947 break;
1948 }
1949 case kDexAnnotationMethod: {
1950 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1951 if (result_style == kAllRaw) {
1952 annotation_value->value_.SetI(index);
1953 } else {
1954 StackHandleScope<2> hs(self);
1955 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1956 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampee01e3642016-07-25 13:06:04 -07001957 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1958 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Jeff Hao13e748b2015-08-25 20:44:19 +00001959 klass->GetDexFile(), index, dex_cache, class_loader);
1960 if (method == nullptr) {
1961 return false;
1962 }
Andreas Gampee01e3642016-07-25 13:06:04 -07001963 size_t pointer_size = class_linker->GetImagePointerSize();
Jeff Hao13e748b2015-08-25 20:44:19 +00001964 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07001965 DCHECK(!Runtime::Current()->IsActiveTransaction());
Jeff Hao13e748b2015-08-25 20:44:19 +00001966 if (method->IsConstructor()) {
Andreas Gampee01e3642016-07-25 13:06:04 -07001967 if (pointer_size == 8U) {
1968 element_object = mirror::Constructor::CreateFromArtMethod<8U, false>(self, method);
1969 } else {
1970 DCHECK_EQ(pointer_size, 4U);
1971 element_object = mirror::Constructor::CreateFromArtMethod<4U, false>(self, method);
1972 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001973 } else {
Andreas Gampee01e3642016-07-25 13:06:04 -07001974 if (pointer_size == 8U) {
1975 element_object = mirror::Method::CreateFromArtMethod<8U, false>(self, method);
1976 } else {
1977 DCHECK_EQ(pointer_size, 4U);
1978 element_object = mirror::Method::CreateFromArtMethod<4U, false>(self, method);
1979 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001980 }
1981 if (element_object == nullptr) {
1982 return false;
1983 }
1984 }
1985 break;
1986 }
1987 case kDexAnnotationField: {
1988 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1989 if (result_style == kAllRaw) {
1990 annotation_value->value_.SetI(index);
1991 } else {
1992 StackHandleScope<2> hs(self);
1993 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1994 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1995 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1996 klass->GetDexFile(), index, dex_cache, class_loader);
1997 if (field == nullptr) {
1998 return false;
1999 }
2000 set_object = true;
Andreas Gampee01e3642016-07-25 13:06:04 -07002001 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2002 if (pointer_size == 8) {
2003 element_object = mirror::Field::CreateFromArtField<8U>(self, field, true);
2004 } else {
2005 DCHECK_EQ(pointer_size, 4U);
2006 element_object = mirror::Field::CreateFromArtField<4U>(self, field, true);
2007 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002008 if (element_object == nullptr) {
2009 return false;
2010 }
2011 }
2012 break;
2013 }
2014 case kDexAnnotationEnum: {
2015 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
2016 if (result_style == kAllRaw) {
2017 annotation_value->value_.SetI(index);
2018 } else {
2019 StackHandleScope<3> hs(self);
2020 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
2021 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
2022 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
2023 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00002024 if (enum_field == nullptr) {
2025 return false;
2026 } else {
Jeff Haod297b552015-11-20 14:56:09 -08002027 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00002028 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
2029 element_object = enum_field->GetObject(field_class.Get());
2030 set_object = true;
2031 }
2032 }
2033 break;
2034 }
2035 case kDexAnnotationArray:
2036 if (result_style == kAllRaw || array_class.Get() == nullptr) {
2037 return false;
2038 } else {
2039 ScopedObjectAccessUnchecked soa(self);
2040 StackHandleScope<2> hs(self);
2041 uint32_t size = DecodeUnsignedLeb128(&annotation);
2042 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
2043 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
2044 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2045 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2046 if (new_array.Get() == nullptr) {
2047 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2048 return false;
2049 }
2050 AnnotationValue new_annotation_value;
2051 for (uint32_t i = 0; i < size; ++i) {
2052 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2053 kPrimitivesOrObjects)) {
2054 return false;
2055 }
2056 if (!component_type->IsPrimitive()) {
2057 mirror::Object* obj = new_annotation_value.value_.GetL();
2058 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2059 } else {
2060 switch (new_annotation_value.type_) {
2061 case kDexAnnotationByte:
2062 new_array->AsByteArray()->SetWithoutChecks<false>(
2063 i, new_annotation_value.value_.GetB());
2064 break;
2065 case kDexAnnotationShort:
2066 new_array->AsShortArray()->SetWithoutChecks<false>(
2067 i, new_annotation_value.value_.GetS());
2068 break;
2069 case kDexAnnotationChar:
2070 new_array->AsCharArray()->SetWithoutChecks<false>(
2071 i, new_annotation_value.value_.GetC());
2072 break;
2073 case kDexAnnotationInt:
2074 new_array->AsIntArray()->SetWithoutChecks<false>(
2075 i, new_annotation_value.value_.GetI());
2076 break;
2077 case kDexAnnotationLong:
2078 new_array->AsLongArray()->SetWithoutChecks<false>(
2079 i, new_annotation_value.value_.GetJ());
2080 break;
2081 case kDexAnnotationFloat:
2082 new_array->AsFloatArray()->SetWithoutChecks<false>(
2083 i, new_annotation_value.value_.GetF());
2084 break;
2085 case kDexAnnotationDouble:
2086 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2087 i, new_annotation_value.value_.GetD());
2088 break;
2089 case kDexAnnotationBoolean:
2090 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2091 i, new_annotation_value.value_.GetZ());
2092 break;
2093 default:
2094 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2095 return false;
2096 }
2097 }
2098 }
2099 element_object = new_array.Get();
2100 set_object = true;
2101 width = 0;
2102 }
2103 break;
2104 case kDexAnnotationAnnotation:
2105 if (result_style == kAllRaw) {
2106 return false;
2107 }
2108 element_object = ProcessEncodedAnnotation(klass, &annotation);
2109 if (element_object == nullptr) {
2110 return false;
2111 }
2112 set_object = true;
2113 width = 0;
2114 break;
2115 case kDexAnnotationNull:
2116 if (result_style == kAllRaw) {
2117 annotation_value->value_.SetI(0);
2118 } else {
2119 CHECK(element_object == nullptr);
2120 set_object = true;
2121 }
2122 width = 0;
2123 break;
2124 default:
2125 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2126 return false;
2127 }
2128
2129 annotation += width;
2130 *annotation_ptr = annotation;
2131
2132 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2133 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2134 set_object = true;
2135 }
2136
2137 if (set_object) {
2138 annotation_value->value_.SetL(element_object);
2139 }
2140
2141 return true;
2142}
2143
2144mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2145 const uint8_t** annotation) const {
2146 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2147 uint32_t size = DecodeUnsignedLeb128(annotation);
2148
2149 Thread* self = Thread::Current();
2150 ScopedObjectAccessUnchecked soa(self);
2151 StackHandleScope<2> hs(self);
2152 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2153 Handle<mirror::Class> annotation_class(hs.NewHandle(
2154 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2155 if (annotation_class.Get() == nullptr) {
2156 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2157 << type_index;
2158 DCHECK(Thread::Current()->IsExceptionPending());
2159 Thread::Current()->ClearException();
2160 return nullptr;
2161 }
2162
2163 mirror::Class* annotation_member_class =
2164 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2165 mirror::Class* annotation_member_array_class =
2166 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002167 if (annotation_member_array_class == nullptr) {
2168 return nullptr;
2169 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002170 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002171 if (size > 0) {
2172 element_array =
2173 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2174 if (element_array == nullptr) {
2175 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2176 return nullptr;
2177 }
2178 }
2179
2180 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2181 for (uint32_t i = 0; i < size; ++i) {
2182 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2183 if (new_member == nullptr) {
2184 return nullptr;
2185 }
2186 h_element_array->SetWithoutChecks<false>(i, new_member);
2187 }
2188
2189 JValue result;
2190 ArtMethod* create_annotation_method =
2191 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2192 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2193 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2194 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2195 if (self->IsExceptionPending()) {
2196 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2197 return nullptr;
2198 }
2199
2200 return result.GetL();
2201}
2202
2203const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2204 const char* descriptor, uint32_t visibility) const {
2205 const AnnotationItem* result = nullptr;
2206 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2207 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao3d080862016-05-26 18:39:17 -07002208 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002209 continue;
2210 }
2211 const uint8_t* annotation = annotation_item->annotation_;
2212 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2213
2214 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2215 result = annotation_item;
2216 break;
2217 }
2218 }
2219 return result;
2220}
2221
2222const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2223 DecodeUnsignedLeb128(&annotation); // unused type_index
2224 uint32_t size = DecodeUnsignedLeb128(&annotation);
2225
2226 while (size != 0) {
2227 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2228 const char* element_name = GetStringData(GetStringId(element_name_index));
2229 if (strcmp(name, element_name) == 0) {
2230 return annotation;
2231 }
2232 SkipAnnotationValue(&annotation);
2233 size--;
2234 }
2235 return nullptr;
2236}
2237
2238bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2239 const uint8_t* annotation = *annotation_ptr;
2240 uint8_t header_byte = *(annotation++);
2241 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2242 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2243 int32_t width = value_arg + 1;
2244
2245 switch (value_type) {
2246 case kDexAnnotationByte:
2247 case kDexAnnotationShort:
2248 case kDexAnnotationChar:
2249 case kDexAnnotationInt:
2250 case kDexAnnotationLong:
2251 case kDexAnnotationFloat:
2252 case kDexAnnotationDouble:
2253 case kDexAnnotationString:
2254 case kDexAnnotationType:
2255 case kDexAnnotationMethod:
2256 case kDexAnnotationField:
2257 case kDexAnnotationEnum:
2258 break;
2259 case kDexAnnotationArray:
2260 {
2261 uint32_t size = DecodeUnsignedLeb128(&annotation);
2262 while (size--) {
2263 if (!SkipAnnotationValue(&annotation)) {
2264 return false;
2265 }
2266 }
2267 width = 0;
2268 break;
2269 }
2270 case kDexAnnotationAnnotation:
2271 {
2272 DecodeUnsignedLeb128(&annotation); // unused type_index
2273 uint32_t size = DecodeUnsignedLeb128(&annotation);
2274 while (size--) {
2275 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2276 if (!SkipAnnotationValue(&annotation)) {
2277 return false;
2278 }
2279 }
2280 width = 0;
2281 break;
2282 }
2283 case kDexAnnotationBoolean:
2284 case kDexAnnotationNull:
2285 width = 0;
2286 break;
2287 default:
2288 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2289 return false;
2290 }
2291
2292 annotation += width;
2293 *annotation_ptr = annotation;
2294 return true;
2295}
2296
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002297std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2298 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2299 dex_file.GetLocation().c_str(),
2300 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2301 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2302 return os;
2303}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002304
Ian Rogersd91d6d62013-09-25 20:26:14 -07002305std::string Signature::ToString() const {
2306 if (dex_file_ == nullptr) {
2307 CHECK(proto_id_ == nullptr);
2308 return "<no signature>";
2309 }
2310 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2311 std::string result;
2312 if (params == nullptr) {
2313 result += "()";
2314 } else {
2315 result += "(";
2316 for (uint32_t i = 0; i < params->Size(); ++i) {
2317 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2318 }
2319 result += ")";
2320 }
2321 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2322 return result;
2323}
2324
Vladimir Markod9cffea2013-11-25 15:08:02 +00002325bool Signature::operator==(const StringPiece& rhs) const {
2326 if (dex_file_ == nullptr) {
2327 return false;
2328 }
2329 StringPiece tail(rhs);
2330 if (!tail.starts_with("(")) {
2331 return false; // Invalid signature
2332 }
2333 tail.remove_prefix(1); // "(";
2334 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2335 if (params != nullptr) {
2336 for (uint32_t i = 0; i < params->Size(); ++i) {
2337 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2338 if (!tail.starts_with(param)) {
2339 return false;
2340 }
2341 tail.remove_prefix(param.length());
2342 }
2343 }
2344 if (!tail.starts_with(")")) {
2345 return false;
2346 }
2347 tail.remove_prefix(1); // ")";
2348 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2349}
2350
Ian Rogersd91d6d62013-09-25 20:26:14 -07002351std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2352 return os << sig.ToString();
2353}
2354
Ian Rogers0571d352011-11-03 19:51:38 -07002355// Decodes the header section from the class data bytes.
2356void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002357 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002358 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2359 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2360 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2361 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2362}
2363
2364void ClassDataItemIterator::ReadClassDataField() {
2365 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2366 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002367 // The user of the iterator is responsible for checking if there
2368 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002369}
2370
2371void ClassDataItemIterator::ReadClassDataMethod() {
2372 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2373 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2374 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002375 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002376 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002377 }
Ian Rogers0571d352011-11-03 19:51:38 -07002378}
2379
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002380EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002381 const DexFile& dex_file,
2382 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002383 : EncodedStaticFieldValueIterator(dex_file,
2384 nullptr,
2385 nullptr,
2386 nullptr,
2387 class_def,
2388 -1,
2389 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002390}
2391
2392EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002393 const DexFile& dex_file,
2394 Handle<mirror::DexCache>* dex_cache,
2395 Handle<mirror::ClassLoader>* class_loader,
2396 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002397 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002398 : EncodedStaticFieldValueIterator(dex_file,
2399 dex_cache, class_loader,
2400 linker,
2401 class_def,
2402 -1,
2403 kByte) {
2404 DCHECK(dex_cache_ != nullptr);
2405 DCHECK(class_loader_ != nullptr);
2406}
2407
2408EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2409 const DexFile& dex_file,
2410 Handle<mirror::DexCache>* dex_cache,
2411 Handle<mirror::ClassLoader>* class_loader,
2412 ClassLinker* linker,
2413 const DexFile::ClassDef& class_def,
2414 size_t pos,
2415 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002416 : dex_file_(dex_file),
2417 dex_cache_(dex_cache),
2418 class_loader_(class_loader),
2419 linker_(linker),
2420 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002421 pos_(pos),
2422 type_(type) {
2423 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002424 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002425 array_size_ = 0;
2426 } else {
2427 array_size_ = DecodeUnsignedLeb128(&ptr_);
2428 }
2429 if (array_size_ > 0) {
2430 Next();
2431 }
2432}
2433
2434void EncodedStaticFieldValueIterator::Next() {
2435 pos_++;
2436 if (pos_ >= array_size_) {
2437 return;
2438 }
Ian Rogers13735952014-10-08 12:43:28 -07002439 uint8_t value_type = *ptr_++;
2440 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002441 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002442 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002443 switch (type_) {
2444 case kBoolean:
2445 jval_.i = (value_arg != 0) ? 1 : 0;
2446 width = 0;
2447 break;
2448 case kByte:
2449 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002450 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002451 break;
2452 case kShort:
2453 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002454 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002455 break;
2456 case kChar:
2457 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002458 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002459 break;
2460 case kInt:
2461 jval_.i = ReadSignedInt(ptr_, value_arg);
2462 break;
2463 case kLong:
2464 jval_.j = ReadSignedLong(ptr_, value_arg);
2465 break;
2466 case kFloat:
2467 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2468 break;
2469 case kDouble:
2470 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2471 break;
2472 case kString:
2473 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002474 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2475 break;
2476 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002477 case kMethod:
2478 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002479 case kArray:
2480 case kAnnotation:
2481 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002482 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002483 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002484 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002485 width = 0;
2486 break;
2487 default:
2488 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002489 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002490 }
2491 ptr_ += width;
2492}
2493
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002494template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002495void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002496 DCHECK(dex_cache_ != nullptr);
2497 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002498 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002499 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2500 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002501 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2502 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2503 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2504 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2505 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2506 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2507 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002508 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002509 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002510 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002511 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002512 break;
2513 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002514 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002515 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2516 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002517 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002518 break;
2519 }
Ian Rogers0571d352011-11-03 19:51:38 -07002520 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2521 }
2522}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002523template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2524template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002525
2526CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2527 handler_.address_ = -1;
2528 int32_t offset = -1;
2529
2530 // Short-circuit the overwhelmingly common cases.
2531 switch (code_item.tries_size_) {
2532 case 0:
2533 break;
2534 case 1: {
2535 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2536 uint32_t start = tries->start_addr_;
2537 if (address >= start) {
2538 uint32_t end = start + tries->insn_count_;
2539 if (address < end) {
2540 offset = tries->handler_off_;
2541 }
2542 }
2543 break;
2544 }
2545 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002546 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002547 }
Logan Chien736df022012-04-27 16:25:57 +08002548 Init(code_item, offset);
2549}
2550
2551CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2552 const DexFile::TryItem& try_item) {
2553 handler_.address_ = -1;
2554 Init(code_item, try_item.handler_off_);
2555}
2556
2557void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2558 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002559 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002560 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002561 } else {
2562 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002563 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002564 remaining_count_ = -1;
2565 catch_all_ = false;
2566 DCHECK(!HasNext());
2567 }
2568}
2569
Ian Rogers13735952014-10-08 12:43:28 -07002570void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002571 current_data_ = handler_data;
2572 remaining_count_ = DecodeSignedLeb128(&current_data_);
2573
2574 // If remaining_count_ is non-positive, then it is the negative of
2575 // the number of catch types, and the catches are followed by a
2576 // catch-all handler.
2577 if (remaining_count_ <= 0) {
2578 catch_all_ = true;
2579 remaining_count_ = -remaining_count_;
2580 } else {
2581 catch_all_ = false;
2582 }
2583 Next();
2584}
2585
2586void CatchHandlerIterator::Next() {
2587 if (remaining_count_ > 0) {
2588 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2589 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2590 remaining_count_--;
2591 return;
2592 }
2593
2594 if (catch_all_) {
2595 handler_.type_idx_ = DexFile::kDexNoIndex16;
2596 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2597 catch_all_ = false;
2598 return;
2599 }
2600
2601 // no more handler
2602 remaining_count_ = -1;
2603}
2604
Carl Shapiro1fb86202011-06-27 17:43:13 -07002605} // namespace art