1 /*
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  */
16 
17 #include "dex_file.h"
18 
19 #include <limits.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <zlib.h>
24 
25 #include <memory>
26 #include <ostream>
27 #include <sstream>
28 #include <type_traits>
29 
30 #include "android-base/stringprintf.h"
31 
32 #include "base/enums.h"
33 #include "base/hiddenapi_domain.h"
34 #include "base/leb128.h"
35 #include "base/stl_util.h"
36 #include "class_accessor-inl.h"
37 #include "descriptors_names.h"
38 #include "dex_file-inl.h"
39 #include "standard_dex_file.h"
40 #include "utf-inl.h"
41 
42 namespace art {
43 
44 using android::base::StringPrintf;
45 
46 using dex::CallSiteIdItem;
47 using dex::ClassDef;
48 using dex::FieldId;
49 using dex::MapList;
50 using dex::MapItem;
51 using dex::MethodHandleItem;
52 using dex::MethodId;
53 using dex::ProtoId;
54 using dex::StringId;
55 using dex::TryItem;
56 using dex::TypeId;
57 using dex::TypeList;
58 
59 static_assert(sizeof(dex::StringIndex) == sizeof(uint32_t), "StringIndex size is wrong");
60 static_assert(std::is_trivially_copyable<dex::StringIndex>::value, "StringIndex not trivial");
61 static_assert(sizeof(dex::TypeIndex) == sizeof(uint16_t), "TypeIndex size is wrong");
62 static_assert(std::is_trivially_copyable<dex::TypeIndex>::value, "TypeIndex not trivial");
63 
CalculateChecksum() const64 uint32_t DexFile::CalculateChecksum() const {
65   return CalculateChecksum(Begin(), Size());
66 }
67 
CalculateChecksum(const uint8_t * begin,size_t size)68 uint32_t DexFile::CalculateChecksum(const uint8_t* begin, size_t size) {
69   const uint32_t non_sum_bytes = OFFSETOF_MEMBER(DexFile::Header, signature_);
70   return ChecksumMemoryRange(begin + non_sum_bytes, size - non_sum_bytes);
71 }
72 
ChecksumMemoryRange(const uint8_t * begin,size_t size)73 uint32_t DexFile::ChecksumMemoryRange(const uint8_t* begin, size_t size) {
74   return adler32(adler32(0L, Z_NULL, 0), begin, size);
75 }
76 
GetPermissions() const77 int DexFile::GetPermissions() const {
78   CHECK(container_.get() != nullptr);
79   return container_->GetPermissions();
80 }
81 
IsReadOnly() const82 bool DexFile::IsReadOnly() const {
83   CHECK(container_.get() != nullptr);
84   return container_->IsReadOnly();
85 }
86 
EnableWrite() const87 bool DexFile::EnableWrite() const {
88   CHECK(container_.get() != nullptr);
89   return container_->EnableWrite();
90 }
91 
DisableWrite() const92 bool DexFile::DisableWrite() const {
93   CHECK(container_.get() != nullptr);
94   return container_->DisableWrite();
95 }
96 
DexFile(const uint8_t * base,size_t size,const uint8_t * data_begin,size_t data_size,const std::string & location,uint32_t location_checksum,const OatDexFile * oat_dex_file,std::unique_ptr<DexFileContainer> container,bool is_compact_dex)97 DexFile::DexFile(const uint8_t* base,
98                  size_t size,
99                  const uint8_t* data_begin,
100                  size_t data_size,
101                  const std::string& location,
102                  uint32_t location_checksum,
103                  const OatDexFile* oat_dex_file,
104                  std::unique_ptr<DexFileContainer> container,
105                  bool is_compact_dex)
106     : begin_(base),
107       size_(size),
108       data_begin_(data_begin),
109       data_size_(data_size),
110       location_(location),
111       location_checksum_(location_checksum),
112       header_(reinterpret_cast<const Header*>(base)),
113       string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
114       type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
115       field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
116       method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
117       proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
118       class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
119       method_handles_(nullptr),
120       num_method_handles_(0),
121       call_site_ids_(nullptr),
122       num_call_site_ids_(0),
123       hiddenapi_class_data_(nullptr),
124       oat_dex_file_(oat_dex_file),
125       container_(std::move(container)),
126       is_compact_dex_(is_compact_dex),
127       hiddenapi_domain_(hiddenapi::Domain::kApplication) {
128   CHECK(begin_ != nullptr) << GetLocation();
129   CHECK_GT(size_, 0U) << GetLocation();
130   // Check base (=header) alignment.
131   // Must be 4-byte aligned to avoid undefined behavior when accessing
132   // any of the sections via a pointer.
133   CHECK_ALIGNED(begin_, alignof(Header));
134 
135   InitializeSectionsFromMapList();
136 }
137 
~DexFile()138 DexFile::~DexFile() {
139   // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
140   // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
141   // re-attach, but cleaning up these global references is not obviously useful. It's not as if
142   // the global reference table is otherwise empty!
143 }
144 
Init(std::string * error_msg)145 bool DexFile::Init(std::string* error_msg) {
146   if (!CheckMagicAndVersion(error_msg)) {
147     return false;
148   }
149   return true;
150 }
151 
CheckMagicAndVersion(std::string * error_msg) const152 bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
153   if (!IsMagicValid()) {
154     std::ostringstream oss;
155     oss << "Unrecognized magic number in "  << GetLocation() << ":"
156             << " " << header_->magic_[0]
157             << " " << header_->magic_[1]
158             << " " << header_->magic_[2]
159             << " " << header_->magic_[3];
160     *error_msg = oss.str();
161     return false;
162   }
163   if (!IsVersionValid()) {
164     std::ostringstream oss;
165     oss << "Unrecognized version number in "  << GetLocation() << ":"
166             << " " << header_->magic_[4]
167             << " " << header_->magic_[5]
168             << " " << header_->magic_[6]
169             << " " << header_->magic_[7];
170     *error_msg = oss.str();
171     return false;
172   }
173   return true;
174 }
175 
InitializeSectionsFromMapList()176 void DexFile::InitializeSectionsFromMapList() {
177   const MapList* map_list = reinterpret_cast<const MapList*>(DataBegin() + header_->map_off_);
178   if (header_->map_off_ == 0 || header_->map_off_ > DataSize()) {
179     // Bad offset. The dex file verifier runs after this method and will reject the file.
180     return;
181   }
182   const size_t count = map_list->size_;
183 
184   size_t map_limit = header_->map_off_ + count * sizeof(MapItem);
185   if (header_->map_off_ >= map_limit || map_limit > DataSize()) {
186     // Overflow or out out of bounds. The dex file verifier runs after
187     // this method and will reject the file as it is malformed.
188     return;
189   }
190 
191   for (size_t i = 0; i < count; ++i) {
192     const MapItem& map_item = map_list->list_[i];
193     if (map_item.type_ == kDexTypeMethodHandleItem) {
194       method_handles_ = reinterpret_cast<const MethodHandleItem*>(Begin() + map_item.offset_);
195       num_method_handles_ = map_item.size_;
196     } else if (map_item.type_ == kDexTypeCallSiteIdItem) {
197       call_site_ids_ = reinterpret_cast<const CallSiteIdItem*>(Begin() + map_item.offset_);
198       num_call_site_ids_ = map_item.size_;
199     } else if (map_item.type_ == kDexTypeHiddenapiClassData) {
200       hiddenapi_class_data_ = GetHiddenapiClassDataAtOffset(map_item.offset_);
201     } else {
202       // Pointers to other sections are not necessary to retain in the DexFile struct.
203       // Other items have pointers directly into their data.
204     }
205   }
206 }
207 
GetVersion() const208 uint32_t DexFile::Header::GetVersion() const {
209   const char* version = reinterpret_cast<const char*>(&magic_[kDexMagicSize]);
210   return atoi(version);
211 }
212 
FindClassDef(dex::TypeIndex type_idx) const213 const ClassDef* DexFile::FindClassDef(dex::TypeIndex type_idx) const {
214   size_t num_class_defs = NumClassDefs();
215   // Fast path for rare no class defs case.
216   if (num_class_defs == 0) {
217     return nullptr;
218   }
219   for (size_t i = 0; i < num_class_defs; ++i) {
220     const ClassDef& class_def = GetClassDef(i);
221     if (class_def.class_idx_ == type_idx) {
222       return &class_def;
223     }
224   }
225   return nullptr;
226 }
227 
GetCodeItemOffset(const ClassDef & class_def,uint32_t method_idx) const228 std::optional<uint32_t> DexFile::GetCodeItemOffset(const ClassDef &class_def,
229                                                    uint32_t method_idx) const {
230   ClassAccessor accessor(*this, class_def);
231   CHECK(accessor.HasClassData());
232   for (const ClassAccessor::Method &method : accessor.GetMethods()) {
233     if (method.GetIndex() == method_idx) {
234       return method.GetCodeItemOffset();
235     }
236   }
237   return std::nullopt;
238 }
239 
FindCodeItemOffset(const dex::ClassDef & class_def,uint32_t dex_method_idx) const240 uint32_t DexFile::FindCodeItemOffset(const dex::ClassDef &class_def,
241                                      uint32_t dex_method_idx) const {
242   std::optional<uint32_t> val = GetCodeItemOffset(class_def, dex_method_idx);
243   CHECK(val.has_value()) << "Unable to find method " << dex_method_idx;
244   return *val;
245 }
246 
FindFieldId(const TypeId & declaring_klass,const StringId & name,const TypeId & type) const247 const FieldId* DexFile::FindFieldId(const TypeId& declaring_klass,
248                                     const StringId& name,
249                                     const TypeId& type) const {
250   // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
251   const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
252   const dex::StringIndex name_idx = GetIndexForStringId(name);
253   const dex::TypeIndex type_idx = GetIndexForTypeId(type);
254   int32_t lo = 0;
255   int32_t hi = NumFieldIds() - 1;
256   while (hi >= lo) {
257     int32_t mid = (hi + lo) / 2;
258     const FieldId& field = GetFieldId(mid);
259     if (class_idx > field.class_idx_) {
260       lo = mid + 1;
261     } else if (class_idx < field.class_idx_) {
262       hi = mid - 1;
263     } else {
264       if (name_idx > field.name_idx_) {
265         lo = mid + 1;
266       } else if (name_idx < field.name_idx_) {
267         hi = mid - 1;
268       } else {
269         if (type_idx > field.type_idx_) {
270           lo = mid + 1;
271         } else if (type_idx < field.type_idx_) {
272           hi = mid - 1;
273         } else {
274           return &field;
275         }
276       }
277     }
278   }
279   return nullptr;
280 }
281 
FindMethodId(const TypeId & declaring_klass,const StringId & name,const ProtoId & signature) const282 const MethodId* DexFile::FindMethodId(const TypeId& declaring_klass,
283                                       const StringId& name,
284                                       const ProtoId& signature) const {
285   // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
286   const dex::TypeIndex class_idx = GetIndexForTypeId(declaring_klass);
287   const dex::StringIndex name_idx = GetIndexForStringId(name);
288   const dex::ProtoIndex proto_idx = GetIndexForProtoId(signature);
289   return FindMethodIdByIndex(class_idx, name_idx, proto_idx);
290 }
291 
FindMethodIdByIndex(dex::TypeIndex class_idx,dex::StringIndex name_idx,dex::ProtoIndex proto_idx) const292 const MethodId* DexFile::FindMethodIdByIndex(dex::TypeIndex class_idx,
293                                              dex::StringIndex name_idx,
294                                              dex::ProtoIndex proto_idx) const {
295   // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
296   int32_t lo = 0;
297   int32_t hi = NumMethodIds() - 1;
298   while (hi >= lo) {
299     int32_t mid = (hi + lo) / 2;
300     const MethodId& method = GetMethodId(mid);
301     if (class_idx > method.class_idx_) {
302       lo = mid + 1;
303     } else if (class_idx < method.class_idx_) {
304       hi = mid - 1;
305     } else {
306       if (name_idx > method.name_idx_) {
307         lo = mid + 1;
308       } else if (name_idx < method.name_idx_) {
309         hi = mid - 1;
310       } else {
311         if (proto_idx > method.proto_idx_) {
312           lo = mid + 1;
313         } else if (proto_idx < method.proto_idx_) {
314           hi = mid - 1;
315         } else {
316           DCHECK_EQ(class_idx, method.class_idx_);
317           DCHECK_EQ(proto_idx, method.proto_idx_);
318           DCHECK_EQ(name_idx, method.name_idx_);
319           return &method;
320         }
321       }
322     }
323   }
324   return nullptr;
325 }
326 
FindStringId(const char * string) const327 const StringId* DexFile::FindStringId(const char* string) const {
328   int32_t lo = 0;
329   int32_t hi = NumStringIds() - 1;
330   while (hi >= lo) {
331     int32_t mid = (hi + lo) / 2;
332     const StringId& str_id = GetStringId(dex::StringIndex(mid));
333     const char* str = GetStringData(str_id);
334     int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
335     if (compare > 0) {
336       lo = mid + 1;
337     } else if (compare < 0) {
338       hi = mid - 1;
339     } else {
340       return &str_id;
341     }
342   }
343   return nullptr;
344 }
345 
FindTypeId(const char * string) const346 const TypeId* DexFile::FindTypeId(const char* string) const {
347   int32_t lo = 0;
348   int32_t hi = NumTypeIds() - 1;
349   while (hi >= lo) {
350     int32_t mid = (hi + lo) / 2;
351     const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
352     const StringId& str_id = GetStringId(type_id.descriptor_idx_);
353     const char* str = GetStringData(str_id);
354     int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
355     if (compare > 0) {
356       lo = mid + 1;
357     } else if (compare < 0) {
358       hi = mid - 1;
359     } else {
360       return &type_id;
361     }
362   }
363   return nullptr;
364 }
365 
FindTypeId(dex::StringIndex string_idx) const366 const TypeId* DexFile::FindTypeId(dex::StringIndex string_idx) const {
367   int32_t lo = 0;
368   int32_t hi = NumTypeIds() - 1;
369   while (hi >= lo) {
370     int32_t mid = (hi + lo) / 2;
371     const TypeId& type_id = GetTypeId(dex::TypeIndex(mid));
372     if (string_idx > type_id.descriptor_idx_) {
373       lo = mid + 1;
374     } else if (string_idx < type_id.descriptor_idx_) {
375       hi = mid - 1;
376     } else {
377       return &type_id;
378     }
379   }
380   return nullptr;
381 }
382 
FindProtoId(dex::TypeIndex return_type_idx,const dex::TypeIndex * signature_type_idxs,uint32_t signature_length) const383 const ProtoId* DexFile::FindProtoId(dex::TypeIndex return_type_idx,
384                                     const dex::TypeIndex* signature_type_idxs,
385                                     uint32_t signature_length) const {
386   int32_t lo = 0;
387   int32_t hi = NumProtoIds() - 1;
388   while (hi >= lo) {
389     int32_t mid = (hi + lo) / 2;
390     const dex::ProtoIndex proto_idx = static_cast<dex::ProtoIndex>(mid);
391     const ProtoId& proto = GetProtoId(proto_idx);
392     int compare = return_type_idx.index_ - proto.return_type_idx_.index_;
393     if (compare == 0) {
394       DexFileParameterIterator it(*this, proto);
395       size_t i = 0;
396       while (it.HasNext() && i < signature_length && compare == 0) {
397         compare = signature_type_idxs[i].index_ - it.GetTypeIdx().index_;
398         it.Next();
399         i++;
400       }
401       if (compare == 0) {
402         if (it.HasNext()) {
403           compare = -1;
404         } else if (i < signature_length) {
405           compare = 1;
406         }
407       }
408     }
409     if (compare > 0) {
410       lo = mid + 1;
411     } else if (compare < 0) {
412       hi = mid - 1;
413     } else {
414       return &proto;
415     }
416   }
417   return nullptr;
418 }
419 
420 // Given a signature place the type ids into the given vector
CreateTypeList(std::string_view signature,dex::TypeIndex * return_type_idx,std::vector<dex::TypeIndex> * param_type_idxs) const421 bool DexFile::CreateTypeList(std::string_view signature,
422                              dex::TypeIndex* return_type_idx,
423                              std::vector<dex::TypeIndex>* param_type_idxs) const {
424   if (signature[0] != '(') {
425     return false;
426   }
427   size_t offset = 1;
428   size_t end = signature.size();
429   bool process_return = false;
430   while (offset < end) {
431     size_t start_offset = offset;
432     char c = signature[offset];
433     offset++;
434     if (c == ')') {
435       process_return = true;
436       continue;
437     }
438     while (c == '[') {  // process array prefix
439       if (offset >= end) {  // expect some descriptor following [
440         return false;
441       }
442       c = signature[offset];
443       offset++;
444     }
445     if (c == 'L') {  // process type descriptors
446       do {
447         if (offset >= end) {  // unexpected early termination of descriptor
448           return false;
449         }
450         c = signature[offset];
451         offset++;
452       } while (c != ';');
453     }
454     // TODO: avoid creating a std::string just to get a 0-terminated char array
455     std::string descriptor(signature.data() + start_offset, offset - start_offset);
456     const TypeId* type_id = FindTypeId(descriptor.c_str());
457     if (type_id == nullptr) {
458       return false;
459     }
460     dex::TypeIndex type_idx = GetIndexForTypeId(*type_id);
461     if (!process_return) {
462       param_type_idxs->push_back(type_idx);
463     } else {
464       *return_type_idx = type_idx;
465       return offset == end;  // return true if the signature had reached a sensible end
466     }
467   }
468   return false;  // failed to correctly parse return type
469 }
470 
FindTryItem(const TryItem * try_items,uint32_t tries_size,uint32_t address)471 int32_t DexFile::FindTryItem(const TryItem* try_items, uint32_t tries_size, uint32_t address) {
472   uint32_t min = 0;
473   uint32_t max = tries_size;
474   while (min < max) {
475     const uint32_t mid = (min + max) / 2;
476 
477     const TryItem& ti = try_items[mid];
478     const uint32_t start = ti.start_addr_;
479     const uint32_t end = start + ti.insn_count_;
480 
481     if (address < start) {
482       max = mid;
483     } else if (address >= end) {
484       min = mid + 1;
485     } else {  // We have a winner!
486       return mid;
487     }
488   }
489   // No match.
490   return -1;
491 }
492 
493 // Read a signed integer.  "zwidth" is the zero-based byte count.
ReadSignedInt(const uint8_t * ptr,int zwidth)494 int32_t DexFile::ReadSignedInt(const uint8_t* ptr, int zwidth) {
495   int32_t val = 0;
496   for (int i = zwidth; i >= 0; --i) {
497     val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
498   }
499   val >>= (3 - zwidth) * 8;
500   return val;
501 }
502 
503 // Read an unsigned integer.  "zwidth" is the zero-based byte count,
504 // "fill_on_right" indicates which side we want to zero-fill from.
ReadUnsignedInt(const uint8_t * ptr,int zwidth,bool fill_on_right)505 uint32_t DexFile::ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
506   uint32_t val = 0;
507   for (int i = zwidth; i >= 0; --i) {
508     val = (val >> 8) | (((uint32_t)*ptr++) << 24);
509   }
510   if (!fill_on_right) {
511     val >>= (3 - zwidth) * 8;
512   }
513   return val;
514 }
515 
516 // Read a signed long.  "zwidth" is the zero-based byte count.
ReadSignedLong(const uint8_t * ptr,int zwidth)517 int64_t DexFile::ReadSignedLong(const uint8_t* ptr, int zwidth) {
518   int64_t val = 0;
519   for (int i = zwidth; i >= 0; --i) {
520     val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
521   }
522   val >>= (7 - zwidth) * 8;
523   return val;
524 }
525 
526 // Read an unsigned long.  "zwidth" is the zero-based byte count,
527 // "fill_on_right" indicates which side we want to zero-fill from.
ReadUnsignedLong(const uint8_t * ptr,int zwidth,bool fill_on_right)528 uint64_t DexFile::ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
529   uint64_t val = 0;
530   for (int i = zwidth; i >= 0; --i) {
531     val = (val >> 8) | (((uint64_t)*ptr++) << 56);
532   }
533   if (!fill_on_right) {
534     val >>= (7 - zwidth) * 8;
535   }
536   return val;
537 }
538 
AppendPrettyMethod(uint32_t method_idx,bool with_signature,std::string * const result) const539 void DexFile::AppendPrettyMethod(uint32_t method_idx,
540                                  bool with_signature,
541                                  std::string* const result) const {
542   if (method_idx >= NumMethodIds()) {
543     android::base::StringAppendF(result, "<<invalid-method-idx-%d>>", method_idx);
544     return;
545   }
546   const MethodId& method_id = GetMethodId(method_idx);
547   const ProtoId* proto_id = with_signature ? &GetProtoId(method_id.proto_idx_) : nullptr;
548   if (with_signature) {
549     AppendPrettyDescriptor(StringByTypeIdx(proto_id->return_type_idx_), result);
550     result->push_back(' ');
551   }
552   AppendPrettyDescriptor(GetMethodDeclaringClassDescriptor(method_id), result);
553   result->push_back('.');
554   result->append(GetMethodName(method_id));
555   if (with_signature) {
556     result->push_back('(');
557     const TypeList* params = GetProtoParameters(*proto_id);
558     if (params != nullptr) {
559       const char* separator = "";
560       for (uint32_t i = 0u, size = params->Size(); i != size; ++i) {
561         result->append(separator);
562         separator = ", ";
563         AppendPrettyDescriptor(StringByTypeIdx(params->GetTypeItem(i).type_idx_), result);
564       }
565     }
566     result->push_back(')');
567   }
568 }
569 
PrettyField(uint32_t field_idx,bool with_type) const570 std::string DexFile::PrettyField(uint32_t field_idx, bool with_type) const {
571   if (field_idx >= NumFieldIds()) {
572     return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
573   }
574   const FieldId& field_id = GetFieldId(field_idx);
575   std::string result;
576   if (with_type) {
577     result += GetFieldTypeDescriptor(field_id);
578     result += ' ';
579   }
580   AppendPrettyDescriptor(GetFieldDeclaringClassDescriptor(field_id), &result);
581   result += '.';
582   result += GetFieldName(field_id);
583   return result;
584 }
585 
PrettyType(dex::TypeIndex type_idx) const586 std::string DexFile::PrettyType(dex::TypeIndex type_idx) const {
587   if (type_idx.index_ >= NumTypeIds()) {
588     return StringPrintf("<<invalid-type-idx-%d>>", type_idx.index_);
589   }
590   const TypeId& type_id = GetTypeId(type_idx);
591   return PrettyDescriptor(GetTypeDescriptor(type_id));
592 }
593 
GetProtoIndexForCallSite(uint32_t call_site_idx) const594 dex::ProtoIndex DexFile::GetProtoIndexForCallSite(uint32_t call_site_idx) const {
595   const CallSiteIdItem& csi = GetCallSiteId(call_site_idx);
596   CallSiteArrayValueIterator it(*this, csi);
597   it.Next();
598   it.Next();
599   DCHECK_EQ(EncodedArrayValueIterator::ValueType::kMethodType, it.GetValueType());
600   return dex::ProtoIndex(it.GetJavaValue().i);
601 }
602 
603 // Checks that visibility is as expected. Includes special behavior for M and
604 // before to allow runtime and build visibility when expecting runtime.
operator <<(std::ostream & os,const DexFile & dex_file)605 std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
606   os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
607                      dex_file.GetLocation().c_str(),
608                      dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
609                      dex_file.Begin(), dex_file.Begin() + dex_file.Size());
610   return os;
611 }
612 
EncodedArrayValueIterator(const DexFile & dex_file,const uint8_t * array_data)613 EncodedArrayValueIterator::EncodedArrayValueIterator(const DexFile& dex_file,
614                                                      const uint8_t* array_data)
615     : dex_file_(dex_file),
616       array_size_(),
617       pos_(-1),
618       ptr_(array_data),
619       type_(kByte) {
620   array_size_ = (ptr_ != nullptr) ? DecodeUnsignedLeb128(&ptr_) : 0;
621   if (array_size_ > 0) {
622     Next();
623   }
624 }
625 
Next()626 void EncodedArrayValueIterator::Next() {
627   pos_++;
628   if (pos_ >= array_size_) {
629     return;
630   }
631   uint8_t value_type = *ptr_++;
632   uint8_t value_arg = value_type >> kEncodedValueArgShift;
633   size_t width = value_arg + 1;  // assume and correct later
634   type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
635   switch (type_) {
636   case kBoolean:
637     jval_.i = (value_arg != 0) ? 1 : 0;
638     width = 0;
639     break;
640   case kByte:
641     jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
642     CHECK(IsInt<8>(jval_.i));
643     break;
644   case kShort:
645     jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
646     CHECK(IsInt<16>(jval_.i));
647     break;
648   case kChar:
649     jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
650     CHECK(IsUint<16>(jval_.i));
651     break;
652   case kInt:
653     jval_.i = DexFile::ReadSignedInt(ptr_, value_arg);
654     break;
655   case kLong:
656     jval_.j = DexFile::ReadSignedLong(ptr_, value_arg);
657     break;
658   case kFloat:
659     jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, true);
660     break;
661   case kDouble:
662     jval_.j = DexFile::ReadUnsignedLong(ptr_, value_arg, true);
663     break;
664   case kString:
665   case kType:
666   case kMethodType:
667   case kMethodHandle:
668     jval_.i = DexFile::ReadUnsignedInt(ptr_, value_arg, false);
669     break;
670   case kField:
671   case kMethod:
672   case kEnum:
673   case kArray:
674   case kAnnotation:
675     UNIMPLEMENTED(FATAL) << ": type " << type_;
676     UNREACHABLE();
677   case kNull:
678     jval_.l = nullptr;
679     width = 0;
680     break;
681   default:
682     LOG(FATAL) << "Unreached";
683     UNREACHABLE();
684   }
685   ptr_ += width;
686 }
687 
688 namespace dex {
689 
operator <<(std::ostream & os,const ProtoIndex & index)690 std::ostream& operator<<(std::ostream& os, const ProtoIndex& index) {
691   os << "ProtoIndex[" << index.index_ << "]";
692   return os;
693 }
694 
operator <<(std::ostream & os,const StringIndex & index)695 std::ostream& operator<<(std::ostream& os, const StringIndex& index) {
696   os << "StringIndex[" << index.index_ << "]";
697   return os;
698 }
699 
operator <<(std::ostream & os,const TypeIndex & index)700 std::ostream& operator<<(std::ostream& os, const TypeIndex& index) {
701   os << "TypeIndex[" << index.index_ << "]";
702   return os;
703 }
704 
705 }  // namespace dex
706 
707 }  // namespace art
708