blob: 3a93aace83787168657cffe87c1510e8d072056f [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"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "base/hash_map.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080033#include "base/logging.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010034#include "base/stl_util.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080035#include "base/stringprintf.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000036#include "class_linker-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
jeffhao10037c82012-01-23 15:06:23 -080038#include "dex_file_verifier.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070039#include "globals.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030040#include "handle_scope-inl.h"
Ian Rogers0571d352011-11-03 19:51:38 -070041#include "leb128.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000042#include "mirror/field.h"
43#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/string.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070045#include "os.h"
Jeff Hao13e748b2015-08-25 20:44:19 +000046#include "reflection.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070047#include "safe_map.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070048#include "thread.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030049#include "type_lookup_table.h"
Ian Rogersa6724902013-09-23 09:23:37 -070050#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070051#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070052#include "well_known_classes.h"
Brian Carlstromb0460ea2011-07-29 10:08:05 -070053#include "zip_archive.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070054
Andreas Gampe277ccbd2014-11-03 21:36:10 -080055#pragma GCC diagnostic push
56#pragma GCC diagnostic ignored "-Wshadow"
57#include "ScopedFd.h"
58#pragma GCC diagnostic pop
59
Carl Shapiro1fb86202011-06-27 17:43:13 -070060namespace art {
61
Ian Rogers13735952014-10-08 12:43:28 -070062const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
63const uint8_t DexFile::kDexMagicVersion[] = { '0', '3', '5', '\0' };
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070064
Ian Rogers8d31bbd2013-10-13 10:44:14 -070065static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070066 CHECK(magic != nullptr);
Vladimir Markofd995762013-11-06 16:36:36 +000067 ScopedFd fd(open(filename, O_RDONLY, 0));
68 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070070 return -1;
71 }
Vladimir Markofd995762013-11-06 16:36:36 +000072 int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070073 if (n != sizeof(*magic)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070074 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070075 return -1;
76 }
Vladimir Markofd995762013-11-06 16:36:36 +000077 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070078 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
79 strerror(errno));
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070080 return -1;
81 }
Vladimir Markofd995762013-11-06 16:36:36 +000082 return fd.release();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070083}
84
Ian Rogers8d31bbd2013-10-13 10:44:14 -070085bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070086 CHECK(checksum != nullptr);
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -070087 uint32_t magic;
Andreas Gampe833a4852014-05-21 18:46:59 -070088
89 // Strip ":...", which is the location
90 const char* zip_entry_name = kClassesDex;
91 const char* file_part = filename;
Vladimir Markoaa4497d2014-09-05 14:01:17 +010092 std::string file_part_storage;
Andreas Gampe833a4852014-05-21 18:46:59 -070093
Vladimir Markoaa4497d2014-09-05 14:01:17 +010094 if (DexFile::IsMultiDexLocation(filename)) {
95 file_part_storage = GetBaseLocation(filename);
96 file_part = file_part_storage.c_str();
97 zip_entry_name = filename + file_part_storage.size() + 1;
98 DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
Andreas Gampe833a4852014-05-21 18:46:59 -070099 }
100
101 ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
Vladimir Markofd995762013-11-06 16:36:36 +0000102 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700103 DCHECK(!error_msg->empty());
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700104 return false;
105 }
106 if (IsZipMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700107 std::unique_ptr<ZipArchive> zip_archive(
108 ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
109 if (zip_archive.get() == nullptr) {
Andreas Gampe0b3ed3d2015-03-04 15:38:51 -0800110 *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
111 error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800112 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700113 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700114 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700115 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700116 *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
117 zip_entry_name, error_msg->c_str());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800118 return false;
119 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700120 *checksum = zip_entry->GetCrc32();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800121 return true;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700122 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700123 if (IsDexMagic(magic)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 std::unique_ptr<const DexFile> dex_file(
125 DexFile::OpenFile(fd.release(), filename, false, error_msg));
126 if (dex_file.get() == nullptr) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800127 return false;
128 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700129 *checksum = dex_file->GetHeader().checksum_;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800130 return true;
131 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800133 return false;
Brian Carlstrom78128a62011-09-15 17:21:19 -0700134}
135
Andreas Gampe833a4852014-05-21 18:46:59 -0700136bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800137 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700138 DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700139 uint32_t magic;
Vladimir Markofd995762013-11-06 16:36:36 +0000140 ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
141 if (fd.get() == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700142 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700143 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700144 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700145 if (IsZipMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700146 return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700147 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700148 if (IsDexMagic(magic)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700149 std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
150 error_msg));
151 if (dex_file.get() != nullptr) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800152 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700153 return true;
154 } else {
155 return false;
156 }
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700157 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700158 *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
Alexander Ivchenkobacce5c2014-06-26 16:32:11 +0400159 return false;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700160}
161
Andreas Gampe0cba0042015-04-29 20:47:16 -0700162static bool ContainsClassesDex(int fd, const char* filename) {
163 std::string error_msg;
164 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
165 if (zip_archive.get() == nullptr) {
166 return false;
167 }
168 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
169 return (zip_entry.get() != nullptr);
170}
171
172bool DexFile::MaybeDex(const char* filename) {
173 uint32_t magic;
174 std::string error_msg;
175 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
176 if (fd.get() == -1) {
177 return false;
178 }
179 if (IsZipMagic(magic)) {
180 return ContainsClassesDex(fd.release(), filename);
181 } else if (IsDexMagic(magic)) {
182 return true;
183 }
184 return false;
185}
186
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800187int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700188 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800189 return 0;
190 } else {
191 return mem_map_->GetProtect();
192 }
193}
194
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200195bool DexFile::IsReadOnly() const {
196 return GetPermissions() == PROT_READ;
197}
198
Brian Carlstrome0948e12013-08-29 09:36:15 -0700199bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200200 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200202 return false;
203 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700204 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200205 }
206}
207
Brian Carlstrome0948e12013-08-29 09:36:15 -0700208bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200209 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700210 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200211 return false;
212 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -0700213 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +0200214 }
215}
216
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800217std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
218 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700219 CHECK(location != nullptr);
Ian Rogers700a4022014-05-19 16:49:03 -0700220 std::unique_ptr<MemMap> map;
Vladimir Markofd995762013-11-06 16:36:36 +0000221 {
222 ScopedFd delayed_close(fd);
223 struct stat sbuf;
224 memset(&sbuf, 0, sizeof(sbuf));
225 if (fstat(fd, &sbuf) == -1) {
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800226 *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
Vladimir Markofd995762013-11-06 16:36:36 +0000227 return nullptr;
228 }
229 if (S_ISDIR(sbuf.st_mode)) {
230 *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
231 return nullptr;
232 }
233 size_t length = sbuf.st_size;
234 map.reset(MemMap::MapFile(length, PROT_READ, MAP_PRIVATE, fd, 0, location, error_msg));
235 if (map.get() == nullptr) {
236 DCHECK(!error_msg->empty());
237 return nullptr;
238 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700239 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800240
241 if (map->Size() < sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700242 *error_msg = StringPrintf(
Brian Carlstrom4fa0bcd2013-12-10 11:24:21 -0800243 "DexFile: failed to open dex file '%s' that is too short to have a header", location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700244 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800245 }
246
247 const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
248
Andreas Gampe928f72b2014-09-09 19:53:48 -0700249 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
250 error_msg));
251 if (dex_file.get() == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700252 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
253 error_msg->c_str());
254 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800255 }
jeffhao54c1ceb2012-02-01 11:45:32 -0800256
Andreas Gampe928f72b2014-09-09 19:53:48 -0700257 if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
258 location, error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 return nullptr;
jeffhao54c1ceb2012-02-01 11:45:32 -0800260 }
261
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800262 return dex_file;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700263}
264
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700265const char* DexFile::kClassesDex = "classes.dex";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700266
Andreas Gampe833a4852014-05-21 18:46:59 -0700267bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800268 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700269 DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
Ian Rogers700a4022014-05-19 16:49:03 -0700270 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 if (zip_archive.get() == nullptr) {
272 DCHECK(!error_msg->empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700273 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700274 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700275 return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800276}
277
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800278std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
279 uint32_t location_checksum,
280 MemMap* mem_map,
281 std::string* error_msg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800282 return OpenMemory(mem_map->Begin(),
283 mem_map->Size(),
284 location,
285 location_checksum,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700286 mem_map,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800287 nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700288 error_msg);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800289}
290
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800291std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
292 const std::string& location, std::string* error_msg,
293 ZipOpenErrorCode* error_code) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800294 CHECK(!location.empty());
Andreas Gampe833a4852014-05-21 18:46:59 -0700295 std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700296 if (zip_entry.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700297 *error_code = ZipOpenErrorCode::kEntryNotFound;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700298 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700299 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700300 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700301 if (map.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700302 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700304 *error_code = ZipOpenErrorCode::kExtractToMemoryError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 return nullptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700306 }
Ian Rogers700a4022014-05-19 16:49:03 -0700307 std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 error_msg));
309 if (dex_file.get() == nullptr) {
310 *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
311 error_msg->c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700312 *error_code = ZipOpenErrorCode::kDexFileError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700313 return nullptr;
jeffhaof6174e82012-01-31 16:14:17 -0800314 }
Brian Carlstrome0948e12013-08-29 09:36:15 -0700315 if (!dex_file->DisableWrite()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700318 return nullptr;
Brian Carlstrome0948e12013-08-29 09:36:15 -0700319 }
320 CHECK(dex_file->IsReadOnly()) << location;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700321 if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
322 location.c_str(), error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700323 *error_code = ZipOpenErrorCode::kVerifyError;
Brian Carlstromd6cec902014-05-25 16:08:51 -0700324 return nullptr;
325 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700326 *error_code = ZipOpenErrorCode::kNoError;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800327 return dex_file;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700328}
329
Andreas Gampe90e34042015-04-27 20:01:52 -0700330// Technically we do not have a limitation with respect to the number of dex files that can be in a
331// multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
332// (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
333// seems an excessive number.
334static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
335
Andreas Gampe833a4852014-05-21 18:46:59 -0700336bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800337 std::string* error_msg,
338 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700339 DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
Andreas Gampe833a4852014-05-21 18:46:59 -0700340 ZipOpenErrorCode error_code;
341 std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
342 &error_code));
343 if (dex_file.get() == nullptr) {
344 return false;
345 } else {
346 // Had at least classes.dex.
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800347 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700348
349 // Now try some more.
Andreas Gampe833a4852014-05-21 18:46:59 -0700350
351 // We could try to avoid std::string allocations by working on a char array directly. As we
352 // do not expect a lot of iterations, this seems too involved and brittle.
353
Andreas Gampe90e34042015-04-27 20:01:52 -0700354 for (size_t i = 1; ; ++i) {
355 std::string name = GetMultiDexClassesDexName(i);
356 std::string fake_location = GetMultiDexLocation(i, location.c_str());
Andreas Gampe833a4852014-05-21 18:46:59 -0700357 std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
358 error_msg, &error_code));
359 if (next_dex_file.get() == nullptr) {
360 if (error_code != ZipOpenErrorCode::kEntryNotFound) {
361 LOG(WARNING) << error_msg;
362 }
363 break;
364 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800365 dex_files->push_back(std::move(next_dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700366 }
367
Andreas Gampe90e34042015-04-27 20:01:52 -0700368 if (i == kWarnOnManyDexFilesThreshold) {
369 LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
370 << " dex files. Please consider coalescing and shrinking the number to "
371 " avoid runtime overhead.";
372 }
373
374 if (i == std::numeric_limits<size_t>::max()) {
375 LOG(ERROR) << "Overflow in number of dex files!";
376 break;
377 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700378 }
379
380 return true;
381 }
382}
383
384
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800385std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
386 size_t size,
387 const std::string& location,
388 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800389 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700390 const OatDexFile* oat_dex_file,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800391 std::string* error_msg) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700392 CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
Andreas Gampefd9eb392014-11-06 16:52:58 -0800393 std::unique_ptr<DexFile> dex_file(
Richard Uhler07b3c232015-03-31 15:57:54 -0700394 new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 if (!dex_file->Init(error_msg)) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800396 dex_file.reset();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700397 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800398 return std::unique_ptr<const DexFile>(dex_file.release());
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700399}
400
Ian Rogers13735952014-10-08 12:43:28 -0700401DexFile::DexFile(const uint8_t* base, size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800402 const std::string& location,
403 uint32_t location_checksum,
Andreas Gampefd9eb392014-11-06 16:52:58 -0800404 MemMap* mem_map,
Richard Uhler07b3c232015-03-31 15:57:54 -0700405 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800406 : begin_(base),
407 size_(size),
408 location_(location),
409 location_checksum_(location_checksum),
410 mem_map_(mem_map),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800411 header_(reinterpret_cast<const Header*>(base)),
412 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
413 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
414 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
415 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
416 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700417 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Richard Uhler07b3c232015-03-31 15:57:54 -0700418 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700419 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800420 CHECK_GT(size_, 0U) << GetLocation();
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300421 const uint8_t* lookup_data = (oat_dex_file != nullptr)
422 ? oat_dex_file->GetLookupTableData()
423 : nullptr;
424 if (lookup_data != nullptr) {
425 if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
426 LOG(WARNING) << "found truncated lookup table in " << GetLocation();
427 } else {
428 lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
429 }
430 }
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800431}
432
Jesse Wilson6bf19152011-09-29 13:12:33 -0400433DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700434 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
435 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
436 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
437 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400438}
439
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700440bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700442 return false;
443 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700444 return true;
445}
446
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800448 if (!IsMagicValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700449 std::ostringstream oss;
450 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800451 << " " << header_->magic_[0]
452 << " " << header_->magic_[1]
453 << " " << header_->magic_[2]
454 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700455 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700456 return false;
457 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800458 if (!IsVersionValid(header_->magic_)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700459 std::ostringstream oss;
460 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800461 << " " << header_->magic_[4]
462 << " " << header_->magic_[5]
463 << " " << header_->magic_[6]
464 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700465 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700466 return false;
467 }
468 return true;
469}
470
Ian Rogers13735952014-10-08 12:43:28 -0700471bool DexFile::IsMagicValid(const uint8_t* magic) {
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800472 return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
473}
474
Ian Rogers13735952014-10-08 12:43:28 -0700475bool DexFile::IsVersionValid(const uint8_t* magic) {
476 const uint8_t* version = &magic[sizeof(kDexMagic)];
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800477 return (memcmp(version, kDexMagicVersion, sizeof(kDexMagicVersion)) == 0);
478}
479
Ian Rogersd81871c2011-10-03 13:57:23 -0700480uint32_t DexFile::GetVersion() const {
481 const char* version = reinterpret_cast<const char*>(&GetHeader().magic_[sizeof(kDexMagic)]);
482 return atoi(version);
483}
484
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -0800485const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
486 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300487 if (LIKELY(lookup_table_ != nullptr)) {
488 const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
489 return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
Ian Rogers68b56852014-08-29 20:19:11 -0700490 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300491
Ian Rogers68b56852014-08-29 20:19:11 -0700492 // Fast path for rate no class defs case.
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300493 const uint32_t num_class_defs = NumClassDefs();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700494 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700495 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700496 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300497 const TypeId* type_id = FindTypeId(descriptor);
498 if (type_id != nullptr) {
499 uint16_t type_idx = GetIndexForTypeId(*type_id);
500 for (size_t i = 0; i < num_class_defs; ++i) {
501 const ClassDef& class_def = GetClassDef(i);
502 if (class_def.class_idx_ == type_idx) {
503 return &class_def;
Ian Rogers68b56852014-08-29 20:19:11 -0700504 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700505 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700506 }
Ian Rogers68b56852014-08-29 20:19:11 -0700507 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700508}
509
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700510const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
511 size_t num_class_defs = NumClassDefs();
512 for (size_t i = 0; i < num_class_defs; ++i) {
513 const ClassDef& class_def = GetClassDef(i);
514 if (class_def.class_idx_ == type_idx) {
515 return &class_def;
516 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700517 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700518 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700519}
520
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800521const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
522 const DexFile::StringId& name,
523 const DexFile::TypeId& type) const {
524 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
525 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
526 const uint32_t name_idx = GetIndexForStringId(name);
527 const uint16_t type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700528 int32_t lo = 0;
529 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800530 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700531 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800532 const DexFile::FieldId& field = GetFieldId(mid);
533 if (class_idx > field.class_idx_) {
534 lo = mid + 1;
535 } else if (class_idx < field.class_idx_) {
536 hi = mid - 1;
537 } else {
538 if (name_idx > field.name_idx_) {
539 lo = mid + 1;
540 } else if (name_idx < field.name_idx_) {
541 hi = mid - 1;
542 } else {
543 if (type_idx > field.type_idx_) {
544 lo = mid + 1;
545 } else if (type_idx < field.type_idx_) {
546 hi = mid - 1;
547 } else {
548 return &field;
549 }
550 }
551 }
552 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700553 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800554}
555
556const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700557 const DexFile::StringId& name,
558 const DexFile::ProtoId& signature) const {
559 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800560 const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
Ian Rogers0571d352011-11-03 19:51:38 -0700561 const uint32_t name_idx = GetIndexForStringId(name);
562 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700563 int32_t lo = 0;
564 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700565 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700566 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700567 const DexFile::MethodId& method = GetMethodId(mid);
568 if (class_idx > method.class_idx_) {
569 lo = mid + 1;
570 } else if (class_idx < method.class_idx_) {
571 hi = mid - 1;
572 } else {
573 if (name_idx > method.name_idx_) {
574 lo = mid + 1;
575 } else if (name_idx < method.name_idx_) {
576 hi = mid - 1;
577 } else {
578 if (proto_idx > method.proto_idx_) {
579 lo = mid + 1;
580 } else if (proto_idx < method.proto_idx_) {
581 hi = mid - 1;
582 } else {
583 return &method;
584 }
585 }
586 }
587 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700588 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700589}
590
Ian Rogers637c65b2013-05-31 11:46:00 -0700591const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700592 int32_t lo = 0;
593 int32_t hi = NumStringIds() - 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::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700597 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700598 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
599 if (compare > 0) {
600 lo = mid + 1;
601 } else if (compare < 0) {
602 hi = mid - 1;
603 } else {
604 return &str_id;
605 }
606 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700608}
609
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300610const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
611 int32_t lo = 0;
612 int32_t hi = NumTypeIds() - 1;
613 while (hi >= lo) {
614 int32_t mid = (hi + lo) / 2;
615 const TypeId& type_id = GetTypeId(mid);
616 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
617 const char* str = GetStringData(str_id);
618 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
619 if (compare > 0) {
620 lo = mid + 1;
621 } else if (compare < 0) {
622 hi = mid - 1;
623 } else {
624 return &type_id;
625 }
626 }
627 return nullptr;
628}
629
Vladimir Markoa48aef42014-12-03 17:53:53 +0000630const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700631 int32_t lo = 0;
632 int32_t hi = NumStringIds() - 1;
633 while (hi >= lo) {
634 int32_t mid = (hi + lo) / 2;
Ian Rogers637c65b2013-05-31 11:46:00 -0700635 const DexFile::StringId& str_id = GetStringId(mid);
Ian Rogerscf5077a2013-10-31 12:37:54 -0700636 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000637 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700638 if (compare > 0) {
639 lo = mid + 1;
640 } else if (compare < 0) {
641 hi = mid - 1;
642 } else {
643 return &str_id;
644 }
645 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700647}
648
649const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700650 int32_t lo = 0;
651 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700652 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700653 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700654 const TypeId& type_id = GetTypeId(mid);
655 if (string_idx > type_id.descriptor_idx_) {
656 lo = mid + 1;
657 } else if (string_idx < type_id.descriptor_idx_) {
658 hi = mid - 1;
659 } else {
660 return &type_id;
661 }
662 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700663 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700664}
665
666const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000667 const uint16_t* signature_type_idxs,
668 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700669 int32_t lo = 0;
670 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700671 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700672 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700673 const DexFile::ProtoId& proto = GetProtoId(mid);
674 int compare = return_type_idx - proto.return_type_idx_;
675 if (compare == 0) {
676 DexFileParameterIterator it(*this, proto);
677 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000678 while (it.HasNext() && i < signature_length && compare == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800679 compare = signature_type_idxs[i] - it.GetTypeIdx();
Ian Rogers0571d352011-11-03 19:51:38 -0700680 it.Next();
681 i++;
682 }
683 if (compare == 0) {
684 if (it.HasNext()) {
685 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000686 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700687 compare = 1;
688 }
689 }
690 }
691 if (compare > 0) {
692 lo = mid + 1;
693 } else if (compare < 0) {
694 hi = mid - 1;
695 } else {
696 return &proto;
697 }
698 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700699 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700700}
701
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300702void DexFile::CreateTypeLookupTable() const {
703 lookup_table_.reset(TypeLookupTable::Create(*this));
704}
705
Ian Rogers0571d352011-11-03 19:51:38 -0700706// Given a signature place the type ids into the given vector
Ian Rogersd91d6d62013-09-25 20:26:14 -0700707bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
708 std::vector<uint16_t>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700709 if (signature[0] != '(') {
710 return false;
711 }
712 size_t offset = 1;
713 size_t end = signature.size();
714 bool process_return = false;
715 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000716 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700717 char c = signature[offset];
718 offset++;
719 if (c == ')') {
720 process_return = true;
721 continue;
722 }
Ian Rogers0571d352011-11-03 19:51:38 -0700723 while (c == '[') { // process array prefix
724 if (offset >= end) { // expect some descriptor following [
725 return false;
726 }
727 c = signature[offset];
728 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700729 }
730 if (c == 'L') { // process type descriptors
731 do {
732 if (offset >= end) { // unexpected early termination of descriptor
733 return false;
734 }
735 c = signature[offset];
736 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700737 } while (c != ';');
738 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000739 // TODO: avoid creating a std::string just to get a 0-terminated char array
740 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700741 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700742 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700743 return false;
744 }
745 uint16_t type_idx = GetIndexForTypeId(*type_id);
746 if (!process_return) {
747 param_type_idxs->push_back(type_idx);
748 } else {
749 *return_type_idx = type_idx;
750 return offset == end; // return true if the signature had reached a sensible end
751 }
752 }
753 return false; // failed to correctly parse return type
754}
755
Ian Rogersd91d6d62013-09-25 20:26:14 -0700756const Signature DexFile::CreateSignature(const StringPiece& signature) const {
757 uint16_t return_type_idx;
758 std::vector<uint16_t> param_type_indices;
759 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
760 if (!success) {
761 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700762 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700763 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700764 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700765 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700766 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700767 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700768}
769
Mathieu Chartiere401d142015-04-22 13:56:20 -0700770int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700771 // For native method, lineno should be -2 to indicate it is native. Note that
772 // "line number == -2" is how libcore tells from StackTraceElement.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700773 if (method->GetCodeItemOffset() == 0) {
Shih-wei Liaoff0f9be2011-08-29 15:43:53 -0700774 return -2;
775 }
776
TDYa127c8dc1012012-04-19 07:03:33 -0700777 const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700778 DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700779
780 // A method with no line number info should return -1
781 LineNumFromPcContext context(rel_pc, -1);
TDYa127c8dc1012012-04-19 07:03:33 -0700782 DecodeDebugInfo(code_item, method->IsStatic(), method->GetDexMethodIndex(), LineNumForPcCb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700783 nullptr, &context);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700784 return context.line_num_;
785}
786
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700787int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700788 // Note: Signed type is important for max and min.
789 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700790 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700791
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700792 while (min <= max) {
793 int32_t mid = min + ((max - min) / 2);
794
795 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
796 uint32_t start = ti->start_addr_;
797 uint32_t end = start + ti->insn_count_;
798
Ian Rogers0571d352011-11-03 19:51:38 -0700799 if (address < start) {
800 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700801 } else if (address >= end) {
802 min = mid + 1;
803 } else { // We have a winner!
804 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700805 }
806 }
807 // No match.
808 return -1;
809}
810
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700811int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
812 int32_t try_item = FindTryItem(code_item, address);
813 if (try_item == -1) {
814 return -1;
815 } else {
816 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
817 }
818}
819
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800820void DexFile::DecodeDebugInfo0(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800821 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700822 void* context, const uint8_t* stream, LocalInfo* local_in_reg)
823 const {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700824 uint32_t line = DecodeUnsignedLeb128(&stream);
825 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
826 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
827 uint32_t address = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700828 bool need_locals = (local_cb != nullptr);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700829
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800830 if (!is_static) {
Elliott Hughes30646832011-10-13 16:59:46 -0700831 if (need_locals) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800832 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700833 local_in_reg[arg_reg].name_ = "this";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800834 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700835 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700836 local_in_reg[arg_reg].start_address_ = 0;
837 local_in_reg[arg_reg].is_live_ = true;
838 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700839 arg_reg++;
840 }
841
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800842 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
Ian Rogers0571d352011-11-03 19:51:38 -0700843 for (uint32_t i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700844 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700845 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800846 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700847 return;
848 }
Elliott Hughes392b1242011-11-30 13:55:50 -0800849 uint32_t id = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700850 const char* descriptor = it.GetDescriptor();
Elliott Hughes392b1242011-11-30 13:55:50 -0800851 if (need_locals && id != kDexNoIndex) {
Ian Rogers0571d352011-11-03 19:51:38 -0700852 const char* name = StringDataByIdx(id);
Elliott Hughes30646832011-10-13 16:59:46 -0700853 local_in_reg[arg_reg].name_ = name;
854 local_in_reg[arg_reg].descriptor_ = descriptor;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700855 local_in_reg[arg_reg].signature_ = nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700856 local_in_reg[arg_reg].start_address_ = address;
857 local_in_reg[arg_reg].is_live_ = true;
858 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700859 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700860 case 'D':
861 case 'J':
862 arg_reg += 2;
863 break;
864 default:
865 arg_reg += 1;
866 break;
867 }
868 }
869
Ian Rogers0571d352011-11-03 19:51:38 -0700870 if (it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800871 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
872 << " for method " << PrettyMethod(method_idx, *this);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700873 return;
874 }
875
876 for (;;) {
877 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700878 uint16_t reg;
Jeff Haob7cefc72013-11-14 14:51:09 -0800879 uint32_t name_idx;
880 uint32_t descriptor_idx;
881 uint32_t signature_idx = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700882
Shih-wei Liao195487c2011-08-20 13:29:04 -0700883 switch (opcode) {
884 case DBG_END_SEQUENCE:
885 return;
886
887 case DBG_ADVANCE_PC:
888 address += DecodeUnsignedLeb128(&stream);
889 break;
890
891 case DBG_ADVANCE_LINE:
Shih-wei Liao8a05d272011-10-15 18:45:43 -0700892 line += DecodeSignedLeb128(&stream);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700893 break;
894
895 case DBG_START_LOCAL:
896 case DBG_START_LOCAL_EXTENDED:
897 reg = DecodeUnsignedLeb128(&stream);
898 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700899 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800900 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700901 return;
902 }
903
jeffhaof8728872011-10-28 19:11:13 -0700904 name_idx = DecodeUnsignedLeb128P1(&stream);
905 descriptor_idx = DecodeUnsignedLeb128P1(&stream);
906 if (opcode == DBG_START_LOCAL_EXTENDED) {
907 signature_idx = DecodeUnsignedLeb128P1(&stream);
908 }
909
Shih-wei Liao195487c2011-08-20 13:29:04 -0700910 // Emit what was previously there, if anything
Elliott Hughes30646832011-10-13 16:59:46 -0700911 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800912 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700913
Ian Rogers0571d352011-11-03 19:51:38 -0700914 local_in_reg[reg].name_ = StringDataByIdx(name_idx);
915 local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
Aart Bik4cc60732015-06-24 16:33:32 -0700916 local_in_reg[reg].signature_ =
917 (opcode == DBG_START_LOCAL_EXTENDED) ? StringDataByIdx(signature_idx)
918 : nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -0700919 local_in_reg[reg].start_address_ = address;
920 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700921 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700922 break;
923
924 case DBG_END_LOCAL:
925 reg = DecodeUnsignedLeb128(&stream);
926 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700927 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800928 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700929 return;
930 }
931
Elliott Hughes30646832011-10-13 16:59:46 -0700932 if (need_locals) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800933 InvokeLocalCbIfLive(context, reg, address, local_in_reg, local_cb);
Elliott Hughes30646832011-10-13 16:59:46 -0700934 local_in_reg[reg].is_live_ = false;
935 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700936 break;
937
938 case DBG_RESTART_LOCAL:
939 reg = DecodeUnsignedLeb128(&stream);
940 if (reg > code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700941 LOG(ERROR) << "invalid stream - reg > reg size (" << reg << " > "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800942 << code_item->registers_size_ << ") in " << GetLocation();
Shih-wei Liao195487c2011-08-20 13:29:04 -0700943 return;
944 }
945
Elliott Hughes30646832011-10-13 16:59:46 -0700946 if (need_locals) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700947 if (local_in_reg[reg].name_ == nullptr || local_in_reg[reg].descriptor_ == nullptr) {
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800948 LOG(ERROR) << "invalid stream - no name or descriptor in " << GetLocation();
Elliott Hughes30646832011-10-13 16:59:46 -0700949 return;
950 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700951
Elliott Hughes30646832011-10-13 16:59:46 -0700952 // If the register is live, the "restart" is superfluous,
953 // and we don't want to mess with the existing start address.
954 if (!local_in_reg[reg].is_live_) {
955 local_in_reg[reg].start_address_ = address;
956 local_in_reg[reg].is_live_ = true;
957 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700958 }
959 break;
960
961 case DBG_SET_PROLOGUE_END:
962 case DBG_SET_EPILOGUE_BEGIN:
963 case DBG_SET_FILE:
964 break;
965
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700966 default: {
967 int adjopcode = opcode - DBG_FIRST_SPECIAL;
968
Shih-wei Liao195487c2011-08-20 13:29:04 -0700969 address += adjopcode / DBG_LINE_RANGE;
970 line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
971
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700972 if (position_cb != nullptr) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800973 if (position_cb(context, address, line)) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700974 // early exit
975 return;
976 }
977 }
978 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700979 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700980 }
981 }
982}
983
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800984void DexFile::DecodeDebugInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
Elliott Hughes2435a572012-02-17 16:07:41 -0800985 DexDebugNewPositionCb position_cb, DexDebugNewLocalCb local_cb,
986 void* context) const {
Sebastien Hertzcb19ebf2014-03-11 15:26:35 +0100987 DCHECK(code_item != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700988 const uint8_t* stream = GetDebugInfoStream(code_item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700989 std::unique_ptr<LocalInfo[]> local_in_reg(local_cb != nullptr ?
Brian Carlstrome0948e12013-08-29 09:36:15 -0700990 new LocalInfo[code_item->registers_size_] :
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700991 nullptr);
992 if (stream != nullptr) {
993 DecodeDebugInfo0(code_item, is_static, method_idx, position_cb, local_cb, context, stream,
994 &local_in_reg[0]);
Ian Rogers0571d352011-11-03 19:51:38 -0700995 }
996 for (int reg = 0; reg < code_item->registers_size_; reg++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700997 InvokeLocalCbIfLive(context, reg, code_item->insns_size_in_code_units_, &local_in_reg[0],
998 local_cb);
Ian Rogers0571d352011-11-03 19:51:38 -0700999 }
1000}
1001
Elliott Hughes2435a572012-02-17 16:07:41 -08001002bool DexFile::LineNumForPcCb(void* raw_context, uint32_t address, uint32_t line_num) {
1003 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -07001004
1005 // We know that this callback will be called in
1006 // ascending address order, so keep going until we find
1007 // a match or we've just gone past it.
1008 if (address > context->address_) {
1009 // The line number from the previous positions callback
1010 // wil be the final result.
1011 return true;
1012 } else {
1013 context->line_num_ = line_num;
1014 return address == context->address_;
1015 }
1016}
1017
Andreas Gampe833a4852014-05-21 18:46:59 -07001018bool DexFile::IsMultiDexLocation(const char* location) {
1019 return strrchr(location, kMultiDexSeparator) != nullptr;
1020}
1021
Andreas Gampe90e34042015-04-27 20:01:52 -07001022std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1023 if (index == 0) {
1024 return "classes.dex";
1025 } else {
1026 return StringPrintf("classes%zu.dex", index + 1);
1027 }
1028}
1029
1030std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1031 if (index == 0) {
Calin Juravle4e1d5792014-07-15 23:56:47 +01001032 return dex_location;
1033 } else {
Andreas Gampe90e34042015-04-27 20:01:52 -07001034 return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
Calin Juravle4e1d5792014-07-15 23:56:47 +01001035 }
1036}
1037
1038std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1039 CHECK_NE(dex_location, static_cast<const char*>(nullptr));
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001040 std::string base_location = GetBaseLocation(dex_location);
1041 const char* suffix = dex_location + base_location.size();
1042 DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1043 UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1044 if (path != nullptr && path.get() != base_location) {
1045 return std::string(path.get()) + suffix;
1046 } else if (suffix[0] == 0) {
1047 return base_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001048 } else {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001049 return dex_location;
Calin Juravle4e1d5792014-07-15 23:56:47 +01001050 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001051}
1052
Jeff Hao13e748b2015-08-25 20:44:19 +00001053// Read a signed integer. "zwidth" is the zero-based byte count.
1054static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1055 int32_t val = 0;
1056 for (int i = zwidth; i >= 0; --i) {
1057 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1058 }
1059 val >>= (3 - zwidth) * 8;
1060 return val;
1061}
1062
1063// Read an unsigned integer. "zwidth" is the zero-based byte count,
1064// "fill_on_right" indicates which side we want to zero-fill from.
1065static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1066 uint32_t val = 0;
1067 for (int i = zwidth; i >= 0; --i) {
1068 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1069 }
1070 if (!fill_on_right) {
1071 val >>= (3 - zwidth) * 8;
1072 }
1073 return val;
1074}
1075
1076// Read a signed long. "zwidth" is the zero-based byte count.
1077static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1078 int64_t val = 0;
1079 for (int i = zwidth; i >= 0; --i) {
1080 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1081 }
1082 val >>= (7 - zwidth) * 8;
1083 return val;
1084}
1085
1086// Read an unsigned long. "zwidth" is the zero-based byte count,
1087// "fill_on_right" indicates which side we want to zero-fill from.
1088static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1089 uint64_t val = 0;
1090 for (int i = zwidth; i >= 0; --i) {
1091 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1092 }
1093 if (!fill_on_right) {
1094 val >>= (7 - zwidth) * 8;
1095 }
1096 return val;
1097}
1098
1099const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1100 mirror::Class* klass = field->GetDeclaringClass();
1101 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1102 if (annotations_dir == nullptr) {
1103 return nullptr;
1104 }
1105 const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1106 if (field_annotations == nullptr) {
1107 return nullptr;
1108 }
1109 uint32_t field_index = field->GetDexFieldIndex();
1110 uint32_t field_count = annotations_dir->fields_size_;
1111 for (uint32_t i = 0; i < field_count; ++i) {
1112 if (field_annotations[i].field_idx_ == field_index) {
1113 return GetFieldAnnotationSetItem(field_annotations[i]);
1114 }
1115 }
1116 return nullptr;
1117}
1118
1119mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1120 Handle<mirror::Class> annotation_class) const {
1121 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1122 if (annotation_set == nullptr) {
1123 return nullptr;
1124 }
1125 StackHandleScope<1> hs(Thread::Current());
1126 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1127 return GetAnnotationObjectFromAnnotationSet(
1128 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1129}
1130
1131mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1132 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1133 StackHandleScope<1> hs(Thread::Current());
1134 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1135 return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1136}
1137
Jeff Hao2a5892f2015-08-31 15:00:40 -07001138mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
Jeff Hao13e748b2015-08-25 20:44:19 +00001139 const {
1140 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1141 if (annotation_set == nullptr) {
1142 return nullptr;
1143 }
1144 StackHandleScope<1> hs(Thread::Current());
1145 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1146 return GetSignatureValue(field_class, annotation_set);
1147}
1148
1149bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1150 const {
1151 const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1152 if (annotation_set == nullptr) {
1153 return false;
1154 }
1155 StackHandleScope<1> hs(Thread::Current());
1156 Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1157 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1158 field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1159 return annotation_item != nullptr;
1160}
1161
1162const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1163 mirror::Class* klass = method->GetDeclaringClass();
1164 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1165 if (annotations_dir == nullptr) {
1166 return nullptr;
1167 }
1168 const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1169 if (method_annotations == nullptr) {
1170 return nullptr;
1171 }
1172 uint32_t method_index = method->GetDexMethodIndex();
1173 uint32_t method_count = annotations_dir->methods_size_;
1174 for (uint32_t i = 0; i < method_count; ++i) {
1175 if (method_annotations[i].method_idx_ == method_index) {
1176 return GetMethodAnnotationSetItem(method_annotations[i]);
1177 }
1178 }
1179 return nullptr;
1180}
1181
1182const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1183 const {
1184 mirror::Class* klass = method->GetDeclaringClass();
1185 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1186 if (annotations_dir == nullptr) {
1187 return nullptr;
1188 }
1189 const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1190 if (parameter_annotations == nullptr) {
1191 return nullptr;
1192 }
1193 uint32_t method_index = method->GetDexMethodIndex();
1194 uint32_t parameter_count = annotations_dir->parameters_size_;
1195 for (uint32_t i = 0; i < parameter_count; ++i) {
1196 if (parameter_annotations[i].method_idx_ == method_index) {
1197 return &parameter_annotations[i];
1198 }
1199 }
1200 return nullptr;
1201}
1202
1203mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1204 mirror::Class* klass = method->GetDeclaringClass();
1205 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1206 if (annotations_dir == nullptr) {
1207 return nullptr;
1208 }
1209 const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1210 if (annotation_set == nullptr) {
1211 return nullptr;
1212 }
1213 const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1214 "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1215 if (annotation_item == nullptr) {
1216 return nullptr;
1217 }
1218 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1219 if (annotation == nullptr) {
1220 return nullptr;
1221 }
1222 uint8_t header_byte = *(annotation++);
1223 if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1224 return nullptr;
1225 }
1226 annotation = SearchEncodedAnnotation(annotation, method->GetName());
1227 if (annotation == nullptr) {
1228 return nullptr;
1229 }
1230 AnnotationValue annotation_value;
1231 StackHandleScope<2> hs(Thread::Current());
1232 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Vladimir Marko05792b92015-08-03 11:56:49 +01001233 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1234 Handle<mirror::Class> return_type(hs.NewHandle(
1235 method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001236 if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1237 return nullptr;
1238 }
1239 return annotation_value.value_.GetL();
1240}
1241
1242mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1243 Handle<mirror::Class> annotation_class) const {
1244 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1245 if (annotation_set == nullptr) {
1246 return nullptr;
1247 }
1248 StackHandleScope<1> hs(Thread::Current());
1249 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1250 return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1251 kDexVisibilityRuntime, annotation_class);
1252}
1253
1254mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1255 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1256 StackHandleScope<1> hs(Thread::Current());
1257 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1258 return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1259}
1260
Jeff Hao2a5892f2015-08-31 15:00:40 -07001261mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
Jeff Hao13e748b2015-08-25 20:44:19 +00001262 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1263 if (annotation_set == nullptr) {
1264 return nullptr;
1265 }
1266 StackHandleScope<1> hs(Thread::Current());
1267 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1268 return GetThrowsValue(method_class, annotation_set);
1269}
1270
1271mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1272 const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1273 if (parameter_annotations == nullptr) {
1274 return nullptr;
1275 }
1276 const AnnotationSetRefList* set_ref_list =
1277 GetParameterAnnotationSetRefList(parameter_annotations);
1278 if (set_ref_list == nullptr) {
1279 return nullptr;
1280 }
1281 uint32_t size = set_ref_list->size_;
1282 StackHandleScope<1> hs(Thread::Current());
1283 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1284 return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1285}
1286
1287bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1288 const {
1289 const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1290 if (annotation_set == nullptr) {
1291 return false;
1292 }
1293 StackHandleScope<1> hs(Thread::Current());
1294 Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1295 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1296 method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001297 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001298}
1299
1300const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1301 const {
1302 const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1303 if (annotations_dir == nullptr) {
1304 return nullptr;
1305 }
1306 return GetClassAnnotationSet(annotations_dir);
1307}
1308
1309mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1310 Handle<mirror::Class> annotation_class) const {
1311 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1312 if (annotation_set == nullptr) {
1313 return nullptr;
1314 }
1315 return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1316 annotation_class);
1317}
1318
1319mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1320 const {
1321 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1322 return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1323}
1324
Jeff Hao2a5892f2015-08-31 15:00:40 -07001325mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1326 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1327 if (annotation_set == nullptr) {
1328 return nullptr;
1329 }
1330 const AnnotationItem* annotation_item = SearchAnnotationSet(
1331 annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1332 if (annotation_item == nullptr) {
1333 return nullptr;
1334 }
1335 StackHandleScope<1> hs(Thread::Current());
1336 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1337 Handle<mirror::Class> class_array_class(hs.NewHandle(
1338 Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1339 if (class_array_class.Get() == nullptr) {
1340 return nullptr;
1341 }
1342 mirror::Object* obj = GetAnnotationValue(
1343 klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1344 if (obj == nullptr) {
1345 return nullptr;
1346 }
1347 return obj->AsObjectArray<mirror::Class>();
1348}
1349
1350mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1351 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1352 if (annotation_set == nullptr) {
1353 return nullptr;
1354 }
1355 const AnnotationItem* annotation_item = SearchAnnotationSet(
1356 annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1357 if (annotation_item == nullptr) {
1358 return nullptr;
1359 }
1360 mirror::Object* obj = GetAnnotationValue(
1361 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationType);
1362 if (obj == nullptr) {
1363 return nullptr;
1364 }
1365 return obj->AsClass();
1366}
1367
1368mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1369 mirror::Class* declaring_class = GetDeclaringClass(klass);
1370 if (declaring_class != nullptr) {
1371 return declaring_class;
1372 }
1373 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1374 if (annotation_set == nullptr) {
1375 return nullptr;
1376 }
1377 const AnnotationItem* annotation_item = SearchAnnotationSet(
1378 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1379 if (annotation_item == nullptr) {
1380 return nullptr;
1381 }
1382 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1383 if (annotation == nullptr) {
1384 return nullptr;
1385 }
1386 AnnotationValue annotation_value;
1387 if (!ProcessAnnotationValue(
1388 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1389 return nullptr;
1390 }
1391 if (annotation_value.type_ != kDexAnnotationMethod) {
1392 return nullptr;
1393 }
1394 StackHandleScope<2> hs(Thread::Current());
1395 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1396 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1397 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1398 klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1399 if (method == nullptr) {
1400 return nullptr;
1401 }
1402 return method->GetDeclaringClass();
1403}
1404
1405mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1406 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1407 if (annotation_set == nullptr) {
1408 return nullptr;
1409 }
1410 const AnnotationItem* annotation_item = SearchAnnotationSet(
1411 annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1412 if (annotation_item == nullptr) {
1413 return nullptr;
1414 }
1415 return GetAnnotationValue(
1416 klass, annotation_item, "value", NullHandle<mirror::Class>(), kDexAnnotationMethod);
1417}
1418
1419bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1420 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1421 if (annotation_set == nullptr) {
1422 return false;
1423 }
1424 const AnnotationItem* annotation_item = SearchAnnotationSet(
1425 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1426 if (annotation_item == nullptr) {
1427 return false;
1428 }
1429 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1430 if (annotation == nullptr) {
1431 return false;
1432 }
1433 AnnotationValue annotation_value;
1434 if (!ProcessAnnotationValue(
1435 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllObjects)) {
1436 return false;
1437 }
1438 if (annotation_value.type_ != kDexAnnotationNull &&
1439 annotation_value.type_ != kDexAnnotationString) {
1440 return false;
1441 }
1442 *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1443 return true;
1444}
1445
1446bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1447 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1448 if (annotation_set == nullptr) {
1449 return false;
1450 }
1451 const AnnotationItem* annotation_item = SearchAnnotationSet(
1452 annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1453 if (annotation_item == nullptr) {
1454 return false;
1455 }
1456 const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1457 if (annotation == nullptr) {
1458 return false;
1459 }
1460 AnnotationValue annotation_value;
1461 if (!ProcessAnnotationValue(
1462 klass, &annotation, &annotation_value, NullHandle<mirror::Class>(), kAllRaw)) {
1463 return false;
1464 }
1465 if (annotation_value.type_ != kDexAnnotationInt) {
1466 return false;
1467 }
1468 *flags = annotation_value.value_.GetI();
1469 return true;
1470}
1471
Jeff Hao13e748b2015-08-25 20:44:19 +00001472bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1473 Handle<mirror::Class> annotation_class) const {
1474 const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1475 if (annotation_set == nullptr) {
1476 return false;
1477 }
1478 const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1479 klass, annotation_set, kDexVisibilityRuntime, annotation_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001480 return annotation_item != nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001481}
1482
1483mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1484 Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1485 Thread* self = Thread::Current();
1486 ScopedObjectAccessUnchecked soa(self);
1487 StackHandleScope<5> hs(self);
1488 uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1489 const char* name = StringDataByIdx(element_name_index);
1490 Handle<mirror::String> string_name(
1491 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1492
1493 ArtMethod* annotation_method =
1494 annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1495 if (annotation_method == nullptr) {
1496 return nullptr;
1497 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001498 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1499 Handle<mirror::Class> method_return(hs.NewHandle(
1500 annotation_method->GetReturnType(true /* resolve */, pointer_size)));
Jeff Hao13e748b2015-08-25 20:44:19 +00001501
1502 AnnotationValue annotation_value;
1503 if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1504 return nullptr;
1505 }
1506 Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1507
1508 mirror::Class* annotation_member_class =
1509 WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1510 Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1511 Handle<mirror::Method> method_object(
1512 hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1513
1514 if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1515 method_object.Get() == nullptr || method_return.Get() == nullptr) {
1516 LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1517 new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1518 return nullptr;
1519 }
1520
1521 JValue result;
1522 ArtMethod* annotation_member_init =
1523 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1524 uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1525 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1526 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1527 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1528 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1529 };
1530 annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1531 if (self->IsExceptionPending()) {
1532 LOG(INFO) << "Exception in AnnotationMember.<init>";
1533 return nullptr;
1534 }
1535
1536 return new_member.Get();
1537}
1538
1539const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1540 Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1541 Handle<mirror::Class> annotation_class) const {
1542 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1543 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1544 if (annotation_item->visibility_ != visibility) {
1545 continue;
1546 }
1547 const uint8_t* annotation = annotation_item->annotation_;
1548 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1549 mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1550 klass->GetDexFile(), type_index, klass.Get());
1551 if (resolved_class == nullptr) {
1552 std::string temp;
1553 LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1554 klass->GetDescriptor(&temp), type_index);
1555 CHECK(Thread::Current()->IsExceptionPending());
1556 Thread::Current()->ClearException();
1557 continue;
1558 }
1559 if (resolved_class == annotation_class.Get()) {
1560 return annotation_item;
1561 }
1562 }
1563
1564 return nullptr;
1565}
1566
1567mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1568 const AnnotationSetItem* annotation_set, uint32_t visibility,
1569 Handle<mirror::Class> annotation_class) const {
1570 const AnnotationItem* annotation_item =
1571 GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1572 if (annotation_item == nullptr) {
1573 return nullptr;
1574 }
1575 const uint8_t* annotation = annotation_item->annotation_;
1576 return ProcessEncodedAnnotation(klass, &annotation);
1577}
1578
1579mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1580 const AnnotationItem* annotation_item, const char* annotation_name,
1581 Handle<mirror::Class> array_class, uint32_t expected_type) const {
1582 const uint8_t* annotation =
1583 SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1584 if (annotation == nullptr) {
1585 return nullptr;
1586 }
1587 AnnotationValue annotation_value;
1588 if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1589 return nullptr;
1590 }
1591 if (annotation_value.type_ != expected_type) {
1592 return nullptr;
1593 }
1594 return annotation_value.value_.GetL();
1595}
1596
Jeff Hao2a5892f2015-08-31 15:00:40 -07001597mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001598 const AnnotationSetItem* annotation_set) const {
1599 StackHandleScope<1> hs(Thread::Current());
1600 const AnnotationItem* annotation_item =
1601 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1602 if (annotation_item == nullptr) {
1603 return nullptr;
1604 }
1605 mirror::Class* string_class = mirror::String::GetJavaLangString();
1606 Handle<mirror::Class> string_array_class(hs.NewHandle(
1607 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001608 if (string_array_class.Get() == nullptr) {
1609 return nullptr;
1610 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001611 mirror::Object* obj =
1612 GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1613 if (obj == nullptr) {
1614 return nullptr;
1615 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001616 return obj->AsObjectArray<mirror::String>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001617}
1618
Jeff Hao2a5892f2015-08-31 15:00:40 -07001619mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
Jeff Hao13e748b2015-08-25 20:44:19 +00001620 const AnnotationSetItem* annotation_set) const {
1621 StackHandleScope<1> hs(Thread::Current());
1622 const AnnotationItem* annotation_item =
1623 SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1624 if (annotation_item == nullptr) {
1625 return nullptr;
1626 }
1627 mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1628 Handle<mirror::Class> class_array_class(hs.NewHandle(
1629 Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
Jeff Hao2a5892f2015-08-31 15:00:40 -07001630 if (class_array_class.Get() == nullptr) {
1631 return nullptr;
1632 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001633 mirror::Object* obj =
1634 GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1635 if (obj == nullptr) {
1636 return nullptr;
1637 }
Jeff Hao2a5892f2015-08-31 15:00:40 -07001638 return obj->AsObjectArray<mirror::Class>();
Jeff Hao13e748b2015-08-25 20:44:19 +00001639}
1640
1641mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1642 const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1643 Thread* self = Thread::Current();
1644 ScopedObjectAccessUnchecked soa(self);
1645 StackHandleScope<2> hs(self);
1646 Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1647 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1648 if (annotation_set == nullptr) {
1649 return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1650 }
1651
1652 uint32_t size = annotation_set->size_;
1653 Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1654 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1655 if (result.Get() == nullptr) {
1656 return nullptr;
1657 }
1658
1659 uint32_t dest_index = 0;
1660 for (uint32_t i = 0; i < size; ++i) {
1661 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1662 if (annotation_item->visibility_ != visibility) {
1663 continue;
1664 }
1665 const uint8_t* annotation = annotation_item->annotation_;
1666 mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1667 if (annotation_obj != nullptr) {
1668 result->SetWithoutChecks<false>(dest_index, annotation_obj);
1669 ++dest_index;
Jeff Hao2a5892f2015-08-31 15:00:40 -07001670 } else if (self->IsExceptionPending()) {
1671 return nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00001672 }
1673 }
1674
1675 if (dest_index == size) {
1676 return result.Get();
1677 }
1678
1679 mirror::ObjectArray<mirror::Object>* trimmed_result =
1680 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001681 if (trimmed_result == nullptr) {
1682 return nullptr;
1683 }
1684
Jeff Hao13e748b2015-08-25 20:44:19 +00001685 for (uint32_t i = 0; i < dest_index; ++i) {
1686 mirror::Object* obj = result->GetWithoutChecks(i);
1687 trimmed_result->SetWithoutChecks<false>(i, obj);
1688 }
1689
1690 return trimmed_result;
1691}
1692
1693mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1694 Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1695 Thread* self = Thread::Current();
1696 ScopedObjectAccessUnchecked soa(self);
1697 StackHandleScope<1> hs(self);
1698 mirror::Class* annotation_array_class =
1699 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1700 mirror::Class* annotation_array_array_class =
1701 Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07001702 if (annotation_array_array_class == nullptr) {
1703 return nullptr;
1704 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001705 Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1706 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1707 if (annotation_array_array.Get() == nullptr) {
1708 LOG(ERROR) << "Annotation set ref array allocation failed";
1709 return nullptr;
1710 }
1711 for (uint32_t index = 0; index < size; ++index) {
1712 const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1713 const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1714 mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1715 if (annotation_set == nullptr) {
1716 return nullptr;
1717 }
1718 annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1719 }
1720 return annotation_array_array.Get();
1721}
1722
1723bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1724 AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1725 DexFile::AnnotationResultStyle result_style) const {
1726 Thread* self = Thread::Current();
1727 mirror::Object* element_object = nullptr;
1728 bool set_object = false;
1729 Primitive::Type primitive_type = Primitive::kPrimVoid;
1730 const uint8_t* annotation = *annotation_ptr;
1731 uint8_t header_byte = *(annotation++);
1732 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1733 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1734 int32_t width = value_arg + 1;
1735 annotation_value->type_ = value_type;
1736
1737 switch (value_type) {
1738 case kDexAnnotationByte:
1739 annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1740 primitive_type = Primitive::kPrimByte;
1741 break;
1742 case kDexAnnotationShort:
1743 annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1744 primitive_type = Primitive::kPrimShort;
1745 break;
1746 case kDexAnnotationChar:
1747 annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1748 false)));
1749 primitive_type = Primitive::kPrimChar;
1750 break;
1751 case kDexAnnotationInt:
1752 annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1753 primitive_type = Primitive::kPrimInt;
1754 break;
1755 case kDexAnnotationLong:
1756 annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1757 primitive_type = Primitive::kPrimLong;
1758 break;
1759 case kDexAnnotationFloat:
1760 annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1761 primitive_type = Primitive::kPrimFloat;
1762 break;
1763 case kDexAnnotationDouble:
1764 annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1765 primitive_type = Primitive::kPrimDouble;
1766 break;
1767 case kDexAnnotationBoolean:
1768 annotation_value->value_.SetZ(value_arg != 0);
1769 primitive_type = Primitive::kPrimBoolean;
1770 width = 0;
1771 break;
1772 case kDexAnnotationString: {
1773 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1774 if (result_style == kAllRaw) {
1775 annotation_value->value_.SetI(index);
1776 } else {
1777 StackHandleScope<1> hs(self);
1778 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1779 element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1780 klass->GetDexFile(), index, dex_cache);
1781 set_object = true;
1782 if (element_object == nullptr) {
1783 return false;
1784 }
1785 }
1786 break;
1787 }
1788 case kDexAnnotationType: {
1789 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1790 if (result_style == kAllRaw) {
1791 annotation_value->value_.SetI(index);
1792 } else {
1793 element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1794 klass->GetDexFile(), index, klass.Get());
1795 set_object = true;
1796 if (element_object == nullptr) {
Jeff Haofc8d2472015-09-02 13:52:20 -07001797 CHECK(self->IsExceptionPending());
1798 if (result_style == kAllObjects) {
1799 const char* msg = StringByTypeIdx(index);
1800 self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1801 element_object = self->GetException();
1802 self->ClearException();
1803 } else {
1804 return false;
1805 }
Jeff Hao13e748b2015-08-25 20:44:19 +00001806 }
1807 }
1808 break;
1809 }
1810 case kDexAnnotationMethod: {
1811 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1812 if (result_style == kAllRaw) {
1813 annotation_value->value_.SetI(index);
1814 } else {
1815 StackHandleScope<2> hs(self);
1816 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1817 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1818 ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1819 klass->GetDexFile(), index, dex_cache, class_loader);
1820 if (method == nullptr) {
1821 return false;
1822 }
1823 set_object = true;
1824 if (method->IsConstructor()) {
1825 element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1826 } else {
1827 element_object = mirror::Method::CreateFromArtMethod(self, method);
1828 }
1829 if (element_object == nullptr) {
1830 return false;
1831 }
1832 }
1833 break;
1834 }
1835 case kDexAnnotationField: {
1836 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1837 if (result_style == kAllRaw) {
1838 annotation_value->value_.SetI(index);
1839 } else {
1840 StackHandleScope<2> hs(self);
1841 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1842 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1843 ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1844 klass->GetDexFile(), index, dex_cache, class_loader);
1845 if (field == nullptr) {
1846 return false;
1847 }
1848 set_object = true;
1849 element_object = mirror::Field::CreateFromArtField(self, field, true);
1850 if (element_object == nullptr) {
1851 return false;
1852 }
1853 }
1854 break;
1855 }
1856 case kDexAnnotationEnum: {
1857 uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1858 if (result_style == kAllRaw) {
1859 annotation_value->value_.SetI(index);
1860 } else {
1861 StackHandleScope<3> hs(self);
1862 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1863 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1864 ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1865 klass->GetDexFile(), index, dex_cache, class_loader, true);
1866 Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1867 if (enum_field == nullptr) {
1868 return false;
1869 } else {
1870 Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1871 element_object = enum_field->GetObject(field_class.Get());
1872 set_object = true;
1873 }
1874 }
1875 break;
1876 }
1877 case kDexAnnotationArray:
1878 if (result_style == kAllRaw || array_class.Get() == nullptr) {
1879 return false;
1880 } else {
1881 ScopedObjectAccessUnchecked soa(self);
1882 StackHandleScope<2> hs(self);
1883 uint32_t size = DecodeUnsignedLeb128(&annotation);
1884 Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1885 Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1886 self, array_class.Get(), size, array_class->GetComponentSizeShift(),
1887 Runtime::Current()->GetHeap()->GetCurrentAllocator())));
1888 if (new_array.Get() == nullptr) {
1889 LOG(ERROR) << "Annotation element array allocation failed with size " << size;
1890 return false;
1891 }
1892 AnnotationValue new_annotation_value;
1893 for (uint32_t i = 0; i < size; ++i) {
1894 if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
1895 kPrimitivesOrObjects)) {
1896 return false;
1897 }
1898 if (!component_type->IsPrimitive()) {
1899 mirror::Object* obj = new_annotation_value.value_.GetL();
1900 new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
1901 } else {
1902 switch (new_annotation_value.type_) {
1903 case kDexAnnotationByte:
1904 new_array->AsByteArray()->SetWithoutChecks<false>(
1905 i, new_annotation_value.value_.GetB());
1906 break;
1907 case kDexAnnotationShort:
1908 new_array->AsShortArray()->SetWithoutChecks<false>(
1909 i, new_annotation_value.value_.GetS());
1910 break;
1911 case kDexAnnotationChar:
1912 new_array->AsCharArray()->SetWithoutChecks<false>(
1913 i, new_annotation_value.value_.GetC());
1914 break;
1915 case kDexAnnotationInt:
1916 new_array->AsIntArray()->SetWithoutChecks<false>(
1917 i, new_annotation_value.value_.GetI());
1918 break;
1919 case kDexAnnotationLong:
1920 new_array->AsLongArray()->SetWithoutChecks<false>(
1921 i, new_annotation_value.value_.GetJ());
1922 break;
1923 case kDexAnnotationFloat:
1924 new_array->AsFloatArray()->SetWithoutChecks<false>(
1925 i, new_annotation_value.value_.GetF());
1926 break;
1927 case kDexAnnotationDouble:
1928 new_array->AsDoubleArray()->SetWithoutChecks<false>(
1929 i, new_annotation_value.value_.GetD());
1930 break;
1931 case kDexAnnotationBoolean:
1932 new_array->AsBooleanArray()->SetWithoutChecks<false>(
1933 i, new_annotation_value.value_.GetZ());
1934 break;
1935 default:
1936 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
1937 return false;
1938 }
1939 }
1940 }
1941 element_object = new_array.Get();
1942 set_object = true;
1943 width = 0;
1944 }
1945 break;
1946 case kDexAnnotationAnnotation:
1947 if (result_style == kAllRaw) {
1948 return false;
1949 }
1950 element_object = ProcessEncodedAnnotation(klass, &annotation);
1951 if (element_object == nullptr) {
1952 return false;
1953 }
1954 set_object = true;
1955 width = 0;
1956 break;
1957 case kDexAnnotationNull:
1958 if (result_style == kAllRaw) {
1959 annotation_value->value_.SetI(0);
1960 } else {
1961 CHECK(element_object == nullptr);
1962 set_object = true;
1963 }
1964 width = 0;
1965 break;
1966 default:
1967 LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
1968 return false;
1969 }
1970
1971 annotation += width;
1972 *annotation_ptr = annotation;
1973
1974 if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
1975 element_object = BoxPrimitive(primitive_type, annotation_value->value_);
1976 set_object = true;
1977 }
1978
1979 if (set_object) {
1980 annotation_value->value_.SetL(element_object);
1981 }
1982
1983 return true;
1984}
1985
1986mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
1987 const uint8_t** annotation) const {
1988 uint32_t type_index = DecodeUnsignedLeb128(annotation);
1989 uint32_t size = DecodeUnsignedLeb128(annotation);
1990
1991 Thread* self = Thread::Current();
1992 ScopedObjectAccessUnchecked soa(self);
1993 StackHandleScope<2> hs(self);
1994 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1995 Handle<mirror::Class> annotation_class(hs.NewHandle(
1996 class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
1997 if (annotation_class.Get() == nullptr) {
1998 LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
1999 << type_index;
2000 DCHECK(Thread::Current()->IsExceptionPending());
2001 Thread::Current()->ClearException();
2002 return nullptr;
2003 }
2004
2005 mirror::Class* annotation_member_class =
2006 soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2007 mirror::Class* annotation_member_array_class =
2008 class_linker->FindArrayClass(self, &annotation_member_class);
Jeff Hao2a5892f2015-08-31 15:00:40 -07002009 if (annotation_member_array_class == nullptr) {
2010 return nullptr;
2011 }
Jeff Hao13e748b2015-08-25 20:44:19 +00002012 mirror::ObjectArray<mirror::Object>* element_array = nullptr;
Jeff Hao13e748b2015-08-25 20:44:19 +00002013 if (size > 0) {
2014 element_array =
2015 mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2016 if (element_array == nullptr) {
2017 LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2018 return nullptr;
2019 }
2020 }
2021
2022 Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2023 for (uint32_t i = 0; i < size; ++i) {
2024 mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2025 if (new_member == nullptr) {
2026 return nullptr;
2027 }
2028 h_element_array->SetWithoutChecks<false>(i, new_member);
2029 }
2030
2031 JValue result;
2032 ArtMethod* create_annotation_method =
2033 soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2034 uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2035 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2036 create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2037 if (self->IsExceptionPending()) {
2038 LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2039 return nullptr;
2040 }
2041
2042 return result.GetL();
2043}
2044
2045const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2046 const char* descriptor, uint32_t visibility) const {
2047 const AnnotationItem* result = nullptr;
2048 for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2049 const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2050 if (annotation_item->visibility_ != visibility) {
2051 continue;
2052 }
2053 const uint8_t* annotation = annotation_item->annotation_;
2054 uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2055
2056 if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2057 result = annotation_item;
2058 break;
2059 }
2060 }
2061 return result;
2062}
2063
2064const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2065 DecodeUnsignedLeb128(&annotation); // unused type_index
2066 uint32_t size = DecodeUnsignedLeb128(&annotation);
2067
2068 while (size != 0) {
2069 uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2070 const char* element_name = GetStringData(GetStringId(element_name_index));
2071 if (strcmp(name, element_name) == 0) {
2072 return annotation;
2073 }
2074 SkipAnnotationValue(&annotation);
2075 size--;
2076 }
2077 return nullptr;
2078}
2079
2080bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2081 const uint8_t* annotation = *annotation_ptr;
2082 uint8_t header_byte = *(annotation++);
2083 uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2084 uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2085 int32_t width = value_arg + 1;
2086
2087 switch (value_type) {
2088 case kDexAnnotationByte:
2089 case kDexAnnotationShort:
2090 case kDexAnnotationChar:
2091 case kDexAnnotationInt:
2092 case kDexAnnotationLong:
2093 case kDexAnnotationFloat:
2094 case kDexAnnotationDouble:
2095 case kDexAnnotationString:
2096 case kDexAnnotationType:
2097 case kDexAnnotationMethod:
2098 case kDexAnnotationField:
2099 case kDexAnnotationEnum:
2100 break;
2101 case kDexAnnotationArray:
2102 {
2103 uint32_t size = DecodeUnsignedLeb128(&annotation);
2104 while (size--) {
2105 if (!SkipAnnotationValue(&annotation)) {
2106 return false;
2107 }
2108 }
2109 width = 0;
2110 break;
2111 }
2112 case kDexAnnotationAnnotation:
2113 {
2114 DecodeUnsignedLeb128(&annotation); // unused type_index
2115 uint32_t size = DecodeUnsignedLeb128(&annotation);
2116 while (size--) {
2117 DecodeUnsignedLeb128(&annotation); // unused element_name_index
2118 if (!SkipAnnotationValue(&annotation)) {
2119 return false;
2120 }
2121 }
2122 width = 0;
2123 break;
2124 }
2125 case kDexAnnotationBoolean:
2126 case kDexAnnotationNull:
2127 width = 0;
2128 break;
2129 default:
2130 LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2131 return false;
2132 }
2133
2134 annotation += width;
2135 *annotation_ptr = annotation;
2136 return true;
2137}
2138
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08002139std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2140 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2141 dex_file.GetLocation().c_str(),
2142 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2143 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2144 return os;
2145}
Calin Juravle4e1d5792014-07-15 23:56:47 +01002146
Ian Rogersd91d6d62013-09-25 20:26:14 -07002147std::string Signature::ToString() const {
2148 if (dex_file_ == nullptr) {
2149 CHECK(proto_id_ == nullptr);
2150 return "<no signature>";
2151 }
2152 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2153 std::string result;
2154 if (params == nullptr) {
2155 result += "()";
2156 } else {
2157 result += "(";
2158 for (uint32_t i = 0; i < params->Size(); ++i) {
2159 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2160 }
2161 result += ")";
2162 }
2163 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2164 return result;
2165}
2166
Vladimir Markod9cffea2013-11-25 15:08:02 +00002167bool Signature::operator==(const StringPiece& rhs) const {
2168 if (dex_file_ == nullptr) {
2169 return false;
2170 }
2171 StringPiece tail(rhs);
2172 if (!tail.starts_with("(")) {
2173 return false; // Invalid signature
2174 }
2175 tail.remove_prefix(1); // "(";
2176 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2177 if (params != nullptr) {
2178 for (uint32_t i = 0; i < params->Size(); ++i) {
2179 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2180 if (!tail.starts_with(param)) {
2181 return false;
2182 }
2183 tail.remove_prefix(param.length());
2184 }
2185 }
2186 if (!tail.starts_with(")")) {
2187 return false;
2188 }
2189 tail.remove_prefix(1); // ")";
2190 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2191}
2192
Ian Rogersd91d6d62013-09-25 20:26:14 -07002193std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2194 return os << sig.ToString();
2195}
2196
Ian Rogers0571d352011-11-03 19:51:38 -07002197// Decodes the header section from the class data bytes.
2198void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002199 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002200 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2201 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2202 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2203 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2204}
2205
2206void ClassDataItemIterator::ReadClassDataField() {
2207 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2208 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +01002209 // The user of the iterator is responsible for checking if there
2210 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -07002211}
2212
2213void ClassDataItemIterator::ReadClassDataMethod() {
2214 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2215 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2216 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -07002217 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -07002218 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07002219 }
Ian Rogers0571d352011-11-03 19:51:38 -07002220}
2221
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002222EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2223 const DexFile& dex_file, Handle<mirror::DexCache>* dex_cache,
2224 Handle<mirror::ClassLoader>* class_loader, ClassLinker* linker,
2225 const DexFile::ClassDef& class_def)
Brian Carlstrom88f36542012-10-16 23:24:21 -07002226 : dex_file_(dex_file), dex_cache_(dex_cache), class_loader_(class_loader), linker_(linker),
2227 array_size_(), pos_(-1), type_(kByte) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002228 DCHECK(dex_cache != nullptr);
2229 DCHECK(class_loader != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -07002230 ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002231 if (ptr_ == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002232 array_size_ = 0;
2233 } else {
2234 array_size_ = DecodeUnsignedLeb128(&ptr_);
2235 }
2236 if (array_size_ > 0) {
2237 Next();
2238 }
2239}
2240
2241void EncodedStaticFieldValueIterator::Next() {
2242 pos_++;
2243 if (pos_ >= array_size_) {
2244 return;
2245 }
Ian Rogers13735952014-10-08 12:43:28 -07002246 uint8_t value_type = *ptr_++;
2247 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -07002248 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -07002249 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -07002250 switch (type_) {
2251 case kBoolean:
2252 jval_.i = (value_arg != 0) ? 1 : 0;
2253 width = 0;
2254 break;
2255 case kByte:
2256 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002257 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002258 break;
2259 case kShort:
2260 jval_.i = ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002261 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002262 break;
2263 case kChar:
2264 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08002265 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07002266 break;
2267 case kInt:
2268 jval_.i = ReadSignedInt(ptr_, value_arg);
2269 break;
2270 case kLong:
2271 jval_.j = ReadSignedLong(ptr_, value_arg);
2272 break;
2273 case kFloat:
2274 jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2275 break;
2276 case kDouble:
2277 jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2278 break;
2279 case kString:
2280 case kType:
Ian Rogers0571d352011-11-03 19:51:38 -07002281 jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2282 break;
2283 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07002284 case kMethod:
2285 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07002286 case kArray:
2287 case kAnnotation:
2288 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07002289 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002290 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002291 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002292 width = 0;
2293 break;
2294 default:
2295 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07002296 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07002297 }
2298 ptr_ += width;
2299}
2300
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002301template<bool kTransactionActive>
Mathieu Chartierc7853442015-03-27 14:35:38 -07002302void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
Ian Rogers0571d352011-11-03 19:51:38 -07002303 switch (type_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002304 case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2305 break;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002306 case kByte: field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2307 case kShort: field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2308 case kChar: field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2309 case kInt: field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2310 case kLong: field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2311 case kFloat: field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2312 case kDouble: field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002313 case kNull: field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
Ian Rogers0571d352011-11-03 19:51:38 -07002314 case kString: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002315 mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002316 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Ian Rogers0571d352011-11-03 19:51:38 -07002317 break;
2318 }
Brian Carlstrom88f36542012-10-16 23:24:21 -07002319 case kType: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002320 mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2321 *class_loader_);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002322 field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
Brian Carlstrom88f36542012-10-16 23:24:21 -07002323 break;
2324 }
Ian Rogers0571d352011-11-03 19:51:38 -07002325 default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2326 }
2327}
Mathieu Chartierc7853442015-03-27 14:35:38 -07002328template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2329template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
Ian Rogers0571d352011-11-03 19:51:38 -07002330
2331CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2332 handler_.address_ = -1;
2333 int32_t offset = -1;
2334
2335 // Short-circuit the overwhelmingly common cases.
2336 switch (code_item.tries_size_) {
2337 case 0:
2338 break;
2339 case 1: {
2340 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2341 uint32_t start = tries->start_addr_;
2342 if (address >= start) {
2343 uint32_t end = start + tries->insn_count_;
2344 if (address < end) {
2345 offset = tries->handler_off_;
2346 }
2347 }
2348 break;
2349 }
2350 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07002351 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07002352 }
Logan Chien736df022012-04-27 16:25:57 +08002353 Init(code_item, offset);
2354}
2355
2356CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2357 const DexFile::TryItem& try_item) {
2358 handler_.address_ = -1;
2359 Init(code_item, try_item.handler_off_);
2360}
2361
2362void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2363 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07002364 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08002365 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07002366 } else {
2367 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002368 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002369 remaining_count_ = -1;
2370 catch_all_ = false;
2371 DCHECK(!HasNext());
2372 }
2373}
2374
Ian Rogers13735952014-10-08 12:43:28 -07002375void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07002376 current_data_ = handler_data;
2377 remaining_count_ = DecodeSignedLeb128(&current_data_);
2378
2379 // If remaining_count_ is non-positive, then it is the negative of
2380 // the number of catch types, and the catches are followed by a
2381 // catch-all handler.
2382 if (remaining_count_ <= 0) {
2383 catch_all_ = true;
2384 remaining_count_ = -remaining_count_;
2385 } else {
2386 catch_all_ = false;
2387 }
2388 Next();
2389}
2390
2391void CatchHandlerIterator::Next() {
2392 if (remaining_count_ > 0) {
2393 handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2394 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2395 remaining_count_--;
2396 return;
2397 }
2398
2399 if (catch_all_) {
2400 handler_.type_idx_ = DexFile::kDexNoIndex16;
2401 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
2402 catch_all_ = false;
2403 return;
2404 }
2405
2406 // no more handler
2407 remaining_count_ = -1;
2408}
2409
Carl Shapiro1fb86202011-06-27 17:43:13 -07002410} // namespace art