blob: 88696e96409467e2ffdae513f6df80ce5d0f5548 [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"
Jeff Hao13e748b2015-08-25 20:44:19 +000038#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070039#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080040#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070041#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030042#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070043#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000044#include "mirror/field.h"
45#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070047#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000048#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070050#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070052#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070053#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070055#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070056
Andreas Gampe277ccbd2014-11-03 21:36:10 -080057#pragma GCC diagnostic push
58#pragma GCC diagnostic ignored "-Wshadow"
59#include "ScopedFd.h"
60#pragma GCC diagnostic pop
61
Carl Shapiro1fb86202011-06-27 17:43:13 -070062namespace art {
63
Ian Rogers13735952014-10-08 12:43:28 -070064const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
Alex Lightc4961812016-03-23 10:20:41 -070065const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
66 {'0', '3', '5', '\0'},
67 // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
68 // files with that version number would erroneously be accepted and run.
69 {'0', '3', '7', '\0'}
70};
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070071
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070073 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070074 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070075
76 // Strip ":...", which is the location
77 const char* zip_entry_name = kClassesDex;
78 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010079 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070080
Vladimir Markoaa4497d2014-09-05 14:01:17 +010081 if (DexFile::IsMultiDexLocation(filename)) {
82 file_part_storage = GetBaseLocation(filename);
83 file_part = file_part_storage.c_str();
84 zip_entry_name = filename + file_part_storage.size() + 1;
85 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070086 }
87
88 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +000089 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070090 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070091 return false;
92 }
93 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 std::unique_ptr<ZipArchive> zip_archive(
95 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
96 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -080097 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
98 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -080099 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700100 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700101 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700103 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
104 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800105 return false;
106 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700107 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800108 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700109 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700110 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 std::unique_ptr<const DexFile> dex_file(
112 DexFile::OpenFile(fd.release(), filename, false, error_msg));
113 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114 return false;
115 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700116 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800117 return true;
118 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700119 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800120 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700121}
122
Andreas Gampe833a4852014-05-21 18:46:59 -0700123bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800124 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800125 ScopedTrace trace(std::string("Open dex file ") + location);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700127 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000128 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
129 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700131 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700132 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700133 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700134 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700135 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700136 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700137 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
138 error_msg));
139 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800140 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700141 return true;
142 } else {
143 return false;
144 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700145 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700146 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400147 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700148}
149
Andreas Gampe0cba0042015-04-29 20:47:16 -0700150static bool ContainsClassesDex(int fd, const char* filename) {
151 std::string error_msg;
152 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
153 if (zip_archive.get() == nullptr) {
154 return false;
155 }
156 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
157 return (zip_entry.get() != nullptr);
158}
159
160bool DexFile::MaybeDex(const char* filename) {
161 uint32_t magic;
162 std::string error_msg;
163 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
164 if (fd.get() == -1) {
165 return false;
166 }
167 if (IsZipMagic(magic)) {
168 return ContainsClassesDex(fd.release(), filename);
169 } else if (IsDexMagic(magic)) {
170 return true;
171 }
172 return false;
173}
174
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800175int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700176 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800177 return 0;
178 } else {
179 return mem_map_->GetProtect();
180 }
181}
182
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200183bool DexFile::IsReadOnly() const {
184 return GetPermissions() == PROT_READ;
185}
186
Brian Carlstrome0948e12013-08-29 09:36:15 -0700187bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200188 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700189 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200190 return false;
191 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700192 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200193 }
194}
195
Brian Carlstrome0948e12013-08-29 09:36:15 -0700196bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200197 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700198 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200199 return false;
200 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700201 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 }
203}
204
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800205std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
206 const std::string& location,
207 uint32_t location_checksum,
208 const OatDexFile* oat_dex_file,
209 bool verify,
210 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800211 ScopedTrace trace(std::string("Open dex file from RAM ") + location);
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800212 std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
213 size,
214 location,
215 location_checksum,
216 nullptr,
217 oat_dex_file,
218 error_msg);
219 if (verify && !DexFileVerifier::Verify(dex_file.get(),
220 dex_file->Begin(),
221 dex_file->Size(),
222 location.c_str(),
223 error_msg)) {
224 return nullptr;
225 }
226
227 return dex_file;
228}
229
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800230std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
231 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800232 ScopedTrace trace(std::string("Open dex file ") + location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700233 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700234 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000235 {
236 ScopedFd delayed_close(fd);
237 struct stat sbuf;
238 memset(&sbuf, 0, sizeof(sbuf));
239 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800240 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000241 return nullptr;
242 }
243 if (S_ISDIR(sbuf.st_mode)) {
244 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
245 return nullptr;
246 }
247 size_t length = sbuf.st_size;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800248 map.reset(MemMap::MapFile(length,
249 PROT_READ,
250 MAP_PRIVATE,
251 fd,
252 0,
253 /*low_4gb*/false,
254 location,
255 error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000256 if (map.get() == nullptr) {
257 DCHECK(!error_msg->empty());
258 return nullptr;
259 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700260 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800261
262 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700263 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800264 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800266 }
267
268 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
269
Andreas Gampe928f72b2014-09-09 19:53:48 -0700270 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
271 error_msg));
272 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700273 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
274 error_msg->c_str());
275 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800276 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800277
Andreas Gampe928f72b2014-09-09 19:53:48 -0700278 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
279 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800281 }
282
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800283 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700284}
285
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700286const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700287
Andreas Gampe833a4852014-05-21 18:46:59 -0700288bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800290 ScopedTrace trace("Dex file open Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700291 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700292 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700293 if (zip_archive.get() == nullptr) {
294 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700296 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800298}
299
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800300std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
301 uint32_t location_checksum,
302 MemMap* mem_map,
303 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800304 return OpenMemory(mem_map->Begin(),
305 mem_map->Size(),
306 location,
307 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800309 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311}
312
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800313std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
314 const std::string& location, std::string* error_msg,
315 ZipOpenErrorCode* error_code) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800316 ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800317 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700318 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700319 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700320 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700321 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700322 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700324 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700325 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700327 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700328 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700329 }
Ian Rogers700a4022014-05-19 16:49:03 -0700330 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700331 error_msg));
332 if (dex_file.get() == nullptr) {
333 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
334 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700335 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800337 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700338 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700339 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700341 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700342 }
343 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700344 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
345 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700346 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700347 return nullptr;
348 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700349 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800350 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700351}
352
Andreas Gampe90e34042015-04-27 20:01:52 -0700353// Technically we do not have a limitation with respect to the number of dex files that can be in a
354// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
355// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
356// seems an excessive number.
357static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
358
Andreas Gampe833a4852014-05-21 18:46:59 -0700359bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800360 std::string* error_msg,
361 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800362 ScopedTrace trace("Dex file open from Zip " + std::string(location));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700363 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700364 ZipOpenErrorCode error_code;
365 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
366 &error_code));
367 if (dex_file.get() == nullptr) {
368 return false;
369 } else {
370 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800371 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700372
373 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700374
375 // We could try to avoid std::string allocations by working on a char array directly. As we
376 // do not expect a lot of iterations, this seems too involved and brittle.
377
Andreas Gampe90e34042015-04-27 20:01:52 -0700378 for (size_t i = 1; ; ++i) {
379 std::string name = GetMultiDexClassesDexName(i);
380 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700381 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
382 error_msg, &error_code));
383 if (next_dex_file.get() == nullptr) {
384 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
385 LOG(WARNING) << error_msg;
386 }
387 break;
388 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800389 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700390 }
391
Andreas Gampe90e34042015-04-27 20:01:52 -0700392 if (i == kWarnOnManyDexFilesThreshold) {
393 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
394 << " dex files. Please consider coalescing and shrinking the number to "
395 " avoid runtime overhead.";
396 }
397
398 if (i == std::numeric_limits<size_t>::max()) {
399 LOG(ERROR) << "Overflow in number of dex files!";
400 break;
401 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700402 }
403
404 return true;
405 }
406}
407
408
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
410 size_t size,
411 const std::string& location,
412 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800413 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700414 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800415 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700416 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800417 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800420 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700421 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800422 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700423}
424
Ian Rogers13735952014-10-08 12:43:28 -0700425DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800426 const std::string& location,
427 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800428 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700429 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800430 : begin_(base),
431 size_(size),
432 location_(location),
433 location_checksum_(location_checksum),
434 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800435 header_(reinterpret_cast<const Header*>(base)),
436 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
437 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
438 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
439 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
440 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700441 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700442 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700443 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800444 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300445 const uint8_t* lookup_data = (oat_dex_file != nullptr)
446 ? oat_dex_file->GetLookupTableData()
447 : nullptr;
448 if (lookup_data != nullptr) {
449 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
450 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
451 } else {
452 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
453 }
454 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800455}
456
Jesse Wilson6bf19152011-09-29 13:12:33 -0400457DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700458 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
459 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
460 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
461 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400462}
463
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700464bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700465 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700466 return false;
467 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700468 return true;
469}
470
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700471bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800472 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700473 std::ostringstream oss;
474 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800475 << " " << header_->magic_[0]
476 << " " << header_->magic_[1]
477 << " " << header_->magic_[2]
478 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700479 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700480 return false;
481 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800482 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700483 std::ostringstream oss;
484 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800485 << " " << header_->magic_[4]
486 << " " << header_->magic_[5]
487 << " " << header_->magic_[6]
488 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700489 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700490 return false;
491 }
492 return true;
493}
494
Ian Rogers13735952014-10-08 12:43:28 -0700495bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800496 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
497}
498
Ian Rogers13735952014-10-08 12:43:28 -0700499bool DexFile::IsVersionValid(const uint8_t* magic) {
500 const uint8_t* version = &magic[sizeof(kDexMagic)];
Alex Lightc4961812016-03-23 10:20:41 -0700501 for (uint32_t i = 0; i < kNumDexVersions; i++) {
502 if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
503 return true;
504 }
505 }
506 return false;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800507}
508
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700509uint32_t DexFile::Header::GetVersion() const {
510 const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700511 return atoi(version);
512}
513
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800514const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
515 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300516 if (LIKELY(lookup_table_ != nullptr)) {
517 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
518 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700519 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300520
Ian Rogers68b56852014-08-29 20:19:11 -0700521 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300522 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700523 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700524 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700525 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300526 const TypeId* type_id = FindTypeId(descriptor);
527 if (type_id != nullptr) {
528 uint16_t type_idx = GetIndexForTypeId(*type_id);
529 for (size_t i = 0; i < num_class_defs; ++i) {
530 const ClassDef& class_def = GetClassDef(i);
531 if (class_def.class_idx_ == type_idx) {
532 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700533 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700534 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700535 }
Ian Rogers68b56852014-08-29 20:19:11 -0700536 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700537}
538
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700539const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
540 size_t num_class_defs = NumClassDefs();
541 for (size_t i = 0; i < num_class_defs; ++i) {
542 const ClassDef& class_def = GetClassDef(i);
543 if (class_def.class_idx_ == type_idx) {
544 return &class_def;
545 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700546 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700547 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700548}
549
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800550const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
551 const DexFile::StringId& name,
552 const DexFile::TypeId& type) const {
553 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
554 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
555 const uint32_t name_idx = GetIndexForStringId(name);
556 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700557 int32_t lo = 0;
558 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800559 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700560 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800561 const DexFile::FieldId& field = GetFieldId(mid);
562 if (class_idx > field.class_idx_) {
563 lo = mid + 1;
564 } else if (class_idx < field.class_idx_) {
565 hi = mid - 1;
566 } else {
567 if (name_idx > field.name_idx_) {
568 lo = mid + 1;
569 } else if (name_idx < field.name_idx_) {
570 hi = mid - 1;
571 } else {
572 if (type_idx > field.type_idx_) {
573 lo = mid + 1;
574 } else if (type_idx < field.type_idx_) {
575 hi = mid - 1;
576 } else {
577 return &field;
578 }
579 }
580 }
581 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700582 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800583}
584
585const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700586 const DexFile::StringId& name,
587 const DexFile::ProtoId& signature) const {
588 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800589 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700590 const uint32_t name_idx = GetIndexForStringId(name);
591 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t lo = 0;
593 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700594 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700595 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700596 const DexFile::MethodId& method = GetMethodId(mid);
597 if (class_idx > method.class_idx_) {
598 lo = mid + 1;
599 } else if (class_idx < method.class_idx_) {
600 hi = mid - 1;
601 } else {
602 if (name_idx > method.name_idx_) {
603 lo = mid + 1;
604 } else if (name_idx < method.name_idx_) {
605 hi = mid - 1;
606 } else {
607 if (proto_idx > method.proto_idx_) {
608 lo = mid + 1;
609 } else if (proto_idx < method.proto_idx_) {
610 hi = mid - 1;
611 } else {
612 return &method;
613 }
614 }
615 }
616 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700617 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700618}
619
Ian Rogers637c65b2013-05-31 11:46:00 -0700620const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700621 int32_t lo = 0;
622 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700623 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700624 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700625 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700626 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700627 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
628 if (compare > 0) {
629 lo = mid + 1;
630 } else if (compare < 0) {
631 hi = mid - 1;
632 } else {
633 return &str_id;
634 }
635 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700637}
638
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300639const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
640 int32_t lo = 0;
641 int32_t hi = NumTypeIds() - 1;
642 while (hi >= lo) {
643 int32_t mid = (hi + lo) / 2;
644 const TypeId& type_id = GetTypeId(mid);
645 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
646 const char* str = GetStringData(str_id);
647 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
648 if (compare > 0) {
649 lo = mid + 1;
650 } else if (compare < 0) {
651 hi = mid - 1;
652 } else {
653 return &type_id;
654 }
655 }
656 return nullptr;
657}
658
Vladimir Markoa48aef42014-12-03 17:53:53 +0000659const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700660 int32_t lo = 0;
661 int32_t hi = NumStringIds() - 1;
662 while (hi >= lo) {
663 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700664 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700665 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000666 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700667 if (compare > 0) {
668 lo = mid + 1;
669 } else if (compare < 0) {
670 hi = mid - 1;
671 } else {
672 return &str_id;
673 }
674 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700675 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700676}
677
678const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700679 int32_t lo = 0;
680 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700681 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700682 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700683 const TypeId& type_id = GetTypeId(mid);
684 if (string_idx > type_id.descriptor_idx_) {
685 lo = mid + 1;
686 } else if (string_idx < type_id.descriptor_idx_) {
687 hi = mid - 1;
688 } else {
689 return &type_id;
690 }
691 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700692 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700693}
694
695const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000696 const uint16_t* signature_type_idxs,
697 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700698 int32_t lo = 0;
699 int32_t hi = NumProtoIds() - 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 DexFile::ProtoId& proto = GetProtoId(mid);
703 int compare = return_type_idx - proto.return_type_idx_;
704 if (compare == 0) {
705 DexFileParameterIterator it(*this, proto);
706 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000707 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800708 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700709 it.Next();
710 i++;
711 }
712 if (compare == 0) {
713 if (it.HasNext()) {
714 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000715 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700716 compare = 1;
717 }
718 }
719 }
720 if (compare > 0) {
721 lo = mid + 1;
722 } else if (compare < 0) {
723 hi = mid - 1;
724 } else {
725 return &proto;
726 }
727 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700729}
730
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000731void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
732 lookup_table_.reset(TypeLookupTable::Create(*this, storage));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300733}
734
Ian Rogers0571d352011-11-03 19:51:38 -0700735// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700736bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
737 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700738 if (signature[0] != '(') {
739 return false;
740 }
741 size_t offset = 1;
742 size_t end = signature.size();
743 bool process_return = false;
744 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000745 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700746 char c = signature[offset];
747 offset++;
748 if (c == ')') {
749 process_return = true;
750 continue;
751 }
Ian Rogers0571d352011-11-03 19:51:38 -0700752 while (c == '[') { // process array prefix
753 if (offset >= end) { // expect some descriptor following [
754 return false;
755 }
756 c = signature[offset];
757 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700758 }
759 if (c == 'L') { // process type descriptors
760 do {
761 if (offset >= end) { // unexpected early termination of descriptor
762 return false;
763 }
764 c = signature[offset];
765 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700766 } while (c != ';');
767 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000768 // TODO: avoid creating a std::string just to get a 0-terminated char array
769 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700770 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700772 return false;
773 }
774 uint16_t type_idx = GetIndexForTypeId(*type_id);
775 if (!process_return) {
776 param_type_idxs->push_back(type_idx);
777 } else {
778 *return_type_idx = type_idx;
779 return offset == end; // return true if the signature had reached a sensible end
780 }
781 }
782 return false; // failed to correctly parse return type
783}
784
Ian Rogersd91d6d62013-09-25 20:26:14 -0700785const Signature DexFile::CreateSignature(const StringPiece& signature) const {
786 uint16_t return_type_idx;
787 std::vector<uint16_t> param_type_indices;
788 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
789 if (!success) {
790 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700791 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700792 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700793 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700794 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700795 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700796 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700797}
798
Mathieu Chartiere401d142015-04-22 13:56:20 -0700799int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700800 // For native method, lineno should be -2 to indicate it is native. Note that
801 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700803 return -2;
804 }
805
TDYa127c8dc1012012-04-19 07:03:33 -0700806 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700807 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700808
809 // A method with no line number info should return -1
810 LineNumFromPcContext context(rel_pc, -1);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000811 DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700812 return context.line_num_;
813}
814
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700815int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700816 // Note: Signed type is important for max and min.
817 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700818 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700819
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700820 while (min <= max) {
821 int32_t mid = min + ((max - min) / 2);
822
823 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
824 uint32_t start = ti->start_addr_;
825 uint32_t end = start + ti->insn_count_;
826
Ian Rogers0571d352011-11-03 19:51:38 -0700827 if (address < start) {
828 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700829 } else if (address >= end) {
830 min = mid + 1;
831 } else { // We have a winner!
832 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700833 }
834 }
835 // No match.
836 return -1;
837}
838
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700839int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
840 int32_t try_item = FindTryItem(code_item, address);
841 if (try_item == -1) {
842 return -1;
843 } else {
844 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
845 }
846}
847
David Srbeckyb06e28e2015-12-10 13:15:00 +0000848bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
849 DexDebugNewLocalCb local_cb, void* context) const {
850 DCHECK(local_cb != nullptr);
851 if (code_item == nullptr) {
852 return false;
853 }
854 const uint8_t* stream = GetDebugInfoStream(code_item);
855 if (stream == nullptr) {
856 return false;
857 }
858 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700859
David Srbeckyb06e28e2015-12-10 13:15:00 +0000860 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000862 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
863 local_in_reg[arg_reg].name_ = "this";
864 local_in_reg[arg_reg].descriptor_ = descriptor;
865 local_in_reg[arg_reg].signature_ = nullptr;
866 local_in_reg[arg_reg].start_address_ = 0;
867 local_in_reg[arg_reg].reg_ = arg_reg;
868 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700869 arg_reg++;
870 }
871
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800872 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000873 DecodeUnsignedLeb128(&stream); // Line.
874 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
875 uint32_t i;
876 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700877 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700878 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800879 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000880 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700881 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000882 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700883 const char* descriptor = it.GetDescriptor();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000884 local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
885 local_in_reg[arg_reg].descriptor_ = descriptor;
886 local_in_reg[arg_reg].signature_ = nullptr;
887 local_in_reg[arg_reg].start_address_ = 0;
888 local_in_reg[arg_reg].reg_ = arg_reg;
889 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700890 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700891 case 'D':
892 case 'J':
893 arg_reg += 2;
894 break;
895 default:
896 arg_reg += 1;
897 break;
898 }
899 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000900 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800901 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
902 << " for method " << PrettyMethod(method_idx, *this);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000903 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700904 }
905
David Srbeckyb06e28e2015-12-10 13:15:00 +0000906 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700907 for (;;) {
908 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700909 switch (opcode) {
910 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000911 // Emit all variables which are still alive at the end of the method.
912 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
913 if (local_in_reg[reg].is_live_) {
914 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
915 local_cb(context, local_in_reg[reg]);
916 }
917 }
918 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700919 case DBG_ADVANCE_PC:
920 address += DecodeUnsignedLeb128(&stream);
921 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000923 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700924 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700925 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000926 case DBG_START_LOCAL_EXTENDED: {
927 uint16_t reg = DecodeUnsignedLeb128(&stream);
928 if (reg >= code_item->registers_size_) {
929 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800930 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000931 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700932 }
933
David Srbeckyb06e28e2015-12-10 13:15:00 +0000934 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
935 uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
936 uint32_t signature_idx = kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700937 if (opcode == DBG_START_LOCAL_EXTENDED) {
938 signature_idx = DecodeUnsignedLeb128P1(&stream);
939 }
940
Shih-wei Liao195487c2011-08-20 13:29:04 -0700941 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000942 if (local_in_reg[reg].is_live_) {
943 local_in_reg[reg].end_address_ = address;
944 local_cb(context, local_in_reg[reg]);
945 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700946
David Srbeckyb06e28e2015-12-10 13:15:00 +0000947 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
948 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
949 local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
950 local_in_reg[reg].start_address_ = address;
951 local_in_reg[reg].reg_ = reg;
952 local_in_reg[reg].is_live_ = true;
953 break;
954 }
955 case DBG_END_LOCAL: {
956 uint16_t reg = DecodeUnsignedLeb128(&stream);
957 if (reg >= code_item->registers_size_) {
958 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
959 << code_item->registers_size_ << ") in " << GetLocation();
960 return false;
961 }
962 if (!local_in_reg[reg].is_live_) {
963 LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
964 return false;
965 }
966 local_in_reg[reg].end_address_ = address;
967 local_cb(context, local_in_reg[reg]);
968 local_in_reg[reg].is_live_ = false;
969 break;
970 }
971 case DBG_RESTART_LOCAL: {
972 uint16_t reg = DecodeUnsignedLeb128(&stream);
973 if (reg >= code_item->registers_size_) {
974 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
975 << code_item->registers_size_ << ") in " << GetLocation();
976 return false;
977 }
978 // If the register is live, the "restart" is superfluous,
979 // and we don't want to mess with the existing start address.
980 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700981 local_in_reg[reg].start_address_ = address;
982 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700983 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700984 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000985 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700986 case DBG_SET_PROLOGUE_END:
987 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700988 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000989 case DBG_SET_FILE:
990 DecodeUnsignedLeb128P1(&stream); // name.
991 break;
992 default:
993 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
994 break;
995 }
996 }
997}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700998
David Srbeckyb06e28e2015-12-10 13:15:00 +0000999bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1000 void* context) const {
1001 DCHECK(position_cb != nullptr);
1002 if (code_item == nullptr) {
1003 return false;
1004 }
1005 const uint8_t* stream = GetDebugInfoStream(code_item);
1006 if (stream == nullptr) {
1007 return false;
1008 }
1009
1010 PositionInfo entry = PositionInfo();
1011 entry.line_ = DecodeUnsignedLeb128(&stream);
1012 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1013 for (uint32_t i = 0; i < parameters_size; ++i) {
1014 DecodeUnsignedLeb128P1(&stream); // Parameter name.
1015 }
1016
1017 for (;;) {
1018 uint8_t opcode = *stream++;
1019 switch (opcode) {
1020 case DBG_END_SEQUENCE:
1021 return true; // end of stream.
1022 case DBG_ADVANCE_PC:
1023 entry.address_ += DecodeUnsignedLeb128(&stream);
1024 break;
1025 case DBG_ADVANCE_LINE:
1026 entry.line_ += DecodeSignedLeb128(&stream);
1027 break;
1028 case DBG_START_LOCAL:
1029 DecodeUnsignedLeb128(&stream); // reg.
1030 DecodeUnsignedLeb128P1(&stream); // name.
1031 DecodeUnsignedLeb128P1(&stream); // descriptor.
1032 break;
1033 case DBG_START_LOCAL_EXTENDED:
1034 DecodeUnsignedLeb128(&stream); // reg.
1035 DecodeUnsignedLeb128P1(&stream); // name.
1036 DecodeUnsignedLeb128P1(&stream); // descriptor.
1037 DecodeUnsignedLeb128P1(&stream); // signature.
1038 break;
1039 case DBG_END_LOCAL:
1040 case DBG_RESTART_LOCAL:
1041 DecodeUnsignedLeb128(&stream); // reg.
1042 break;
1043 case DBG_SET_PROLOGUE_END:
1044 entry.prologue_end_ = true;
1045 break;
1046 case DBG_SET_EPILOGUE_BEGIN:
1047 entry.epilogue_begin_ = true;
1048 break;
1049 case DBG_SET_FILE: {
1050 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1051 entry.source_file_ = StringDataByIdx(name_idx);
1052 break;
1053 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001054 default: {
1055 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +00001056 entry.address_ += adjopcode / DBG_LINE_RANGE;
1057 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1058 if (position_cb(context, entry)) {
1059 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -07001060 }
David Srbeckyb06e28e2015-12-10 13:15:00 +00001061 entry.prologue_end_ = false;
1062 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -07001063 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -07001064 }
Shih-wei Liao195487c2011-08-20 13:29:04 -07001065 }
1066 }
1067}
1068
David Srbeckyb06e28e2015-12-10 13:15:00 +00001069bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -08001070 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001071
1072 // We know that this callback will be called in
1073 // ascending address order, so keep going until we find
1074 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +00001075 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -07001076 // The line number from the previous positions callback
1077 // wil be the final result.
1078 return true;
1079 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +00001080 context->line_num_ = entry.line_;
1081 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -07001082 }
1083}
1084
Andreas Gampe833a4852014-05-21 18:46:59 -07001085bool DexFile::IsMultiDexLocation(const char* location) {
1086 return strrchr(location, kMultiDexSeparator) != nullptr;
1087}
1088
Andreas Gampe90e34042015-04-27 20:01:52 -07001089std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1090 if (index == 0) {
1091 return "classes.dex";
1092 } else {
1093 return StringPrintf("classes%zu.dex", index + 1);
1094 }
1095}
1096
1097std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1098 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001099 return dex_location;
1100 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001101 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001102 }
1103}
1104
1105std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1106 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001107 std::string base_location = GetBaseLocation(dex_location);
1108 const char* suffix = dex_location + base_location.size();
1109 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1110 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1111 if (path != nullptr && path.get() != base_location) {
1112 return std::string(path.get()) + suffix;
1113 } else if (suffix[0] == 0) {
1114 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001115 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001116 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001117 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001118}
1119
Jeff Hao13e748b2015-08-25 20:44:19 +00001120// Read a signed integer. "zwidth" is the zero-based byte count.
1121static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1122 int32_t val = 0;
1123 for (int i = zwidth; i >= 0; --i) {
1124 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1125 }
1126 val >>= (3 - zwidth) * 8;
1127 return val;
1128}
1129
1130// Read an unsigned integer. "zwidth" is the zero-based byte count,
1131// "fill_on_right" indicates which side we want to zero-fill from.
1132static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1133 uint32_t val = 0;
1134 for (int i = zwidth; i >= 0; --i) {
1135 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1136 }
1137 if (!fill_on_right) {
1138 val >>= (3 - zwidth) * 8;
1139 }
1140 return val;
1141}
1142
1143// Read a signed long. "zwidth" is the zero-based byte count.
1144static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1145 int64_t val = 0;
1146 for (int i = zwidth; i >= 0; --i) {
1147 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1148 }
1149 val >>= (7 - zwidth) * 8;
1150 return val;
1151}
1152
1153// Read an unsigned long. "zwidth" is the zero-based byte count,
1154// "fill_on_right" indicates which side we want to zero-fill from.
1155static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1156 uint64_t val = 0;
1157 for (int i = zwidth; i >= 0; --i) {
1158 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1159 }
1160 if (!fill_on_right) {
1161 val >>= (7 - zwidth) * 8;
1162 }
1163 return val;
1164}
1165
Jeff Hao7e50a7a2016-05-26 18:39:17 -07001166// Checks that visibility is as expected. Includes special behavior for M and
1167// before to allow runtime and build visibility when expecting runtime.
1168static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1169 if (expected == DexFile::kDexVisibilityRuntime) {
1170 int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1171 if (sdk_version > 0 && sdk_version <= 23) {
1172 return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1173 }
1174 }
1175 return actual == expected;
1176}
1177
Jeff Hao13e748b2015-08-25 20:44:19 +00001178const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1179 mirror::Class* klass = field->GetDeclaringClass();
1180 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1181 if (annotations_dir == nullptr) {
1182 return nullptr;
1183 }
1184 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1185 if (field_annotations == nullptr) {
1186 return nullptr;
1187 }
1188 uint32_t field_index = field->GetDexFieldIndex();
1189 uint32_t field_count = annotations_dir->fields_size_;
1190 for (uint32_t i = 0; i < field_count; ++i) {
1191 if (field_annotations[i].field_idx_ == field_index) {
1192 return GetFieldAnnotationSetItem(field_annotations[i]);
1193 }
1194 }
1195 return nullptr;
1196}
1197
1198mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1199 Handle<mirror::Class> annotation_class) const {
1200 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1201 if (annotation_set == nullptr) {
1202 return nullptr;
1203 }
1204 StackHandleScope<1> hs(Thread::Current());
1205 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1206 return GetAnnotationObjectFromAnnotationSet(
1207 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1208}
1209
1210mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1211 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1212 StackHandleScope<1> hs(Thread::Current());
1213 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1214 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1215}
1216
Jeff Hao2a5892f2015-08-31 15:00:40 -07001217mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001218 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 GetSignatureValue(field_class, annotation_set);
1226}
1227
1228bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1229 const {
1230 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1231 if (annotation_set == nullptr) {
1232 return false;
1233 }
1234 StackHandleScope<1> hs(Thread::Current());
1235 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1236 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1237 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1238 return annotation_item != nullptr;
1239}
1240
1241const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1242 mirror::Class* klass = method->GetDeclaringClass();
1243 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1244 if (annotations_dir == nullptr) {
1245 return nullptr;
1246 }
1247 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1248 if (method_annotations == nullptr) {
1249 return nullptr;
1250 }
1251 uint32_t method_index = method->GetDexMethodIndex();
1252 uint32_t method_count = annotations_dir->methods_size_;
1253 for (uint32_t i = 0; i < method_count; ++i) {
1254 if (method_annotations[i].method_idx_ == method_index) {
1255 return GetMethodAnnotationSetItem(method_annotations[i]);
1256 }
1257 }
1258 return nullptr;
1259}
1260
1261const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1262 const {
1263 mirror::Class* klass = method->GetDeclaringClass();
1264 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1265 if (annotations_dir == nullptr) {
1266 return nullptr;
1267 }
1268 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1269 if (parameter_annotations == nullptr) {
1270 return nullptr;
1271 }
1272 uint32_t method_index = method->GetDexMethodIndex();
1273 uint32_t parameter_count = annotations_dir->parameters_size_;
1274 for (uint32_t i = 0; i < parameter_count; ++i) {
1275 if (parameter_annotations[i].method_idx_ == method_index) {
1276 return &parameter_annotations[i];
1277 }
1278 }
1279 return nullptr;
1280}
1281
1282mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1283 mirror::Class* klass = method->GetDeclaringClass();
1284 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1285 if (annotations_dir == nullptr) {
1286 return nullptr;
1287 }
1288 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1289 if (annotation_set == nullptr) {
1290 return nullptr;
1291 }
1292 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1293 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1294 if (annotation_item == nullptr) {
1295 return nullptr;
1296 }
1297 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1298 if (annotation == nullptr) {
1299 return nullptr;
1300 }
1301 uint8_t header_byte = *(annotation++);
1302 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1303 return nullptr;
1304 }
1305 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1306 if (annotation == nullptr) {
1307 return nullptr;
1308 }
1309 AnnotationValue annotation_value;
1310 StackHandleScope<2> hs(Thread::Current());
1311 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001312 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1313 Handle<mirror::Class> return_type(hs.NewHandle(
1314 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001315 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1316 return nullptr;
1317 }
1318 return annotation_value.value_.GetL();
1319}
1320
1321mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1322 Handle<mirror::Class> annotation_class) const {
1323 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1324 if (annotation_set == nullptr) {
1325 return nullptr;
1326 }
1327 StackHandleScope<1> hs(Thread::Current());
1328 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1329 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1330 kDexVisibilityRuntime, annotation_class);
1331}
1332
1333mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1334 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1335 StackHandleScope<1> hs(Thread::Current());
1336 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1337 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1338}
1339
Jeff Hao2a5892f2015-08-31 15:00:40 -07001340mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001341 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1342 if (annotation_set == nullptr) {
1343 return nullptr;
1344 }
1345 StackHandleScope<1> hs(Thread::Current());
1346 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1347 return GetThrowsValue(method_class, annotation_set);
1348}
1349
1350mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1351 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1352 if (parameter_annotations == nullptr) {
1353 return nullptr;
1354 }
1355 const AnnotationSetRefList* set_ref_list =
1356 GetParameterAnnotationSetRefList(parameter_annotations);
1357 if (set_ref_list == nullptr) {
1358 return nullptr;
1359 }
1360 uint32_t size = set_ref_list->size_;
1361 StackHandleScope<1> hs(Thread::Current());
1362 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1363 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1364}
1365
Jeff Hao08305322016-04-04 19:50:14 -07001366mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1367 const {
1368 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1369 if (annotation_set == nullptr) {
1370 return nullptr;
1371 }
1372 StackHandleScope<1> hs(Thread::Current());
1373 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1374 return GetSignatureValue(method_class, annotation_set);
1375}
1376
Jeff Hao13e748b2015-08-25 20:44:19 +00001377bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1378 const {
1379 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1380 if (annotation_set == nullptr) {
1381 return false;
1382 }
1383 StackHandleScope<1> hs(Thread::Current());
1384 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1385 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1386 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001387 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001388}
1389
1390const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1391 const {
1392 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1393 if (annotations_dir == nullptr) {
1394 return nullptr;
1395 }
1396 return GetClassAnnotationSet(annotations_dir);
1397}
1398
1399mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1400 Handle<mirror::Class> annotation_class) const {
1401 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1402 if (annotation_set == nullptr) {
1403 return nullptr;
1404 }
1405 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1406 annotation_class);
1407}
1408
1409mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1410 const {
1411 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1412 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1413}
1414
Jeff Hao2a5892f2015-08-31 15:00:40 -07001415mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1416 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1417 if (annotation_set == nullptr) {
1418 return nullptr;
1419 }
1420 const AnnotationItem* annotation_item = SearchAnnotationSet(
1421 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1422 if (annotation_item == nullptr) {
1423 return nullptr;
1424 }
1425 StackHandleScope<1> hs(Thread::Current());
1426 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1427 Handle<mirror::Class> class_array_class(hs.NewHandle(
1428 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1429 if (class_array_class.Get() == nullptr) {
1430 return nullptr;
1431 }
1432 mirror::Object* obj = GetAnnotationValue(
1433 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1434 if (obj == nullptr) {
1435 return nullptr;
1436 }
1437 return obj->AsObjectArray<mirror::Class>();
1438}
1439
1440mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1441 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1442 if (annotation_set == nullptr) {
1443 return nullptr;
1444 }
1445 const AnnotationItem* annotation_item = SearchAnnotationSet(
1446 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1447 if (annotation_item == nullptr) {
1448 return nullptr;
1449 }
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001450 mirror::Object* obj = GetAnnotationValue(klass,
1451 annotation_item,
1452 "value",
1453 ScopedNullHandle<mirror::Class>(),
1454 kDexAnnotationType);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001455 if (obj == nullptr) {
1456 return nullptr;
1457 }
1458 return obj->AsClass();
1459}
1460
1461mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1462 mirror::Class* declaring_class = GetDeclaringClass(klass);
1463 if (declaring_class != nullptr) {
1464 return declaring_class;
1465 }
1466 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1467 if (annotation_set == nullptr) {
1468 return nullptr;
1469 }
1470 const AnnotationItem* annotation_item = SearchAnnotationSet(
1471 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1472 if (annotation_item == nullptr) {
1473 return nullptr;
1474 }
1475 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1476 if (annotation == nullptr) {
1477 return nullptr;
1478 }
1479 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001480 if (!ProcessAnnotationValue(klass,
1481 &annotation,
1482 &annotation_value,
1483 ScopedNullHandle<mirror::Class>(),
1484 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001485 return nullptr;
1486 }
1487 if (annotation_value.type_ != kDexAnnotationMethod) {
1488 return nullptr;
1489 }
1490 StackHandleScope<2> hs(Thread::Current());
1491 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1492 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1493 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1494 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1495 if (method == nullptr) {
1496 return nullptr;
1497 }
1498 return method->GetDeclaringClass();
1499}
1500
1501mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1502 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1503 if (annotation_set == nullptr) {
1504 return nullptr;
1505 }
1506 const AnnotationItem* annotation_item = SearchAnnotationSet(
1507 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1508 if (annotation_item == nullptr) {
1509 return nullptr;
1510 }
1511 return GetAnnotationValue(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001512 klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001513}
1514
1515bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1516 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1517 if (annotation_set == nullptr) {
1518 return false;
1519 }
1520 const AnnotationItem* annotation_item = SearchAnnotationSet(
1521 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1522 if (annotation_item == nullptr) {
1523 return false;
1524 }
1525 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1526 if (annotation == nullptr) {
1527 return false;
1528 }
1529 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001530 if (!ProcessAnnotationValue(klass,
1531 &annotation,
1532 &annotation_value,
1533 ScopedNullHandle<mirror::Class>(),
1534 kAllObjects)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001535 return false;
1536 }
1537 if (annotation_value.type_ != kDexAnnotationNull &&
1538 annotation_value.type_ != kDexAnnotationString) {
1539 return false;
1540 }
1541 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1542 return true;
1543}
1544
1545bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1546 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1547 if (annotation_set == nullptr) {
1548 return false;
1549 }
1550 const AnnotationItem* annotation_item = SearchAnnotationSet(
1551 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1552 if (annotation_item == nullptr) {
1553 return false;
1554 }
1555 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1556 if (annotation == nullptr) {
1557 return false;
1558 }
1559 AnnotationValue annotation_value;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001560 if (!ProcessAnnotationValue(klass,
1561 &annotation,
1562 &annotation_value,
1563 ScopedNullHandle<mirror::Class>(),
1564 kAllRaw)) {
Jeff Hao2a5892f2015-08-31 15:00:40 -07001565 return false;
1566 }
1567 if (annotation_value.type_ != kDexAnnotationInt) {
1568 return false;
1569 }
1570 *flags = annotation_value.value_.GetI();
1571 return true;
1572}
1573
Jeff Hao08305322016-04-04 19:50:14 -07001574mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1575 Handle<mirror::Class> klass) const {
1576 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1577 if (annotation_set == nullptr) {
1578 return nullptr;
1579 }
1580 return GetSignatureValue(klass, annotation_set);
1581}
1582
Jeff Hao13e748b2015-08-25 20:44:19 +00001583bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1584 Handle<mirror::Class> annotation_class) const {
1585 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1586 if (annotation_set == nullptr) {
1587 return false;
1588 }
1589 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1590 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001591 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001592}
1593
1594mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1595 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1596 Thread* self = Thread::Current();
1597 ScopedObjectAccessUnchecked soa(self);
1598 StackHandleScope<5> hs(self);
1599 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1600 const char* name = StringDataByIdx(element_name_index);
1601 Handle<mirror::String> string_name(
1602 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1603
1604 ArtMethod* annotation_method =
1605 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1606 if (annotation_method == nullptr) {
1607 return nullptr;
1608 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001609 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1610 Handle<mirror::Class> method_return(hs.NewHandle(
1611 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001612
1613 AnnotationValue annotation_value;
1614 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1615 return nullptr;
1616 }
1617 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1618
1619 mirror::Class* annotation_member_class =
1620 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1621 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1622 Handle<mirror::Method> method_object(
1623 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1624
1625 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1626 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1627 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1628 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1629 return nullptr;
1630 }
1631
1632 JValue result;
1633 ArtMethod* annotation_member_init =
1634 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1635 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1636 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1637 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1638 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1639 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1640 };
1641 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1642 if (self->IsExceptionPending()) {
1643 LOG(INFO) << "Exception in AnnotationMember.<init>";
1644 return nullptr;
1645 }
1646
1647 return new_member.Get();
1648}
1649
1650const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1651 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1652 Handle<mirror::Class> annotation_class) const {
1653 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1654 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao7e50a7a2016-05-26 18:39:17 -07001655 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00001656 continue;
1657 }
1658 const uint8_t* annotation = annotation_item->annotation_;
1659 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1660 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1661 klass->GetDexFile(), type_index, klass.Get());
1662 if (resolved_class == nullptr) {
1663 std::string temp;
1664 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1665 klass->GetDescriptor(&temp), type_index);
1666 CHECK(Thread::Current()->IsExceptionPending());
1667 Thread::Current()->ClearException();
1668 continue;
1669 }
1670 if (resolved_class == annotation_class.Get()) {
1671 return annotation_item;
1672 }
1673 }
1674
1675 return nullptr;
1676}
1677
1678mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1679 const AnnotationSetItem* annotation_set, uint32_t visibility,
1680 Handle<mirror::Class> annotation_class) const {
1681 const AnnotationItem* annotation_item =
1682 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1683 if (annotation_item == nullptr) {
1684 return nullptr;
1685 }
1686 const uint8_t* annotation = annotation_item->annotation_;
1687 return ProcessEncodedAnnotation(klass, &annotation);
1688}
1689
1690mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1691 const AnnotationItem* annotation_item, const char* annotation_name,
1692 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1693 const uint8_t* annotation =
1694 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1695 if (annotation == nullptr) {
1696 return nullptr;
1697 }
1698 AnnotationValue annotation_value;
1699 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1700 return nullptr;
1701 }
1702 if (annotation_value.type_ != expected_type) {
1703 return nullptr;
1704 }
1705 return annotation_value.value_.GetL();
1706}
1707
Jeff Hao2a5892f2015-08-31 15:00:40 -07001708mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001709 const AnnotationSetItem* annotation_set) const {
1710 StackHandleScope<1> hs(Thread::Current());
1711 const AnnotationItem* annotation_item =
1712 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1713 if (annotation_item == nullptr) {
1714 return nullptr;
1715 }
1716 mirror::Class* string_class = mirror::String::GetJavaLangString();
1717 Handle<mirror::Class> string_array_class(hs.NewHandle(
1718 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001719 if (string_array_class.Get() == nullptr) {
1720 return nullptr;
1721 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001722 mirror::Object* obj =
1723 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1724 if (obj == nullptr) {
1725 return nullptr;
1726 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001727 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001728}
1729
Jeff Hao2a5892f2015-08-31 15:00:40 -07001730mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001731 const AnnotationSetItem* annotation_set) const {
1732 StackHandleScope<1> hs(Thread::Current());
1733 const AnnotationItem* annotation_item =
1734 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1735 if (annotation_item == nullptr) {
1736 return nullptr;
1737 }
1738 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1739 Handle<mirror::Class> class_array_class(hs.NewHandle(
1740 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001741 if (class_array_class.Get() == nullptr) {
1742 return nullptr;
1743 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001744 mirror::Object* obj =
1745 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1746 if (obj == nullptr) {
1747 return nullptr;
1748 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001749 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001750}
1751
1752mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1753 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1754 Thread* self = Thread::Current();
1755 ScopedObjectAccessUnchecked soa(self);
1756 StackHandleScope<2> hs(self);
1757 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1758 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1759 if (annotation_set == nullptr) {
1760 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1761 }
1762
1763 uint32_t size = annotation_set->size_;
1764 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1765 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1766 if (result.Get() == nullptr) {
1767 return nullptr;
1768 }
1769
1770 uint32_t dest_index = 0;
1771 for (uint32_t i = 0; i < size; ++i) {
1772 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao7e50a7a2016-05-26 18:39:17 -07001773 // Note that we do not use IsVisibilityCompatible here because older code
1774 // was correct for this case.
Jeff Hao13e748b2015-08-25 20:44:19 +00001775 if (annotation_item->visibility_ != visibility) {
1776 continue;
1777 }
1778 const uint8_t* annotation = annotation_item->annotation_;
1779 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1780 if (annotation_obj != nullptr) {
1781 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1782 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001783 } else if (self->IsExceptionPending()) {
1784 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001785 }
1786 }
1787
1788 if (dest_index == size) {
1789 return result.Get();
1790 }
1791
1792 mirror::ObjectArray<mirror::Object>* trimmed_result =
1793 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001794 if (trimmed_result == nullptr) {
1795 return nullptr;
1796 }
1797
Jeff Hao13e748b2015-08-25 20:44:19 +00001798 for (uint32_t i = 0; i < dest_index; ++i) {
1799 mirror::Object* obj = result->GetWithoutChecks(i);
1800 trimmed_result->SetWithoutChecks<false>(i, obj);
1801 }
1802
1803 return trimmed_result;
1804}
1805
1806mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1807 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1808 Thread* self = Thread::Current();
1809 ScopedObjectAccessUnchecked soa(self);
1810 StackHandleScope<1> hs(self);
1811 mirror::Class* annotation_array_class =
1812 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1813 mirror::Class* annotation_array_array_class =
1814 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001815 if (annotation_array_array_class == nullptr) {
1816 return nullptr;
1817 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001818 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1819 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1820 if (annotation_array_array.Get() == nullptr) {
1821 LOG(ERROR) << "Annotation set ref array allocation failed";
1822 return nullptr;
1823 }
1824 for (uint32_t index = 0; index < size; ++index) {
1825 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1826 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1827 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1828 if (annotation_set == nullptr) {
1829 return nullptr;
1830 }
1831 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1832 }
1833 return annotation_array_array.Get();
1834}
1835
1836bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1837 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1838 DexFile::AnnotationResultStyle result_style) const {
1839 Thread* self = Thread::Current();
1840 mirror::Object* element_object = nullptr;
1841 bool set_object = false;
1842 Primitive::Type primitive_type = Primitive::kPrimVoid;
1843 const uint8_t* annotation = *annotation_ptr;
1844 uint8_t header_byte = *(annotation++);
1845 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1846 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1847 int32_t width = value_arg + 1;
1848 annotation_value->type_ = value_type;
1849
1850 switch (value_type) {
1851 case kDexAnnotationByte:
1852 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1853 primitive_type = Primitive::kPrimByte;
1854 break;
1855 case kDexAnnotationShort:
1856 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1857 primitive_type = Primitive::kPrimShort;
1858 break;
1859 case kDexAnnotationChar:
1860 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1861 false)));
1862 primitive_type = Primitive::kPrimChar;
1863 break;
1864 case kDexAnnotationInt:
1865 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1866 primitive_type = Primitive::kPrimInt;
1867 break;
1868 case kDexAnnotationLong:
1869 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1870 primitive_type = Primitive::kPrimLong;
1871 break;
1872 case kDexAnnotationFloat:
1873 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1874 primitive_type = Primitive::kPrimFloat;
1875 break;
1876 case kDexAnnotationDouble:
1877 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1878 primitive_type = Primitive::kPrimDouble;
1879 break;
1880 case kDexAnnotationBoolean:
1881 annotation_value->value_.SetZ(value_arg != 0);
1882 primitive_type = Primitive::kPrimBoolean;
1883 width = 0;
1884 break;
1885 case kDexAnnotationString: {
1886 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1887 if (result_style == kAllRaw) {
1888 annotation_value->value_.SetI(index);
1889 } else {
1890 StackHandleScope<1> hs(self);
1891 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1892 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1893 klass->GetDexFile(), index, dex_cache);
1894 set_object = true;
1895 if (element_object == nullptr) {
1896 return false;
1897 }
1898 }
1899 break;
1900 }
1901 case kDexAnnotationType: {
1902 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1903 if (result_style == kAllRaw) {
1904 annotation_value->value_.SetI(index);
1905 } else {
1906 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1907 klass->GetDexFile(), index, klass.Get());
1908 set_object = true;
1909 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001910 CHECK(self->IsExceptionPending());
1911 if (result_style == kAllObjects) {
1912 const char* msg = StringByTypeIdx(index);
1913 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1914 element_object = self->GetException();
1915 self->ClearException();
1916 } else {
1917 return false;
1918 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001919 }
1920 }
1921 break;
1922 }
1923 case kDexAnnotationMethod: {
1924 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1925 if (result_style == kAllRaw) {
1926 annotation_value->value_.SetI(index);
1927 } else {
1928 StackHandleScope<2> hs(self);
1929 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1930 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1931 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1932 klass->GetDexFile(), index, dex_cache, class_loader);
1933 if (method == nullptr) {
1934 return false;
1935 }
1936 set_object = true;
1937 if (method->IsConstructor()) {
1938 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1939 } else {
1940 element_object = mirror::Method::CreateFromArtMethod(self, method);
1941 }
1942 if (element_object == nullptr) {
1943 return false;
1944 }
1945 }
1946 break;
1947 }
1948 case kDexAnnotationField: {
1949 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1950 if (result_style == kAllRaw) {
1951 annotation_value->value_.SetI(index);
1952 } else {
1953 StackHandleScope<2> hs(self);
1954 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1955 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1956 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1957 klass->GetDexFile(), index, dex_cache, class_loader);
1958 if (field == nullptr) {
1959 return false;
1960 }
1961 set_object = true;
1962 element_object = mirror::Field::CreateFromArtField(self, field, true);
1963 if (element_object == nullptr) {
1964 return false;
1965 }
1966 }
1967 break;
1968 }
1969 case kDexAnnotationEnum: {
1970 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1971 if (result_style == kAllRaw) {
1972 annotation_value->value_.SetI(index);
1973 } else {
1974 StackHandleScope<3> hs(self);
1975 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1976 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1977 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1978 klass->GetDexFile(), index, dex_cache, class_loader, true);
Jeff Hao13e748b2015-08-25 20:44:19 +00001979 if (enum_field == nullptr) {
1980 return false;
1981 } else {
Jeff Haod297b552015-11-20 14:56:09 -08001982 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
Jeff Hao13e748b2015-08-25 20:44:19 +00001983 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1984 element_object = enum_field->GetObject(field_class.Get());
1985 set_object = true;
1986 }
1987 }
1988 break;
1989 }
1990 case kDexAnnotationArray:
1991 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1992 return false;
1993 } else {
1994 ScopedObjectAccessUnchecked soa(self);
1995 StackHandleScope<2> hs(self);
1996 uint32_t size = DecodeUnsignedLeb128(&annotation);
1997 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1998 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1999 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2000 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2001 if (new_array.Get() == nullptr) {
2002 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2003 return false;
2004 }
2005 AnnotationValue new_annotation_value;
2006 for (uint32_t i = 0; i < size; ++i) {
2007 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2008 kPrimitivesOrObjects)) {
2009 return false;
2010 }
2011 if (!component_type->IsPrimitive()) {
2012 mirror::Object* obj = new_annotation_value.value_.GetL();
2013 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2014 } else {
2015 switch (new_annotation_value.type_) {
2016 case kDexAnnotationByte:
2017 new_array->AsByteArray()->SetWithoutChecks<false>(
2018 i, new_annotation_value.value_.GetB());
2019 break;
2020 case kDexAnnotationShort:
2021 new_array->AsShortArray()->SetWithoutChecks<false>(
2022 i, new_annotation_value.value_.GetS());
2023 break;
2024 case kDexAnnotationChar:
2025 new_array->AsCharArray()->SetWithoutChecks<false>(
2026 i, new_annotation_value.value_.GetC());
2027 break;
2028 case kDexAnnotationInt:
2029 new_array->AsIntArray()->SetWithoutChecks<false>(
2030 i, new_annotation_value.value_.GetI());
2031 break;
2032 case kDexAnnotationLong:
2033 new_array->AsLongArray()->SetWithoutChecks<false>(
2034 i, new_annotation_value.value_.GetJ());
2035 break;
2036 case kDexAnnotationFloat:
2037 new_array->AsFloatArray()->SetWithoutChecks<false>(
2038 i, new_annotation_value.value_.GetF());
2039 break;
2040 case kDexAnnotationDouble:
2041 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2042 i, new_annotation_value.value_.GetD());
2043 break;
2044 case kDexAnnotationBoolean:
2045 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2046 i, new_annotation_value.value_.GetZ());
2047 break;
2048 default:
2049 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2050 return false;
2051 }
2052 }
2053 }
2054 element_object = new_array.Get();
2055 set_object = true;
2056 width = 0;
2057 }
2058 break;
2059 case kDexAnnotationAnnotation:
2060 if (result_style == kAllRaw) {
2061 return false;
2062 }
2063 element_object = ProcessEncodedAnnotation(klass, &annotation);
2064 if (element_object == nullptr) {
2065 return false;
2066 }
2067 set_object = true;
2068 width = 0;
2069 break;
2070 case kDexAnnotationNull:
2071 if (result_style == kAllRaw) {
2072 annotation_value->value_.SetI(0);
2073 } else {
2074 CHECK(element_object == nullptr);
2075 set_object = true;
2076 }
2077 width = 0;
2078 break;
2079 default:
2080 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2081 return false;
2082 }
2083
2084 annotation += width;
2085 *annotation_ptr = annotation;
2086
2087 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2088 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2089 set_object = true;
2090 }
2091
2092 if (set_object) {
2093 annotation_value->value_.SetL(element_object);
2094 }
2095
2096 return true;
2097}
2098
2099mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2100 const uint8_t** annotation) const {
2101 uint32_t type_index = DecodeUnsignedLeb128(annotation);
2102 uint32_t size = DecodeUnsignedLeb128(annotation);
2103
2104 Thread* self = Thread::Current();
2105 ScopedObjectAccessUnchecked soa(self);
2106 StackHandleScope<2> hs(self);
2107 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2108 Handle<mirror::Class> annotation_class(hs.NewHandle(
2109 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2110 if (annotation_class.Get() == nullptr) {
2111 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2112 << type_index;
2113 DCHECK(Thread::Current()->IsExceptionPending());
2114 Thread::Current()->ClearException();
2115 return nullptr;
2116 }
2117
2118 mirror::Class* annotation_member_class =
2119 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2120 mirror::Class* annotation_member_array_class =
2121 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002122 if (annotation_member_array_class == nullptr) {
2123 return nullptr;
2124 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002125 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002126 if (size > 0) {
2127 element_array =
2128 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2129 if (element_array == nullptr) {
2130 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2131 return nullptr;
2132 }
2133 }
2134
2135 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2136 for (uint32_t i = 0; i < size; ++i) {
2137 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2138 if (new_member == nullptr) {
2139 return nullptr;
2140 }
2141 h_element_array->SetWithoutChecks<false>(i, new_member);
2142 }
2143
2144 JValue result;
2145 ArtMethod* create_annotation_method =
2146 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2147 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2148 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2149 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2150 if (self->IsExceptionPending()) {
2151 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2152 return nullptr;
2153 }
2154
2155 return result.GetL();
2156}
2157
2158const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2159 const char* descriptor, uint32_t visibility) const {
2160 const AnnotationItem* result = nullptr;
2161 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2162 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
Jeff Hao7e50a7a2016-05-26 18:39:17 -07002163 if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
Jeff Hao13e748b2015-08-25 20:44:19 +00002164 continue;
2165 }
2166 const uint8_t* annotation = annotation_item->annotation_;
2167 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2168
2169 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2170 result = annotation_item;
2171 break;
2172 }
2173 }
2174 return result;
2175}
2176
2177const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2178 DecodeUnsignedLeb128(&annotation); // unused type_index
2179 uint32_t size = DecodeUnsignedLeb128(&annotation);
2180
2181 while (size != 0) {
2182 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2183 const char* element_name = GetStringData(GetStringId(element_name_index));
2184 if (strcmp(name, element_name) == 0) {
2185 return annotation;
2186 }
2187 SkipAnnotationValue(&annotation);
2188 size--;
2189 }
2190 return nullptr;
2191}
2192
2193bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2194 const uint8_t* annotation = *annotation_ptr;
2195 uint8_t header_byte = *(annotation++);
2196 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2197 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2198 int32_t width = value_arg + 1;
2199
2200 switch (value_type) {
2201 case kDexAnnotationByte:
2202 case kDexAnnotationShort:
2203 case kDexAnnotationChar:
2204 case kDexAnnotationInt:
2205 case kDexAnnotationLong:
2206 case kDexAnnotationFloat:
2207 case kDexAnnotationDouble:
2208 case kDexAnnotationString:
2209 case kDexAnnotationType:
2210 case kDexAnnotationMethod:
2211 case kDexAnnotationField:
2212 case kDexAnnotationEnum:
2213 break;
2214 case kDexAnnotationArray:
2215 {
2216 uint32_t size = DecodeUnsignedLeb128(&annotation);
2217 while (size--) {
2218 if (!SkipAnnotationValue(&annotation)) {
2219 return false;
2220 }
2221 }
2222 width = 0;
2223 break;
2224 }
2225 case kDexAnnotationAnnotation:
2226 {
2227 DecodeUnsignedLeb128(&annotation); // unused type_index
2228 uint32_t size = DecodeUnsignedLeb128(&annotation);
2229 while (size--) {
2230 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2231 if (!SkipAnnotationValue(&annotation)) {
2232 return false;
2233 }
2234 }
2235 width = 0;
2236 break;
2237 }
2238 case kDexAnnotationBoolean:
2239 case kDexAnnotationNull:
2240 width = 0;
2241 break;
2242 default:
2243 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2244 return false;
2245 }
2246
2247 annotation += width;
2248 *annotation_ptr = annotation;
2249 return true;
2250}
2251
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002252std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2253 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2254 dex_file.GetLocation().c_str(),
2255 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2256 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2257 return os;
2258}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002259
Ian Rogersd91d6d62013-09-25 20:26:14 -07002260std::string Signature::ToString() const {
2261 if (dex_file_ == nullptr) {
2262 CHECK(proto_id_ == nullptr);
2263 return "<no signature>";
2264 }
2265 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2266 std::string result;
2267 if (params == nullptr) {
2268 result += "()";
2269 } else {
2270 result += "(";
2271 for (uint32_t i = 0; i < params->Size(); ++i) {
2272 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2273 }
2274 result += ")";
2275 }
2276 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2277 return result;
2278}
2279
Vladimir Markod9cffea2013-11-25 15:08:02 +00002280bool Signature::operator==(const StringPiece& rhs) const {
2281 if (dex_file_ == nullptr) {
2282 return false;
2283 }
2284 StringPiece tail(rhs);
2285 if (!tail.starts_with("(")) {
2286 return false; // Invalid signature
2287 }
2288 tail.remove_prefix(1); // "(";
2289 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2290 if (params != nullptr) {
2291 for (uint32_t i = 0; i < params->Size(); ++i) {
2292 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2293 if (!tail.starts_with(param)) {
2294 return false;
2295 }
2296 tail.remove_prefix(param.length());
2297 }
2298 }
2299 if (!tail.starts_with(")")) {
2300 return false;
2301 }
2302 tail.remove_prefix(1); // ")";
2303 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2304}
2305
Ian Rogersd91d6d62013-09-25 20:26:14 -07002306std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2307 return os << sig.ToString();
2308}
2309
Ian Rogers0571d352011-11-03 19:51:38 -07002310// Decodes the header section from the class data bytes.
2311void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002312 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002313 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2314 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2315 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2316 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2317}
2318
2319void ClassDataItemIterator::ReadClassDataField() {
2320 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2321 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002322 // The user of the iterator is responsible for checking if there
2323 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002324}
2325
2326void ClassDataItemIterator::ReadClassDataMethod() {
2327 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2328 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2329 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002330 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002331 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002332 }
Ian Rogers0571d352011-11-03 19:51:38 -07002333}
2334
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002335EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002336 const DexFile& dex_file,
2337 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002338 : EncodedStaticFieldValueIterator(dex_file,
2339 nullptr,
2340 nullptr,
2341 nullptr,
2342 class_def,
2343 -1,
2344 kByte) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002345}
2346
2347EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002348 const DexFile& dex_file,
2349 Handle<mirror::DexCache>* dex_cache,
2350 Handle<mirror::ClassLoader>* class_loader,
2351 ClassLinker* linker,
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002352 const DexFile::ClassDef& class_def)
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002353 : EncodedStaticFieldValueIterator(dex_file,
2354 dex_cache, class_loader,
2355 linker,
2356 class_def,
2357 -1,
2358 kByte) {
2359 DCHECK(dex_cache_ != nullptr);
2360 DCHECK(class_loader_ != nullptr);
2361}
2362
2363EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2364 const DexFile& dex_file,
2365 Handle<mirror::DexCache>* dex_cache,
2366 Handle<mirror::ClassLoader>* class_loader,
2367 ClassLinker* linker,
2368 const DexFile::ClassDef& class_def,
2369 size_t pos,
2370 ValueType type)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002371 : dex_file_(dex_file),
2372 dex_cache_(dex_cache),
2373 class_loader_(class_loader),
2374 linker_(linker),
2375 array_size_(),
Shinichiro Hamaji50a2f8d2015-12-11 09:45:28 +09002376 pos_(pos),
2377 type_(type) {
2378 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002379 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002380 array_size_ = 0;
2381 } else {
2382 array_size_ = DecodeUnsignedLeb128(&ptr_);
2383 }
2384 if (array_size_ > 0) {
2385 Next();
2386 }
2387}
2388
2389void EncodedStaticFieldValueIterator::Next() {
2390 pos_++;
2391 if (pos_ >= array_size_) {
2392 return;
2393 }
Ian Rogers13735952014-10-08 12:43:28 -07002394 uint8_t value_type = *ptr_++;
2395 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002396 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002397 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002398 switch (type_) {
2399 case kBoolean:
2400 jval_.i = (value_arg != 0) ? 1 : 0;
2401 width = 0;
2402 break;
2403 case kByte:
2404 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002405 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002406 break;
2407 case kShort:
2408 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002409 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002410 break;
2411 case kChar:
2412 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002413 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002414 break;
2415 case kInt:
2416 jval_.i = ReadSignedInt(ptr_, value_arg);
2417 break;
2418 case kLong:
2419 jval_.j = ReadSignedLong(ptr_, value_arg);
2420 break;
2421 case kFloat:
2422 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2423 break;
2424 case kDouble:
2425 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2426 break;
2427 case kString:
2428 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002429 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2430 break;
2431 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002432 case kMethod:
2433 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002434 case kArray:
2435 case kAnnotation:
2436 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002437 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002438 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002439 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002440 width = 0;
2441 break;
2442 default:
2443 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002444 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002445 }
2446 ptr_ += width;
2447}
2448
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002449template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002450void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09002451 DCHECK(dex_cache_ != nullptr);
2452 DCHECK(class_loader_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002453 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002454 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2455 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002456 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2457 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2458 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2459 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2460 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2461 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2462 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002463 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002464 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002465 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002466 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002467 break;
2468 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002469 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002470 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2471 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002472 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002473 break;
2474 }
Ian Rogers0571d352011-11-03 19:51:38 -07002475 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2476 }
2477}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002478template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2479template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002480
2481CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2482 handler_.address_ = -1;
2483 int32_t offset = -1;
2484
2485 // Short-circuit the overwhelmingly common cases.
2486 switch (code_item.tries_size_) {
2487 case 0:
2488 break;
2489 case 1: {
2490 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2491 uint32_t start = tries->start_addr_;
2492 if (address >= start) {
2493 uint32_t end = start + tries->insn_count_;
2494 if (address < end) {
2495 offset = tries->handler_off_;
2496 }
2497 }
2498 break;
2499 }
2500 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002501 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002502 }
Logan Chien736df022012-04-27 16:25:57 +08002503 Init(code_item, offset);
2504}
2505
2506CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2507 const DexFile::TryItem& try_item) {
2508 handler_.address_ = -1;
2509 Init(code_item, try_item.handler_off_);
2510}
2511
2512void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2513 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002514 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002515 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002516 } else {
2517 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002518 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002519 remaining_count_ = -1;
2520 catch_all_ = false;
2521 DCHECK(!HasNext());
2522 }
2523}
2524
Ian Rogers13735952014-10-08 12:43:28 -07002525void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002526 current_data_ = handler_data;
2527 remaining_count_ = DecodeSignedLeb128(&current_data_);
2528
2529 // If remaining_count_ is non-positive, then it is the negative of
2530 // the number of catch types, and the catches are followed by a
2531 // catch-all handler.
2532 if (remaining_count_ <= 0) {
2533 catch_all_ = true;
2534 remaining_count_ = -remaining_count_;
2535 } else {
2536 catch_all_ = false;
2537 }
2538 Next();
2539}
2540
2541void CatchHandlerIterator::Next() {
2542 if (remaining_count_ > 0) {
2543 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2544 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2545 remaining_count_--;
2546 return;
2547 }
2548
2549 if (catch_all_) {
2550 handler_.type_idx_ = DexFile::kDexNoIndex16;
2551 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2552 catch_all_ = false;
2553 return;
2554 }
2555
2556 // no more handler
2557 remaining_count_ = -1;
2558}
2559
Carl Shapiro1fb86202011-06-27 17:43:13 -07002560} // namespace art