blob: 08c047d8e9bf1f5394d5d36fa700f2b68cdef0cc [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>
Andreas Gampe0dfc3152017-04-24 07:58:06 -070025#include <sys/mman.h> // For the PROT_* and MAP_* constants.
Alex Light40528472017-03-28 09:07:36 -070026#include <zlib.h>
Ian Rogersc7dd2952014-10-21 23:31:19 -070027
Ian Rogers700a4022014-05-19 16:49:03 -070028#include <memory>
Ian Rogersc7dd2952014-10-21 23:31:19 -070029#include <sstream>
Andreas Gampea5b09a62016-11-17 15:21:22 -080030#include <type_traits>
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070031
Andreas Gampe46ee31b2016-12-14 10:11:49 -080032#include "android-base/stringprintf.h"
33
Andreas Gampe542451c2016-07-26 09:02:02 -070034#include "base/enums.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080035#include "base/logging.h"
Andreas Gampe5678db52017-06-08 14:11:18 -070036#include "base/stl_util.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070038#include "dex_file_loader.h"
Vladimir Marko3a21e382016-09-02 12:38:38 +010039#include "jvalue.h"
Ian Rogers0571d352011-11-03 19:51:38 -070040#include "leb128.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070041#include "mem_map.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070042#include "os.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070043#include "standard_dex_file.h"
Ian Rogersa6724902013-09-23 09:23:37 -070044#include "utf-inl.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070045#include "utils.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070046
47namespace art {
48
Andreas Gampe46ee31b2016-12-14 10:11:49 -080049using android::base::StringPrintf;
50
Andreas Gampe8a0128a2016-11-28 07:38:35 -080051static_assert(sizeof(dex::StringIndex) == sizeof(uint32_t), "StringIndex size is wrong");
52static_assert(std::is_trivially_copyable<dex::StringIndex>::value, "StringIndex not trivial");
Andreas Gampea5b09a62016-11-17 15:21:22 -080053static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
54static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
55
Alex Light40528472017-03-28 09:07:36 -070056uint32_t DexFile::CalculateChecksum() const {
57 const uint32_t non_sum = OFFSETOF_MEMBER(DexFile::Header, signature_);
58 const uint8_t* non_sum_ptr = Begin() + non_sum;
59 return adler32(adler32(0L, Z_NULL, 0), non_sum_ptr, Size() - non_sum);
60}
61
Vladimir Marko3a21e382016-09-02 12:38:38 +010062struct DexFile::AnnotationValue {
63 JValue value_;
64 uint8_t type_;
65};
66
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080067int DexFile::GetPermissions() const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070068 if (mem_map_.get() == nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080069 return 0;
70 } else {
71 return mem_map_->GetProtect();
72 }
73}
74
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020075bool DexFile::IsReadOnly() const {
76 return GetPermissions() == PROT_READ;
77}
78
Brian Carlstrome0948e12013-08-29 09:36:15 -070079bool DexFile::EnableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020080 CHECK(IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -070081 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020082 return false;
83 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -070084 return mem_map_->Protect(PROT_READ | PROT_WRITE);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020085 }
86}
87
Brian Carlstrome0948e12013-08-29 09:36:15 -070088bool DexFile::DisableWrite() const {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020089 CHECK(!IsReadOnly());
Mathieu Chartier2cebb242015-04-21 16:50:40 -070090 if (mem_map_.get() == nullptr) {
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020091 return false;
92 } else {
Brian Carlstrome0948e12013-08-29 09:36:15 -070093 return mem_map_->Protect(PROT_READ);
Sebastien Hertz2d6ba512013-05-17 11:31:37 +020094 }
95}
96
David Sehr733ddb22016-09-19 15:02:18 -070097DexFile::DexFile(const uint8_t* base,
98 size_t size,
Brian Carlstrom0d6adac2014-02-05 17:39:16 -080099 const std::string& location,
100 uint32_t location_checksum,
Richard Uhler07b3c232015-03-31 15:57:54 -0700101 const OatDexFile* oat_dex_file)
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800102 : begin_(base),
103 size_(size),
104 location_(location),
105 location_checksum_(location_checksum),
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800106 header_(reinterpret_cast<const Header*>(base)),
107 string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
108 type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
109 field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
110 method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
111 proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
Ian Rogers68b56852014-08-29 20:19:11 -0700112 class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000113 method_handles_(nullptr),
114 num_method_handles_(0),
115 call_site_ids_(nullptr),
116 num_call_site_ids_(0),
Richard Uhler07b3c232015-03-31 15:57:54 -0700117 oat_dex_file_(oat_dex_file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 CHECK(begin_ != nullptr) << GetLocation();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800119 CHECK_GT(size_, 0U) << GetLocation();
Igor Murashkin271a0f82017-02-14 21:14:17 +0000120 // Check base (=header) alignment.
121 // Must be 4-byte aligned to avoid undefined behavior when accessing
122 // any of the sections via a pointer.
123 CHECK_ALIGNED(begin_, alignof(Header));
124
Orion Hodson12f4ff42017-01-13 16:43:12 +0000125 InitializeSectionsFromMapList();
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800126}
127
Jesse Wilson6bf19152011-09-29 13:12:33 -0400128DexFile::~DexFile() {
Elliott Hughes8cef0b82011-10-11 19:24:00 -0700129 // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
130 // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
131 // re-attach, but cleaning up these global references is not obviously useful. It's not as if
132 // the global reference table is otherwise empty!
Jesse Wilson6bf19152011-09-29 13:12:33 -0400133}
134
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700135bool DexFile::Init(std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700136 if (!CheckMagicAndVersion(error_msg)) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700137 return false;
138 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700139 return true;
140}
141
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700142bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700143 if (!IsMagicValid()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700144 std::ostringstream oss;
145 oss << "Unrecognized magic number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800146 << " " << header_->magic_[0]
147 << " " << header_->magic_[1]
148 << " " << header_->magic_[2]
149 << " " << header_->magic_[3];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700151 return false;
152 }
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700153 if (!IsVersionValid()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700154 std::ostringstream oss;
155 oss << "Unrecognized version number in " << GetLocation() << ":"
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800156 << " " << header_->magic_[4]
157 << " " << header_->magic_[5]
158 << " " << header_->magic_[6]
159 << " " << header_->magic_[7];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700160 *error_msg = oss.str();
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700161 return false;
162 }
163 return true;
164}
165
Orion Hodson12f4ff42017-01-13 16:43:12 +0000166void DexFile::InitializeSectionsFromMapList() {
167 const MapList* map_list = reinterpret_cast<const MapList*>(begin_ + header_->map_off_);
Jeff Haoa4cd6772017-04-13 14:36:29 -0700168 if (header_->map_off_ == 0 || header_->map_off_ > size_) {
169 // Bad offset. The dex file verifier runs after this method and will reject the file.
170 return;
171 }
Orion Hodson12f4ff42017-01-13 16:43:12 +0000172 const size_t count = map_list->size_;
173
174 size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
175 if (header_->map_off_ >= map_limit || map_limit > size_) {
176 // Overflow or out out of bounds. The dex file verifier runs after
177 // this method and will reject the file as it is malformed.
178 return;
179 }
180
181 for (size_t i = 0; i < count; ++i) {
182 const MapItem& map_item = map_list->list_[i];
183 if (map_item.type_ == kDexTypeMethodHandleItem) {
184 method_handles_ = reinterpret_cast<const MethodHandleItem*>(begin_ + map_item.offset_);
185 num_method_handles_ = map_item.size_;
186 } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
187 call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(begin_ + map_item.offset_);
188 num_call_site_ids_ = map_item.size_;
189 }
190 }
191}
192
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700193uint32_t DexFile::Header::GetVersion() const {
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700194 const char* version = reinterpret_cast<const char*>(&magic_[kDexMagicSize]);
Ian Rogersd81871c2011-10-03 13:57:23 -0700195 return atoi(version);
196}
197
Andreas Gampea5b09a62016-11-17 15:21:22 -0800198const DexFile::ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
David Sehr9aa352e2016-09-15 18:13:52 -0700199 size_t num_class_defs = NumClassDefs();
Roland Levillainab880f42016-05-12 16:24:36 +0100200 // Fast path for rare no class defs case.
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700201 if (num_class_defs == 0) {
Ian Rogers68b56852014-08-29 20:19:11 -0700202 return nullptr;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700203 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700204 for (size_t i = 0; i < num_class_defs; ++i) {
205 const ClassDef& class_def = GetClassDef(i);
206 if (class_def.class_idx_ == type_idx) {
207 return &class_def;
208 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700209 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700210 return nullptr;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700211}
212
Alex Light9c20a142016-08-23 15:05:12 -0700213uint32_t DexFile::FindCodeItemOffset(const DexFile::ClassDef& class_def,
214 uint32_t method_idx) const {
215 const uint8_t* class_data = GetClassData(class_def);
216 CHECK(class_data != nullptr);
217 ClassDataItemIterator it(*this, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700218 it.SkipAllFields();
Alex Light9c20a142016-08-23 15:05:12 -0700219 while (it.HasNextDirectMethod()) {
220 if (it.GetMemberIndex() == method_idx) {
221 return it.GetMethodCodeItemOffset();
222 }
223 it.Next();
224 }
225 while (it.HasNextVirtualMethod()) {
226 if (it.GetMemberIndex() == method_idx) {
227 return it.GetMethodCodeItemOffset();
228 }
229 it.Next();
230 }
231 LOG(FATAL) << "Unable to find method " << method_idx;
232 UNREACHABLE();
233}
234
Bharadwaj Kalandhabhatta043c9082017-06-06 17:14:12 -0700235uint32_t DexFile::GetCodeItemSize(const DexFile::CodeItem& code_item) {
236 uintptr_t code_item_start = reinterpret_cast<uintptr_t>(&code_item);
237 uint32_t insns_size = code_item.insns_size_in_code_units_;
238 uint32_t tries_size = code_item.tries_size_;
239 const uint8_t* handler_data = GetCatchHandlerData(code_item, 0);
240
241 if (tries_size == 0 || handler_data == nullptr) {
242 uintptr_t insns_end = reinterpret_cast<uintptr_t>(&code_item.insns_[insns_size]);
243 return insns_end - code_item_start;
244 } else {
245 // Get the start of the handler data.
246 uint32_t handlers_size = DecodeUnsignedLeb128(&handler_data);
247 // Manually read each handler.
248 for (uint32_t i = 0; i < handlers_size; ++i) {
249 int32_t uleb128_count = DecodeSignedLeb128(&handler_data) * 2;
250 if (uleb128_count <= 0) {
251 uleb128_count = -uleb128_count + 1;
252 }
253 for (int32_t j = 0; j < uleb128_count; ++j) {
254 DecodeUnsignedLeb128(&handler_data);
255 }
256 }
257 return reinterpret_cast<uintptr_t>(handler_data) - code_item_start;
258 }
259}
260
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800261const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
Roland Levillainab880f42016-05-12 16:24:36 +0100262 const DexFile::StringId& name,
263 const DexFile::TypeId& type) const {
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800264 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800265 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800266 const dex::StringIndex name_idx = GetIndexForStringId(name);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800267 const dex::TypeIndex type_idx = GetIndexForTypeId(type);
Ian Rogersf8582c32013-05-29 16:33:03 -0700268 int32_t lo = 0;
269 int32_t hi = NumFieldIds() - 1;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800270 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700271 int32_t mid = (hi + lo) / 2;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800272 const DexFile::FieldId& field = GetFieldId(mid);
273 if (class_idx > field.class_idx_) {
274 lo = mid + 1;
275 } else if (class_idx < field.class_idx_) {
276 hi = mid - 1;
277 } else {
278 if (name_idx > field.name_idx_) {
279 lo = mid + 1;
280 } else if (name_idx < field.name_idx_) {
281 hi = mid - 1;
282 } else {
283 if (type_idx > field.type_idx_) {
284 lo = mid + 1;
285 } else if (type_idx < field.type_idx_) {
286 hi = mid - 1;
287 } else {
288 return &field;
289 }
290 }
291 }
292 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700293 return nullptr;
Ian Rogers9b1a4f42011-11-14 18:35:10 -0800294}
295
296const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
Ian Rogers0571d352011-11-03 19:51:38 -0700297 const DexFile::StringId& name,
298 const DexFile::ProtoId& signature) const {
299 // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
Andreas Gampea5b09a62016-11-17 15:21:22 -0800300 const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800301 const dex::StringIndex name_idx = GetIndexForStringId(name);
Ian Rogers0571d352011-11-03 19:51:38 -0700302 const uint16_t proto_idx = GetIndexForProtoId(signature);
Ian Rogersf8582c32013-05-29 16:33:03 -0700303 int32_t lo = 0;
304 int32_t hi = NumMethodIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700305 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700306 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700307 const DexFile::MethodId& method = GetMethodId(mid);
308 if (class_idx > method.class_idx_) {
309 lo = mid + 1;
310 } else if (class_idx < method.class_idx_) {
311 hi = mid - 1;
312 } else {
313 if (name_idx > method.name_idx_) {
314 lo = mid + 1;
315 } else if (name_idx < method.name_idx_) {
316 hi = mid - 1;
317 } else {
318 if (proto_idx > method.proto_idx_) {
319 lo = mid + 1;
320 } else if (proto_idx < method.proto_idx_) {
321 hi = mid - 1;
322 } else {
323 return &method;
324 }
325 }
326 }
327 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700328 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700329}
330
Ian Rogers637c65b2013-05-31 11:46:00 -0700331const DexFile::StringId* DexFile::FindStringId(const char* string) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700332 int32_t lo = 0;
333 int32_t hi = NumStringIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700334 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700335 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800336 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700337 const char* str = GetStringData(str_id);
Ian Rogers637c65b2013-05-31 11:46:00 -0700338 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
339 if (compare > 0) {
340 lo = mid + 1;
341 } else if (compare < 0) {
342 hi = mid - 1;
343 } else {
344 return &str_id;
345 }
346 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700347 return nullptr;
Ian Rogers637c65b2013-05-31 11:46:00 -0700348}
349
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300350const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
351 int32_t lo = 0;
352 int32_t hi = NumTypeIds() - 1;
353 while (hi >= lo) {
354 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800355 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300356 const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
357 const char* str = GetStringData(str_id);
358 int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
359 if (compare > 0) {
360 lo = mid + 1;
361 } else if (compare < 0) {
362 hi = mid - 1;
363 } else {
364 return &type_id;
365 }
366 }
367 return nullptr;
368}
369
Vladimir Markoa48aef42014-12-03 17:53:53 +0000370const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
Ian Rogers637c65b2013-05-31 11:46:00 -0700371 int32_t lo = 0;
372 int32_t hi = NumStringIds() - 1;
373 while (hi >= lo) {
374 int32_t mid = (hi + lo) / 2;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800375 const DexFile::StringId& str_id = GetStringId(dex::StringIndex(mid));
Ian Rogerscf5077a2013-10-31 12:37:54 -0700376 const char* str = GetStringData(str_id);
Vladimir Markoa48aef42014-12-03 17:53:53 +0000377 int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
Ian Rogers0571d352011-11-03 19:51:38 -0700378 if (compare > 0) {
379 lo = mid + 1;
380 } else if (compare < 0) {
381 hi = mid - 1;
382 } else {
383 return &str_id;
384 }
385 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700386 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700387}
388
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800389const DexFile::TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700390 int32_t lo = 0;
391 int32_t hi = NumTypeIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700392 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700393 int32_t mid = (hi + lo) / 2;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800394 const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
Ian Rogers0571d352011-11-03 19:51:38 -0700395 if (string_idx > type_id.descriptor_idx_) {
396 lo = mid + 1;
397 } else if (string_idx < type_id.descriptor_idx_) {
398 hi = mid - 1;
399 } else {
400 return &type_id;
401 }
402 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700403 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700404}
405
Andreas Gampea5b09a62016-11-17 15:21:22 -0800406const DexFile::ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
407 const dex::TypeIndex* signature_type_idxs,
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000408 uint32_t signature_length) const {
Ian Rogersf8582c32013-05-29 16:33:03 -0700409 int32_t lo = 0;
410 int32_t hi = NumProtoIds() - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700411 while (hi >= lo) {
Ian Rogersf8582c32013-05-29 16:33:03 -0700412 int32_t mid = (hi + lo) / 2;
Ian Rogers0571d352011-11-03 19:51:38 -0700413 const DexFile::ProtoId& proto = GetProtoId(mid);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800414 int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700415 if (compare == 0) {
416 DexFileParameterIterator it(*this, proto);
417 size_t i = 0;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000418 while (it.HasNext() && i < signature_length && compare == 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800419 compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
Ian Rogers0571d352011-11-03 19:51:38 -0700420 it.Next();
421 i++;
422 }
423 if (compare == 0) {
424 if (it.HasNext()) {
425 compare = -1;
Vladimir Marko5c96e6b2013-11-14 15:34:17 +0000426 } else if (i < signature_length) {
Ian Rogers0571d352011-11-03 19:51:38 -0700427 compare = 1;
428 }
429 }
430 }
431 if (compare > 0) {
432 lo = mid + 1;
433 } else if (compare < 0) {
434 hi = mid - 1;
435 } else {
436 return &proto;
437 }
438 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700439 return nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -0700440}
441
442// Given a signature place the type ids into the given vector
Andreas Gampea5b09a62016-11-17 15:21:22 -0800443bool DexFile::CreateTypeList(const StringPiece& signature,
444 dex::TypeIndex* return_type_idx,
445 std::vector<dex::TypeIndex>* param_type_idxs) const {
Ian Rogers0571d352011-11-03 19:51:38 -0700446 if (signature[0] != '(') {
447 return false;
448 }
449 size_t offset = 1;
450 size_t end = signature.size();
451 bool process_return = false;
452 while (offset < end) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000453 size_t start_offset = offset;
Ian Rogers0571d352011-11-03 19:51:38 -0700454 char c = signature[offset];
455 offset++;
456 if (c == ')') {
457 process_return = true;
458 continue;
459 }
Ian Rogers0571d352011-11-03 19:51:38 -0700460 while (c == '[') { // process array prefix
461 if (offset >= end) { // expect some descriptor following [
462 return false;
463 }
464 c = signature[offset];
465 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700466 }
467 if (c == 'L') { // process type descriptors
468 do {
469 if (offset >= end) { // unexpected early termination of descriptor
470 return false;
471 }
472 c = signature[offset];
473 offset++;
Ian Rogers0571d352011-11-03 19:51:38 -0700474 } while (c != ';');
475 }
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000476 // TODO: avoid creating a std::string just to get a 0-terminated char array
477 std::string descriptor(signature.data() + start_offset, offset - start_offset);
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700478 const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700479 if (type_id == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -0700480 return false;
481 }
Andreas Gampea5b09a62016-11-17 15:21:22 -0800482 dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
Ian Rogers0571d352011-11-03 19:51:38 -0700483 if (!process_return) {
484 param_type_idxs->push_back(type_idx);
485 } else {
486 *return_type_idx = type_idx;
487 return offset == end; // return true if the signature had reached a sensible end
488 }
489 }
490 return false; // failed to correctly parse return type
491}
492
Ian Rogersd91d6d62013-09-25 20:26:14 -0700493const Signature DexFile::CreateSignature(const StringPiece& signature) const {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800494 dex::TypeIndex return_type_idx;
495 std::vector<dex::TypeIndex> param_type_indices;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700496 bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
497 if (!success) {
498 return Signature::NoSignature();
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700499 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700500 const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700501 if (proto_id == nullptr) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700502 return Signature::NoSignature();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -0700503 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700504 return Signature(this, *proto_id);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700505}
506
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700507int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
Ian Rogers0571d352011-11-03 19:51:38 -0700508 // Note: Signed type is important for max and min.
509 int32_t min = 0;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700510 int32_t max = code_item.tries_size_ - 1;
Ian Rogers0571d352011-11-03 19:51:38 -0700511
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700512 while (min <= max) {
513 int32_t mid = min + ((max - min) / 2);
514
515 const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
516 uint32_t start = ti->start_addr_;
517 uint32_t end = start + ti->insn_count_;
518
Ian Rogers0571d352011-11-03 19:51:38 -0700519 if (address < start) {
520 max = mid - 1;
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700521 } else if (address >= end) {
522 min = mid + 1;
523 } else { // We have a winner!
524 return mid;
Ian Rogers0571d352011-11-03 19:51:38 -0700525 }
526 }
527 // No match.
528 return -1;
529}
530
Ian Rogersdbbc99d2013-04-18 16:51:54 -0700531int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
532 int32_t try_item = FindTryItem(code_item, address);
533 if (try_item == -1) {
534 return -1;
535 } else {
536 return DexFile::GetTryItems(code_item, try_item)->handler_off_;
537 }
538}
539
David Srbeckyb06e28e2015-12-10 13:15:00 +0000540bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
541 DexDebugNewLocalCb local_cb, void* context) const {
542 DCHECK(local_cb != nullptr);
543 if (code_item == nullptr) {
544 return false;
545 }
546 const uint8_t* stream = GetDebugInfoStream(code_item);
547 if (stream == nullptr) {
548 return false;
549 }
550 std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
Shih-wei Liao195487c2011-08-20 13:29:04 -0700551
David Srbeckyb06e28e2015-12-10 13:15:00 +0000552 uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800553 if (!is_static) {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000554 const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
555 local_in_reg[arg_reg].name_ = "this";
556 local_in_reg[arg_reg].descriptor_ = descriptor;
557 local_in_reg[arg_reg].signature_ = nullptr;
558 local_in_reg[arg_reg].start_address_ = 0;
559 local_in_reg[arg_reg].reg_ = arg_reg;
560 local_in_reg[arg_reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700561 arg_reg++;
562 }
563
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800564 DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000565 DecodeUnsignedLeb128(&stream); // Line.
566 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
567 uint32_t i;
568 for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700569 if (arg_reg >= code_item->registers_size_) {
jeffhaof8728872011-10-28 19:11:13 -0700570 LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800571 << " >= " << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000572 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700573 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000574 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Ian Rogers0571d352011-11-03 19:51:38 -0700575 const char* descriptor = it.GetDescriptor();
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800576 local_in_reg[arg_reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000577 local_in_reg[arg_reg].descriptor_ = descriptor;
578 local_in_reg[arg_reg].signature_ = nullptr;
579 local_in_reg[arg_reg].start_address_ = 0;
580 local_in_reg[arg_reg].reg_ = arg_reg;
581 local_in_reg[arg_reg].is_live_ = true;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700582 switch (*descriptor) {
Shih-wei Liao195487c2011-08-20 13:29:04 -0700583 case 'D':
584 case 'J':
585 arg_reg += 2;
586 break;
587 default:
588 arg_reg += 1;
589 break;
590 }
591 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000592 if (i != parameters_size || it.HasNext()) {
Brian Carlstromf79fccb2014-02-20 08:55:10 -0800593 LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
David Sehr709b0702016-10-13 09:12:37 -0700594 << " for method " << this->PrettyMethod(method_idx);
David Srbeckyb06e28e2015-12-10 13:15:00 +0000595 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700596 }
597
David Srbeckyb06e28e2015-12-10 13:15:00 +0000598 uint32_t address = 0;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700599 for (;;) {
600 uint8_t opcode = *stream++;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700601 switch (opcode) {
602 case DBG_END_SEQUENCE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000603 // Emit all variables which are still alive at the end of the method.
604 for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
605 if (local_in_reg[reg].is_live_) {
606 local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
607 local_cb(context, local_in_reg[reg]);
608 }
609 }
610 return true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700611 case DBG_ADVANCE_PC:
612 address += DecodeUnsignedLeb128(&stream);
613 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700614 case DBG_ADVANCE_LINE:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000615 DecodeSignedLeb128(&stream); // Line.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700616 break;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700617 case DBG_START_LOCAL:
David Srbeckyb06e28e2015-12-10 13:15:00 +0000618 case DBG_START_LOCAL_EXTENDED: {
619 uint16_t reg = DecodeUnsignedLeb128(&stream);
620 if (reg >= code_item->registers_size_) {
621 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
Brian Carlstrom2aab9472011-12-12 15:21:43 -0800622 << code_item->registers_size_ << ") in " << GetLocation();
David Srbeckyb06e28e2015-12-10 13:15:00 +0000623 return false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700624 }
625
David Srbeckyb06e28e2015-12-10 13:15:00 +0000626 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Jeff Haoc1225362017-05-01 17:29:35 -0700627 uint16_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700628 uint32_t signature_idx = dex::kDexNoIndex;
jeffhaof8728872011-10-28 19:11:13 -0700629 if (opcode == DBG_START_LOCAL_EXTENDED) {
630 signature_idx = DecodeUnsignedLeb128P1(&stream);
631 }
632
Shih-wei Liao195487c2011-08-20 13:29:04 -0700633 // Emit what was previously there, if anything
David Srbeckyb06e28e2015-12-10 13:15:00 +0000634 if (local_in_reg[reg].is_live_) {
635 local_in_reg[reg].end_address_ = address;
636 local_cb(context, local_in_reg[reg]);
637 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700638
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800639 local_in_reg[reg].name_ = StringDataByIdx(dex::StringIndex(name_idx));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800640 local_in_reg[reg].descriptor_ =
641 StringByTypeIdx(dex::TypeIndex(dchecked_integral_cast<uint16_t>(descriptor_idx)));;
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800642 local_in_reg[reg].signature_ = StringDataByIdx(dex::StringIndex(signature_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000643 local_in_reg[reg].start_address_ = address;
644 local_in_reg[reg].reg_ = reg;
645 local_in_reg[reg].is_live_ = true;
646 break;
647 }
648 case DBG_END_LOCAL: {
649 uint16_t reg = DecodeUnsignedLeb128(&stream);
650 if (reg >= code_item->registers_size_) {
651 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
652 << code_item->registers_size_ << ") in " << GetLocation();
653 return false;
654 }
Aart Bik2058b1d2017-05-17 13:32:26 -0700655 // If the register is live, close it properly. Otherwise, closing an already
656 // closed register is sloppy, but harmless if no further action is taken.
657 if (local_in_reg[reg].is_live_) {
658 local_in_reg[reg].end_address_ = address;
659 local_cb(context, local_in_reg[reg]);
660 local_in_reg[reg].is_live_ = false;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000661 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000662 break;
663 }
664 case DBG_RESTART_LOCAL: {
665 uint16_t reg = DecodeUnsignedLeb128(&stream);
666 if (reg >= code_item->registers_size_) {
667 LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
668 << code_item->registers_size_ << ") in " << GetLocation();
669 return false;
670 }
671 // If the register is live, the "restart" is superfluous,
672 // and we don't want to mess with the existing start address.
673 if (!local_in_reg[reg].is_live_) {
Elliott Hughes30646832011-10-13 16:59:46 -0700674 local_in_reg[reg].start_address_ = address;
675 local_in_reg[reg].is_live_ = true;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700676 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700677 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000678 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700679 case DBG_SET_PROLOGUE_END:
680 case DBG_SET_EPILOGUE_BEGIN:
Shih-wei Liao195487c2011-08-20 13:29:04 -0700681 break;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000682 case DBG_SET_FILE:
683 DecodeUnsignedLeb128P1(&stream); // name.
684 break;
685 default:
686 address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
687 break;
688 }
689 }
690}
Shih-wei Liao195487c2011-08-20 13:29:04 -0700691
David Srbeckyb06e28e2015-12-10 13:15:00 +0000692bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
693 void* context) const {
694 DCHECK(position_cb != nullptr);
695 if (code_item == nullptr) {
696 return false;
697 }
698 const uint8_t* stream = GetDebugInfoStream(code_item);
699 if (stream == nullptr) {
700 return false;
701 }
702
703 PositionInfo entry = PositionInfo();
704 entry.line_ = DecodeUnsignedLeb128(&stream);
705 uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
706 for (uint32_t i = 0; i < parameters_size; ++i) {
707 DecodeUnsignedLeb128P1(&stream); // Parameter name.
708 }
709
710 for (;;) {
711 uint8_t opcode = *stream++;
712 switch (opcode) {
713 case DBG_END_SEQUENCE:
714 return true; // end of stream.
715 case DBG_ADVANCE_PC:
716 entry.address_ += DecodeUnsignedLeb128(&stream);
717 break;
718 case DBG_ADVANCE_LINE:
719 entry.line_ += DecodeSignedLeb128(&stream);
720 break;
721 case DBG_START_LOCAL:
722 DecodeUnsignedLeb128(&stream); // reg.
723 DecodeUnsignedLeb128P1(&stream); // name.
724 DecodeUnsignedLeb128P1(&stream); // descriptor.
725 break;
726 case DBG_START_LOCAL_EXTENDED:
727 DecodeUnsignedLeb128(&stream); // reg.
728 DecodeUnsignedLeb128P1(&stream); // name.
729 DecodeUnsignedLeb128P1(&stream); // descriptor.
730 DecodeUnsignedLeb128P1(&stream); // signature.
731 break;
732 case DBG_END_LOCAL:
733 case DBG_RESTART_LOCAL:
734 DecodeUnsignedLeb128(&stream); // reg.
735 break;
736 case DBG_SET_PROLOGUE_END:
737 entry.prologue_end_ = true;
738 break;
739 case DBG_SET_EPILOGUE_BEGIN:
740 entry.epilogue_begin_ = true;
741 break;
742 case DBG_SET_FILE: {
743 uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800744 entry.source_file_ = StringDataByIdx(dex::StringIndex(name_idx));
David Srbeckyb06e28e2015-12-10 13:15:00 +0000745 break;
746 }
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700747 default: {
748 int adjopcode = opcode - DBG_FIRST_SPECIAL;
David Srbeckyb06e28e2015-12-10 13:15:00 +0000749 entry.address_ += adjopcode / DBG_LINE_RANGE;
750 entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
751 if (position_cb(context, entry)) {
752 return true; // early exit.
Shih-wei Liao195487c2011-08-20 13:29:04 -0700753 }
David Srbeckyb06e28e2015-12-10 13:15:00 +0000754 entry.prologue_end_ = false;
755 entry.epilogue_begin_ = false;
Shih-wei Liao195487c2011-08-20 13:29:04 -0700756 break;
Shih-wei Liao8e1b4ff2011-10-15 15:43:51 -0700757 }
Shih-wei Liao195487c2011-08-20 13:29:04 -0700758 }
759 }
760}
761
David Srbeckyb06e28e2015-12-10 13:15:00 +0000762bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800763 LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
Ian Rogers0571d352011-11-03 19:51:38 -0700764
765 // We know that this callback will be called in
766 // ascending address order, so keep going until we find
767 // a match or we've just gone past it.
David Srbeckyb06e28e2015-12-10 13:15:00 +0000768 if (entry.address_ > context->address_) {
Ian Rogers0571d352011-11-03 19:51:38 -0700769 // The line number from the previous positions callback
770 // wil be the final result.
771 return true;
772 } else {
David Srbeckyb06e28e2015-12-10 13:15:00 +0000773 context->line_num_ = entry.line_;
774 return entry.address_ == context->address_;
Ian Rogers0571d352011-11-03 19:51:38 -0700775 }
776}
777
Jeff Hao13e748b2015-08-25 20:44:19 +0000778// Read a signed integer. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -0700779int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000780 int32_t val = 0;
781 for (int i = zwidth; i >= 0; --i) {
782 val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
783 }
784 val >>= (3 - zwidth) * 8;
785 return val;
786}
787
788// Read an unsigned integer. "zwidth" is the zero-based byte count,
789// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -0700790uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000791 uint32_t val = 0;
792 for (int i = zwidth; i >= 0; --i) {
793 val = (val >> 8) | (((uint32_t)*ptr++) << 24);
794 }
795 if (!fill_on_right) {
796 val >>= (3 - zwidth) * 8;
797 }
798 return val;
799}
800
801// Read a signed long. "zwidth" is the zero-based byte count.
David Sehr9323e6e2016-09-13 08:58:35 -0700802int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000803 int64_t val = 0;
804 for (int i = zwidth; i >= 0; --i) {
805 val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
806 }
807 val >>= (7 - zwidth) * 8;
808 return val;
809}
810
811// Read an unsigned long. "zwidth" is the zero-based byte count,
812// "fill_on_right" indicates which side we want to zero-fill from.
David Sehr9323e6e2016-09-13 08:58:35 -0700813uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000814 uint64_t val = 0;
815 for (int i = zwidth; i >= 0; --i) {
816 val = (val >> 8) | (((uint64_t)*ptr++) << 56);
817 }
818 if (!fill_on_right) {
819 val >>= (7 - zwidth) * 8;
820 }
821 return val;
822}
823
David Sehr709b0702016-10-13 09:12:37 -0700824std::string DexFile::PrettyMethod(uint32_t method_idx, bool with_signature) const {
825 if (method_idx >= NumMethodIds()) {
826 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
827 }
828 const DexFile::MethodId& method_id = GetMethodId(method_idx);
Vladimir Markob8a55f82017-09-21 16:21:43 +0100829 std::string result;
830 const DexFile::ProtoId* proto_id = with_signature ? &GetProtoId(method_id.proto_idx_) : nullptr;
831 if (with_signature) {
832 AppendPrettyDescriptor(StringByTypeIdx(proto_id->return_type_idx_), &result);
833 result += ' ';
834 }
835 AppendPrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id), &result);
David Sehr709b0702016-10-13 09:12:37 -0700836 result += '.';
837 result += GetMethodName(method_id);
838 if (with_signature) {
Vladimir Markob8a55f82017-09-21 16:21:43 +0100839 result += '(';
840 const DexFile::TypeList* params = GetProtoParameters(*proto_id);
841 if (params != nullptr) {
842 const char* separator = "";
843 for (uint32_t i = 0u, size = params->Size(); i != size; ++i) {
844 result += separator;
845 separator = ", ";
846 AppendPrettyDescriptor(StringByTypeIdx(params->GetTypeItem(i).type_idx_), &result);
847 }
David Sehr709b0702016-10-13 09:12:37 -0700848 }
Vladimir Markob8a55f82017-09-21 16:21:43 +0100849 result += ')';
David Sehr709b0702016-10-13 09:12:37 -0700850 }
851 return result;
852}
853
854std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
855 if (field_idx >= NumFieldIds()) {
856 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
857 }
858 const DexFile::FieldId& field_id = GetFieldId(field_idx);
859 std::string result;
860 if (with_type) {
861 result += GetFieldTypeDescriptor(field_id);
862 result += ' ';
863 }
Vladimir Markob8a55f82017-09-21 16:21:43 +0100864 AppendPrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id), &result);
David Sehr709b0702016-10-13 09:12:37 -0700865 result += '.';
866 result += GetFieldName(field_id);
867 return result;
868}
869
Andreas Gampea5b09a62016-11-17 15:21:22 -0800870std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
871 if (type_idx.index_ >= NumTypeIds()) {
872 return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
David Sehr709b0702016-10-13 09:12:37 -0700873 }
874 const DexFile::TypeId& type_id = GetTypeId(type_idx);
875 return PrettyDescriptor(GetTypeDescriptor(type_id));
876}
877
Jeff Hao3d080862016-05-26 18:39:17 -0700878// Checks that visibility is as expected. Includes special behavior for M and
879// before to allow runtime and build visibility when expecting runtime.
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800880std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
881 os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
882 dex_file.GetLocation().c_str(),
883 dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
884 dex_file.Begin(), dex_file.Begin() + dex_file.Size());
885 return os;
886}
Calin Juravle4e1d5792014-07-15 23:56:47 +0100887
Ian Rogersd91d6d62013-09-25 20:26:14 -0700888std::string Signature::ToString() const {
889 if (dex_file_ == nullptr) {
890 CHECK(proto_id_ == nullptr);
891 return "<no signature>";
892 }
893 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
894 std::string result;
895 if (params == nullptr) {
896 result += "()";
897 } else {
898 result += "(";
899 for (uint32_t i = 0; i < params->Size(); ++i) {
900 result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
901 }
902 result += ")";
903 }
904 result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
905 return result;
906}
907
Orion Hodson6c4921b2016-09-21 15:41:06 +0100908uint32_t Signature::GetNumberOfParameters() const {
909 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
910 return (params != nullptr) ? params->Size() : 0;
911}
912
913bool Signature::IsVoid() const {
914 const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
915 return strcmp(return_type, "V") == 0;
916}
917
Vladimir Markod9cffea2013-11-25 15:08:02 +0000918bool Signature::operator==(const StringPiece& rhs) const {
919 if (dex_file_ == nullptr) {
920 return false;
921 }
922 StringPiece tail(rhs);
923 if (!tail.starts_with("(")) {
924 return false; // Invalid signature
925 }
926 tail.remove_prefix(1); // "(";
927 const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
928 if (params != nullptr) {
929 for (uint32_t i = 0; i < params->Size(); ++i) {
930 StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
931 if (!tail.starts_with(param)) {
932 return false;
933 }
934 tail.remove_prefix(param.length());
935 }
936 }
937 if (!tail.starts_with(")")) {
938 return false;
939 }
940 tail.remove_prefix(1); // ")";
941 return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
942}
943
Ian Rogersd91d6d62013-09-25 20:26:14 -0700944std::ostream& operator<<(std::ostream& os, const Signature& sig) {
945 return os << sig.ToString();
946}
947
Ian Rogers0571d352011-11-03 19:51:38 -0700948// Decodes the header section from the class data bytes.
949void ClassDataItemIterator::ReadClassDataHeader() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700950 CHECK(ptr_pos_ != nullptr);
Ian Rogers0571d352011-11-03 19:51:38 -0700951 header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
952 header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
953 header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
954 header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
955}
956
957void ClassDataItemIterator::ReadClassDataField() {
958 field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
959 field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
Vladimir Marko23682bf2015-06-24 14:28:03 +0100960 // The user of the iterator is responsible for checking if there
961 // are unordered or duplicate indexes.
Ian Rogers0571d352011-11-03 19:51:38 -0700962}
963
964void ClassDataItemIterator::ReadClassDataMethod() {
965 method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
966 method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
967 method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
Brian Carlstrom68adbe42012-05-11 17:18:08 -0700968 if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
Andreas Gampe4fdbba02014-06-19 20:24:22 -0700969 LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700970 }
Ian Rogers0571d352011-11-03 19:51:38 -0700971}
972
Orion Hodson12f4ff42017-01-13 16:43:12 +0000973EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
974 const uint8_t* array_data)
Shinichiro Hamaji82863f02015-11-05 16:51:33 +0900975 : dex_file_(dex_file),
Shinichiro Hamaji82863f02015-11-05 16:51:33 +0900976 array_size_(),
David Sehr9323e6e2016-09-13 08:58:35 -0700977 pos_(-1),
Orion Hodson12f4ff42017-01-13 16:43:12 +0000978 ptr_(array_data),
David Sehr9323e6e2016-09-13 08:58:35 -0700979 type_(kByte) {
Orion Hodson12f4ff42017-01-13 16:43:12 +0000980 array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
Ian Rogers0571d352011-11-03 19:51:38 -0700981 if (array_size_ > 0) {
982 Next();
983 }
984}
985
Orion Hodson12f4ff42017-01-13 16:43:12 +0000986void EncodedArrayValueIterator::Next() {
Ian Rogers0571d352011-11-03 19:51:38 -0700987 pos_++;
988 if (pos_ >= array_size_) {
989 return;
990 }
Ian Rogers13735952014-10-08 12:43:28 -0700991 uint8_t value_type = *ptr_++;
992 uint8_t value_arg = value_type >> kEncodedValueArgShift;
Ian Rogers0571d352011-11-03 19:51:38 -0700993 size_t width = value_arg + 1; // assume and correct later
Brian Carlstrom88f36542012-10-16 23:24:21 -0700994 type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
Ian Rogers0571d352011-11-03 19:51:38 -0700995 switch (type_) {
996 case kBoolean:
997 jval_.i = (value_arg != 0) ? 1 : 0;
998 width = 0;
999 break;
1000 case kByte:
David Sehr9323e6e2016-09-13 08:58:35 -07001001 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001002 CHECK(IsInt<8>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001003 break;
1004 case kShort:
David Sehr9323e6e2016-09-13 08:58:35 -07001005 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001006 CHECK(IsInt<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001007 break;
1008 case kChar:
David Sehr9323e6e2016-09-13 08:58:35 -07001009 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08001010 CHECK(IsUint<16>(jval_.i));
Ian Rogers0571d352011-11-03 19:51:38 -07001011 break;
1012 case kInt:
David Sehr9323e6e2016-09-13 08:58:35 -07001013 jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001014 break;
1015 case kLong:
David Sehr9323e6e2016-09-13 08:58:35 -07001016 jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
Ian Rogers0571d352011-11-03 19:51:38 -07001017 break;
1018 case kFloat:
David Sehr9323e6e2016-09-13 08:58:35 -07001019 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001020 break;
1021 case kDouble:
David Sehr9323e6e2016-09-13 08:58:35 -07001022 jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
Ian Rogers0571d352011-11-03 19:51:38 -07001023 break;
1024 case kString:
1025 case kType:
Orion Hodson12f4ff42017-01-13 16:43:12 +00001026 case kMethodType:
1027 case kMethodHandle:
David Sehr9323e6e2016-09-13 08:58:35 -07001028 jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
Ian Rogers0571d352011-11-03 19:51:38 -07001029 break;
1030 case kField:
Brian Carlstrom88f36542012-10-16 23:24:21 -07001031 case kMethod:
1032 case kEnum:
Ian Rogers0571d352011-11-03 19:51:38 -07001033 case kArray:
1034 case kAnnotation:
1035 UNIMPLEMENTED(FATAL) << ": type " << type_;
Ian Rogers2c4257b2014-10-24 14:20:06 -07001036 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001037 case kNull:
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001038 jval_.l = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001039 width = 0;
1040 break;
1041 default:
1042 LOG(FATAL) << "Unreached";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001043 UNREACHABLE();
Ian Rogers0571d352011-11-03 19:51:38 -07001044 }
1045 ptr_ += width;
1046}
1047
Ian Rogers0571d352011-11-03 19:51:38 -07001048CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
1049 handler_.address_ = -1;
1050 int32_t offset = -1;
1051
1052 // Short-circuit the overwhelmingly common cases.
1053 switch (code_item.tries_size_) {
1054 case 0:
1055 break;
1056 case 1: {
1057 const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
1058 uint32_t start = tries->start_addr_;
1059 if (address >= start) {
1060 uint32_t end = start + tries->insn_count_;
1061 if (address < end) {
1062 offset = tries->handler_off_;
1063 }
1064 }
1065 break;
1066 }
1067 default:
Ian Rogersdbbc99d2013-04-18 16:51:54 -07001068 offset = DexFile::FindCatchHandlerOffset(code_item, address);
Ian Rogers0571d352011-11-03 19:51:38 -07001069 }
Logan Chien736df022012-04-27 16:25:57 +08001070 Init(code_item, offset);
1071}
1072
1073CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
1074 const DexFile::TryItem& try_item) {
1075 handler_.address_ = -1;
1076 Init(code_item, try_item.handler_off_);
1077}
1078
1079void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
1080 int32_t offset) {
Ian Rogers0571d352011-11-03 19:51:38 -07001081 if (offset >= 0) {
Logan Chien736df022012-04-27 16:25:57 +08001082 Init(DexFile::GetCatchHandlerData(code_item, offset));
Ian Rogers0571d352011-11-03 19:51:38 -07001083 } else {
1084 // Not found, initialize as empty
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001085 current_data_ = nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001086 remaining_count_ = -1;
1087 catch_all_ = false;
1088 DCHECK(!HasNext());
1089 }
1090}
1091
Ian Rogers13735952014-10-08 12:43:28 -07001092void CatchHandlerIterator::Init(const uint8_t* handler_data) {
Ian Rogers0571d352011-11-03 19:51:38 -07001093 current_data_ = handler_data;
1094 remaining_count_ = DecodeSignedLeb128(&current_data_);
1095
1096 // If remaining_count_ is non-positive, then it is the negative of
1097 // the number of catch types, and the catches are followed by a
1098 // catch-all handler.
1099 if (remaining_count_ <= 0) {
1100 catch_all_ = true;
1101 remaining_count_ = -remaining_count_;
1102 } else {
1103 catch_all_ = false;
1104 }
1105 Next();
1106}
1107
1108void CatchHandlerIterator::Next() {
1109 if (remaining_count_ > 0) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001110 handler_.type_idx_ = dex::TypeIndex(DecodeUnsignedLeb128(&current_data_));
Ian Rogers0571d352011-11-03 19:51:38 -07001111 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1112 remaining_count_--;
1113 return;
1114 }
1115
1116 if (catch_all_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001117 handler_.type_idx_ = dex::TypeIndex(DexFile::kDexNoIndex16);
Ian Rogers0571d352011-11-03 19:51:38 -07001118 handler_.address_ = DecodeUnsignedLeb128(&current_data_);
1119 catch_all_ = false;
1120 return;
1121 }
1122
1123 // no more handler
1124 remaining_count_ = -1;
1125}
1126
Andreas Gampea5b09a62016-11-17 15:21:22 -08001127namespace dex {
1128
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001129std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
1130 os << "StringIndex[" << index.index_ << "]";
1131 return os;
1132}
1133
Andreas Gampea5b09a62016-11-17 15:21:22 -08001134std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
1135 os << "TypeIndex[" << index.index_ << "]";
1136 return os;
1137}
1138
1139} // namespace dex
1140
Carl Shapiro1fb86202011-06-27 17:43:13 -07001141} // namespace art