• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fcntl.h>
20 #include <limits.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/file.h>
25 #include <sys/stat.h>
26 
27 #include <memory>
28 #include <sstream>
29 
30 #include "art_field-inl.h"
31 #include "art_method-inl.h"
32 #include "base/file_magic.h"
33 #include "base/hash_map.h"
34 #include "base/logging.h"
35 #include "base/stl_util.h"
36 #include "base/stringprintf.h"
37 #include "base/systrace.h"
38 #include "class_linker-inl.h"
39 #include "dex_file-inl.h"
40 #include "dex_file_verifier.h"
41 #include "globals.h"
42 #include "handle_scope-inl.h"
43 #include "leb128.h"
44 #include "mirror/field.h"
45 #include "mirror/method.h"
46 #include "mirror/string.h"
47 #include "os.h"
48 #include "reflection.h"
49 #include "safe_map.h"
50 #include "thread.h"
51 #include "type_lookup_table.h"
52 #include "utf-inl.h"
53 #include "utils.h"
54 #include "well_known_classes.h"
55 #include "zip_archive.h"
56 
57 #pragma GCC diagnostic push
58 #pragma GCC diagnostic ignored "-Wshadow"
59 #include "ScopedFd.h"
60 #pragma GCC diagnostic pop
61 
62 namespace art {
63 
64 const uint8_t DexFile::kDexMagic[] = { 'd', 'e', 'x', '\n' };
65 const uint8_t DexFile::kDexMagicVersions[DexFile::kNumDexVersions][DexFile::kDexVersionLen] = {
66   {'0', '3', '5', '\0'},
67   // Dex version 036 skipped because of an old dalvik bug on some versions of android where dex
68   // files with that version number would erroneously be accepted and run.
69   {'0', '3', '7', '\0'}
70 };
71 
GetChecksum(const char * filename,uint32_t * checksum,std::string * error_msg)72 bool DexFile::GetChecksum(const char* filename, uint32_t* checksum, std::string* error_msg) {
73   CHECK(checksum != nullptr);
74   uint32_t magic;
75 
76   // Strip ":...", which is the location
77   const char* zip_entry_name = kClassesDex;
78   const char* file_part = filename;
79   std::string file_part_storage;
80 
81   if (DexFile::IsMultiDexLocation(filename)) {
82     file_part_storage = GetBaseLocation(filename);
83     file_part = file_part_storage.c_str();
84     zip_entry_name = filename + file_part_storage.size() + 1;
85     DCHECK_EQ(zip_entry_name[-1], kMultiDexSeparator);
86   }
87 
88   ScopedFd fd(OpenAndReadMagic(file_part, &magic, error_msg));
89   if (fd.get() == -1) {
90     DCHECK(!error_msg->empty());
91     return false;
92   }
93   if (IsZipMagic(magic)) {
94     std::unique_ptr<ZipArchive> zip_archive(
95         ZipArchive::OpenFromFd(fd.release(), filename, error_msg));
96     if (zip_archive.get() == nullptr) {
97       *error_msg = StringPrintf("Failed to open zip archive '%s' (error msg: %s)", file_part,
98                                 error_msg->c_str());
99       return false;
100     }
101     std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(zip_entry_name, error_msg));
102     if (zip_entry.get() == nullptr) {
103       *error_msg = StringPrintf("Zip archive '%s' doesn't contain %s (error msg: %s)", file_part,
104                                 zip_entry_name, error_msg->c_str());
105       return false;
106     }
107     *checksum = zip_entry->GetCrc32();
108     return true;
109   }
110   if (IsDexMagic(magic)) {
111     std::unique_ptr<const DexFile> dex_file(
112         DexFile::OpenFile(fd.release(), filename, false, error_msg));
113     if (dex_file.get() == nullptr) {
114       return false;
115     }
116     *checksum = dex_file->GetHeader().checksum_;
117     return true;
118   }
119   *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
120   return false;
121 }
122 
Open(const char * filename,const char * location,std::string * error_msg,std::vector<std::unique_ptr<const DexFile>> * dex_files)123 bool DexFile::Open(const char* filename, const char* location, std::string* error_msg,
124                    std::vector<std::unique_ptr<const DexFile>>* dex_files) {
125   ScopedTrace trace(std::string("Open dex file ") + location);
126   DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
127   uint32_t magic;
128   ScopedFd fd(OpenAndReadMagic(filename, &magic, error_msg));
129   if (fd.get() == -1) {
130     DCHECK(!error_msg->empty());
131     return false;
132   }
133   if (IsZipMagic(magic)) {
134     return DexFile::OpenZip(fd.release(), location, error_msg, dex_files);
135   }
136   if (IsDexMagic(magic)) {
137     std::unique_ptr<const DexFile> dex_file(DexFile::OpenFile(fd.release(), location, true,
138                                                               error_msg));
139     if (dex_file.get() != nullptr) {
140       dex_files->push_back(std::move(dex_file));
141       return true;
142     } else {
143       return false;
144     }
145   }
146   *error_msg = StringPrintf("Expected valid zip or dex file: '%s'", filename);
147   return false;
148 }
149 
ContainsClassesDex(int fd,const char * filename)150 static bool ContainsClassesDex(int fd, const char* filename) {
151   std::string error_msg;
152   std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, filename, &error_msg));
153   if (zip_archive.get() == nullptr) {
154     return false;
155   }
156   std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(DexFile::kClassesDex, &error_msg));
157   return (zip_entry.get() != nullptr);
158 }
159 
MaybeDex(const char * filename)160 bool DexFile::MaybeDex(const char* filename) {
161   uint32_t magic;
162   std::string error_msg;
163   ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
164   if (fd.get() == -1) {
165     return false;
166   }
167   if (IsZipMagic(magic)) {
168     return ContainsClassesDex(fd.release(), filename);
169   } else if (IsDexMagic(magic)) {
170     return true;
171   }
172   return false;
173 }
174 
GetPermissions() const175 int DexFile::GetPermissions() const {
176   if (mem_map_.get() == nullptr) {
177     return 0;
178   } else {
179     return mem_map_->GetProtect();
180   }
181 }
182 
IsReadOnly() const183 bool DexFile::IsReadOnly() const {
184   return GetPermissions() == PROT_READ;
185 }
186 
EnableWrite() const187 bool DexFile::EnableWrite() const {
188   CHECK(IsReadOnly());
189   if (mem_map_.get() == nullptr) {
190     return false;
191   } else {
192     return mem_map_->Protect(PROT_READ | PROT_WRITE);
193   }
194 }
195 
DisableWrite() const196 bool DexFile::DisableWrite() const {
197   CHECK(!IsReadOnly());
198   if (mem_map_.get() == nullptr) {
199     return false;
200   } else {
201     return mem_map_->Protect(PROT_READ);
202   }
203 }
204 
Open(const uint8_t * base,size_t size,const std::string & location,uint32_t location_checksum,const OatDexFile * oat_dex_file,bool verify,std::string * error_msg)205 std::unique_ptr<const DexFile> DexFile::Open(const uint8_t* base, size_t size,
206                                              const std::string& location,
207                                              uint32_t location_checksum,
208                                              const OatDexFile* oat_dex_file,
209                                              bool verify,
210                                              std::string* error_msg) {
211   ScopedTrace trace(std::string("Open dex file from RAM ") + location);
212   std::unique_ptr<const DexFile> dex_file = OpenMemory(base,
213                                                        size,
214                                                        location,
215                                                        location_checksum,
216                                                        nullptr,
217                                                        oat_dex_file,
218                                                        error_msg);
219   if (verify && !DexFileVerifier::Verify(dex_file.get(),
220                                          dex_file->Begin(),
221                                          dex_file->Size(),
222                                          location.c_str(),
223                                          error_msg)) {
224     return nullptr;
225   }
226 
227   return dex_file;
228 }
229 
OpenFile(int fd,const char * location,bool verify,std::string * error_msg)230 std::unique_ptr<const DexFile> DexFile::OpenFile(int fd, const char* location, bool verify,
231                                                  std::string* error_msg) {
232   ScopedTrace trace(std::string("Open dex file ") + location);
233   CHECK(location != nullptr);
234   std::unique_ptr<MemMap> map;
235   {
236     ScopedFd delayed_close(fd);
237     struct stat sbuf;
238     memset(&sbuf, 0, sizeof(sbuf));
239     if (fstat(fd, &sbuf) == -1) {
240       *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", location, strerror(errno));
241       return nullptr;
242     }
243     if (S_ISDIR(sbuf.st_mode)) {
244       *error_msg = StringPrintf("Attempt to mmap directory '%s'", location);
245       return nullptr;
246     }
247     size_t length = sbuf.st_size;
248     map.reset(MemMap::MapFile(length,
249                               PROT_READ,
250                               MAP_PRIVATE,
251                               fd,
252                               0,
253                               /*low_4gb*/false,
254                               location,
255                               error_msg));
256     if (map.get() == nullptr) {
257       DCHECK(!error_msg->empty());
258       return nullptr;
259     }
260   }
261 
262   if (map->Size() < sizeof(DexFile::Header)) {
263     *error_msg = StringPrintf(
264         "DexFile: failed to open dex file '%s' that is too short to have a header", location);
265     return nullptr;
266   }
267 
268   const Header* dex_header = reinterpret_cast<const Header*>(map->Begin());
269 
270   std::unique_ptr<const DexFile> dex_file(OpenMemory(location, dex_header->checksum_, map.release(),
271                                                      error_msg));
272   if (dex_file.get() == nullptr) {
273     *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location,
274                               error_msg->c_str());
275     return nullptr;
276   }
277 
278   if (verify && !DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
279                                          location, error_msg)) {
280     return nullptr;
281   }
282 
283   return dex_file;
284 }
285 
286 const char* DexFile::kClassesDex = "classes.dex";
287 
OpenZip(int fd,const std::string & location,std::string * error_msg,std::vector<std::unique_ptr<const DexFile>> * dex_files)288 bool DexFile::OpenZip(int fd, const std::string& location, std::string* error_msg,
289                       std::vector<std::unique_ptr<const DexFile>>* dex_files) {
290   ScopedTrace trace("Dex file open Zip " + std::string(location));
291   DCHECK(dex_files != nullptr) << "DexFile::OpenZip: out-param is nullptr";
292   std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(fd, location.c_str(), error_msg));
293   if (zip_archive.get() == nullptr) {
294     DCHECK(!error_msg->empty());
295     return false;
296   }
297   return DexFile::OpenFromZip(*zip_archive, location, error_msg, dex_files);
298 }
299 
OpenMemory(const std::string & location,uint32_t location_checksum,MemMap * mem_map,std::string * error_msg)300 std::unique_ptr<const DexFile> DexFile::OpenMemory(const std::string& location,
301                                                    uint32_t location_checksum,
302                                                    MemMap* mem_map,
303                                                    std::string* error_msg) {
304   return OpenMemory(mem_map->Begin(),
305                     mem_map->Size(),
306                     location,
307                     location_checksum,
308                     mem_map,
309                     nullptr,
310                     error_msg);
311 }
312 
Open(const ZipArchive & zip_archive,const char * entry_name,const std::string & location,std::string * error_msg,ZipOpenErrorCode * error_code)313 std::unique_ptr<const DexFile> DexFile::Open(const ZipArchive& zip_archive, const char* entry_name,
314                                              const std::string& location, std::string* error_msg,
315                                              ZipOpenErrorCode* error_code) {
316   ScopedTrace trace("Dex file open from Zip Archive " + std::string(location));
317   CHECK(!location.empty());
318   std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
319   if (zip_entry.get() == nullptr) {
320     *error_code = ZipOpenErrorCode::kEntryNotFound;
321     return nullptr;
322   }
323   std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg));
324   if (map.get() == nullptr) {
325     *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
326                               error_msg->c_str());
327     *error_code = ZipOpenErrorCode::kExtractToMemoryError;
328     return nullptr;
329   }
330   std::unique_ptr<const DexFile> dex_file(OpenMemory(location, zip_entry->GetCrc32(), map.release(),
331                                                error_msg));
332   if (dex_file.get() == nullptr) {
333     *error_msg = StringPrintf("Failed to open dex file '%s' from memory: %s", location.c_str(),
334                               error_msg->c_str());
335     *error_code = ZipOpenErrorCode::kDexFileError;
336     return nullptr;
337   }
338   if (!dex_file->DisableWrite()) {
339     *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
340     *error_code = ZipOpenErrorCode::kMakeReadOnlyError;
341     return nullptr;
342   }
343   CHECK(dex_file->IsReadOnly()) << location;
344   if (!DexFileVerifier::Verify(dex_file.get(), dex_file->Begin(), dex_file->Size(),
345                                location.c_str(), error_msg)) {
346     *error_code = ZipOpenErrorCode::kVerifyError;
347     return nullptr;
348   }
349   *error_code = ZipOpenErrorCode::kNoError;
350   return dex_file;
351 }
352 
353 // Technically we do not have a limitation with respect to the number of dex files that can be in a
354 // multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
355 // (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
356 // seems an excessive number.
357 static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
358 
OpenFromZip(const ZipArchive & zip_archive,const std::string & location,std::string * error_msg,std::vector<std::unique_ptr<const DexFile>> * dex_files)359 bool DexFile::OpenFromZip(const ZipArchive& zip_archive, const std::string& location,
360                           std::string* error_msg,
361                           std::vector<std::unique_ptr<const DexFile>>* dex_files) {
362   ScopedTrace trace("Dex file open from Zip " + std::string(location));
363   DCHECK(dex_files != nullptr) << "DexFile::OpenFromZip: out-param is nullptr";
364   ZipOpenErrorCode error_code;
365   std::unique_ptr<const DexFile> dex_file(Open(zip_archive, kClassesDex, location, error_msg,
366                                                &error_code));
367   if (dex_file.get() == nullptr) {
368     return false;
369   } else {
370     // Had at least classes.dex.
371     dex_files->push_back(std::move(dex_file));
372 
373     // Now try some more.
374 
375     // We could try to avoid std::string allocations by working on a char array directly. As we
376     // do not expect a lot of iterations, this seems too involved and brittle.
377 
378     for (size_t i = 1; ; ++i) {
379       std::string name = GetMultiDexClassesDexName(i);
380       std::string fake_location = GetMultiDexLocation(i, location.c_str());
381       std::unique_ptr<const DexFile> next_dex_file(Open(zip_archive, name.c_str(), fake_location,
382                                                         error_msg, &error_code));
383       if (next_dex_file.get() == nullptr) {
384         if (error_code != ZipOpenErrorCode::kEntryNotFound) {
385           LOG(WARNING) << error_msg;
386         }
387         break;
388       } else {
389         dex_files->push_back(std::move(next_dex_file));
390       }
391 
392       if (i == kWarnOnManyDexFilesThreshold) {
393         LOG(WARNING) << location << " has in excess of " << kWarnOnManyDexFilesThreshold
394                      << " dex files. Please consider coalescing and shrinking the number to "
395                         " avoid runtime overhead.";
396       }
397 
398       if (i == std::numeric_limits<size_t>::max()) {
399         LOG(ERROR) << "Overflow in number of dex files!";
400         break;
401       }
402     }
403 
404     return true;
405   }
406 }
407 
408 
OpenMemory(const uint8_t * base,size_t size,const std::string & location,uint32_t location_checksum,MemMap * mem_map,const OatDexFile * oat_dex_file,std::string * error_msg)409 std::unique_ptr<const DexFile> DexFile::OpenMemory(const uint8_t* base,
410                                                    size_t size,
411                                                    const std::string& location,
412                                                    uint32_t location_checksum,
413                                                    MemMap* mem_map,
414                                                    const OatDexFile* oat_dex_file,
415                                                    std::string* error_msg) {
416   CHECK_ALIGNED(base, 4);  // various dex file structures must be word aligned
417   std::unique_ptr<DexFile> dex_file(
418       new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
419   if (!dex_file->Init(error_msg)) {
420     dex_file.reset();
421   }
422   return std::unique_ptr<const DexFile>(dex_file.release());
423 }
424 
DexFile(const uint8_t * base,size_t size,const std::string & location,uint32_t location_checksum,MemMap * mem_map,const OatDexFile * oat_dex_file)425 DexFile::DexFile(const uint8_t* base, size_t size,
426                  const std::string& location,
427                  uint32_t location_checksum,
428                  MemMap* mem_map,
429                  const OatDexFile* oat_dex_file)
430     : begin_(base),
431       size_(size),
432       location_(location),
433       location_checksum_(location_checksum),
434       mem_map_(mem_map),
435       header_(reinterpret_cast<const Header*>(base)),
436       string_ids_(reinterpret_cast<const StringId*>(base + header_->string_ids_off_)),
437       type_ids_(reinterpret_cast<const TypeId*>(base + header_->type_ids_off_)),
438       field_ids_(reinterpret_cast<const FieldId*>(base + header_->field_ids_off_)),
439       method_ids_(reinterpret_cast<const MethodId*>(base + header_->method_ids_off_)),
440       proto_ids_(reinterpret_cast<const ProtoId*>(base + header_->proto_ids_off_)),
441       class_defs_(reinterpret_cast<const ClassDef*>(base + header_->class_defs_off_)),
442       oat_dex_file_(oat_dex_file) {
443   CHECK(begin_ != nullptr) << GetLocation();
444   CHECK_GT(size_, 0U) << GetLocation();
445   const uint8_t* lookup_data = (oat_dex_file != nullptr)
446       ? oat_dex_file->GetLookupTableData()
447       : nullptr;
448   if (lookup_data != nullptr) {
449     if (lookup_data + TypeLookupTable::RawDataLength(*this) > oat_dex_file->GetOatFile()->End()) {
450       LOG(WARNING) << "found truncated lookup table in " << GetLocation();
451     } else {
452       lookup_table_.reset(TypeLookupTable::Open(lookup_data, *this));
453     }
454   }
455 }
456 
~DexFile()457 DexFile::~DexFile() {
458   // We don't call DeleteGlobalRef on dex_object_ because we're only called by DestroyJavaVM, and
459   // that's only called after DetachCurrentThread, which means there's no JNIEnv. We could
460   // re-attach, but cleaning up these global references is not obviously useful. It's not as if
461   // the global reference table is otherwise empty!
462 }
463 
Init(std::string * error_msg)464 bool DexFile::Init(std::string* error_msg) {
465   if (!CheckMagicAndVersion(error_msg)) {
466     return false;
467   }
468   return true;
469 }
470 
CheckMagicAndVersion(std::string * error_msg) const471 bool DexFile::CheckMagicAndVersion(std::string* error_msg) const {
472   if (!IsMagicValid(header_->magic_)) {
473     std::ostringstream oss;
474     oss << "Unrecognized magic number in "  << GetLocation() << ":"
475             << " " << header_->magic_[0]
476             << " " << header_->magic_[1]
477             << " " << header_->magic_[2]
478             << " " << header_->magic_[3];
479     *error_msg = oss.str();
480     return false;
481   }
482   if (!IsVersionValid(header_->magic_)) {
483     std::ostringstream oss;
484     oss << "Unrecognized version number in "  << GetLocation() << ":"
485             << " " << header_->magic_[4]
486             << " " << header_->magic_[5]
487             << " " << header_->magic_[6]
488             << " " << header_->magic_[7];
489     *error_msg = oss.str();
490     return false;
491   }
492   return true;
493 }
494 
IsMagicValid(const uint8_t * magic)495 bool DexFile::IsMagicValid(const uint8_t* magic) {
496   return (memcmp(magic, kDexMagic, sizeof(kDexMagic)) == 0);
497 }
498 
IsVersionValid(const uint8_t * magic)499 bool DexFile::IsVersionValid(const uint8_t* magic) {
500   const uint8_t* version = &magic[sizeof(kDexMagic)];
501   for (uint32_t i = 0; i < kNumDexVersions; i++) {
502     if (memcmp(version, kDexMagicVersions[i], kDexVersionLen) == 0) {
503       return true;
504     }
505   }
506   return false;
507 }
508 
GetVersion() const509 uint32_t DexFile::Header::GetVersion() const {
510   const char* version = reinterpret_cast<const char*>(&magic_[sizeof(kDexMagic)]);
511   return atoi(version);
512 }
513 
FindClassDef(const char * descriptor,size_t hash) const514 const DexFile::ClassDef* DexFile::FindClassDef(const char* descriptor, size_t hash) const {
515   DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
516   if (LIKELY(lookup_table_ != nullptr)) {
517     const uint32_t class_def_idx = lookup_table_->Lookup(descriptor, hash);
518     return (class_def_idx != DexFile::kDexNoIndex) ? &GetClassDef(class_def_idx) : nullptr;
519   }
520 
521   // Fast path for rate no class defs case.
522   const uint32_t num_class_defs = NumClassDefs();
523   if (num_class_defs == 0) {
524     return nullptr;
525   }
526   const TypeId* type_id = FindTypeId(descriptor);
527   if (type_id != nullptr) {
528     uint16_t type_idx = GetIndexForTypeId(*type_id);
529     for (size_t i = 0; i < num_class_defs; ++i) {
530       const ClassDef& class_def = GetClassDef(i);
531       if (class_def.class_idx_ == type_idx) {
532         return &class_def;
533       }
534     }
535   }
536   return nullptr;
537 }
538 
FindClassDef(uint16_t type_idx) const539 const DexFile::ClassDef* DexFile::FindClassDef(uint16_t type_idx) const {
540   size_t num_class_defs = NumClassDefs();
541   for (size_t i = 0; i < num_class_defs; ++i) {
542     const ClassDef& class_def = GetClassDef(i);
543     if (class_def.class_idx_ == type_idx) {
544       return &class_def;
545     }
546   }
547   return nullptr;
548 }
549 
FindFieldId(const DexFile::TypeId & declaring_klass,const DexFile::StringId & name,const DexFile::TypeId & type) const550 const DexFile::FieldId* DexFile::FindFieldId(const DexFile::TypeId& declaring_klass,
551                                               const DexFile::StringId& name,
552                                               const DexFile::TypeId& type) const {
553   // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
554   const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
555   const uint32_t name_idx = GetIndexForStringId(name);
556   const uint16_t type_idx = GetIndexForTypeId(type);
557   int32_t lo = 0;
558   int32_t hi = NumFieldIds() - 1;
559   while (hi >= lo) {
560     int32_t mid = (hi + lo) / 2;
561     const DexFile::FieldId& field = GetFieldId(mid);
562     if (class_idx > field.class_idx_) {
563       lo = mid + 1;
564     } else if (class_idx < field.class_idx_) {
565       hi = mid - 1;
566     } else {
567       if (name_idx > field.name_idx_) {
568         lo = mid + 1;
569       } else if (name_idx < field.name_idx_) {
570         hi = mid - 1;
571       } else {
572         if (type_idx > field.type_idx_) {
573           lo = mid + 1;
574         } else if (type_idx < field.type_idx_) {
575           hi = mid - 1;
576         } else {
577           return &field;
578         }
579       }
580     }
581   }
582   return nullptr;
583 }
584 
FindMethodId(const DexFile::TypeId & declaring_klass,const DexFile::StringId & name,const DexFile::ProtoId & signature) const585 const DexFile::MethodId* DexFile::FindMethodId(const DexFile::TypeId& declaring_klass,
586                                                const DexFile::StringId& name,
587                                                const DexFile::ProtoId& signature) const {
588   // Binary search MethodIds knowing that they are sorted by class_idx, name_idx then proto_idx
589   const uint16_t class_idx = GetIndexForTypeId(declaring_klass);
590   const uint32_t name_idx = GetIndexForStringId(name);
591   const uint16_t proto_idx = GetIndexForProtoId(signature);
592   int32_t lo = 0;
593   int32_t hi = NumMethodIds() - 1;
594   while (hi >= lo) {
595     int32_t mid = (hi + lo) / 2;
596     const DexFile::MethodId& method = GetMethodId(mid);
597     if (class_idx > method.class_idx_) {
598       lo = mid + 1;
599     } else if (class_idx < method.class_idx_) {
600       hi = mid - 1;
601     } else {
602       if (name_idx > method.name_idx_) {
603         lo = mid + 1;
604       } else if (name_idx < method.name_idx_) {
605         hi = mid - 1;
606       } else {
607         if (proto_idx > method.proto_idx_) {
608           lo = mid + 1;
609         } else if (proto_idx < method.proto_idx_) {
610           hi = mid - 1;
611         } else {
612           return &method;
613         }
614       }
615     }
616   }
617   return nullptr;
618 }
619 
FindStringId(const char * string) const620 const DexFile::StringId* DexFile::FindStringId(const char* string) const {
621   int32_t lo = 0;
622   int32_t hi = NumStringIds() - 1;
623   while (hi >= lo) {
624     int32_t mid = (hi + lo) / 2;
625     const DexFile::StringId& str_id = GetStringId(mid);
626     const char* str = GetStringData(str_id);
627     int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
628     if (compare > 0) {
629       lo = mid + 1;
630     } else if (compare < 0) {
631       hi = mid - 1;
632     } else {
633       return &str_id;
634     }
635   }
636   return nullptr;
637 }
638 
FindTypeId(const char * string) const639 const DexFile::TypeId* DexFile::FindTypeId(const char* string) const {
640   int32_t lo = 0;
641   int32_t hi = NumTypeIds() - 1;
642   while (hi >= lo) {
643     int32_t mid = (hi + lo) / 2;
644     const TypeId& type_id = GetTypeId(mid);
645     const DexFile::StringId& str_id = GetStringId(type_id.descriptor_idx_);
646     const char* str = GetStringData(str_id);
647     int compare = CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(string, str);
648     if (compare > 0) {
649       lo = mid + 1;
650     } else if (compare < 0) {
651       hi = mid - 1;
652     } else {
653       return &type_id;
654     }
655   }
656   return nullptr;
657 }
658 
FindStringId(const uint16_t * string,size_t length) const659 const DexFile::StringId* DexFile::FindStringId(const uint16_t* string, size_t length) const {
660   int32_t lo = 0;
661   int32_t hi = NumStringIds() - 1;
662   while (hi >= lo) {
663     int32_t mid = (hi + lo) / 2;
664     const DexFile::StringId& str_id = GetStringId(mid);
665     const char* str = GetStringData(str_id);
666     int compare = CompareModifiedUtf8ToUtf16AsCodePointValues(str, string, length);
667     if (compare > 0) {
668       lo = mid + 1;
669     } else if (compare < 0) {
670       hi = mid - 1;
671     } else {
672       return &str_id;
673     }
674   }
675   return nullptr;
676 }
677 
FindTypeId(uint32_t string_idx) const678 const DexFile::TypeId* DexFile::FindTypeId(uint32_t string_idx) const {
679   int32_t lo = 0;
680   int32_t hi = NumTypeIds() - 1;
681   while (hi >= lo) {
682     int32_t mid = (hi + lo) / 2;
683     const TypeId& type_id = GetTypeId(mid);
684     if (string_idx > type_id.descriptor_idx_) {
685       lo = mid + 1;
686     } else if (string_idx < type_id.descriptor_idx_) {
687       hi = mid - 1;
688     } else {
689       return &type_id;
690     }
691   }
692   return nullptr;
693 }
694 
FindProtoId(uint16_t return_type_idx,const uint16_t * signature_type_idxs,uint32_t signature_length) const695 const DexFile::ProtoId* DexFile::FindProtoId(uint16_t return_type_idx,
696                                              const uint16_t* signature_type_idxs,
697                                              uint32_t signature_length) const {
698   int32_t lo = 0;
699   int32_t hi = NumProtoIds() - 1;
700   while (hi >= lo) {
701     int32_t mid = (hi + lo) / 2;
702     const DexFile::ProtoId& proto = GetProtoId(mid);
703     int compare = return_type_idx - proto.return_type_idx_;
704     if (compare == 0) {
705       DexFileParameterIterator it(*this, proto);
706       size_t i = 0;
707       while (it.HasNext() && i < signature_length && compare == 0) {
708         compare = signature_type_idxs[i] - it.GetTypeIdx();
709         it.Next();
710         i++;
711       }
712       if (compare == 0) {
713         if (it.HasNext()) {
714           compare = -1;
715         } else if (i < signature_length) {
716           compare = 1;
717         }
718       }
719     }
720     if (compare > 0) {
721       lo = mid + 1;
722     } else if (compare < 0) {
723       hi = mid - 1;
724     } else {
725       return &proto;
726     }
727   }
728   return nullptr;
729 }
730 
CreateTypeLookupTable(uint8_t * storage) const731 void DexFile::CreateTypeLookupTable(uint8_t* storage) const {
732   lookup_table_.reset(TypeLookupTable::Create(*this, storage));
733 }
734 
735 // Given a signature place the type ids into the given vector
CreateTypeList(const StringPiece & signature,uint16_t * return_type_idx,std::vector<uint16_t> * param_type_idxs) const736 bool DexFile::CreateTypeList(const StringPiece& signature, uint16_t* return_type_idx,
737                              std::vector<uint16_t>* param_type_idxs) const {
738   if (signature[0] != '(') {
739     return false;
740   }
741   size_t offset = 1;
742   size_t end = signature.size();
743   bool process_return = false;
744   while (offset < end) {
745     size_t start_offset = offset;
746     char c = signature[offset];
747     offset++;
748     if (c == ')') {
749       process_return = true;
750       continue;
751     }
752     while (c == '[') {  // process array prefix
753       if (offset >= end) {  // expect some descriptor following [
754         return false;
755       }
756       c = signature[offset];
757       offset++;
758     }
759     if (c == 'L') {  // process type descriptors
760       do {
761         if (offset >= end) {  // unexpected early termination of descriptor
762           return false;
763         }
764         c = signature[offset];
765         offset++;
766       } while (c != ';');
767     }
768     // TODO: avoid creating a std::string just to get a 0-terminated char array
769     std::string descriptor(signature.data() + start_offset, offset - start_offset);
770     const DexFile::TypeId* type_id = FindTypeId(descriptor.c_str());
771     if (type_id == nullptr) {
772       return false;
773     }
774     uint16_t type_idx = GetIndexForTypeId(*type_id);
775     if (!process_return) {
776       param_type_idxs->push_back(type_idx);
777     } else {
778       *return_type_idx = type_idx;
779       return offset == end;  // return true if the signature had reached a sensible end
780     }
781   }
782   return false;  // failed to correctly parse return type
783 }
784 
CreateSignature(const StringPiece & signature) const785 const Signature DexFile::CreateSignature(const StringPiece& signature) const {
786   uint16_t return_type_idx;
787   std::vector<uint16_t> param_type_indices;
788   bool success = CreateTypeList(signature, &return_type_idx, &param_type_indices);
789   if (!success) {
790     return Signature::NoSignature();
791   }
792   const ProtoId* proto_id = FindProtoId(return_type_idx, param_type_indices);
793   if (proto_id == nullptr) {
794     return Signature::NoSignature();
795   }
796   return Signature(this, *proto_id);
797 }
798 
GetLineNumFromPC(ArtMethod * method,uint32_t rel_pc) const799 int32_t DexFile::GetLineNumFromPC(ArtMethod* method, uint32_t rel_pc) const {
800   // For native method, lineno should be -2 to indicate it is native. Note that
801   // "line number == -2" is how libcore tells from StackTraceElement.
802   if (method->GetCodeItemOffset() == 0) {
803     return -2;
804   }
805 
806   const CodeItem* code_item = GetCodeItem(method->GetCodeItemOffset());
807   DCHECK(code_item != nullptr) << PrettyMethod(method) << " " << GetLocation();
808 
809   // A method with no line number info should return -1
810   LineNumFromPcContext context(rel_pc, -1);
811   DecodeDebugPositionInfo(code_item, LineNumForPcCb, &context);
812   return context.line_num_;
813 }
814 
FindTryItem(const CodeItem & code_item,uint32_t address)815 int32_t DexFile::FindTryItem(const CodeItem &code_item, uint32_t address) {
816   // Note: Signed type is important for max and min.
817   int32_t min = 0;
818   int32_t max = code_item.tries_size_ - 1;
819 
820   while (min <= max) {
821     int32_t mid = min + ((max - min) / 2);
822 
823     const art::DexFile::TryItem* ti = GetTryItems(code_item, mid);
824     uint32_t start = ti->start_addr_;
825     uint32_t end = start + ti->insn_count_;
826 
827     if (address < start) {
828       max = mid - 1;
829     } else if (address >= end) {
830       min = mid + 1;
831     } else {  // We have a winner!
832       return mid;
833     }
834   }
835   // No match.
836   return -1;
837 }
838 
FindCatchHandlerOffset(const CodeItem & code_item,uint32_t address)839 int32_t DexFile::FindCatchHandlerOffset(const CodeItem &code_item, uint32_t address) {
840   int32_t try_item = FindTryItem(code_item, address);
841   if (try_item == -1) {
842     return -1;
843   } else {
844     return DexFile::GetTryItems(code_item, try_item)->handler_off_;
845   }
846 }
847 
DecodeDebugLocalInfo(const CodeItem * code_item,bool is_static,uint32_t method_idx,DexDebugNewLocalCb local_cb,void * context) const848 bool DexFile::DecodeDebugLocalInfo(const CodeItem* code_item, bool is_static, uint32_t method_idx,
849                                    DexDebugNewLocalCb local_cb, void* context) const {
850   DCHECK(local_cb != nullptr);
851   if (code_item == nullptr) {
852     return false;
853   }
854   const uint8_t* stream = GetDebugInfoStream(code_item);
855   if (stream == nullptr) {
856     return false;
857   }
858   std::vector<LocalInfo> local_in_reg(code_item->registers_size_);
859 
860   uint16_t arg_reg = code_item->registers_size_ - code_item->ins_size_;
861   if (!is_static) {
862     const char* descriptor = GetMethodDeclaringClassDescriptor(GetMethodId(method_idx));
863     local_in_reg[arg_reg].name_ = "this";
864     local_in_reg[arg_reg].descriptor_ = descriptor;
865     local_in_reg[arg_reg].signature_ = nullptr;
866     local_in_reg[arg_reg].start_address_ = 0;
867     local_in_reg[arg_reg].reg_ = arg_reg;
868     local_in_reg[arg_reg].is_live_ = true;
869     arg_reg++;
870   }
871 
872   DexFileParameterIterator it(*this, GetMethodPrototype(GetMethodId(method_idx)));
873   DecodeUnsignedLeb128(&stream);  // Line.
874   uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
875   uint32_t i;
876   for (i = 0; i < parameters_size && it.HasNext(); ++i, it.Next()) {
877     if (arg_reg >= code_item->registers_size_) {
878       LOG(ERROR) << "invalid stream - arg reg >= reg size (" << arg_reg
879                  << " >= " << code_item->registers_size_ << ") in " << GetLocation();
880       return false;
881     }
882     uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
883     const char* descriptor = it.GetDescriptor();
884     local_in_reg[arg_reg].name_ = StringDataByIdx(name_idx);
885     local_in_reg[arg_reg].descriptor_ = descriptor;
886     local_in_reg[arg_reg].signature_ = nullptr;
887     local_in_reg[arg_reg].start_address_ = 0;
888     local_in_reg[arg_reg].reg_ = arg_reg;
889     local_in_reg[arg_reg].is_live_ = true;
890     switch (*descriptor) {
891       case 'D':
892       case 'J':
893         arg_reg += 2;
894         break;
895       default:
896         arg_reg += 1;
897         break;
898     }
899   }
900   if (i != parameters_size || it.HasNext()) {
901     LOG(ERROR) << "invalid stream - problem with parameter iterator in " << GetLocation()
902                << " for method " << PrettyMethod(method_idx, *this);
903     return false;
904   }
905 
906   uint32_t address = 0;
907   for (;;)  {
908     uint8_t opcode = *stream++;
909     switch (opcode) {
910       case DBG_END_SEQUENCE:
911         // Emit all variables which are still alive at the end of the method.
912         for (uint16_t reg = 0; reg < code_item->registers_size_; reg++) {
913           if (local_in_reg[reg].is_live_) {
914             local_in_reg[reg].end_address_ = code_item->insns_size_in_code_units_;
915             local_cb(context, local_in_reg[reg]);
916           }
917         }
918         return true;
919       case DBG_ADVANCE_PC:
920         address += DecodeUnsignedLeb128(&stream);
921         break;
922       case DBG_ADVANCE_LINE:
923         DecodeSignedLeb128(&stream);  // Line.
924         break;
925       case DBG_START_LOCAL:
926       case DBG_START_LOCAL_EXTENDED: {
927         uint16_t reg = DecodeUnsignedLeb128(&stream);
928         if (reg >= code_item->registers_size_) {
929           LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
930                      << code_item->registers_size_ << ") in " << GetLocation();
931           return false;
932         }
933 
934         uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
935         uint32_t descriptor_idx = DecodeUnsignedLeb128P1(&stream);
936         uint32_t signature_idx = kDexNoIndex;
937         if (opcode == DBG_START_LOCAL_EXTENDED) {
938           signature_idx = DecodeUnsignedLeb128P1(&stream);
939         }
940 
941         // Emit what was previously there, if anything
942         if (local_in_reg[reg].is_live_) {
943           local_in_reg[reg].end_address_ = address;
944           local_cb(context, local_in_reg[reg]);
945         }
946 
947         local_in_reg[reg].name_ = StringDataByIdx(name_idx);
948         local_in_reg[reg].descriptor_ = StringByTypeIdx(descriptor_idx);
949         local_in_reg[reg].signature_ = StringDataByIdx(signature_idx);
950         local_in_reg[reg].start_address_ = address;
951         local_in_reg[reg].reg_ = reg;
952         local_in_reg[reg].is_live_ = true;
953         break;
954       }
955       case DBG_END_LOCAL: {
956         uint16_t reg = DecodeUnsignedLeb128(&stream);
957         if (reg >= code_item->registers_size_) {
958           LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
959                      << code_item->registers_size_ << ") in " << GetLocation();
960           return false;
961         }
962         if (!local_in_reg[reg].is_live_) {
963           LOG(ERROR) << "invalid stream - end without start in " << GetLocation();
964           return false;
965         }
966         local_in_reg[reg].end_address_ = address;
967         local_cb(context, local_in_reg[reg]);
968         local_in_reg[reg].is_live_ = false;
969         break;
970       }
971       case DBG_RESTART_LOCAL: {
972         uint16_t reg = DecodeUnsignedLeb128(&stream);
973         if (reg >= code_item->registers_size_) {
974           LOG(ERROR) << "invalid stream - reg >= reg size (" << reg << " >= "
975                      << code_item->registers_size_ << ") in " << GetLocation();
976           return false;
977         }
978         // If the register is live, the "restart" is superfluous,
979         // and we don't want to mess with the existing start address.
980         if (!local_in_reg[reg].is_live_) {
981           local_in_reg[reg].start_address_ = address;
982           local_in_reg[reg].is_live_ = true;
983         }
984         break;
985       }
986       case DBG_SET_PROLOGUE_END:
987       case DBG_SET_EPILOGUE_BEGIN:
988         break;
989       case DBG_SET_FILE:
990         DecodeUnsignedLeb128P1(&stream);  // name.
991         break;
992       default:
993         address += (opcode - DBG_FIRST_SPECIAL) / DBG_LINE_RANGE;
994         break;
995     }
996   }
997 }
998 
DecodeDebugPositionInfo(const CodeItem * code_item,DexDebugNewPositionCb position_cb,void * context) const999 bool DexFile::DecodeDebugPositionInfo(const CodeItem* code_item, DexDebugNewPositionCb position_cb,
1000                                       void* context) const {
1001   DCHECK(position_cb != nullptr);
1002   if (code_item == nullptr) {
1003     return false;
1004   }
1005   const uint8_t* stream = GetDebugInfoStream(code_item);
1006   if (stream == nullptr) {
1007     return false;
1008   }
1009 
1010   PositionInfo entry = PositionInfo();
1011   entry.line_ = DecodeUnsignedLeb128(&stream);
1012   uint32_t parameters_size = DecodeUnsignedLeb128(&stream);
1013   for (uint32_t i = 0; i < parameters_size; ++i) {
1014     DecodeUnsignedLeb128P1(&stream);  // Parameter name.
1015   }
1016 
1017   for (;;)  {
1018     uint8_t opcode = *stream++;
1019     switch (opcode) {
1020       case DBG_END_SEQUENCE:
1021         return true;  // end of stream.
1022       case DBG_ADVANCE_PC:
1023         entry.address_ += DecodeUnsignedLeb128(&stream);
1024         break;
1025       case DBG_ADVANCE_LINE:
1026         entry.line_ += DecodeSignedLeb128(&stream);
1027         break;
1028       case DBG_START_LOCAL:
1029         DecodeUnsignedLeb128(&stream);  // reg.
1030         DecodeUnsignedLeb128P1(&stream);  // name.
1031         DecodeUnsignedLeb128P1(&stream);  // descriptor.
1032         break;
1033       case DBG_START_LOCAL_EXTENDED:
1034         DecodeUnsignedLeb128(&stream);  // reg.
1035         DecodeUnsignedLeb128P1(&stream);  // name.
1036         DecodeUnsignedLeb128P1(&stream);  // descriptor.
1037         DecodeUnsignedLeb128P1(&stream);  // signature.
1038         break;
1039       case DBG_END_LOCAL:
1040       case DBG_RESTART_LOCAL:
1041         DecodeUnsignedLeb128(&stream);  // reg.
1042         break;
1043       case DBG_SET_PROLOGUE_END:
1044         entry.prologue_end_ = true;
1045         break;
1046       case DBG_SET_EPILOGUE_BEGIN:
1047         entry.epilogue_begin_ = true;
1048         break;
1049       case DBG_SET_FILE: {
1050         uint32_t name_idx = DecodeUnsignedLeb128P1(&stream);
1051         entry.source_file_ = StringDataByIdx(name_idx);
1052         break;
1053       }
1054       default: {
1055         int adjopcode = opcode - DBG_FIRST_SPECIAL;
1056         entry.address_ += adjopcode / DBG_LINE_RANGE;
1057         entry.line_ += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE);
1058         if (position_cb(context, entry)) {
1059           return true;  // early exit.
1060         }
1061         entry.prologue_end_ = false;
1062         entry.epilogue_begin_ = false;
1063         break;
1064       }
1065     }
1066   }
1067 }
1068 
LineNumForPcCb(void * raw_context,const PositionInfo & entry)1069 bool DexFile::LineNumForPcCb(void* raw_context, const PositionInfo& entry) {
1070   LineNumFromPcContext* context = reinterpret_cast<LineNumFromPcContext*>(raw_context);
1071 
1072   // We know that this callback will be called in
1073   // ascending address order, so keep going until we find
1074   // a match or we've just gone past it.
1075   if (entry.address_ > context->address_) {
1076     // The line number from the previous positions callback
1077     // wil be the final result.
1078     return true;
1079   } else {
1080     context->line_num_ = entry.line_;
1081     return entry.address_ == context->address_;
1082   }
1083 }
1084 
IsMultiDexLocation(const char * location)1085 bool DexFile::IsMultiDexLocation(const char* location) {
1086   return strrchr(location, kMultiDexSeparator) != nullptr;
1087 }
1088 
GetMultiDexClassesDexName(size_t index)1089 std::string DexFile::GetMultiDexClassesDexName(size_t index) {
1090   if (index == 0) {
1091     return "classes.dex";
1092   } else {
1093     return StringPrintf("classes%zu.dex", index + 1);
1094   }
1095 }
1096 
GetMultiDexLocation(size_t index,const char * dex_location)1097 std::string DexFile::GetMultiDexLocation(size_t index, const char* dex_location) {
1098   if (index == 0) {
1099     return dex_location;
1100   } else {
1101     return StringPrintf("%s" kMultiDexSeparatorString "classes%zu.dex", dex_location, index + 1);
1102   }
1103 }
1104 
GetDexCanonicalLocation(const char * dex_location)1105 std::string DexFile::GetDexCanonicalLocation(const char* dex_location) {
1106   CHECK_NE(dex_location, static_cast<const char*>(nullptr));
1107   std::string base_location = GetBaseLocation(dex_location);
1108   const char* suffix = dex_location + base_location.size();
1109   DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
1110   UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
1111   if (path != nullptr && path.get() != base_location) {
1112     return std::string(path.get()) + suffix;
1113   } else if (suffix[0] == 0) {
1114     return base_location;
1115   } else {
1116     return dex_location;
1117   }
1118 }
1119 
1120 // Read a signed integer.  "zwidth" is the zero-based byte count.
ReadSignedInt(const uint8_t * ptr,int zwidth)1121 static int32_t ReadSignedInt(const uint8_t* ptr, int zwidth) {
1122   int32_t val = 0;
1123   for (int i = zwidth; i >= 0; --i) {
1124     val = ((uint32_t)val >> 8) | (((int32_t)*ptr++) << 24);
1125   }
1126   val >>= (3 - zwidth) * 8;
1127   return val;
1128 }
1129 
1130 // Read an unsigned integer.  "zwidth" is the zero-based byte count,
1131 // "fill_on_right" indicates which side we want to zero-fill from.
ReadUnsignedInt(const uint8_t * ptr,int zwidth,bool fill_on_right)1132 static uint32_t ReadUnsignedInt(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1133   uint32_t val = 0;
1134   for (int i = zwidth; i >= 0; --i) {
1135     val = (val >> 8) | (((uint32_t)*ptr++) << 24);
1136   }
1137   if (!fill_on_right) {
1138     val >>= (3 - zwidth) * 8;
1139   }
1140   return val;
1141 }
1142 
1143 // Read a signed long.  "zwidth" is the zero-based byte count.
ReadSignedLong(const uint8_t * ptr,int zwidth)1144 static int64_t ReadSignedLong(const uint8_t* ptr, int zwidth) {
1145   int64_t val = 0;
1146   for (int i = zwidth; i >= 0; --i) {
1147     val = ((uint64_t)val >> 8) | (((int64_t)*ptr++) << 56);
1148   }
1149   val >>= (7 - zwidth) * 8;
1150   return val;
1151 }
1152 
1153 // Read an unsigned long.  "zwidth" is the zero-based byte count,
1154 // "fill_on_right" indicates which side we want to zero-fill from.
ReadUnsignedLong(const uint8_t * ptr,int zwidth,bool fill_on_right)1155 static uint64_t ReadUnsignedLong(const uint8_t* ptr, int zwidth, bool fill_on_right) {
1156   uint64_t val = 0;
1157   for (int i = zwidth; i >= 0; --i) {
1158     val = (val >> 8) | (((uint64_t)*ptr++) << 56);
1159   }
1160   if (!fill_on_right) {
1161     val >>= (7 - zwidth) * 8;
1162   }
1163   return val;
1164 }
1165 
1166 // Checks that visibility is as expected. Includes special behavior for M and
1167 // before to allow runtime and build visibility when expecting runtime.
IsVisibilityCompatible(uint32_t actual,uint32_t expected)1168 static bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
1169   if (expected == DexFile::kDexVisibilityRuntime) {
1170     int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
1171     if (sdk_version > 0 && sdk_version <= 23) {
1172       return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
1173     }
1174   }
1175   return actual == expected;
1176 }
1177 
FindAnnotationSetForField(ArtField * field) const1178 const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForField(ArtField* field) const {
1179   mirror::Class* klass = field->GetDeclaringClass();
1180   const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1181   if (annotations_dir == nullptr) {
1182     return nullptr;
1183   }
1184   const FieldAnnotationsItem* field_annotations = GetFieldAnnotations(annotations_dir);
1185   if (field_annotations == nullptr) {
1186     return nullptr;
1187   }
1188   uint32_t field_index = field->GetDexFieldIndex();
1189   uint32_t field_count = annotations_dir->fields_size_;
1190   for (uint32_t i = 0; i < field_count; ++i) {
1191     if (field_annotations[i].field_idx_ == field_index) {
1192       return GetFieldAnnotationSetItem(field_annotations[i]);
1193     }
1194   }
1195   return nullptr;
1196 }
1197 
GetAnnotationForField(ArtField * field,Handle<mirror::Class> annotation_class) const1198 mirror::Object* DexFile::GetAnnotationForField(ArtField* field,
1199                                                Handle<mirror::Class> annotation_class) const {
1200   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1201   if (annotation_set == nullptr) {
1202     return nullptr;
1203   }
1204   StackHandleScope<1> hs(Thread::Current());
1205   Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1206   return GetAnnotationObjectFromAnnotationSet(
1207       field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1208 }
1209 
GetAnnotationsForField(ArtField * field) const1210 mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForField(ArtField* field) const {
1211   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1212   StackHandleScope<1> hs(Thread::Current());
1213   Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1214   return ProcessAnnotationSet(field_class, annotation_set, kDexVisibilityRuntime);
1215 }
1216 
GetSignatureAnnotationForField(ArtField * field) const1217 mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForField(ArtField* field)
1218     const {
1219   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1220   if (annotation_set == nullptr) {
1221     return nullptr;
1222   }
1223   StackHandleScope<1> hs(Thread::Current());
1224   Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1225   return GetSignatureValue(field_class, annotation_set);
1226 }
1227 
IsFieldAnnotationPresent(ArtField * field,Handle<mirror::Class> annotation_class) const1228 bool DexFile::IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class)
1229     const {
1230   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1231   if (annotation_set == nullptr) {
1232     return false;
1233   }
1234   StackHandleScope<1> hs(Thread::Current());
1235   Handle<mirror::Class> field_class(hs.NewHandle(field->GetDeclaringClass()));
1236   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1237       field_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1238   return annotation_item != nullptr;
1239 }
1240 
FindAnnotationSetForMethod(ArtMethod * method) const1241 const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForMethod(ArtMethod* method) const {
1242   mirror::Class* klass = method->GetDeclaringClass();
1243   const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1244   if (annotations_dir == nullptr) {
1245     return nullptr;
1246   }
1247   const MethodAnnotationsItem* method_annotations = GetMethodAnnotations(annotations_dir);
1248   if (method_annotations == nullptr) {
1249     return nullptr;
1250   }
1251   uint32_t method_index = method->GetDexMethodIndex();
1252   uint32_t method_count = annotations_dir->methods_size_;
1253   for (uint32_t i = 0; i < method_count; ++i) {
1254     if (method_annotations[i].method_idx_ == method_index) {
1255       return GetMethodAnnotationSetItem(method_annotations[i]);
1256     }
1257   }
1258   return nullptr;
1259 }
1260 
FindAnnotationsItemForMethod(ArtMethod * method) const1261 const DexFile::ParameterAnnotationsItem* DexFile::FindAnnotationsItemForMethod(ArtMethod* method)
1262     const {
1263   mirror::Class* klass = method->GetDeclaringClass();
1264   const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1265   if (annotations_dir == nullptr) {
1266     return nullptr;
1267   }
1268   const ParameterAnnotationsItem* parameter_annotations = GetParameterAnnotations(annotations_dir);
1269   if (parameter_annotations == nullptr) {
1270     return nullptr;
1271   }
1272   uint32_t method_index = method->GetDexMethodIndex();
1273   uint32_t parameter_count = annotations_dir->parameters_size_;
1274   for (uint32_t i = 0; i < parameter_count; ++i) {
1275     if (parameter_annotations[i].method_idx_ == method_index) {
1276       return &parameter_annotations[i];
1277     }
1278   }
1279   return nullptr;
1280 }
1281 
GetAnnotationDefaultValue(ArtMethod * method) const1282 mirror::Object* DexFile::GetAnnotationDefaultValue(ArtMethod* method) const {
1283   mirror::Class* klass = method->GetDeclaringClass();
1284   const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1285   if (annotations_dir == nullptr) {
1286     return nullptr;
1287   }
1288   const AnnotationSetItem* annotation_set = GetClassAnnotationSet(annotations_dir);
1289   if (annotation_set == nullptr) {
1290     return nullptr;
1291   }
1292   const AnnotationItem* annotation_item = SearchAnnotationSet(annotation_set,
1293       "Ldalvik/annotation/AnnotationDefault;", kDexVisibilitySystem);
1294   if (annotation_item == nullptr) {
1295     return nullptr;
1296   }
1297   const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1298   if (annotation == nullptr) {
1299     return nullptr;
1300   }
1301   uint8_t header_byte = *(annotation++);
1302   if ((header_byte & kDexAnnotationValueTypeMask) != kDexAnnotationAnnotation) {
1303     return nullptr;
1304   }
1305   annotation = SearchEncodedAnnotation(annotation, method->GetName());
1306   if (annotation == nullptr) {
1307     return nullptr;
1308   }
1309   AnnotationValue annotation_value;
1310   StackHandleScope<2> hs(Thread::Current());
1311   Handle<mirror::Class> h_klass(hs.NewHandle(klass));
1312   size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1313   Handle<mirror::Class> return_type(hs.NewHandle(
1314       method->GetReturnType(true /* resolve */, pointer_size)));
1315   if (!ProcessAnnotationValue(h_klass, &annotation, &annotation_value, return_type, kAllObjects)) {
1316     return nullptr;
1317   }
1318   return annotation_value.value_.GetL();
1319 }
1320 
GetAnnotationForMethod(ArtMethod * method,Handle<mirror::Class> annotation_class) const1321 mirror::Object* DexFile::GetAnnotationForMethod(ArtMethod* method,
1322                                                 Handle<mirror::Class> annotation_class) const {
1323   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1324   if (annotation_set == nullptr) {
1325     return nullptr;
1326   }
1327   StackHandleScope<1> hs(Thread::Current());
1328   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1329   return GetAnnotationObjectFromAnnotationSet(method_class, annotation_set,
1330                                               kDexVisibilityRuntime, annotation_class);
1331 }
1332 
GetAnnotationsForMethod(ArtMethod * method) const1333 mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForMethod(ArtMethod* method) const {
1334   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1335   StackHandleScope<1> hs(Thread::Current());
1336   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1337   return ProcessAnnotationSet(method_class, annotation_set, kDexVisibilityRuntime);
1338 }
1339 
GetExceptionTypesForMethod(ArtMethod * method) const1340 mirror::ObjectArray<mirror::Class>* DexFile::GetExceptionTypesForMethod(ArtMethod* method) const {
1341   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1342   if (annotation_set == nullptr) {
1343     return nullptr;
1344   }
1345   StackHandleScope<1> hs(Thread::Current());
1346   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1347   return GetThrowsValue(method_class, annotation_set);
1348 }
1349 
GetParameterAnnotations(ArtMethod * method) const1350 mirror::ObjectArray<mirror::Object>* DexFile::GetParameterAnnotations(ArtMethod* method) const {
1351   const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1352   if (parameter_annotations == nullptr) {
1353     return nullptr;
1354   }
1355   const AnnotationSetRefList* set_ref_list =
1356       GetParameterAnnotationSetRefList(parameter_annotations);
1357   if (set_ref_list == nullptr) {
1358     return nullptr;
1359   }
1360   uint32_t size = set_ref_list->size_;
1361   StackHandleScope<1> hs(Thread::Current());
1362   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1363   return ProcessAnnotationSetRefList(method_class, set_ref_list, size);
1364 }
1365 
GetSignatureAnnotationForMethod(ArtMethod * method) const1366 mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForMethod(ArtMethod* method)
1367     const {
1368   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1369   if (annotation_set == nullptr) {
1370     return nullptr;
1371   }
1372   StackHandleScope<1> hs(Thread::Current());
1373   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1374   return GetSignatureValue(method_class, annotation_set);
1375 }
1376 
IsMethodAnnotationPresent(ArtMethod * method,Handle<mirror::Class> annotation_class) const1377 bool DexFile::IsMethodAnnotationPresent(ArtMethod* method, Handle<mirror::Class> annotation_class)
1378     const {
1379   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1380   if (annotation_set == nullptr) {
1381     return false;
1382   }
1383   StackHandleScope<1> hs(Thread::Current());
1384   Handle<mirror::Class> method_class(hs.NewHandle(method->GetDeclaringClass()));
1385   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1386       method_class, annotation_set, kDexVisibilityRuntime, annotation_class);
1387   return annotation_item != nullptr;
1388 }
1389 
FindAnnotationSetForClass(Handle<mirror::Class> klass) const1390 const DexFile::AnnotationSetItem* DexFile::FindAnnotationSetForClass(Handle<mirror::Class> klass)
1391     const {
1392   const AnnotationsDirectoryItem* annotations_dir = GetAnnotationsDirectory(*klass->GetClassDef());
1393   if (annotations_dir == nullptr) {
1394     return nullptr;
1395   }
1396   return GetClassAnnotationSet(annotations_dir);
1397 }
1398 
GetAnnotationForClass(Handle<mirror::Class> klass,Handle<mirror::Class> annotation_class) const1399 mirror::Object* DexFile::GetAnnotationForClass(Handle<mirror::Class> klass,
1400                                                Handle<mirror::Class> annotation_class) const {
1401   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1402   if (annotation_set == nullptr) {
1403     return nullptr;
1404   }
1405   return GetAnnotationObjectFromAnnotationSet(klass, annotation_set, kDexVisibilityRuntime,
1406                                               annotation_class);
1407 }
1408 
GetAnnotationsForClass(Handle<mirror::Class> klass) const1409 mirror::ObjectArray<mirror::Object>* DexFile::GetAnnotationsForClass(Handle<mirror::Class> klass)
1410     const {
1411   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1412   return ProcessAnnotationSet(klass, annotation_set, kDexVisibilityRuntime);
1413 }
1414 
GetDeclaredClasses(Handle<mirror::Class> klass) const1415 mirror::ObjectArray<mirror::Class>* DexFile::GetDeclaredClasses(Handle<mirror::Class> klass) const {
1416   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1417   if (annotation_set == nullptr) {
1418     return nullptr;
1419   }
1420   const AnnotationItem* annotation_item = SearchAnnotationSet(
1421       annotation_set, "Ldalvik/annotation/MemberClasses;", kDexVisibilitySystem);
1422   if (annotation_item == nullptr) {
1423     return nullptr;
1424   }
1425   StackHandleScope<1> hs(Thread::Current());
1426   mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1427   Handle<mirror::Class> class_array_class(hs.NewHandle(
1428       Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1429   if (class_array_class.Get() == nullptr) {
1430     return nullptr;
1431   }
1432   mirror::Object* obj = GetAnnotationValue(
1433       klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1434   if (obj == nullptr) {
1435     return nullptr;
1436   }
1437   return obj->AsObjectArray<mirror::Class>();
1438 }
1439 
GetDeclaringClass(Handle<mirror::Class> klass) const1440 mirror::Class* DexFile::GetDeclaringClass(Handle<mirror::Class> klass) const {
1441   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1442   if (annotation_set == nullptr) {
1443     return nullptr;
1444   }
1445   const AnnotationItem* annotation_item = SearchAnnotationSet(
1446       annotation_set, "Ldalvik/annotation/EnclosingClass;", kDexVisibilitySystem);
1447   if (annotation_item == nullptr) {
1448     return nullptr;
1449   }
1450   mirror::Object* obj = GetAnnotationValue(klass,
1451                                            annotation_item,
1452                                            "value",
1453                                            ScopedNullHandle<mirror::Class>(),
1454                                            kDexAnnotationType);
1455   if (obj == nullptr) {
1456     return nullptr;
1457   }
1458   return obj->AsClass();
1459 }
1460 
GetEnclosingClass(Handle<mirror::Class> klass) const1461 mirror::Class* DexFile::GetEnclosingClass(Handle<mirror::Class> klass) const {
1462   mirror::Class* declaring_class = GetDeclaringClass(klass);
1463   if (declaring_class != nullptr) {
1464     return declaring_class;
1465   }
1466   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1467   if (annotation_set == nullptr) {
1468     return nullptr;
1469   }
1470   const AnnotationItem* annotation_item = SearchAnnotationSet(
1471       annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1472   if (annotation_item == nullptr) {
1473     return nullptr;
1474   }
1475   const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "value");
1476   if (annotation == nullptr) {
1477     return nullptr;
1478   }
1479   AnnotationValue annotation_value;
1480   if (!ProcessAnnotationValue(klass,
1481                               &annotation,
1482                               &annotation_value,
1483                               ScopedNullHandle<mirror::Class>(),
1484                               kAllRaw)) {
1485     return nullptr;
1486   }
1487   if (annotation_value.type_ != kDexAnnotationMethod) {
1488     return nullptr;
1489   }
1490   StackHandleScope<2> hs(Thread::Current());
1491   Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1492   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1493   ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1494       klass->GetDexFile(), annotation_value.value_.GetI(), dex_cache, class_loader);
1495   if (method == nullptr) {
1496     return nullptr;
1497   }
1498   return method->GetDeclaringClass();
1499 }
1500 
GetEnclosingMethod(Handle<mirror::Class> klass) const1501 mirror::Object* DexFile::GetEnclosingMethod(Handle<mirror::Class> klass) const {
1502   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1503   if (annotation_set == nullptr) {
1504     return nullptr;
1505   }
1506   const AnnotationItem* annotation_item = SearchAnnotationSet(
1507       annotation_set, "Ldalvik/annotation/EnclosingMethod;", kDexVisibilitySystem);
1508   if (annotation_item == nullptr) {
1509     return nullptr;
1510   }
1511   return GetAnnotationValue(
1512       klass, annotation_item, "value", ScopedNullHandle<mirror::Class>(), kDexAnnotationMethod);
1513 }
1514 
GetInnerClass(Handle<mirror::Class> klass,mirror::String ** name) const1515 bool DexFile::GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) const {
1516   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1517   if (annotation_set == nullptr) {
1518     return false;
1519   }
1520   const AnnotationItem* annotation_item = SearchAnnotationSet(
1521       annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1522   if (annotation_item == nullptr) {
1523     return false;
1524   }
1525   const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "name");
1526   if (annotation == nullptr) {
1527     return false;
1528   }
1529   AnnotationValue annotation_value;
1530   if (!ProcessAnnotationValue(klass,
1531                               &annotation,
1532                               &annotation_value,
1533                               ScopedNullHandle<mirror::Class>(),
1534                               kAllObjects)) {
1535     return false;
1536   }
1537   if (annotation_value.type_ != kDexAnnotationNull &&
1538       annotation_value.type_ != kDexAnnotationString) {
1539     return false;
1540   }
1541   *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1542   return true;
1543 }
1544 
GetInnerClassFlags(Handle<mirror::Class> klass,uint32_t * flags) const1545 bool DexFile::GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) const {
1546   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1547   if (annotation_set == nullptr) {
1548     return false;
1549   }
1550   const AnnotationItem* annotation_item = SearchAnnotationSet(
1551       annotation_set, "Ldalvik/annotation/InnerClass;", kDexVisibilitySystem);
1552   if (annotation_item == nullptr) {
1553     return false;
1554   }
1555   const uint8_t* annotation = SearchEncodedAnnotation(annotation_item->annotation_, "accessFlags");
1556   if (annotation == nullptr) {
1557     return false;
1558   }
1559   AnnotationValue annotation_value;
1560   if (!ProcessAnnotationValue(klass,
1561                               &annotation,
1562                               &annotation_value,
1563                               ScopedNullHandle<mirror::Class>(),
1564                               kAllRaw)) {
1565     return false;
1566   }
1567   if (annotation_value.type_ != kDexAnnotationInt) {
1568     return false;
1569   }
1570   *flags = annotation_value.value_.GetI();
1571   return true;
1572 }
1573 
GetSignatureAnnotationForClass(Handle<mirror::Class> klass) const1574 mirror::ObjectArray<mirror::String>* DexFile::GetSignatureAnnotationForClass(
1575     Handle<mirror::Class> klass) const {
1576   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1577   if (annotation_set == nullptr) {
1578     return nullptr;
1579   }
1580   return GetSignatureValue(klass, annotation_set);
1581 }
1582 
IsClassAnnotationPresent(Handle<mirror::Class> klass,Handle<mirror::Class> annotation_class) const1583 bool DexFile::IsClassAnnotationPresent(Handle<mirror::Class> klass,
1584                                        Handle<mirror::Class> annotation_class) const {
1585   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(klass);
1586   if (annotation_set == nullptr) {
1587     return false;
1588   }
1589   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1590       klass, annotation_set, kDexVisibilityRuntime, annotation_class);
1591   return annotation_item != nullptr;
1592 }
1593 
CreateAnnotationMember(Handle<mirror::Class> klass,Handle<mirror::Class> annotation_class,const uint8_t ** annotation) const1594 mirror::Object* DexFile::CreateAnnotationMember(Handle<mirror::Class> klass,
1595     Handle<mirror::Class> annotation_class, const uint8_t** annotation) const {
1596   Thread* self = Thread::Current();
1597   ScopedObjectAccessUnchecked soa(self);
1598   StackHandleScope<5> hs(self);
1599   uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
1600   const char* name = StringDataByIdx(element_name_index);
1601   Handle<mirror::String> string_name(
1602       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
1603 
1604   ArtMethod* annotation_method =
1605       annotation_class->FindDeclaredVirtualMethodByName(name, sizeof(void*));
1606   if (annotation_method == nullptr) {
1607     return nullptr;
1608   }
1609   size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1610   Handle<mirror::Class> method_return(hs.NewHandle(
1611       annotation_method->GetReturnType(true /* resolve */, pointer_size)));
1612 
1613   AnnotationValue annotation_value;
1614   if (!ProcessAnnotationValue(klass, annotation, &annotation_value, method_return, kAllObjects)) {
1615     return nullptr;
1616   }
1617   Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
1618 
1619   mirror::Class* annotation_member_class =
1620       WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
1621   Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
1622   Handle<mirror::Method> method_object(
1623       hs.NewHandle(mirror::Method::CreateFromArtMethod(self, annotation_method)));
1624 
1625   if (new_member.Get() == nullptr || string_name.Get() == nullptr ||
1626       method_object.Get() == nullptr || method_return.Get() == nullptr) {
1627     LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
1628         new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
1629     return nullptr;
1630   }
1631 
1632   JValue result;
1633   ArtMethod* annotation_member_init =
1634       soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
1635   uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
1636                        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
1637                        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
1638                        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
1639                        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
1640   };
1641   annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
1642   if (self->IsExceptionPending()) {
1643     LOG(INFO) << "Exception in AnnotationMember.<init>";
1644     return nullptr;
1645   }
1646 
1647   return new_member.Get();
1648 }
1649 
GetAnnotationItemFromAnnotationSet(Handle<mirror::Class> klass,const AnnotationSetItem * annotation_set,uint32_t visibility,Handle<mirror::Class> annotation_class) const1650 const DexFile::AnnotationItem* DexFile::GetAnnotationItemFromAnnotationSet(
1651     Handle<mirror::Class> klass, const AnnotationSetItem* annotation_set, uint32_t visibility,
1652     Handle<mirror::Class> annotation_class) const {
1653   for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1654     const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1655     if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
1656       continue;
1657     }
1658     const uint8_t* annotation = annotation_item->annotation_;
1659     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1660     mirror::Class* resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
1661         klass->GetDexFile(), type_index, klass.Get());
1662     if (resolved_class == nullptr) {
1663       std::string temp;
1664       LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
1665                                    klass->GetDescriptor(&temp), type_index);
1666       CHECK(Thread::Current()->IsExceptionPending());
1667       Thread::Current()->ClearException();
1668       continue;
1669     }
1670     if (resolved_class == annotation_class.Get()) {
1671       return annotation_item;
1672     }
1673   }
1674 
1675   return nullptr;
1676 }
1677 
GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,const AnnotationSetItem * annotation_set,uint32_t visibility,Handle<mirror::Class> annotation_class) const1678 mirror::Object* DexFile::GetAnnotationObjectFromAnnotationSet(Handle<mirror::Class> klass,
1679     const AnnotationSetItem* annotation_set, uint32_t visibility,
1680     Handle<mirror::Class> annotation_class) const {
1681   const AnnotationItem* annotation_item =
1682       GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
1683   if (annotation_item == nullptr) {
1684     return nullptr;
1685   }
1686   const uint8_t* annotation = annotation_item->annotation_;
1687   return ProcessEncodedAnnotation(klass, &annotation);
1688 }
1689 
GetAnnotationValue(Handle<mirror::Class> klass,const AnnotationItem * annotation_item,const char * annotation_name,Handle<mirror::Class> array_class,uint32_t expected_type) const1690 mirror::Object* DexFile::GetAnnotationValue(Handle<mirror::Class> klass,
1691     const AnnotationItem* annotation_item, const char* annotation_name,
1692     Handle<mirror::Class> array_class, uint32_t expected_type) const {
1693   const uint8_t* annotation =
1694       SearchEncodedAnnotation(annotation_item->annotation_, annotation_name);
1695   if (annotation == nullptr) {
1696     return nullptr;
1697   }
1698   AnnotationValue annotation_value;
1699   if (!ProcessAnnotationValue(klass, &annotation, &annotation_value, array_class, kAllObjects)) {
1700     return nullptr;
1701   }
1702   if (annotation_value.type_ != expected_type) {
1703     return nullptr;
1704   }
1705   return annotation_value.value_.GetL();
1706 }
1707 
GetSignatureValue(Handle<mirror::Class> klass,const AnnotationSetItem * annotation_set) const1708 mirror::ObjectArray<mirror::String>* DexFile::GetSignatureValue(Handle<mirror::Class> klass,
1709     const AnnotationSetItem* annotation_set) const {
1710   StackHandleScope<1> hs(Thread::Current());
1711   const AnnotationItem* annotation_item =
1712       SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Signature;", kDexVisibilitySystem);
1713   if (annotation_item == nullptr) {
1714     return nullptr;
1715   }
1716   mirror::Class* string_class = mirror::String::GetJavaLangString();
1717   Handle<mirror::Class> string_array_class(hs.NewHandle(
1718       Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
1719   if (string_array_class.Get() == nullptr) {
1720     return nullptr;
1721   }
1722   mirror::Object* obj =
1723       GetAnnotationValue(klass, annotation_item, "value", string_array_class, kDexAnnotationArray);
1724   if (obj == nullptr) {
1725     return nullptr;
1726   }
1727   return obj->AsObjectArray<mirror::String>();
1728 }
1729 
GetThrowsValue(Handle<mirror::Class> klass,const AnnotationSetItem * annotation_set) const1730 mirror::ObjectArray<mirror::Class>* DexFile::GetThrowsValue(Handle<mirror::Class> klass,
1731     const AnnotationSetItem* annotation_set) const {
1732   StackHandleScope<1> hs(Thread::Current());
1733   const AnnotationItem* annotation_item =
1734       SearchAnnotationSet(annotation_set, "Ldalvik/annotation/Throws;", kDexVisibilitySystem);
1735   if (annotation_item == nullptr) {
1736     return nullptr;
1737   }
1738   mirror::Class* class_class = mirror::Class::GetJavaLangClass();
1739   Handle<mirror::Class> class_array_class(hs.NewHandle(
1740       Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
1741   if (class_array_class.Get() == nullptr) {
1742     return nullptr;
1743   }
1744   mirror::Object* obj =
1745       GetAnnotationValue(klass, annotation_item, "value", class_array_class, kDexAnnotationArray);
1746   if (obj == nullptr) {
1747     return nullptr;
1748   }
1749   return obj->AsObjectArray<mirror::Class>();
1750 }
1751 
ProcessAnnotationSet(Handle<mirror::Class> klass,const AnnotationSetItem * annotation_set,uint32_t visibility) const1752 mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSet(Handle<mirror::Class> klass,
1753     const AnnotationSetItem* annotation_set, uint32_t visibility) const {
1754   Thread* self = Thread::Current();
1755   ScopedObjectAccessUnchecked soa(self);
1756   StackHandleScope<2> hs(self);
1757   Handle<mirror::Class> annotation_array_class(hs.NewHandle(
1758       soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array)));
1759   if (annotation_set == nullptr) {
1760     return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
1761   }
1762 
1763   uint32_t size = annotation_set->size_;
1764   Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
1765       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
1766   if (result.Get() == nullptr) {
1767     return nullptr;
1768   }
1769 
1770   uint32_t dest_index = 0;
1771   for (uint32_t i = 0; i < size; ++i) {
1772     const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
1773     // Note that we do not use IsVisibilityCompatible here because older code
1774     // was correct for this case.
1775     if (annotation_item->visibility_ != visibility) {
1776       continue;
1777     }
1778     const uint8_t* annotation = annotation_item->annotation_;
1779     mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
1780     if (annotation_obj != nullptr) {
1781       result->SetWithoutChecks<false>(dest_index, annotation_obj);
1782       ++dest_index;
1783     } else if (self->IsExceptionPending()) {
1784       return nullptr;
1785     }
1786   }
1787 
1788   if (dest_index == size) {
1789     return result.Get();
1790   }
1791 
1792   mirror::ObjectArray<mirror::Object>* trimmed_result =
1793       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
1794   if (trimmed_result == nullptr) {
1795     return nullptr;
1796   }
1797 
1798   for (uint32_t i = 0; i < dest_index; ++i) {
1799     mirror::Object* obj = result->GetWithoutChecks(i);
1800     trimmed_result->SetWithoutChecks<false>(i, obj);
1801   }
1802 
1803   return trimmed_result;
1804 }
1805 
ProcessAnnotationSetRefList(Handle<mirror::Class> klass,const AnnotationSetRefList * set_ref_list,uint32_t size) const1806 mirror::ObjectArray<mirror::Object>* DexFile::ProcessAnnotationSetRefList(
1807     Handle<mirror::Class> klass, const AnnotationSetRefList* set_ref_list, uint32_t size) const {
1808   Thread* self = Thread::Current();
1809   ScopedObjectAccessUnchecked soa(self);
1810   StackHandleScope<1> hs(self);
1811   mirror::Class* annotation_array_class =
1812       soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
1813   mirror::Class* annotation_array_array_class =
1814       Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
1815   if (annotation_array_array_class == nullptr) {
1816     return nullptr;
1817   }
1818   Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
1819       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
1820   if (annotation_array_array.Get() == nullptr) {
1821     LOG(ERROR) << "Annotation set ref array allocation failed";
1822     return nullptr;
1823   }
1824   for (uint32_t index = 0; index < size; ++index) {
1825     const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1826     const AnnotationSetItem* set_item = GetSetRefItemItem(set_ref_item);
1827     mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item, kDexVisibilityRuntime);
1828     if (annotation_set == nullptr) {
1829       return nullptr;
1830     }
1831     annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1832   }
1833   return annotation_array_array.Get();
1834 }
1835 
ProcessAnnotationValue(Handle<mirror::Class> klass,const uint8_t ** annotation_ptr,AnnotationValue * annotation_value,Handle<mirror::Class> array_class,DexFile::AnnotationResultStyle result_style) const1836 bool DexFile::ProcessAnnotationValue(Handle<mirror::Class> klass, const uint8_t** annotation_ptr,
1837     AnnotationValue* annotation_value, Handle<mirror::Class> array_class,
1838     DexFile::AnnotationResultStyle result_style) const {
1839   Thread* self = Thread::Current();
1840   mirror::Object* element_object = nullptr;
1841   bool set_object = false;
1842   Primitive::Type primitive_type = Primitive::kPrimVoid;
1843   const uint8_t* annotation = *annotation_ptr;
1844   uint8_t header_byte = *(annotation++);
1845   uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
1846   uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
1847   int32_t width = value_arg + 1;
1848   annotation_value->type_ = value_type;
1849 
1850   switch (value_type) {
1851     case kDexAnnotationByte:
1852       annotation_value->value_.SetB(static_cast<int8_t>(ReadSignedInt(annotation, value_arg)));
1853       primitive_type = Primitive::kPrimByte;
1854       break;
1855     case kDexAnnotationShort:
1856       annotation_value->value_.SetS(static_cast<int16_t>(ReadSignedInt(annotation, value_arg)));
1857       primitive_type = Primitive::kPrimShort;
1858       break;
1859     case kDexAnnotationChar:
1860       annotation_value->value_.SetC(static_cast<uint16_t>(ReadUnsignedInt(annotation, value_arg,
1861                                                                           false)));
1862       primitive_type = Primitive::kPrimChar;
1863       break;
1864     case kDexAnnotationInt:
1865       annotation_value->value_.SetI(ReadSignedInt(annotation, value_arg));
1866       primitive_type = Primitive::kPrimInt;
1867       break;
1868     case kDexAnnotationLong:
1869       annotation_value->value_.SetJ(ReadSignedLong(annotation, value_arg));
1870       primitive_type = Primitive::kPrimLong;
1871       break;
1872     case kDexAnnotationFloat:
1873       annotation_value->value_.SetI(ReadUnsignedInt(annotation, value_arg, true));
1874       primitive_type = Primitive::kPrimFloat;
1875       break;
1876     case kDexAnnotationDouble:
1877       annotation_value->value_.SetJ(ReadUnsignedLong(annotation, value_arg, true));
1878       primitive_type = Primitive::kPrimDouble;
1879       break;
1880     case kDexAnnotationBoolean:
1881       annotation_value->value_.SetZ(value_arg != 0);
1882       primitive_type = Primitive::kPrimBoolean;
1883       width = 0;
1884       break;
1885     case kDexAnnotationString: {
1886       uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1887       if (result_style == kAllRaw) {
1888         annotation_value->value_.SetI(index);
1889       } else {
1890         StackHandleScope<1> hs(self);
1891         Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1892         element_object = Runtime::Current()->GetClassLinker()->ResolveString(
1893             klass->GetDexFile(), index, dex_cache);
1894         set_object = true;
1895         if (element_object == nullptr) {
1896           return false;
1897         }
1898       }
1899       break;
1900     }
1901     case kDexAnnotationType: {
1902       uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1903       if (result_style == kAllRaw) {
1904         annotation_value->value_.SetI(index);
1905       } else {
1906         element_object = Runtime::Current()->GetClassLinker()->ResolveType(
1907             klass->GetDexFile(), index, klass.Get());
1908         set_object = true;
1909         if (element_object == nullptr) {
1910           CHECK(self->IsExceptionPending());
1911           if (result_style == kAllObjects) {
1912             const char* msg = StringByTypeIdx(index);
1913             self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
1914             element_object = self->GetException();
1915             self->ClearException();
1916           } else {
1917             return false;
1918           }
1919         }
1920       }
1921       break;
1922     }
1923     case kDexAnnotationMethod: {
1924       uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1925       if (result_style == kAllRaw) {
1926         annotation_value->value_.SetI(index);
1927       } else {
1928         StackHandleScope<2> hs(self);
1929         Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1930         Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1931         ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1932             klass->GetDexFile(), index, dex_cache, class_loader);
1933         if (method == nullptr) {
1934           return false;
1935         }
1936         set_object = true;
1937         if (method->IsConstructor()) {
1938           element_object = mirror::Constructor::CreateFromArtMethod(self, method);
1939         } else {
1940           element_object = mirror::Method::CreateFromArtMethod(self, method);
1941         }
1942         if (element_object == nullptr) {
1943           return false;
1944         }
1945       }
1946       break;
1947     }
1948     case kDexAnnotationField: {
1949       uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1950       if (result_style == kAllRaw) {
1951         annotation_value->value_.SetI(index);
1952       } else {
1953         StackHandleScope<2> hs(self);
1954         Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1955         Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1956         ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
1957             klass->GetDexFile(), index, dex_cache, class_loader);
1958         if (field == nullptr) {
1959           return false;
1960         }
1961         set_object = true;
1962         element_object = mirror::Field::CreateFromArtField(self, field, true);
1963         if (element_object == nullptr) {
1964           return false;
1965         }
1966       }
1967       break;
1968     }
1969     case kDexAnnotationEnum: {
1970       uint32_t index = ReadUnsignedInt(annotation, value_arg, false);
1971       if (result_style == kAllRaw) {
1972         annotation_value->value_.SetI(index);
1973       } else {
1974         StackHandleScope<3> hs(self);
1975         Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
1976         Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
1977         ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
1978             klass->GetDexFile(), index, dex_cache, class_loader, true);
1979         if (enum_field == nullptr) {
1980           return false;
1981         } else {
1982           Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
1983           Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
1984           element_object = enum_field->GetObject(field_class.Get());
1985           set_object = true;
1986         }
1987       }
1988       break;
1989     }
1990     case kDexAnnotationArray:
1991       if (result_style == kAllRaw || array_class.Get() == nullptr) {
1992         return false;
1993       } else {
1994         ScopedObjectAccessUnchecked soa(self);
1995         StackHandleScope<2> hs(self);
1996         uint32_t size = DecodeUnsignedLeb128(&annotation);
1997         Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
1998         Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
1999             self, array_class.Get(), size, array_class->GetComponentSizeShift(),
2000             Runtime::Current()->GetHeap()->GetCurrentAllocator())));
2001         if (new_array.Get() == nullptr) {
2002           LOG(ERROR) << "Annotation element array allocation failed with size " << size;
2003           return false;
2004         }
2005         AnnotationValue new_annotation_value;
2006         for (uint32_t i = 0; i < size; ++i) {
2007           if (!ProcessAnnotationValue(klass, &annotation, &new_annotation_value, component_type,
2008                                       kPrimitivesOrObjects)) {
2009             return false;
2010           }
2011           if (!component_type->IsPrimitive()) {
2012             mirror::Object* obj = new_annotation_value.value_.GetL();
2013             new_array->AsObjectArray<mirror::Object>()->SetWithoutChecks<false>(i, obj);
2014           } else {
2015             switch (new_annotation_value.type_) {
2016               case kDexAnnotationByte:
2017                 new_array->AsByteArray()->SetWithoutChecks<false>(
2018                     i, new_annotation_value.value_.GetB());
2019                 break;
2020               case kDexAnnotationShort:
2021                 new_array->AsShortArray()->SetWithoutChecks<false>(
2022                     i, new_annotation_value.value_.GetS());
2023                 break;
2024               case kDexAnnotationChar:
2025                 new_array->AsCharArray()->SetWithoutChecks<false>(
2026                     i, new_annotation_value.value_.GetC());
2027                 break;
2028               case kDexAnnotationInt:
2029                 new_array->AsIntArray()->SetWithoutChecks<false>(
2030                     i, new_annotation_value.value_.GetI());
2031                 break;
2032               case kDexAnnotationLong:
2033                 new_array->AsLongArray()->SetWithoutChecks<false>(
2034                     i, new_annotation_value.value_.GetJ());
2035                 break;
2036               case kDexAnnotationFloat:
2037                 new_array->AsFloatArray()->SetWithoutChecks<false>(
2038                     i, new_annotation_value.value_.GetF());
2039                 break;
2040               case kDexAnnotationDouble:
2041                 new_array->AsDoubleArray()->SetWithoutChecks<false>(
2042                     i, new_annotation_value.value_.GetD());
2043                 break;
2044               case kDexAnnotationBoolean:
2045                 new_array->AsBooleanArray()->SetWithoutChecks<false>(
2046                     i, new_annotation_value.value_.GetZ());
2047                 break;
2048               default:
2049                 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
2050                 return false;
2051             }
2052           }
2053         }
2054         element_object = new_array.Get();
2055         set_object = true;
2056         width = 0;
2057       }
2058       break;
2059     case kDexAnnotationAnnotation:
2060       if (result_style == kAllRaw) {
2061         return false;
2062       }
2063       element_object = ProcessEncodedAnnotation(klass, &annotation);
2064       if (element_object == nullptr) {
2065         return false;
2066       }
2067       set_object = true;
2068       width = 0;
2069       break;
2070     case kDexAnnotationNull:
2071       if (result_style == kAllRaw) {
2072         annotation_value->value_.SetI(0);
2073       } else {
2074         CHECK(element_object == nullptr);
2075         set_object = true;
2076       }
2077       width = 0;
2078       break;
2079     default:
2080       LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
2081       return false;
2082   }
2083 
2084   annotation += width;
2085   *annotation_ptr = annotation;
2086 
2087   if (result_style == kAllObjects && primitive_type != Primitive::kPrimVoid) {
2088     element_object = BoxPrimitive(primitive_type, annotation_value->value_);
2089     set_object = true;
2090   }
2091 
2092   if (set_object) {
2093     annotation_value->value_.SetL(element_object);
2094   }
2095 
2096   return true;
2097 }
2098 
ProcessEncodedAnnotation(Handle<mirror::Class> klass,const uint8_t ** annotation) const2099 mirror::Object* DexFile::ProcessEncodedAnnotation(Handle<mirror::Class> klass,
2100     const uint8_t** annotation) const {
2101   uint32_t type_index = DecodeUnsignedLeb128(annotation);
2102   uint32_t size = DecodeUnsignedLeb128(annotation);
2103 
2104   Thread* self = Thread::Current();
2105   ScopedObjectAccessUnchecked soa(self);
2106   StackHandleScope<2> hs(self);
2107   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2108   Handle<mirror::Class> annotation_class(hs.NewHandle(
2109       class_linker->ResolveType(klass->GetDexFile(), type_index, klass.Get())));
2110   if (annotation_class.Get() == nullptr) {
2111     LOG(INFO) << "Unable to resolve " << PrettyClass(klass.Get()) << " annotation class "
2112               << type_index;
2113     DCHECK(Thread::Current()->IsExceptionPending());
2114     Thread::Current()->ClearException();
2115     return nullptr;
2116   }
2117 
2118   mirror::Class* annotation_member_class =
2119       soa.Decode<mirror::Class*>(WellKnownClasses::libcore_reflect_AnnotationMember);
2120   mirror::Class* annotation_member_array_class =
2121       class_linker->FindArrayClass(self, &annotation_member_class);
2122   if (annotation_member_array_class == nullptr) {
2123     return nullptr;
2124   }
2125   mirror::ObjectArray<mirror::Object>* element_array = nullptr;
2126   if (size > 0) {
2127     element_array =
2128         mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
2129     if (element_array == nullptr) {
2130       LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
2131       return nullptr;
2132     }
2133   }
2134 
2135   Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
2136   for (uint32_t i = 0; i < size; ++i) {
2137     mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
2138     if (new_member == nullptr) {
2139       return nullptr;
2140     }
2141     h_element_array->SetWithoutChecks<false>(i, new_member);
2142   }
2143 
2144   JValue result;
2145   ArtMethod* create_annotation_method =
2146       soa.DecodeMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
2147   uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
2148                        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
2149   create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
2150   if (self->IsExceptionPending()) {
2151     LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
2152     return nullptr;
2153   }
2154 
2155   return result.GetL();
2156 }
2157 
SearchAnnotationSet(const AnnotationSetItem * annotation_set,const char * descriptor,uint32_t visibility) const2158 const DexFile::AnnotationItem* DexFile::SearchAnnotationSet(const AnnotationSetItem* annotation_set,
2159     const char* descriptor, uint32_t visibility) const {
2160   const AnnotationItem* result = nullptr;
2161   for (uint32_t i = 0; i < annotation_set->size_; ++i) {
2162     const AnnotationItem* annotation_item = GetAnnotationItem(annotation_set, i);
2163     if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
2164       continue;
2165     }
2166     const uint8_t* annotation = annotation_item->annotation_;
2167     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
2168 
2169     if (strcmp(descriptor, StringByTypeIdx(type_index)) == 0) {
2170       result = annotation_item;
2171       break;
2172     }
2173   }
2174   return result;
2175 }
2176 
SearchEncodedAnnotation(const uint8_t * annotation,const char * name) const2177 const uint8_t* DexFile::SearchEncodedAnnotation(const uint8_t* annotation, const char* name) const {
2178   DecodeUnsignedLeb128(&annotation);  // unused type_index
2179   uint32_t size = DecodeUnsignedLeb128(&annotation);
2180 
2181   while (size != 0) {
2182     uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
2183     const char* element_name = GetStringData(GetStringId(element_name_index));
2184     if (strcmp(name, element_name) == 0) {
2185       return annotation;
2186     }
2187     SkipAnnotationValue(&annotation);
2188     size--;
2189   }
2190   return nullptr;
2191 }
2192 
SkipAnnotationValue(const uint8_t ** annotation_ptr) const2193 bool DexFile::SkipAnnotationValue(const uint8_t** annotation_ptr) const {
2194   const uint8_t* annotation = *annotation_ptr;
2195   uint8_t header_byte = *(annotation++);
2196   uint8_t value_type = header_byte & kDexAnnotationValueTypeMask;
2197   uint8_t value_arg = header_byte >> kDexAnnotationValueArgShift;
2198   int32_t width = value_arg + 1;
2199 
2200   switch (value_type) {
2201     case kDexAnnotationByte:
2202     case kDexAnnotationShort:
2203     case kDexAnnotationChar:
2204     case kDexAnnotationInt:
2205     case kDexAnnotationLong:
2206     case kDexAnnotationFloat:
2207     case kDexAnnotationDouble:
2208     case kDexAnnotationString:
2209     case kDexAnnotationType:
2210     case kDexAnnotationMethod:
2211     case kDexAnnotationField:
2212     case kDexAnnotationEnum:
2213       break;
2214     case kDexAnnotationArray:
2215     {
2216       uint32_t size = DecodeUnsignedLeb128(&annotation);
2217       while (size--) {
2218         if (!SkipAnnotationValue(&annotation)) {
2219           return false;
2220         }
2221       }
2222       width = 0;
2223       break;
2224     }
2225     case kDexAnnotationAnnotation:
2226     {
2227       DecodeUnsignedLeb128(&annotation);  // unused type_index
2228       uint32_t size = DecodeUnsignedLeb128(&annotation);
2229       while (size--) {
2230         DecodeUnsignedLeb128(&annotation);  // unused element_name_index
2231         if (!SkipAnnotationValue(&annotation)) {
2232           return false;
2233         }
2234       }
2235       width = 0;
2236       break;
2237     }
2238     case kDexAnnotationBoolean:
2239     case kDexAnnotationNull:
2240       width = 0;
2241       break;
2242     default:
2243       LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
2244       return false;
2245   }
2246 
2247   annotation += width;
2248   *annotation_ptr = annotation;
2249   return true;
2250 }
2251 
operator <<(std::ostream & os,const DexFile & dex_file)2252 std::ostream& operator<<(std::ostream& os, const DexFile& dex_file) {
2253   os << StringPrintf("[DexFile: %s dex-checksum=%08x location-checksum=%08x %p-%p]",
2254                      dex_file.GetLocation().c_str(),
2255                      dex_file.GetHeader().checksum_, dex_file.GetLocationChecksum(),
2256                      dex_file.Begin(), dex_file.Begin() + dex_file.Size());
2257   return os;
2258 }
2259 
ToString() const2260 std::string Signature::ToString() const {
2261   if (dex_file_ == nullptr) {
2262     CHECK(proto_id_ == nullptr);
2263     return "<no signature>";
2264   }
2265   const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2266   std::string result;
2267   if (params == nullptr) {
2268     result += "()";
2269   } else {
2270     result += "(";
2271     for (uint32_t i = 0; i < params->Size(); ++i) {
2272       result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
2273     }
2274     result += ")";
2275   }
2276   result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2277   return result;
2278 }
2279 
operator ==(const StringPiece & rhs) const2280 bool Signature::operator==(const StringPiece& rhs) const {
2281   if (dex_file_ == nullptr) {
2282     return false;
2283   }
2284   StringPiece tail(rhs);
2285   if (!tail.starts_with("(")) {
2286     return false;  // Invalid signature
2287   }
2288   tail.remove_prefix(1);  // "(";
2289   const DexFile::TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
2290   if (params != nullptr) {
2291     for (uint32_t i = 0; i < params->Size(); ++i) {
2292       StringPiece param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
2293       if (!tail.starts_with(param)) {
2294         return false;
2295       }
2296       tail.remove_prefix(param.length());
2297     }
2298   }
2299   if (!tail.starts_with(")")) {
2300     return false;
2301   }
2302   tail.remove_prefix(1);  // ")";
2303   return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
2304 }
2305 
operator <<(std::ostream & os,const Signature & sig)2306 std::ostream& operator<<(std::ostream& os, const Signature& sig) {
2307   return os << sig.ToString();
2308 }
2309 
2310 // Decodes the header section from the class data bytes.
ReadClassDataHeader()2311 void ClassDataItemIterator::ReadClassDataHeader() {
2312   CHECK(ptr_pos_ != nullptr);
2313   header_.static_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2314   header_.instance_fields_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2315   header_.direct_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2316   header_.virtual_methods_size_ = DecodeUnsignedLeb128(&ptr_pos_);
2317 }
2318 
ReadClassDataField()2319 void ClassDataItemIterator::ReadClassDataField() {
2320   field_.field_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2321   field_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2322   // The user of the iterator is responsible for checking if there
2323   // are unordered or duplicate indexes.
2324 }
2325 
ReadClassDataMethod()2326 void ClassDataItemIterator::ReadClassDataMethod() {
2327   method_.method_idx_delta_ = DecodeUnsignedLeb128(&ptr_pos_);
2328   method_.access_flags_ = DecodeUnsignedLeb128(&ptr_pos_);
2329   method_.code_off_ = DecodeUnsignedLeb128(&ptr_pos_);
2330   if (last_idx_ != 0 && method_.method_idx_delta_ == 0) {
2331     LOG(WARNING) << "Duplicate method in " << dex_file_.GetLocation();
2332   }
2333 }
2334 
EncodedStaticFieldValueIterator(const DexFile & dex_file,const DexFile::ClassDef & class_def)2335 EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2336     const DexFile& dex_file,
2337     const DexFile::ClassDef& class_def)
2338     : EncodedStaticFieldValueIterator(dex_file,
2339                                       nullptr,
2340                                       nullptr,
2341                                       nullptr,
2342                                       class_def,
2343                                       -1,
2344                                       kByte) {
2345 }
2346 
EncodedStaticFieldValueIterator(const DexFile & dex_file,Handle<mirror::DexCache> * dex_cache,Handle<mirror::ClassLoader> * class_loader,ClassLinker * linker,const DexFile::ClassDef & class_def)2347 EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2348     const DexFile& dex_file,
2349     Handle<mirror::DexCache>* dex_cache,
2350     Handle<mirror::ClassLoader>* class_loader,
2351     ClassLinker* linker,
2352     const DexFile::ClassDef& class_def)
2353     : EncodedStaticFieldValueIterator(dex_file,
2354                                       dex_cache, class_loader,
2355                                       linker,
2356                                       class_def,
2357                                       -1,
2358                                       kByte) {
2359   DCHECK(dex_cache_ != nullptr);
2360   DCHECK(class_loader_ != nullptr);
2361 }
2362 
EncodedStaticFieldValueIterator(const DexFile & dex_file,Handle<mirror::DexCache> * dex_cache,Handle<mirror::ClassLoader> * class_loader,ClassLinker * linker,const DexFile::ClassDef & class_def,size_t pos,ValueType type)2363 EncodedStaticFieldValueIterator::EncodedStaticFieldValueIterator(
2364     const DexFile& dex_file,
2365     Handle<mirror::DexCache>* dex_cache,
2366     Handle<mirror::ClassLoader>* class_loader,
2367     ClassLinker* linker,
2368     const DexFile::ClassDef& class_def,
2369     size_t pos,
2370     ValueType type)
2371     : dex_file_(dex_file),
2372       dex_cache_(dex_cache),
2373       class_loader_(class_loader),
2374       linker_(linker),
2375       array_size_(),
2376       pos_(pos),
2377       type_(type) {
2378   ptr_ = dex_file.GetEncodedStaticFieldValuesArray(class_def);
2379   if (ptr_ == nullptr) {
2380     array_size_ = 0;
2381   } else {
2382     array_size_ = DecodeUnsignedLeb128(&ptr_);
2383   }
2384   if (array_size_ > 0) {
2385     Next();
2386   }
2387 }
2388 
Next()2389 void EncodedStaticFieldValueIterator::Next() {
2390   pos_++;
2391   if (pos_ >= array_size_) {
2392     return;
2393   }
2394   uint8_t value_type = *ptr_++;
2395   uint8_t value_arg = value_type >> kEncodedValueArgShift;
2396   size_t width = value_arg + 1;  // assume and correct later
2397   type_ = static_cast<ValueType>(value_type & kEncodedValueTypeMask);
2398   switch (type_) {
2399   case kBoolean:
2400     jval_.i = (value_arg != 0) ? 1 : 0;
2401     width = 0;
2402     break;
2403   case kByte:
2404     jval_.i = ReadSignedInt(ptr_, value_arg);
2405     CHECK(IsInt<8>(jval_.i));
2406     break;
2407   case kShort:
2408     jval_.i = ReadSignedInt(ptr_, value_arg);
2409     CHECK(IsInt<16>(jval_.i));
2410     break;
2411   case kChar:
2412     jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2413     CHECK(IsUint<16>(jval_.i));
2414     break;
2415   case kInt:
2416     jval_.i = ReadSignedInt(ptr_, value_arg);
2417     break;
2418   case kLong:
2419     jval_.j = ReadSignedLong(ptr_, value_arg);
2420     break;
2421   case kFloat:
2422     jval_.i = ReadUnsignedInt(ptr_, value_arg, true);
2423     break;
2424   case kDouble:
2425     jval_.j = ReadUnsignedLong(ptr_, value_arg, true);
2426     break;
2427   case kString:
2428   case kType:
2429     jval_.i = ReadUnsignedInt(ptr_, value_arg, false);
2430     break;
2431   case kField:
2432   case kMethod:
2433   case kEnum:
2434   case kArray:
2435   case kAnnotation:
2436     UNIMPLEMENTED(FATAL) << ": type " << type_;
2437     UNREACHABLE();
2438   case kNull:
2439     jval_.l = nullptr;
2440     width = 0;
2441     break;
2442   default:
2443     LOG(FATAL) << "Unreached";
2444     UNREACHABLE();
2445   }
2446   ptr_ += width;
2447 }
2448 
2449 template<bool kTransactionActive>
ReadValueToField(ArtField * field) const2450 void EncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
2451   DCHECK(dex_cache_ != nullptr);
2452   DCHECK(class_loader_ != nullptr);
2453   switch (type_) {
2454     case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
2455         break;
2456     case kByte:    field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
2457     case kShort:   field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
2458     case kChar:    field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
2459     case kInt:     field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
2460     case kLong:    field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
2461     case kFloat:   field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
2462     case kDouble:  field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
2463     case kNull:    field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
2464     case kString: {
2465       mirror::String* resolved = linker_->ResolveString(dex_file_, jval_.i, *dex_cache_);
2466       field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
2467       break;
2468     }
2469     case kType: {
2470       mirror::Class* resolved = linker_->ResolveType(dex_file_, jval_.i, *dex_cache_,
2471                                                      *class_loader_);
2472       field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
2473       break;
2474     }
2475     default: UNIMPLEMENTED(FATAL) << ": type " << type_;
2476   }
2477 }
2478 template void EncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
2479 template void EncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
2480 
CatchHandlerIterator(const DexFile::CodeItem & code_item,uint32_t address)2481 CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item, uint32_t address) {
2482   handler_.address_ = -1;
2483   int32_t offset = -1;
2484 
2485   // Short-circuit the overwhelmingly common cases.
2486   switch (code_item.tries_size_) {
2487     case 0:
2488       break;
2489     case 1: {
2490       const DexFile::TryItem* tries = DexFile::GetTryItems(code_item, 0);
2491       uint32_t start = tries->start_addr_;
2492       if (address >= start) {
2493         uint32_t end = start + tries->insn_count_;
2494         if (address < end) {
2495           offset = tries->handler_off_;
2496         }
2497       }
2498       break;
2499     }
2500     default:
2501       offset = DexFile::FindCatchHandlerOffset(code_item, address);
2502   }
2503   Init(code_item, offset);
2504 }
2505 
CatchHandlerIterator(const DexFile::CodeItem & code_item,const DexFile::TryItem & try_item)2506 CatchHandlerIterator::CatchHandlerIterator(const DexFile::CodeItem& code_item,
2507                                            const DexFile::TryItem& try_item) {
2508   handler_.address_ = -1;
2509   Init(code_item, try_item.handler_off_);
2510 }
2511 
Init(const DexFile::CodeItem & code_item,int32_t offset)2512 void CatchHandlerIterator::Init(const DexFile::CodeItem& code_item,
2513                                 int32_t offset) {
2514   if (offset >= 0) {
2515     Init(DexFile::GetCatchHandlerData(code_item, offset));
2516   } else {
2517     // Not found, initialize as empty
2518     current_data_ = nullptr;
2519     remaining_count_ = -1;
2520     catch_all_ = false;
2521     DCHECK(!HasNext());
2522   }
2523 }
2524 
Init(const uint8_t * handler_data)2525 void CatchHandlerIterator::Init(const uint8_t* handler_data) {
2526   current_data_ = handler_data;
2527   remaining_count_ = DecodeSignedLeb128(&current_data_);
2528 
2529   // If remaining_count_ is non-positive, then it is the negative of
2530   // the number of catch types, and the catches are followed by a
2531   // catch-all handler.
2532   if (remaining_count_ <= 0) {
2533     catch_all_ = true;
2534     remaining_count_ = -remaining_count_;
2535   } else {
2536     catch_all_ = false;
2537   }
2538   Next();
2539 }
2540 
Next()2541 void CatchHandlerIterator::Next() {
2542   if (remaining_count_ > 0) {
2543     handler_.type_idx_ = DecodeUnsignedLeb128(&current_data_);
2544     handler_.address_  = DecodeUnsignedLeb128(&current_data_);
2545     remaining_count_--;
2546     return;
2547   }
2548 
2549   if (catch_all_) {
2550     handler_.type_idx_ = DexFile::kDexNoIndex16;
2551     handler_.address_  = DecodeUnsignedLeb128(&current_data_);
2552     catch_all_ = false;
2553     return;
2554   }
2555 
2556   // no more handler
2557   remaining_count_ = -1;
2558 }
2559 
2560 }  // namespace art
2561