• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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_annotations.h"
18 
19 #include <stdlib.h>
20 
21 #include "android-base/macros.h"
22 #include "android-base/stringprintf.h"
23 #include "art_field-inl.h"
24 #include "art_method-alloc-inl.h"
25 #include "base/sdk_version.h"
26 #include "class_linker-inl.h"
27 #include "class_root-inl.h"
28 #include "dex/dex_file-inl.h"
29 #include "dex/dex_instruction-inl.h"
30 #include "jni/jni_internal.h"
31 #include "jvalue-inl.h"
32 #include "mirror/array-alloc-inl.h"
33 #include "mirror/class-alloc-inl.h"
34 #include "mirror/field.h"
35 #include "mirror/method.h"
36 #include "mirror/object_array-alloc-inl.h"
37 #include "mirror/object_array-inl.h"
38 #include "oat_file.h"
39 #include "obj_ptr-inl.h"
40 #include "quicken_info.h"
41 #include "reflection.h"
42 #include "thread.h"
43 #include "well_known_classes.h"
44 
45 namespace art {
46 
47 using android::base::StringPrintf;
48 
49 using dex::AnnotationItem;
50 using dex::AnnotationSetItem;
51 using dex::AnnotationSetRefItem;
52 using dex::AnnotationSetRefList;
53 using dex::AnnotationsDirectoryItem;
54 using dex::FieldAnnotationsItem;
55 using dex::MethodAnnotationsItem;
56 using dex::ParameterAnnotationsItem;
57 
58 struct DexFile::AnnotationValue {
59   JValue value_;
60   uint8_t type_;
61 };
62 
63 namespace {
64 
65 // A helper class that contains all the data needed to do annotation lookup.
66 class ClassData {
67  public:
REQUIRES_SHARED(Locks::mutator_lock_)68   explicit ClassData(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
69     : ClassData(ScopedNullHandle<mirror::Class>(),  // klass
70                 method,
71                 *method->GetDexFile(),
72                 &method->GetClassDef()) {}
73 
74   // Requires Scope to be able to create at least 1 handles.
75   template <typename Scope>
ClassData(Scope & hs,ArtField * field)76   ClassData(Scope& hs, ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_)
77     : ClassData(hs.NewHandle(field->GetDeclaringClass())) { }
78 
REQUIRES_SHARED(art::Locks::mutator_lock_)79   explicit ClassData(Handle<mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_)
80     : ClassData(klass,  // klass
81                 nullptr,  // method
82                 klass->GetDexFile(),
83                 klass->GetClassDef()) {}
84 
GetDexFile() const85   const DexFile& GetDexFile() const REQUIRES_SHARED(Locks::mutator_lock_) {
86     return dex_file_;
87   }
88 
GetClassDef() const89   const dex::ClassDef* GetClassDef() const REQUIRES_SHARED(Locks::mutator_lock_) {
90     return class_def_;
91   }
92 
GetDexCache() const93   ObjPtr<mirror::DexCache> GetDexCache() const REQUIRES_SHARED(Locks::mutator_lock_) {
94     if (method_ != nullptr) {
95       return method_->GetDexCache();
96     } else {
97       return real_klass_->GetDexCache();
98     }
99   }
100 
GetClassLoader() const101   ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
102     if (method_ != nullptr) {
103       return method_->GetDeclaringClass()->GetClassLoader();
104     } else {
105       return real_klass_->GetClassLoader();
106     }
107   }
108 
GetRealClass() const109   ObjPtr<mirror::Class> GetRealClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
110     if (method_ != nullptr) {
111       return method_->GetDeclaringClass();
112     } else {
113       return real_klass_.Get();
114     }
115   }
116 
117  private:
ClassData(Handle<mirror::Class> klass,ArtMethod * method,const DexFile & dex_file,const dex::ClassDef * class_def)118   ClassData(Handle<mirror::Class> klass,
119             ArtMethod* method,
120             const DexFile& dex_file,
121             const dex::ClassDef* class_def) REQUIRES_SHARED(Locks::mutator_lock_)
122       : real_klass_(klass),
123         method_(method),
124         dex_file_(dex_file),
125         class_def_(class_def) {
126     DCHECK((method_ == nullptr) || real_klass_.IsNull());
127   }
128 
129   Handle<mirror::Class> real_klass_;
130   ArtMethod* method_;
131   const DexFile& dex_file_;
132   const dex::ClassDef* class_def_;
133 
134   DISALLOW_COPY_AND_ASSIGN(ClassData);
135 };
136 
137 ObjPtr<mirror::Object> CreateAnnotationMember(const ClassData& klass,
138                                               Handle<mirror::Class> annotation_class,
139                                               const uint8_t** annotation)
140     REQUIRES_SHARED(Locks::mutator_lock_);
141 
IsVisibilityCompatible(uint32_t actual,uint32_t expected)142 bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
143   if (expected == DexFile::kDexVisibilityRuntime) {
144     if (IsSdkVersionSetAndAtMost(Runtime::Current()->GetTargetSdkVersion(), SdkVersion::kM)) {
145       return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
146     }
147   }
148   return actual == expected;
149 }
150 
FindAnnotationSetForField(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t field_index)151 static const AnnotationSetItem* FindAnnotationSetForField(const DexFile& dex_file,
152                                                           const dex::ClassDef& class_def,
153                                                           uint32_t field_index)
154     REQUIRES_SHARED(Locks::mutator_lock_) {
155   const AnnotationsDirectoryItem* annotations_dir = dex_file.GetAnnotationsDirectory(class_def);
156   if (annotations_dir == nullptr) {
157     return nullptr;
158   }
159   const FieldAnnotationsItem* field_annotations = dex_file.GetFieldAnnotations(annotations_dir);
160   if (field_annotations == nullptr) {
161     return nullptr;
162   }
163   uint32_t field_count = annotations_dir->fields_size_;
164   for (uint32_t i = 0; i < field_count; ++i) {
165     if (field_annotations[i].field_idx_ == field_index) {
166       return dex_file.GetFieldAnnotationSetItem(field_annotations[i]);
167     }
168   }
169   return nullptr;
170 }
171 
FindAnnotationSetForField(ArtField * field)172 static const AnnotationSetItem* FindAnnotationSetForField(ArtField* field)
173     REQUIRES_SHARED(Locks::mutator_lock_) {
174   ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
175   const dex::ClassDef* class_def = klass->GetClassDef();
176   if (class_def == nullptr) {
177     DCHECK(klass->IsProxyClass());
178     return nullptr;
179   }
180   return FindAnnotationSetForField(*field->GetDexFile(), *class_def, field->GetDexFieldIndex());
181 }
182 
SearchAnnotationSet(const DexFile & dex_file,const AnnotationSetItem * annotation_set,const char * descriptor,uint32_t visibility)183 const AnnotationItem* SearchAnnotationSet(const DexFile& dex_file,
184                                           const AnnotationSetItem* annotation_set,
185                                           const char* descriptor,
186                                           uint32_t visibility)
187     REQUIRES_SHARED(Locks::mutator_lock_) {
188   const AnnotationItem* result = nullptr;
189   for (uint32_t i = 0; i < annotation_set->size_; ++i) {
190     const AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
191     if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
192       continue;
193     }
194     const uint8_t* annotation = annotation_item->annotation_;
195     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
196 
197     if (strcmp(descriptor, dex_file.StringByTypeIdx(dex::TypeIndex(type_index))) == 0) {
198       result = annotation_item;
199       break;
200     }
201   }
202   return result;
203 }
204 
SkipEncodedValueHeaderByte(const uint8_t ** annotation_ptr)205 inline static void SkipEncodedValueHeaderByte(const uint8_t** annotation_ptr) {
206   (*annotation_ptr)++;
207 }
208 
SkipAnnotationValue(const DexFile & dex_file,const uint8_t ** annotation_ptr)209 bool SkipAnnotationValue(const DexFile& dex_file, const uint8_t** annotation_ptr)
210     REQUIRES_SHARED(Locks::mutator_lock_) {
211   const uint8_t* annotation = *annotation_ptr;
212   uint8_t header_byte = *(annotation++);
213   uint8_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
214   uint8_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
215   int32_t width = value_arg + 1;
216 
217   switch (value_type) {
218     case DexFile::kDexAnnotationByte:
219     case DexFile::kDexAnnotationShort:
220     case DexFile::kDexAnnotationChar:
221     case DexFile::kDexAnnotationInt:
222     case DexFile::kDexAnnotationLong:
223     case DexFile::kDexAnnotationFloat:
224     case DexFile::kDexAnnotationDouble:
225     case DexFile::kDexAnnotationString:
226     case DexFile::kDexAnnotationType:
227     case DexFile::kDexAnnotationMethod:
228     case DexFile::kDexAnnotationField:
229     case DexFile::kDexAnnotationEnum:
230       break;
231     case DexFile::kDexAnnotationArray:
232     {
233       uint32_t size = DecodeUnsignedLeb128(&annotation);
234       for (; size != 0u; --size) {
235         if (!SkipAnnotationValue(dex_file, &annotation)) {
236           return false;
237         }
238       }
239       width = 0;
240       break;
241     }
242     case DexFile::kDexAnnotationAnnotation:
243     {
244       DecodeUnsignedLeb128(&annotation);  // unused type_index
245       uint32_t size = DecodeUnsignedLeb128(&annotation);
246       for (; size != 0u; --size) {
247         DecodeUnsignedLeb128(&annotation);  // unused element_name_index
248         if (!SkipAnnotationValue(dex_file, &annotation)) {
249           return false;
250         }
251       }
252       width = 0;
253       break;
254     }
255     case DexFile::kDexAnnotationBoolean:
256     case DexFile::kDexAnnotationNull:
257       width = 0;
258       break;
259     default:
260       LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
261       UNREACHABLE();
262   }
263 
264   annotation += width;
265   *annotation_ptr = annotation;
266   return true;
267 }
268 
SearchEncodedAnnotation(const DexFile & dex_file,const uint8_t * annotation,const char * name)269 const uint8_t* SearchEncodedAnnotation(const DexFile& dex_file,
270                                        const uint8_t* annotation,
271                                        const char* name)
272     REQUIRES_SHARED(Locks::mutator_lock_) {
273   DecodeUnsignedLeb128(&annotation);  // unused type_index
274   uint32_t size = DecodeUnsignedLeb128(&annotation);
275 
276   while (size != 0) {
277     uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
278     const char* element_name =
279         dex_file.GetStringData(dex_file.GetStringId(dex::StringIndex(element_name_index)));
280     if (strcmp(name, element_name) == 0) {
281       return annotation;
282     }
283     SkipAnnotationValue(dex_file, &annotation);
284     size--;
285   }
286   return nullptr;
287 }
288 
FindAnnotationSetForMethod(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)289 static const AnnotationSetItem* FindAnnotationSetForMethod(const DexFile& dex_file,
290                                                            const dex::ClassDef& class_def,
291                                                            uint32_t method_index) {
292   const AnnotationsDirectoryItem* annotations_dir = dex_file.GetAnnotationsDirectory(class_def);
293   if (annotations_dir == nullptr) {
294     return nullptr;
295   }
296   const MethodAnnotationsItem* method_annotations = dex_file.GetMethodAnnotations(annotations_dir);
297   if (method_annotations == nullptr) {
298     return nullptr;
299   }
300   uint32_t method_count = annotations_dir->methods_size_;
301   for (uint32_t i = 0; i < method_count; ++i) {
302     if (method_annotations[i].method_idx_ == method_index) {
303       return dex_file.GetMethodAnnotationSetItem(method_annotations[i]);
304     }
305   }
306   return nullptr;
307 }
308 
FindAnnotationSetForMethod(ArtMethod * method)309 inline const AnnotationSetItem* FindAnnotationSetForMethod(ArtMethod* method)
310     REQUIRES_SHARED(Locks::mutator_lock_) {
311   if (method->IsProxyMethod()) {
312     return nullptr;
313   }
314   return FindAnnotationSetForMethod(*method->GetDexFile(),
315                                     method->GetClassDef(),
316                                     method->GetDexMethodIndex());
317 }
318 
FindAnnotationsItemForMethod(ArtMethod * method)319 const ParameterAnnotationsItem* FindAnnotationsItemForMethod(ArtMethod* method)
320     REQUIRES_SHARED(Locks::mutator_lock_) {
321   const DexFile* dex_file = method->GetDexFile();
322   const AnnotationsDirectoryItem* annotations_dir =
323       dex_file->GetAnnotationsDirectory(method->GetClassDef());
324   if (annotations_dir == nullptr) {
325     return nullptr;
326   }
327   const ParameterAnnotationsItem* parameter_annotations =
328       dex_file->GetParameterAnnotations(annotations_dir);
329   if (parameter_annotations == nullptr) {
330     return nullptr;
331   }
332   uint32_t method_index = method->GetDexMethodIndex();
333   uint32_t parameter_count = annotations_dir->parameters_size_;
334   for (uint32_t i = 0; i < parameter_count; ++i) {
335     if (parameter_annotations[i].method_idx_ == method_index) {
336       return &parameter_annotations[i];
337     }
338   }
339   return nullptr;
340 }
341 
FindAnnotationSetForClass(const ClassData & klass)342 static const AnnotationSetItem* FindAnnotationSetForClass(const ClassData& klass)
343     REQUIRES_SHARED(Locks::mutator_lock_) {
344   const DexFile& dex_file = klass.GetDexFile();
345   const dex::ClassDef* class_def = klass.GetClassDef();
346   if (class_def == nullptr) {
347     DCHECK(klass.GetRealClass()->IsProxyClass());
348     return nullptr;
349   }
350   const AnnotationsDirectoryItem* annotations_dir = dex_file.GetAnnotationsDirectory(*class_def);
351   if (annotations_dir == nullptr) {
352     return nullptr;
353   }
354   return dex_file.GetClassAnnotationSet(annotations_dir);
355 }
356 
ProcessEncodedAnnotation(const ClassData & klass,const uint8_t ** annotation)357 ObjPtr<mirror::Object> ProcessEncodedAnnotation(const ClassData& klass, const uint8_t** annotation)
358     REQUIRES_SHARED(Locks::mutator_lock_) {
359   uint32_t type_index = DecodeUnsignedLeb128(annotation);
360   uint32_t size = DecodeUnsignedLeb128(annotation);
361 
362   Thread* self = Thread::Current();
363   StackHandleScope<4> hs(self);
364   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
365   Handle<mirror::Class> annotation_class(hs.NewHandle(
366       class_linker->ResolveType(dex::TypeIndex(type_index),
367                                 hs.NewHandle(klass.GetDexCache()),
368                                 hs.NewHandle(klass.GetClassLoader()))));
369   if (annotation_class == nullptr) {
370     LOG(INFO) << "Unable to resolve " << klass.GetRealClass()->PrettyClass()
371               << " annotation class " << type_index;
372     DCHECK(Thread::Current()->IsExceptionPending());
373     Thread::Current()->ClearException();
374     return nullptr;
375   }
376 
377   ObjPtr<mirror::Class> annotation_member_array_class =
378       WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember__array);
379   if (annotation_member_array_class == nullptr) {
380     return nullptr;
381   }
382   ObjPtr<mirror::ObjectArray<mirror::Object>> element_array = nullptr;
383   if (size > 0) {
384     element_array =
385         mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
386     if (element_array == nullptr) {
387       LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
388       return nullptr;
389     }
390   }
391 
392   Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
393   for (uint32_t i = 0; i < size; ++i) {
394     ObjPtr<mirror::Object> new_member = CreateAnnotationMember(klass, annotation_class, annotation);
395     if (new_member == nullptr) {
396       return nullptr;
397     }
398     h_element_array->SetWithoutChecks<false>(i, new_member);
399   }
400 
401   ArtMethod* create_annotation_method =
402       WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation;
403   ObjPtr<mirror::Object> result = create_annotation_method->InvokeStatic<'L', 'L', 'L'>(
404       self, annotation_class.Get(), h_element_array.Get());
405   if (self->IsExceptionPending()) {
406     LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
407     return nullptr;
408   }
409 
410   return result;
411 }
412 
413 template <bool kTransactionActive>
ProcessAnnotationValue(const ClassData & klass,const uint8_t ** annotation_ptr,DexFile::AnnotationValue * annotation_value,Handle<mirror::Class> array_class,DexFile::AnnotationResultStyle result_style)414 bool ProcessAnnotationValue(const ClassData& klass,
415                             const uint8_t** annotation_ptr,
416                             DexFile::AnnotationValue* annotation_value,
417                             Handle<mirror::Class> array_class,
418                             DexFile::AnnotationResultStyle result_style)
419     REQUIRES_SHARED(Locks::mutator_lock_) {
420   const DexFile& dex_file = klass.GetDexFile();
421   Thread* self = Thread::Current();
422   ObjPtr<mirror::Object> element_object = nullptr;
423   bool set_object = false;
424   Primitive::Type primitive_type = Primitive::kPrimVoid;
425   const uint8_t* annotation = *annotation_ptr;
426   uint8_t header_byte = *(annotation++);
427   uint8_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
428   uint8_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
429   int32_t width = value_arg + 1;
430   annotation_value->type_ = value_type;
431 
432   switch (value_type) {
433     case DexFile::kDexAnnotationByte:
434       annotation_value->value_.SetB(
435           static_cast<int8_t>(DexFile::ReadSignedInt(annotation, value_arg)));
436       primitive_type = Primitive::kPrimByte;
437       break;
438     case DexFile::kDexAnnotationShort:
439       annotation_value->value_.SetS(
440           static_cast<int16_t>(DexFile::ReadSignedInt(annotation, value_arg)));
441       primitive_type = Primitive::kPrimShort;
442       break;
443     case DexFile::kDexAnnotationChar:
444       annotation_value->value_.SetC(
445           static_cast<uint16_t>(DexFile::ReadUnsignedInt(annotation, value_arg, false)));
446       primitive_type = Primitive::kPrimChar;
447       break;
448     case DexFile::kDexAnnotationInt:
449       annotation_value->value_.SetI(DexFile::ReadSignedInt(annotation, value_arg));
450       primitive_type = Primitive::kPrimInt;
451       break;
452     case DexFile::kDexAnnotationLong:
453       annotation_value->value_.SetJ(DexFile::ReadSignedLong(annotation, value_arg));
454       primitive_type = Primitive::kPrimLong;
455       break;
456     case DexFile::kDexAnnotationFloat:
457       annotation_value->value_.SetI(DexFile::ReadUnsignedInt(annotation, value_arg, true));
458       primitive_type = Primitive::kPrimFloat;
459       break;
460     case DexFile::kDexAnnotationDouble:
461       annotation_value->value_.SetJ(DexFile::ReadUnsignedLong(annotation, value_arg, true));
462       primitive_type = Primitive::kPrimDouble;
463       break;
464     case DexFile::kDexAnnotationBoolean:
465       annotation_value->value_.SetZ(value_arg != 0);
466       primitive_type = Primitive::kPrimBoolean;
467       width = 0;
468       break;
469     case DexFile::kDexAnnotationString: {
470       uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
471       if (result_style == DexFile::kAllRaw) {
472         annotation_value->value_.SetI(index);
473       } else {
474         StackHandleScope<1> hs(self);
475         element_object = Runtime::Current()->GetClassLinker()->ResolveString(
476             dex::StringIndex(index), hs.NewHandle(klass.GetDexCache()));
477         set_object = true;
478         if (element_object == nullptr) {
479           return false;
480         }
481       }
482       break;
483     }
484     case DexFile::kDexAnnotationType: {
485       uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
486       if (result_style == DexFile::kAllRaw) {
487         annotation_value->value_.SetI(index);
488       } else {
489         dex::TypeIndex type_index(index);
490         StackHandleScope<2> hs(self);
491         element_object = Runtime::Current()->GetClassLinker()->ResolveType(
492             type_index,
493             hs.NewHandle(klass.GetDexCache()),
494             hs.NewHandle(klass.GetClassLoader()));
495         set_object = true;
496         if (element_object == nullptr) {
497           CHECK(self->IsExceptionPending());
498           if (result_style == DexFile::kAllObjects) {
499             const char* msg = dex_file.StringByTypeIdx(type_index);
500             self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
501             element_object = self->GetException();
502             self->ClearException();
503           } else {
504             return false;
505           }
506         }
507       }
508       break;
509     }
510     case DexFile::kDexAnnotationMethod: {
511       uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
512       if (result_style == DexFile::kAllRaw) {
513         annotation_value->value_.SetI(index);
514       } else {
515         ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
516         StackHandleScope<2> hs(self);
517         ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
518             index,
519             hs.NewHandle(klass.GetDexCache()),
520             hs.NewHandle(klass.GetClassLoader()));
521         if (method == nullptr) {
522           return false;
523         }
524         PointerSize pointer_size = class_linker->GetImagePointerSize();
525         set_object = true;
526         if (method->IsConstructor()) {
527           element_object = (pointer_size == PointerSize::k64)
528               ? mirror::Constructor::CreateFromArtMethod<PointerSize::k64>(self, method)
529               : mirror::Constructor::CreateFromArtMethod<PointerSize::k32>(self, method);
530         } else {
531           element_object = (pointer_size == PointerSize::k64)
532               ? mirror::Method::CreateFromArtMethod<PointerSize::k64>(self, method)
533               : mirror::Method::CreateFromArtMethod<PointerSize::k32>(self, method);
534         }
535         if (element_object == nullptr) {
536           return false;
537         }
538       }
539       break;
540     }
541     case DexFile::kDexAnnotationField: {
542       uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
543       if (result_style == DexFile::kAllRaw) {
544         annotation_value->value_.SetI(index);
545       } else {
546         StackHandleScope<2> hs(self);
547         ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
548             index,
549             hs.NewHandle(klass.GetDexCache()),
550             hs.NewHandle(klass.GetClassLoader()));
551         if (field == nullptr) {
552           return false;
553         }
554         set_object = true;
555         element_object = mirror::Field::CreateFromArtField(self, field, true);
556         if (element_object == nullptr) {
557           return false;
558         }
559       }
560       break;
561     }
562     case DexFile::kDexAnnotationEnum: {
563       uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
564       if (result_style == DexFile::kAllRaw) {
565         annotation_value->value_.SetI(index);
566       } else {
567         StackHandleScope<3> hs(self);
568         ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
569             index,
570             hs.NewHandle(klass.GetDexCache()),
571             hs.NewHandle(klass.GetClassLoader()),
572             true);
573         if (enum_field == nullptr) {
574           return false;
575         } else {
576           Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
577           Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
578           element_object = enum_field->GetObject(field_class.Get());
579           set_object = true;
580         }
581       }
582       break;
583     }
584     case DexFile::kDexAnnotationArray:
585       if (result_style == DexFile::kAllRaw || array_class == nullptr) {
586         return false;
587       } else {
588         ScopedObjectAccessUnchecked soa(self);
589         StackHandleScope<2> hs(self);
590         uint32_t size = DecodeUnsignedLeb128(&annotation);
591         Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
592         Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc(
593             self, array_class.Get(), size, array_class->GetComponentSizeShift(),
594             Runtime::Current()->GetHeap()->GetCurrentAllocator())));
595         if (new_array == nullptr) {
596           LOG(ERROR) << "Annotation element array allocation failed with size " << size;
597           return false;
598         }
599         DexFile::AnnotationValue new_annotation_value;
600         for (uint32_t i = 0; i < size; ++i) {
601           if (!ProcessAnnotationValue<kTransactionActive>(klass,
602                                                           &annotation,
603                                                           &new_annotation_value,
604                                                           component_type,
605                                                           DexFile::kPrimitivesOrObjects)) {
606             return false;
607           }
608           if (!component_type->IsPrimitive()) {
609             ObjPtr<mirror::Object> obj = new_annotation_value.value_.GetL();
610             new_array->AsObjectArray<mirror::Object>()->
611                 SetWithoutChecks<kTransactionActive>(i, obj);
612           } else {
613             switch (new_annotation_value.type_) {
614               case DexFile::kDexAnnotationByte:
615                 new_array->AsByteArray()->SetWithoutChecks<kTransactionActive>(
616                     i, new_annotation_value.value_.GetB());
617                 break;
618               case DexFile::kDexAnnotationShort:
619                 new_array->AsShortArray()->SetWithoutChecks<kTransactionActive>(
620                     i, new_annotation_value.value_.GetS());
621                 break;
622               case DexFile::kDexAnnotationChar:
623                 new_array->AsCharArray()->SetWithoutChecks<kTransactionActive>(
624                     i, new_annotation_value.value_.GetC());
625                 break;
626               case DexFile::kDexAnnotationInt:
627                 new_array->AsIntArray()->SetWithoutChecks<kTransactionActive>(
628                     i, new_annotation_value.value_.GetI());
629                 break;
630               case DexFile::kDexAnnotationLong:
631                 new_array->AsLongArray()->SetWithoutChecks<kTransactionActive>(
632                     i, new_annotation_value.value_.GetJ());
633                 break;
634               case DexFile::kDexAnnotationFloat:
635                 new_array->AsFloatArray()->SetWithoutChecks<kTransactionActive>(
636                     i, new_annotation_value.value_.GetF());
637                 break;
638               case DexFile::kDexAnnotationDouble:
639                 new_array->AsDoubleArray()->SetWithoutChecks<kTransactionActive>(
640                     i, new_annotation_value.value_.GetD());
641                 break;
642               case DexFile::kDexAnnotationBoolean:
643                 new_array->AsBooleanArray()->SetWithoutChecks<kTransactionActive>(
644                     i, new_annotation_value.value_.GetZ());
645                 break;
646               default:
647                 LOG(FATAL) << "Found invalid annotation value type while building annotation array";
648                 return false;
649             }
650           }
651         }
652         element_object = new_array.Get();
653         set_object = true;
654         width = 0;
655       }
656       break;
657     case DexFile::kDexAnnotationAnnotation:
658       if (result_style == DexFile::kAllRaw) {
659         return false;
660       }
661       element_object = ProcessEncodedAnnotation(klass, &annotation);
662       if (element_object == nullptr) {
663         return false;
664       }
665       set_object = true;
666       width = 0;
667       break;
668     case DexFile::kDexAnnotationNull:
669       if (result_style == DexFile::kAllRaw) {
670         annotation_value->value_.SetI(0);
671       } else {
672         CHECK(element_object == nullptr);
673         set_object = true;
674       }
675       width = 0;
676       break;
677     default:
678       LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
679       return false;
680   }
681 
682   annotation += width;
683   *annotation_ptr = annotation;
684 
685   if (result_style == DexFile::kAllObjects && primitive_type != Primitive::kPrimVoid) {
686     element_object = BoxPrimitive(primitive_type, annotation_value->value_);
687     set_object = true;
688   }
689 
690   if (set_object) {
691     annotation_value->value_.SetL(element_object);
692   }
693 
694   return true;
695 }
696 
CreateAnnotationMember(const ClassData & klass,Handle<mirror::Class> annotation_class,const uint8_t ** annotation)697 ObjPtr<mirror::Object> CreateAnnotationMember(const ClassData& klass,
698                                               Handle<mirror::Class> annotation_class,
699                                               const uint8_t** annotation) {
700   const DexFile& dex_file = klass.GetDexFile();
701   Thread* self = Thread::Current();
702   ScopedObjectAccessUnchecked soa(self);
703   StackHandleScope<5> hs(self);
704   uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
705   const char* name = dex_file.StringDataByIdx(dex::StringIndex(element_name_index));
706 
707   PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
708   ArtMethod* annotation_method =
709       annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
710   if (annotation_method == nullptr) {
711     return nullptr;
712   }
713 
714   Handle<mirror::String> string_name =
715       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name));
716   if (UNLIKELY(string_name == nullptr)) {
717     LOG(ERROR) << "Failed to allocate name for annotation member";
718     return nullptr;
719   }
720 
721   Handle<mirror::Class> method_return = hs.NewHandle(annotation_method->ResolveReturnType());
722   if (UNLIKELY(method_return == nullptr)) {
723     LOG(ERROR) << "Failed to resolve method return type for annotation member";
724     return nullptr;
725   }
726 
727   DexFile::AnnotationValue annotation_value;
728   if (!ProcessAnnotationValue<false>(klass,
729                                      annotation,
730                                      &annotation_value,
731                                      method_return,
732                                      DexFile::kAllObjects)) {
733     // TODO: Logging the error breaks run-test 005-annotations.
734     // LOG(ERROR) << "Failed to process annotation value for annotation member";
735     return nullptr;
736   }
737   Handle<mirror::Object> value_object = hs.NewHandle(annotation_value.value_.GetL());
738 
739   Handle<mirror::Method> method_object = hs.NewHandle((pointer_size == PointerSize::k64)
740       ? mirror::Method::CreateFromArtMethod<PointerSize::k64>(self, annotation_method)
741       : mirror::Method::CreateFromArtMethod<PointerSize::k32>(self, annotation_method));
742   if (UNLIKELY(method_object == nullptr)) {
743     LOG(ERROR) << "Failed to create method object for annotation member";
744     return nullptr;
745   }
746 
747   Handle<mirror::Object> new_member =
748       WellKnownClasses::libcore_reflect_AnnotationMember_init->NewObject<'L', 'L', 'L', 'L'>(
749           hs, self, string_name, value_object, method_return, method_object);
750   if (new_member == nullptr) {
751     DCHECK(self->IsExceptionPending());
752     LOG(ERROR) << "Failed to create annotation member";
753     return nullptr;
754   }
755 
756   return new_member.Get();
757 }
758 
GetAnnotationItemFromAnnotationSet(const ClassData & klass,const AnnotationSetItem * annotation_set,uint32_t visibility,Handle<mirror::Class> annotation_class)759 const AnnotationItem* GetAnnotationItemFromAnnotationSet(const ClassData& klass,
760                                                          const AnnotationSetItem* annotation_set,
761                                                          uint32_t visibility,
762                                                          Handle<mirror::Class> annotation_class)
763     REQUIRES_SHARED(Locks::mutator_lock_) {
764   const DexFile& dex_file = klass.GetDexFile();
765   for (uint32_t i = 0; i < annotation_set->size_; ++i) {
766     const AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
767     if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
768       continue;
769     }
770     const uint8_t* annotation = annotation_item->annotation_;
771     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
772     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
773     Thread* self = Thread::Current();
774     StackHandleScope<2> hs(self);
775     ObjPtr<mirror::Class> resolved_class = class_linker->ResolveType(
776         dex::TypeIndex(type_index),
777         hs.NewHandle(klass.GetDexCache()),
778         hs.NewHandle(klass.GetClassLoader()));
779     if (resolved_class == nullptr) {
780       std::string temp;
781       LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
782                                    klass.GetRealClass()->GetDescriptor(&temp), type_index);
783       CHECK(self->IsExceptionPending());
784       self->ClearException();
785       continue;
786     }
787     if (resolved_class == annotation_class.Get()) {
788       return annotation_item;
789     }
790   }
791 
792   return nullptr;
793 }
794 
GetAnnotationObjectFromAnnotationSet(const ClassData & klass,const AnnotationSetItem * annotation_set,uint32_t visibility,Handle<mirror::Class> annotation_class)795 ObjPtr<mirror::Object> GetAnnotationObjectFromAnnotationSet(const ClassData& klass,
796                                                             const AnnotationSetItem* annotation_set,
797                                                             uint32_t visibility,
798                                                             Handle<mirror::Class> annotation_class)
799     REQUIRES_SHARED(Locks::mutator_lock_) {
800   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
801       klass, annotation_set, visibility, annotation_class);
802   if (annotation_item == nullptr) {
803     return nullptr;
804   }
805   const uint8_t* annotation = annotation_item->annotation_;
806   return ProcessEncodedAnnotation(klass, &annotation);
807 }
808 
GetAnnotationValue(const ClassData & klass,const AnnotationItem * annotation_item,const char * annotation_name,Handle<mirror::Class> array_class,uint32_t expected_type)809 ObjPtr<mirror::Object> GetAnnotationValue(const ClassData& klass,
810                                           const AnnotationItem* annotation_item,
811                                           const char* annotation_name,
812                                           Handle<mirror::Class> array_class,
813                                           uint32_t expected_type)
814     REQUIRES_SHARED(Locks::mutator_lock_) {
815   const DexFile& dex_file = klass.GetDexFile();
816   const uint8_t* annotation =
817       SearchEncodedAnnotation(dex_file, annotation_item->annotation_, annotation_name);
818   if (annotation == nullptr) {
819     return nullptr;
820   }
821   DexFile::AnnotationValue annotation_value;
822   bool result = Runtime::Current()->IsActiveTransaction()
823       ? ProcessAnnotationValue<true>(klass,
824                                      &annotation,
825                                      &annotation_value,
826                                      array_class,
827                                      DexFile::kAllObjects)
828       : ProcessAnnotationValue<false>(klass,
829                                       &annotation,
830                                       &annotation_value,
831                                       array_class,
832                                       DexFile::kAllObjects);
833   if (!result) {
834     return nullptr;
835   }
836   if (annotation_value.type_ != expected_type) {
837     return nullptr;
838   }
839   return annotation_value.value_.GetL();
840 }
841 
842 template<typename T>
GetAnnotationArrayValue(Handle<mirror::Class> klass,const char * annotation_name,const char * value_name)843 static inline ObjPtr<mirror::ObjectArray<T>> GetAnnotationArrayValue(
844                                      Handle<mirror::Class> klass,
845                                      const char* annotation_name,
846                                      const char* value_name)
847             REQUIRES_SHARED(Locks::mutator_lock_) {
848   ClassData data(klass);
849   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
850   if (annotation_set == nullptr) {
851     return nullptr;
852   }
853   const AnnotationItem* annotation_item =
854       SearchAnnotationSet(data.GetDexFile(), annotation_set, annotation_name,
855                           DexFile::kDexVisibilitySystem);
856   if (annotation_item == nullptr) {
857     return nullptr;
858   }
859   StackHandleScope<1> hs(Thread::Current());
860   Handle<mirror::Class> class_array_class =
861       hs.NewHandle(GetClassRoot<mirror::ObjectArray<T>>());
862   DCHECK(class_array_class != nullptr);
863   ObjPtr<mirror::Object> obj = GetAnnotationValue(data,
864                                                   annotation_item,
865                                                   value_name,
866                                                   class_array_class,
867                                                   DexFile::kDexAnnotationArray);
868   if (obj == nullptr) {
869     return nullptr;
870   }
871   return obj->AsObjectArray<T>();
872 }
873 
GetSignatureValue(const ClassData & klass,const AnnotationSetItem * annotation_set)874 static ObjPtr<mirror::ObjectArray<mirror::String>> GetSignatureValue(
875     const ClassData& klass,
876     const AnnotationSetItem* annotation_set)
877     REQUIRES_SHARED(Locks::mutator_lock_) {
878   const DexFile& dex_file = klass.GetDexFile();
879   StackHandleScope<1> hs(Thread::Current());
880   const AnnotationItem* annotation_item =
881       SearchAnnotationSet(dex_file, annotation_set, "Ldalvik/annotation/Signature;",
882                           DexFile::kDexVisibilitySystem);
883   if (annotation_item == nullptr) {
884     return nullptr;
885   }
886   Handle<mirror::Class> string_array_class =
887       hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::String>>());
888   DCHECK(string_array_class != nullptr);
889   ObjPtr<mirror::Object> obj =
890       GetAnnotationValue(klass, annotation_item, "value", string_array_class,
891                          DexFile::kDexAnnotationArray);
892   if (obj == nullptr) {
893     return nullptr;
894   }
895   return obj->AsObjectArray<mirror::String>();
896 }
897 
GetThrowsValue(const ClassData & klass,const AnnotationSetItem * annotation_set)898 ObjPtr<mirror::ObjectArray<mirror::Class>> GetThrowsValue(const ClassData& klass,
899                                                           const AnnotationSetItem* annotation_set)
900     REQUIRES_SHARED(Locks::mutator_lock_) {
901   const DexFile& dex_file = klass.GetDexFile();
902   const AnnotationItem* annotation_item =
903       SearchAnnotationSet(dex_file, annotation_set, "Ldalvik/annotation/Throws;",
904                           DexFile::kDexVisibilitySystem);
905   if (annotation_item == nullptr) {
906     return nullptr;
907   }
908   StackHandleScope<1> hs(Thread::Current());
909   Handle<mirror::Class> class_array_class =
910       hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::Class>>());
911   DCHECK(class_array_class != nullptr);
912   ObjPtr<mirror::Object> obj =
913       GetAnnotationValue(klass, annotation_item, "value", class_array_class,
914                          DexFile::kDexAnnotationArray);
915   if (obj == nullptr) {
916     return nullptr;
917   }
918   return obj->AsObjectArray<mirror::Class>();
919 }
920 
ProcessAnnotationSet(const ClassData & klass,const AnnotationSetItem * annotation_set,uint32_t visibility)921 ObjPtr<mirror::ObjectArray<mirror::Object>> ProcessAnnotationSet(
922     const ClassData& klass,
923     const AnnotationSetItem* annotation_set,
924     uint32_t visibility)
925     REQUIRES_SHARED(Locks::mutator_lock_) {
926   const DexFile& dex_file = klass.GetDexFile();
927   Thread* self = Thread::Current();
928   StackHandleScope<2> hs(self);
929   Handle<mirror::Class> annotation_array_class(hs.NewHandle(
930       WellKnownClasses::ToClass(WellKnownClasses::java_lang_annotation_Annotation__array)));
931   if (annotation_set == nullptr) {
932     return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
933   }
934 
935   uint32_t size = annotation_set->size_;
936   Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
937       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
938   if (result == nullptr) {
939     return nullptr;
940   }
941 
942   uint32_t dest_index = 0;
943   for (uint32_t i = 0; i < size; ++i) {
944     const AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
945     // Note that we do not use IsVisibilityCompatible here because older code
946     // was correct for this case.
947     if (annotation_item->visibility_ != visibility) {
948       continue;
949     }
950     const uint8_t* annotation = annotation_item->annotation_;
951     ObjPtr<mirror::Object> annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
952     if (annotation_obj != nullptr) {
953       result->SetWithoutChecks<false>(dest_index, annotation_obj);
954       ++dest_index;
955     } else if (self->IsExceptionPending()) {
956       return nullptr;
957     }
958   }
959 
960   if (dest_index == size) {
961     return result.Get();
962   }
963 
964   ObjPtr<mirror::ObjectArray<mirror::Object>> trimmed_result =
965       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
966   if (trimmed_result == nullptr) {
967     return nullptr;
968   }
969 
970   for (uint32_t i = 0; i < dest_index; ++i) {
971     ObjPtr<mirror::Object> obj = result->GetWithoutChecks(i);
972     trimmed_result->SetWithoutChecks<false>(i, obj);
973   }
974 
975   return trimmed_result;
976 }
977 
ProcessAnnotationSetRefList(const ClassData & klass,const AnnotationSetRefList * set_ref_list,uint32_t size)978 ObjPtr<mirror::ObjectArray<mirror::Object>> ProcessAnnotationSetRefList(
979     const ClassData& klass,
980     const AnnotationSetRefList* set_ref_list,
981     uint32_t size)
982     REQUIRES_SHARED(Locks::mutator_lock_) {
983   const DexFile& dex_file = klass.GetDexFile();
984   Thread* self = Thread::Current();
985   StackHandleScope<1> hs(self);
986   ObjPtr<mirror::Class> annotation_array_class =
987       WellKnownClasses::ToClass(WellKnownClasses::java_lang_annotation_Annotation__array);
988   ObjPtr<mirror::Class> annotation_array_array_class =
989       Runtime::Current()->GetClassLinker()->FindArrayClass(self, annotation_array_class);
990   if (annotation_array_array_class == nullptr) {
991     return nullptr;
992   }
993   Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
994       mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
995   if (annotation_array_array == nullptr) {
996     LOG(ERROR) << "Annotation set ref array allocation failed";
997     return nullptr;
998   }
999   for (uint32_t index = 0; index < size; ++index) {
1000     const AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
1001     const AnnotationSetItem* set_item = dex_file.GetSetRefItemItem(set_ref_item);
1002     ObjPtr<mirror::Object> annotation_set = ProcessAnnotationSet(klass,
1003                                                                  set_item,
1004                                                                  DexFile::kDexVisibilityRuntime);
1005     if (annotation_set == nullptr) {
1006       return nullptr;
1007     }
1008     annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
1009   }
1010   return annotation_array_array.Get();
1011 }
1012 }  // namespace
1013 
1014 namespace annotations {
1015 
GetAnnotationForField(ArtField * field,Handle<mirror::Class> annotation_class)1016 ObjPtr<mirror::Object> GetAnnotationForField(ArtField* field,
1017                                              Handle<mirror::Class> annotation_class) {
1018   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1019   if (annotation_set == nullptr) {
1020     return nullptr;
1021   }
1022   StackHandleScope<1> hs(Thread::Current());
1023   const ClassData field_class(hs, field);
1024   return GetAnnotationObjectFromAnnotationSet(field_class,
1025                                               annotation_set,
1026                                               DexFile::kDexVisibilityRuntime,
1027                                               annotation_class);
1028 }
1029 
GetAnnotationsForField(ArtField * field)1030 ObjPtr<mirror::ObjectArray<mirror::Object>> GetAnnotationsForField(ArtField* field) {
1031   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1032   StackHandleScope<1> hs(Thread::Current());
1033   const ClassData field_class(hs, field);
1034   return ProcessAnnotationSet(field_class, annotation_set, DexFile::kDexVisibilityRuntime);
1035 }
1036 
GetSignatureAnnotationForField(ArtField * field)1037 ObjPtr<mirror::ObjectArray<mirror::String>> GetSignatureAnnotationForField(ArtField* field) {
1038   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1039   if (annotation_set == nullptr) {
1040     return nullptr;
1041   }
1042   StackHandleScope<1> hs(Thread::Current());
1043   const ClassData field_class(hs, field);
1044   return GetSignatureValue(field_class, annotation_set);
1045 }
1046 
IsFieldAnnotationPresent(ArtField * field,Handle<mirror::Class> annotation_class)1047 bool IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class) {
1048   const AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1049   if (annotation_set == nullptr) {
1050     return false;
1051   }
1052   StackHandleScope<1> hs(Thread::Current());
1053   const ClassData field_class(hs, field);
1054   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1055       field_class, annotation_set, DexFile::kDexVisibilityRuntime, annotation_class);
1056   return annotation_item != nullptr;
1057 }
1058 
GetAnnotationDefaultValue(ArtMethod * method)1059 ObjPtr<mirror::Object> GetAnnotationDefaultValue(ArtMethod* method) {
1060   const ClassData klass(method);
1061   const DexFile* dex_file = &klass.GetDexFile();
1062   const AnnotationsDirectoryItem* annotations_dir =
1063       dex_file->GetAnnotationsDirectory(*klass.GetClassDef());
1064   if (annotations_dir == nullptr) {
1065     return nullptr;
1066   }
1067   const AnnotationSetItem* annotation_set =
1068       dex_file->GetClassAnnotationSet(annotations_dir);
1069   if (annotation_set == nullptr) {
1070     return nullptr;
1071   }
1072   const AnnotationItem* annotation_item = SearchAnnotationSet(*dex_file, annotation_set,
1073       "Ldalvik/annotation/AnnotationDefault;", DexFile::kDexVisibilitySystem);
1074   if (annotation_item == nullptr) {
1075     return nullptr;
1076   }
1077   const uint8_t* annotation =
1078       SearchEncodedAnnotation(*dex_file, annotation_item->annotation_, "value");
1079   if (annotation == nullptr) {
1080     return nullptr;
1081   }
1082   uint8_t header_byte = *(annotation++);
1083   if ((header_byte & DexFile::kDexAnnotationValueTypeMask) != DexFile::kDexAnnotationAnnotation) {
1084     return nullptr;
1085   }
1086   annotation = SearchEncodedAnnotation(*dex_file, annotation, method->GetName());
1087   if (annotation == nullptr) {
1088     return nullptr;
1089   }
1090   DexFile::AnnotationValue annotation_value;
1091   StackHandleScope<1> hs(Thread::Current());
1092   Handle<mirror::Class> return_type(hs.NewHandle(method->ResolveReturnType()));
1093   if (!ProcessAnnotationValue<false>(klass,
1094                                      &annotation,
1095                                      &annotation_value,
1096                                      return_type,
1097                                      DexFile::kAllObjects)) {
1098     return nullptr;
1099   }
1100   return annotation_value.value_.GetL();
1101 }
1102 
GetAnnotationForMethod(ArtMethod * method,Handle<mirror::Class> annotation_class)1103 ObjPtr<mirror::Object> GetAnnotationForMethod(ArtMethod* method,
1104                                               Handle<mirror::Class> annotation_class) {
1105   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1106   if (annotation_set == nullptr) {
1107     return nullptr;
1108   }
1109   return GetAnnotationObjectFromAnnotationSet(ClassData(method), annotation_set,
1110                                               DexFile::kDexVisibilityRuntime, annotation_class);
1111 }
1112 
GetAnnotationsForMethod(ArtMethod * method)1113 ObjPtr<mirror::ObjectArray<mirror::Object>> GetAnnotationsForMethod(ArtMethod* method) {
1114   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1115   return ProcessAnnotationSet(ClassData(method),
1116                               annotation_set,
1117                               DexFile::kDexVisibilityRuntime);
1118 }
1119 
GetExceptionTypesForMethod(ArtMethod * method)1120 ObjPtr<mirror::ObjectArray<mirror::Class>> GetExceptionTypesForMethod(ArtMethod* method) {
1121   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1122   if (annotation_set == nullptr) {
1123     return nullptr;
1124   }
1125   return GetThrowsValue(ClassData(method), annotation_set);
1126 }
1127 
GetParameterAnnotations(ArtMethod * method)1128 ObjPtr<mirror::ObjectArray<mirror::Object>> GetParameterAnnotations(ArtMethod* method) {
1129   const DexFile* dex_file = method->GetDexFile();
1130   const ParameterAnnotationsItem* parameter_annotations =
1131       FindAnnotationsItemForMethod(method);
1132   if (parameter_annotations == nullptr) {
1133     return nullptr;
1134   }
1135   const AnnotationSetRefList* set_ref_list =
1136       dex_file->GetParameterAnnotationSetRefList(parameter_annotations);
1137   if (set_ref_list == nullptr) {
1138     return nullptr;
1139   }
1140   uint32_t size = set_ref_list->size_;
1141   return ProcessAnnotationSetRefList(ClassData(method), set_ref_list, size);
1142 }
1143 
GetNumberOfAnnotatedMethodParameters(ArtMethod * method)1144 uint32_t GetNumberOfAnnotatedMethodParameters(ArtMethod* method) {
1145   const DexFile* dex_file = method->GetDexFile();
1146   const ParameterAnnotationsItem* parameter_annotations =
1147       FindAnnotationsItemForMethod(method);
1148   if (parameter_annotations == nullptr) {
1149     return 0u;
1150   }
1151   const AnnotationSetRefList* set_ref_list =
1152       dex_file->GetParameterAnnotationSetRefList(parameter_annotations);
1153   if (set_ref_list == nullptr) {
1154     return 0u;
1155   }
1156   return set_ref_list->size_;
1157 }
1158 
GetAnnotationForMethodParameter(ArtMethod * method,uint32_t parameter_idx,Handle<mirror::Class> annotation_class)1159 ObjPtr<mirror::Object> GetAnnotationForMethodParameter(ArtMethod* method,
1160                                                        uint32_t parameter_idx,
1161                                                        Handle<mirror::Class> annotation_class) {
1162   const DexFile* dex_file = method->GetDexFile();
1163   const ParameterAnnotationsItem* parameter_annotations = FindAnnotationsItemForMethod(method);
1164   if (parameter_annotations == nullptr) {
1165     return nullptr;
1166   }
1167   const AnnotationSetRefList* set_ref_list =
1168       dex_file->GetParameterAnnotationSetRefList(parameter_annotations);
1169   if (set_ref_list == nullptr) {
1170     return nullptr;
1171   }
1172   if (parameter_idx >= set_ref_list->size_) {
1173     return nullptr;
1174   }
1175   const AnnotationSetRefItem* annotation_set_ref = &set_ref_list->list_[parameter_idx];
1176   const AnnotationSetItem* annotation_set =
1177      dex_file->GetSetRefItemItem(annotation_set_ref);
1178   if (annotation_set == nullptr) {
1179     return nullptr;
1180   }
1181   return GetAnnotationObjectFromAnnotationSet(ClassData(method),
1182                                               annotation_set,
1183                                               DexFile::kDexVisibilityRuntime,
1184                                               annotation_class);
1185 }
1186 
GetParametersMetadataForMethod(ArtMethod * method,MutableHandle<mirror::ObjectArray<mirror::String>> * names,MutableHandle<mirror::IntArray> * access_flags)1187 bool GetParametersMetadataForMethod(
1188     ArtMethod* method,
1189     /*out*/ MutableHandle<mirror::ObjectArray<mirror::String>>* names,
1190     /*out*/ MutableHandle<mirror::IntArray>* access_flags) {
1191   const AnnotationSetItem* annotation_set =
1192       FindAnnotationSetForMethod(method);
1193   if (annotation_set == nullptr) {
1194     return false;
1195   }
1196 
1197   const DexFile* dex_file = method->GetDexFile();
1198   const AnnotationItem* annotation_item =
1199       SearchAnnotationSet(*dex_file,
1200                           annotation_set,
1201                           "Ldalvik/annotation/MethodParameters;",
1202                           DexFile::kDexVisibilitySystem);
1203   if (annotation_item == nullptr) {
1204     return false;
1205   }
1206 
1207   StackHandleScope<4> hs(Thread::Current());
1208 
1209   // Extract the parameters' names String[].
1210   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1211   Handle<mirror::Class> string_array_class =
1212       hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::String>>(class_linker));
1213   DCHECK(string_array_class != nullptr);
1214 
1215   ClassData data(method);
1216   Handle<mirror::Object> names_obj =
1217       hs.NewHandle(GetAnnotationValue(data,
1218                                       annotation_item,
1219                                       "names",
1220                                       string_array_class,
1221                                       DexFile::kDexAnnotationArray));
1222   if (names_obj == nullptr) {
1223     return false;
1224   }
1225 
1226   // Extract the parameters' access flags int[].
1227   Handle<mirror::Class> int_array_class(hs.NewHandle(GetClassRoot<mirror::IntArray>(class_linker)));
1228   DCHECK(int_array_class != nullptr);
1229   Handle<mirror::Object> access_flags_obj =
1230       hs.NewHandle(GetAnnotationValue(data,
1231                                       annotation_item,
1232                                       "accessFlags",
1233                                       int_array_class,
1234                                       DexFile::kDexAnnotationArray));
1235   if (access_flags_obj == nullptr) {
1236     return false;
1237   }
1238 
1239   names->Assign(names_obj->AsObjectArray<mirror::String>());
1240   access_flags->Assign(access_flags_obj->AsIntArray());
1241   return true;
1242 }
1243 
GetSignatureAnnotationForMethod(ArtMethod * method)1244 ObjPtr<mirror::ObjectArray<mirror::String>> GetSignatureAnnotationForMethod(ArtMethod* method) {
1245   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1246   if (annotation_set == nullptr) {
1247     return nullptr;
1248   }
1249   return GetSignatureValue(ClassData(method), annotation_set);
1250 }
1251 
IsMethodAnnotationPresent(ArtMethod * method,Handle<mirror::Class> annotation_class,uint32_t visibility)1252 bool IsMethodAnnotationPresent(ArtMethod* method,
1253                                Handle<mirror::Class> annotation_class,
1254                                uint32_t visibility /* = DexFile::kDexVisibilityRuntime */) {
1255   const AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1256   if (annotation_set == nullptr) {
1257     return false;
1258   }
1259   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1260       ClassData(method), annotation_set, visibility, annotation_class);
1261   return annotation_item != nullptr;
1262 }
1263 
DCheckNativeAnnotation(const char * descriptor,jclass cls)1264 static void DCheckNativeAnnotation(const char* descriptor, jclass cls) {
1265   if (kIsDebugBuild) {
1266     ScopedObjectAccess soa(Thread::Current());
1267     ObjPtr<mirror::Class> klass = soa.Decode<mirror::Class>(cls);
1268     ClassLinker* linker = Runtime::Current()->GetClassLinker();
1269     // WellKnownClasses may not be initialized yet, so `klass` may be null.
1270     if (klass != nullptr) {
1271       // Lookup using the boot class path loader should yield the annotation class.
1272       CHECK_EQ(klass, linker->LookupClass(soa.Self(), descriptor, /* class_loader= */ nullptr));
1273     }
1274   }
1275 }
1276 
1277 // Check whether a method from the `dex_file` with the given `annotation_set`
1278 // is annotated with `annotation_descriptor` with build visibility.
IsMethodBuildAnnotationPresent(const DexFile & dex_file,const AnnotationSetItem & annotation_set,const char * annotation_descriptor,jclass annotation_class)1279 static bool IsMethodBuildAnnotationPresent(const DexFile& dex_file,
1280                                            const AnnotationSetItem& annotation_set,
1281                                            const char* annotation_descriptor,
1282                                            jclass annotation_class) {
1283   for (uint32_t i = 0; i < annotation_set.size_; ++i) {
1284     const AnnotationItem* annotation_item = dex_file.GetAnnotationItem(&annotation_set, i);
1285     if (!IsVisibilityCompatible(annotation_item->visibility_, DexFile::kDexVisibilityBuild)) {
1286       continue;
1287     }
1288     const uint8_t* annotation = annotation_item->annotation_;
1289     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1290     const char* descriptor = dex_file.StringByTypeIdx(dex::TypeIndex(type_index));
1291     if (strcmp(descriptor, annotation_descriptor) == 0) {
1292       DCheckNativeAnnotation(descriptor, annotation_class);
1293       return true;
1294     }
1295   }
1296   return false;
1297 }
1298 
GetNativeMethodAnnotationAccessFlags(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)1299 uint32_t GetNativeMethodAnnotationAccessFlags(const DexFile& dex_file,
1300                                               const dex::ClassDef& class_def,
1301                                               uint32_t method_index) {
1302   const dex::AnnotationSetItem* annotation_set =
1303       FindAnnotationSetForMethod(dex_file, class_def, method_index);
1304   if (annotation_set == nullptr) {
1305     return 0u;
1306   }
1307   uint32_t access_flags = 0u;
1308   if (IsMethodBuildAnnotationPresent(
1309           dex_file,
1310           *annotation_set,
1311           "Ldalvik/annotation/optimization/FastNative;",
1312           WellKnownClasses::dalvik_annotation_optimization_FastNative)) {
1313     access_flags |= kAccFastNative;
1314   }
1315   if (IsMethodBuildAnnotationPresent(
1316           dex_file,
1317           *annotation_set,
1318           "Ldalvik/annotation/optimization/CriticalNative;",
1319           WellKnownClasses::dalvik_annotation_optimization_CriticalNative)) {
1320     access_flags |= kAccCriticalNative;
1321   }
1322   CHECK_NE(access_flags, kAccFastNative | kAccCriticalNative);
1323   return access_flags;
1324 }
1325 
MethodIsNeverCompile(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)1326 bool MethodIsNeverCompile(const DexFile& dex_file,
1327                           const dex::ClassDef& class_def,
1328                           uint32_t method_index) {
1329   const dex::AnnotationSetItem* annotation_set =
1330       FindAnnotationSetForMethod(dex_file, class_def, method_index);
1331   if (annotation_set == nullptr) {
1332     return false;
1333   }
1334   return IsMethodBuildAnnotationPresent(
1335       dex_file,
1336       *annotation_set,
1337       "Ldalvik/annotation/optimization/NeverCompile;",
1338       WellKnownClasses::dalvik_annotation_optimization_NeverCompile);
1339 }
1340 
MethodIsNeverInline(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)1341 bool MethodIsNeverInline(const DexFile& dex_file,
1342                          const dex::ClassDef& class_def,
1343                          uint32_t method_index) {
1344   const dex::AnnotationSetItem* annotation_set =
1345       FindAnnotationSetForMethod(dex_file, class_def, method_index);
1346   if (annotation_set == nullptr) {
1347     return false;
1348   }
1349   return IsMethodBuildAnnotationPresent(
1350       dex_file,
1351       *annotation_set,
1352       "Ldalvik/annotation/optimization/NeverInline;",
1353       WellKnownClasses::dalvik_annotation_optimization_NeverInline);
1354 }
1355 
FieldIsReachabilitySensitive(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t field_index)1356 bool FieldIsReachabilitySensitive(const DexFile& dex_file,
1357                                   const dex::ClassDef& class_def,
1358                                   uint32_t field_index)
1359     REQUIRES_SHARED(Locks::mutator_lock_) {
1360   const AnnotationSetItem* annotation_set =
1361       FindAnnotationSetForField(dex_file, class_def, field_index);
1362   if (annotation_set == nullptr) {
1363     return false;
1364   }
1365   const AnnotationItem* annotation_item = SearchAnnotationSet(dex_file, annotation_set,
1366       "Ldalvik/annotation/optimization/ReachabilitySensitive;", DexFile::kDexVisibilityRuntime);
1367   // TODO: We're missing the equivalent of DCheckNativeAnnotation (not a DCHECK). Does it matter?
1368   return annotation_item != nullptr;
1369 }
1370 
MethodIsReachabilitySensitive(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)1371 bool MethodIsReachabilitySensitive(const DexFile& dex_file,
1372                                    const dex::ClassDef& class_def,
1373                                    uint32_t method_index)
1374     REQUIRES_SHARED(Locks::mutator_lock_) {
1375   const AnnotationSetItem* annotation_set =
1376       FindAnnotationSetForMethod(dex_file, class_def, method_index);
1377   if (annotation_set == nullptr) {
1378     return false;
1379   }
1380   const AnnotationItem* annotation_item = SearchAnnotationSet(dex_file, annotation_set,
1381       "Ldalvik/annotation/optimization/ReachabilitySensitive;", DexFile::kDexVisibilityRuntime);
1382   return annotation_item != nullptr;
1383 }
1384 
MethodIsReachabilitySensitive(const DexFile & dex_file,uint32_t method_index)1385 static bool MethodIsReachabilitySensitive(const DexFile& dex_file,
1386                                                uint32_t method_index)
1387     REQUIRES_SHARED(Locks::mutator_lock_) {
1388   DCHECK(method_index < dex_file.NumMethodIds());
1389   const dex::MethodId& method_id = dex_file.GetMethodId(method_index);
1390   dex::TypeIndex class_index = method_id.class_idx_;
1391   const dex::ClassDef * class_def = dex_file.FindClassDef(class_index);
1392   return class_def != nullptr
1393          && MethodIsReachabilitySensitive(dex_file, *class_def, method_index);
1394 }
1395 
MethodContainsRSensitiveAccess(const DexFile & dex_file,const dex::ClassDef & class_def,uint32_t method_index)1396 bool MethodContainsRSensitiveAccess(const DexFile& dex_file,
1397                                     const dex::ClassDef& class_def,
1398                                     uint32_t method_index)
1399     REQUIRES_SHARED(Locks::mutator_lock_) {
1400   // TODO: This is too slow to run very regularly. Currently this is only invoked in the
1401   // presence of @DeadReferenceSafe, which will be rare. In the long run, we need to quickly
1402   // check once whether a class has any @ReachabilitySensitive annotations. If not, we can
1403   // immediately return false here for any method in that class.
1404   uint32_t code_item_offset = dex_file.FindCodeItemOffset(class_def, method_index);
1405   const dex::CodeItem* code_item = dex_file.GetCodeItem(code_item_offset);
1406   CodeItemInstructionAccessor accessor(dex_file, code_item);
1407   if (!accessor.HasCodeItem()) {
1408     return false;
1409   }
1410   for (DexInstructionIterator iter = accessor.begin(); iter != accessor.end(); ++iter) {
1411     switch (iter->Opcode()) {
1412       case Instruction::IGET:
1413       case Instruction::IGET_WIDE:
1414       case Instruction::IGET_OBJECT:
1415       case Instruction::IGET_BOOLEAN:
1416       case Instruction::IGET_BYTE:
1417       case Instruction::IGET_CHAR:
1418       case Instruction::IGET_SHORT:
1419       case Instruction::IPUT:
1420       case Instruction::IPUT_WIDE:
1421       case Instruction::IPUT_OBJECT:
1422       case Instruction::IPUT_BOOLEAN:
1423       case Instruction::IPUT_BYTE:
1424       case Instruction::IPUT_CHAR:
1425       case Instruction::IPUT_SHORT:
1426         {
1427           uint32_t field_index = iter->VRegC_22c();
1428           DCHECK(field_index < dex_file.NumFieldIds());
1429           // We only guarantee to pay attention to the annotation if it's in the same class,
1430           // or a containing class, but it's OK to do so in other cases.
1431           const dex::FieldId& field_id = dex_file.GetFieldId(field_index);
1432           dex::TypeIndex class_index = field_id.class_idx_;
1433           const dex::ClassDef * field_class_def = dex_file.FindClassDef(class_index);
1434           // We do not handle the case in which the field is declared in a superclass, and
1435           // don't claim to do so. The annotated field should normally be private.
1436           if (field_class_def != nullptr
1437               && FieldIsReachabilitySensitive(dex_file, *field_class_def, field_index)) {
1438             return true;
1439           }
1440         }
1441         break;
1442       case Instruction::INVOKE_SUPER:
1443         // Cannot call method in same class. TODO: Try an explicit superclass lookup for
1444         // better "best effort"?
1445         break;
1446       case Instruction::INVOKE_INTERFACE:
1447         // We handle an interface call just like a virtual call. We will find annotations
1448         // on interface methods/fields visible to us, but not of the annotation is in a
1449         // super-interface. Again, we could just ignore it.
1450       case Instruction::INVOKE_VIRTUAL:
1451       case Instruction::INVOKE_DIRECT:
1452         {
1453           uint32_t called_method_index = iter->VRegB_35c();
1454           if (MethodIsReachabilitySensitive(dex_file, called_method_index)) {
1455             return true;
1456           }
1457         }
1458         break;
1459       case Instruction::INVOKE_INTERFACE_RANGE:
1460       case Instruction::INVOKE_VIRTUAL_RANGE:
1461       case Instruction::INVOKE_DIRECT_RANGE:
1462         {
1463           uint32_t called_method_index = iter->VRegB_3rc();
1464           if (MethodIsReachabilitySensitive(dex_file, called_method_index)) {
1465             return true;
1466           }
1467         }
1468         break;
1469         // We explicitly do not handle indirect ReachabilitySensitive accesses through VarHandles,
1470         // etc. Thus we ignore INVOKE_CUSTOM / INVOKE_CUSTOM_RANGE / INVOKE_POLYMORPHIC /
1471         // INVOKE_POLYMORPHIC_RANGE.
1472       default:
1473         // There is no way to add an annotation to array elements, and so far we've encountered no
1474         // need for that, so we ignore AGET and APUT.
1475         // It's impractical or impossible to garbage collect a class while one of its methods is
1476         // on the call stack. We allow ReachabilitySensitive annotations on static methods and
1477         // fields, but they can be safely ignored.
1478         break;
1479     }
1480   }
1481   return false;
1482 }
1483 
HasDeadReferenceSafeAnnotation(const DexFile & dex_file,const dex::ClassDef & class_def)1484 bool HasDeadReferenceSafeAnnotation(const DexFile& dex_file,
1485                                     const dex::ClassDef& class_def)
1486   // TODO: This should check outer classes as well.
1487   // It's conservatively correct not to do so.
1488     REQUIRES_SHARED(Locks::mutator_lock_) {
1489   const AnnotationsDirectoryItem* annotations_dir =
1490       dex_file.GetAnnotationsDirectory(class_def);
1491   if (annotations_dir == nullptr) {
1492     return false;
1493   }
1494   const AnnotationSetItem* annotation_set = dex_file.GetClassAnnotationSet(annotations_dir);
1495   if (annotation_set == nullptr) {
1496     return false;
1497   }
1498   const AnnotationItem* annotation_item = SearchAnnotationSet(dex_file, annotation_set,
1499       "Ldalvik/annotation/optimization/DeadReferenceSafe;", DexFile::kDexVisibilityRuntime);
1500   return annotation_item != nullptr;
1501 }
1502 
GetAnnotationForClass(Handle<mirror::Class> klass,Handle<mirror::Class> annotation_class)1503 ObjPtr<mirror::Object> GetAnnotationForClass(Handle<mirror::Class> klass,
1504                                              Handle<mirror::Class> annotation_class) {
1505   ClassData data(klass);
1506   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1507   if (annotation_set == nullptr) {
1508     return nullptr;
1509   }
1510   return GetAnnotationObjectFromAnnotationSet(data,
1511                                               annotation_set,
1512                                               DexFile::kDexVisibilityRuntime,
1513                                               annotation_class);
1514 }
1515 
GetAnnotationsForClass(Handle<mirror::Class> klass)1516 ObjPtr<mirror::ObjectArray<mirror::Object>> GetAnnotationsForClass(Handle<mirror::Class> klass) {
1517   ClassData data(klass);
1518   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1519   return ProcessAnnotationSet(data, annotation_set, DexFile::kDexVisibilityRuntime);
1520 }
1521 
GetDeclaredClasses(Handle<mirror::Class> klass)1522 ObjPtr<mirror::ObjectArray<mirror::Class>> GetDeclaredClasses(Handle<mirror::Class> klass) {
1523   return GetAnnotationArrayValue<mirror::Class>(klass,
1524                                                 "Ldalvik/annotation/MemberClasses;",
1525                                                 "value");
1526 }
1527 
GetDeclaringClass(Handle<mirror::Class> klass)1528 ObjPtr<mirror::Class> GetDeclaringClass(Handle<mirror::Class> klass) {
1529   ClassData data(klass);
1530   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1531   if (annotation_set == nullptr) {
1532     return nullptr;
1533   }
1534   const AnnotationItem* annotation_item =
1535       SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/EnclosingClass;",
1536                           DexFile::kDexVisibilitySystem);
1537   if (annotation_item == nullptr) {
1538     return nullptr;
1539   }
1540   ObjPtr<mirror::Object> obj = GetAnnotationValue(data,
1541                                                   annotation_item,
1542                                                   "value",
1543                                                   ScopedNullHandle<mirror::Class>(),
1544                                                   DexFile::kDexAnnotationType);
1545   if (obj == nullptr) {
1546     return nullptr;
1547   }
1548   if (!obj->IsClass()) {
1549     // TypeNotPresentException, throw the NoClassDefFoundError.
1550     Thread::Current()->SetException(obj->AsThrowable()->GetCause());
1551     return nullptr;
1552   }
1553   return obj->AsClass();
1554 }
1555 
GetEnclosingClass(Handle<mirror::Class> klass)1556 ObjPtr<mirror::Class> GetEnclosingClass(Handle<mirror::Class> klass) {
1557   ObjPtr<mirror::Class> declaring_class = GetDeclaringClass(klass);
1558   if (declaring_class != nullptr || Thread::Current()->IsExceptionPending()) {
1559     return declaring_class;
1560   }
1561   ClassData data(klass);
1562   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1563   if (annotation_set == nullptr) {
1564     return nullptr;
1565   }
1566   const AnnotationItem* annotation_item =
1567       SearchAnnotationSet(data.GetDexFile(),
1568                           annotation_set,
1569                           "Ldalvik/annotation/EnclosingMethod;",
1570                           DexFile::kDexVisibilitySystem);
1571   if (annotation_item == nullptr) {
1572     return nullptr;
1573   }
1574   const uint8_t* annotation =
1575       SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "value");
1576   if (annotation == nullptr) {
1577     return nullptr;
1578   }
1579   DexFile::AnnotationValue annotation_value;
1580   if (!ProcessAnnotationValue<false>(data,
1581                                      &annotation,
1582                                      &annotation_value,
1583                                      ScopedNullHandle<mirror::Class>(),
1584                                      DexFile::kAllRaw)) {
1585     return nullptr;
1586   }
1587   if (annotation_value.type_ != DexFile::kDexAnnotationMethod) {
1588     return nullptr;
1589   }
1590   StackHandleScope<2> hs(Thread::Current());
1591   ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1592       annotation_value.value_.GetI(),
1593       hs.NewHandle(data.GetDexCache()),
1594       hs.NewHandle(data.GetClassLoader()));
1595   if (method == nullptr) {
1596     return nullptr;
1597   }
1598   return method->GetDeclaringClass();
1599 }
1600 
GetEnclosingMethod(Handle<mirror::Class> klass)1601 ObjPtr<mirror::Object> GetEnclosingMethod(Handle<mirror::Class> klass) {
1602   ClassData data(klass);
1603   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1604   if (annotation_set == nullptr) {
1605     return nullptr;
1606   }
1607   const AnnotationItem* annotation_item =
1608       SearchAnnotationSet(data.GetDexFile(),
1609                           annotation_set,
1610                           "Ldalvik/annotation/EnclosingMethod;",
1611                           DexFile::kDexVisibilitySystem);
1612   if (annotation_item == nullptr) {
1613     return nullptr;
1614   }
1615   return GetAnnotationValue(data, annotation_item, "value", ScopedNullHandle<mirror::Class>(),
1616       DexFile::kDexAnnotationMethod);
1617 }
1618 
GetInnerClass(Handle<mirror::Class> klass,ObjPtr<mirror::String> * name)1619 bool GetInnerClass(Handle<mirror::Class> klass, /*out*/ ObjPtr<mirror::String>* name) {
1620   ClassData data(klass);
1621   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1622   if (annotation_set == nullptr) {
1623     return false;
1624   }
1625   const AnnotationItem* annotation_item = SearchAnnotationSet(
1626       data.GetDexFile(),
1627       annotation_set,
1628       "Ldalvik/annotation/InnerClass;",
1629       DexFile::kDexVisibilitySystem);
1630   if (annotation_item == nullptr) {
1631     return false;
1632   }
1633   const uint8_t* annotation =
1634       SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "name");
1635   if (annotation == nullptr) {
1636     return false;
1637   }
1638   DexFile::AnnotationValue annotation_value;
1639   if (!ProcessAnnotationValue<false>(data,
1640                                      &annotation,
1641                                      &annotation_value,
1642                                      ScopedNullHandle<mirror::Class>(),
1643                                      DexFile::kAllObjects)) {
1644     return false;
1645   }
1646   if (annotation_value.type_ != DexFile::kDexAnnotationNull &&
1647       annotation_value.type_ != DexFile::kDexAnnotationString) {
1648     return false;
1649   }
1650   *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1651   return true;
1652 }
1653 
GetInnerClassFlags(Handle<mirror::Class> klass,uint32_t * flags)1654 bool GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) {
1655   ClassData data(klass);
1656   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1657   if (annotation_set == nullptr) {
1658     return false;
1659   }
1660   const AnnotationItem* annotation_item =
1661       SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/InnerClass;",
1662                           DexFile::kDexVisibilitySystem);
1663   if (annotation_item == nullptr) {
1664     return false;
1665   }
1666   const uint8_t* annotation =
1667       SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "accessFlags");
1668   if (annotation == nullptr) {
1669     return false;
1670   }
1671   DexFile::AnnotationValue annotation_value;
1672   if (!ProcessAnnotationValue<false>(data,
1673                                      &annotation,
1674                                      &annotation_value,
1675                                      ScopedNullHandle<mirror::Class>(),
1676                                      DexFile::kAllRaw)) {
1677     return false;
1678   }
1679   if (annotation_value.type_ != DexFile::kDexAnnotationInt) {
1680     return false;
1681   }
1682   *flags = annotation_value.value_.GetI();
1683   return true;
1684 }
1685 
GetSignatureAnnotationForClass(Handle<mirror::Class> klass)1686 ObjPtr<mirror::ObjectArray<mirror::String>> GetSignatureAnnotationForClass(
1687     Handle<mirror::Class> klass) {
1688   ClassData data(klass);
1689   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1690   if (annotation_set == nullptr) {
1691     return nullptr;
1692   }
1693   return GetSignatureValue(data, annotation_set);
1694 }
1695 
GetSourceDebugExtension(Handle<mirror::Class> klass)1696 const char* GetSourceDebugExtension(Handle<mirror::Class> klass) {
1697   // Before instantiating ClassData, check that klass has a DexCache
1698   // assigned.  The ClassData constructor indirectly dereferences it
1699   // when calling klass->GetDexFile().
1700   if (klass->GetDexCache() == nullptr) {
1701     DCHECK(klass->IsPrimitive() || klass->IsArrayClass());
1702     return nullptr;
1703   }
1704 
1705   ClassData data(klass);
1706   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1707   if (annotation_set == nullptr) {
1708     return nullptr;
1709   }
1710 
1711   const AnnotationItem* annotation_item = SearchAnnotationSet(
1712       data.GetDexFile(),
1713       annotation_set,
1714       "Ldalvik/annotation/SourceDebugExtension;",
1715       DexFile::kDexVisibilitySystem);
1716   if (annotation_item == nullptr) {
1717     return nullptr;
1718   }
1719 
1720   const uint8_t* annotation =
1721       SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "value");
1722   if (annotation == nullptr) {
1723     return nullptr;
1724   }
1725   DexFile::AnnotationValue annotation_value;
1726   if (!ProcessAnnotationValue<false>(data,
1727                                      &annotation,
1728                                      &annotation_value,
1729                                      ScopedNullHandle<mirror::Class>(),
1730                                      DexFile::kAllRaw)) {
1731     return nullptr;
1732   }
1733   if (annotation_value.type_ != DexFile::kDexAnnotationString) {
1734     return nullptr;
1735   }
1736   dex::StringIndex index(static_cast<uint32_t>(annotation_value.value_.GetI()));
1737   return data.GetDexFile().StringDataByIdx(index);
1738 }
1739 
GetNestHost(Handle<mirror::Class> klass)1740 ObjPtr<mirror::Class> GetNestHost(Handle<mirror::Class> klass) {
1741   ClassData data(klass);
1742   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1743   if (annotation_set == nullptr) {
1744     return nullptr;
1745   }
1746   const AnnotationItem* annotation_item =
1747       SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/NestHost;",
1748                           DexFile::kDexVisibilitySystem);
1749   if (annotation_item == nullptr) {
1750     return nullptr;
1751   }
1752   ObjPtr<mirror::Object> obj = GetAnnotationValue(data,
1753                                                   annotation_item,
1754                                                   "host",
1755                                                   ScopedNullHandle<mirror::Class>(),
1756                                                   DexFile::kDexAnnotationType);
1757   if (obj == nullptr) {
1758     return nullptr;
1759   }
1760   if (!obj->IsClass()) {
1761     // TypeNotPresentException, throw the NoClassDefFoundError.
1762     Thread::Current()->SetException(obj->AsThrowable()->GetCause());
1763     return nullptr;
1764   }
1765   return obj->AsClass();
1766 }
1767 
GetNestMembers(Handle<mirror::Class> klass)1768 ObjPtr<mirror::ObjectArray<mirror::Class>> GetNestMembers(Handle<mirror::Class> klass) {
1769   return GetAnnotationArrayValue<mirror::Class>(klass,
1770                                                 "Ldalvik/annotation/NestMembers;",
1771                                                 "classes");
1772 }
1773 
GetPermittedSubclasses(Handle<mirror::Class> klass)1774 ObjPtr<mirror::ObjectArray<mirror::Class>> GetPermittedSubclasses(Handle<mirror::Class> klass) {
1775   return GetAnnotationArrayValue<mirror::Class>(klass,
1776                                                 "Ldalvik/annotation/PermittedSubclasses;",
1777                                                 "value");
1778 }
1779 
getRecordAnnotationElement(Handle<mirror::Class> klass,Handle<mirror::Class> array_class,const char * element_name)1780 ObjPtr<mirror::Object> getRecordAnnotationElement(Handle<mirror::Class> klass,
1781                                                   Handle<mirror::Class> array_class,
1782                                                   const char* element_name) {
1783   ClassData data(klass);
1784   const DexFile& dex_file = klass->GetDexFile();
1785   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1786   if (annotation_set == nullptr) {
1787     return nullptr;
1788   }
1789   const AnnotationItem* annotation_item = SearchAnnotationSet(
1790       dex_file, annotation_set, "Ldalvik/annotation/Record;", DexFile::kDexVisibilitySystem);
1791   if (annotation_item == nullptr) {
1792     return nullptr;
1793   }
1794   const uint8_t* annotation =
1795       SearchEncodedAnnotation(dex_file, annotation_item->annotation_, element_name);
1796   if (annotation == nullptr) {
1797     return nullptr;
1798   }
1799   DexFile::AnnotationValue annotation_value;
1800   bool result = Runtime::Current()->IsActiveTransaction()
1801       ? ProcessAnnotationValue<true>(data,
1802                                      &annotation,
1803                                      &annotation_value,
1804                                      array_class,
1805                                      DexFile::kPrimitivesOrObjects)
1806       : ProcessAnnotationValue<false>(data,
1807                                       &annotation,
1808                                       &annotation_value,
1809                                       array_class,
1810                                       DexFile::kPrimitivesOrObjects);
1811   if (!result) {
1812     return nullptr;
1813   }
1814   return annotation_value.value_.GetL();
1815 }
1816 
IsClassAnnotationPresent(Handle<mirror::Class> klass,Handle<mirror::Class> annotation_class)1817 bool IsClassAnnotationPresent(Handle<mirror::Class> klass, Handle<mirror::Class> annotation_class) {
1818   ClassData data(klass);
1819   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1820   if (annotation_set == nullptr) {
1821     return false;
1822   }
1823   const AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1824       data, annotation_set, DexFile::kDexVisibilityRuntime, annotation_class);
1825   return annotation_item != nullptr;
1826 }
1827 
GetLineNumFromPC(const DexFile * dex_file,ArtMethod * method,uint32_t rel_pc)1828 int32_t GetLineNumFromPC(const DexFile* dex_file, ArtMethod* method, uint32_t rel_pc) {
1829   // For native method, lineno should be -2 to indicate it is native. Note that
1830   // "line number == -2" is how libcore tells from StackTraceElement.
1831   if (!method->HasCodeItem()) {
1832     return -2;
1833   }
1834 
1835   CodeItemDebugInfoAccessor accessor(method->DexInstructionDebugInfo());
1836   DCHECK(accessor.HasCodeItem()) << method->PrettyMethod() << " " << dex_file->GetLocation();
1837 
1838   // A method with no line number info should return -1
1839   uint32_t line_num = -1;
1840   accessor.GetLineNumForPc(rel_pc, &line_num);
1841   return line_num;
1842 }
1843 
1844 template<bool kTransactionActive>
ReadValueToField(ArtField * field) const1845 void RuntimeEncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
1846   DCHECK(dex_cache_ != nullptr);
1847   switch (type_) {
1848     case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
1849         break;
1850     case kByte:    field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1851     case kShort:   field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1852     case kChar:    field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1853     case kInt:     field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1854     case kLong:    field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1855     case kFloat:   field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1856     case kDouble:  field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
1857     case kNull:    field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
1858     case kString: {
1859       ObjPtr<mirror::String> resolved = linker_->ResolveString(dex::StringIndex(jval_.i),
1860                                                                dex_cache_);
1861       field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
1862       break;
1863     }
1864     case kType: {
1865       ObjPtr<mirror::Class> resolved = linker_->ResolveType(dex::TypeIndex(jval_.i),
1866                                                             dex_cache_,
1867                                                             class_loader_);
1868       field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
1869       break;
1870     }
1871     default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1872   }
1873 }
1874 template
1875 void RuntimeEncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
1876 template
1877 void RuntimeEncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
1878 
VisitElement(AnnotationVisitor * visitor,const char * element_name,uint8_t depth,uint32_t element_index,const DexFile::AnnotationValue & annotation_value)1879 inline static VisitorStatus VisitElement(AnnotationVisitor* visitor,
1880                                          const char* element_name,
1881                                          uint8_t depth,
1882                                          uint32_t element_index,
1883                                          const DexFile::AnnotationValue& annotation_value)
1884     REQUIRES_SHARED(Locks::mutator_lock_) {
1885   if (depth == 0) {
1886     return visitor->VisitAnnotationElement(
1887         element_name, annotation_value.type_, annotation_value.value_);
1888   } else {
1889     return visitor->VisitArrayElement(
1890         depth - 1, element_index, annotation_value.type_, annotation_value.value_);
1891   }
1892 }
1893 
VisitEncodedValue(const ClassData & klass,const DexFile & dex_file,const uint8_t ** annotation_ptr,AnnotationVisitor * visitor,const char * element_name,uint8_t depth,uint32_t element_index)1894 static VisitorStatus VisitEncodedValue(const ClassData& klass,
1895                                        const DexFile& dex_file,
1896                                        const uint8_t** annotation_ptr,
1897                                        AnnotationVisitor* visitor,
1898                                        const char* element_name,
1899                                        uint8_t depth,
1900                                        uint32_t element_index)
1901     REQUIRES_SHARED(Locks::mutator_lock_) {
1902   DexFile::AnnotationValue annotation_value;
1903   // kTransactionActive is safe because the result_style is kAllRaw.
1904   bool is_consumed = ProcessAnnotationValue<false>(klass,
1905                                                    annotation_ptr,
1906                                                    &annotation_value,
1907                                                    ScopedNullHandle<mirror::Class>(),
1908                                                    DexFile::kAllRaw);
1909 
1910   VisitorStatus status =
1911       VisitElement(visitor, element_name, depth, element_index, annotation_value);
1912   switch (annotation_value.type_) {
1913     case DexFile::kDexAnnotationArray: {
1914       DCHECK(!is_consumed) << " unexpected consumption of array-typed element '" << element_name
1915                            << "' annotating the class " << klass.GetRealClass()->PrettyClass();
1916       SkipEncodedValueHeaderByte(annotation_ptr);
1917       uint32_t array_size = DecodeUnsignedLeb128(annotation_ptr);
1918       uint8_t next_depth = depth + 1;
1919       VisitorStatus element_status = (status == VisitorStatus::kVisitInner) ?
1920                                          VisitorStatus::kVisitNext :
1921                                          VisitorStatus::kVisitBreak;
1922       uint32_t i = 0;
1923       for (; i < array_size && element_status != VisitorStatus::kVisitBreak; ++i) {
1924         element_status = VisitEncodedValue(
1925             klass, dex_file, annotation_ptr, visitor, element_name, next_depth, i);
1926       }
1927       for (; i < array_size; ++i) {
1928         SkipAnnotationValue(dex_file, annotation_ptr);
1929       }
1930       break;
1931     }
1932     case DexFile::kDexAnnotationAnnotation: {
1933       DCHECK(!is_consumed) << " unexpected consumption of annotation-typed element '"
1934                            << element_name << "' annotating the class "
1935                            << klass.GetRealClass()->PrettyClass();
1936       SkipEncodedValueHeaderByte(annotation_ptr);
1937       DecodeUnsignedLeb128(annotation_ptr);  // unused type_index
1938       uint32_t size = DecodeUnsignedLeb128(annotation_ptr);
1939       for (; size != 0u; --size) {
1940         DecodeUnsignedLeb128(annotation_ptr);  // unused element_name_index
1941         SkipAnnotationValue(dex_file, annotation_ptr);
1942       }
1943       break;
1944     }
1945     default: {
1946       // kDexAnnotationArray and kDexAnnotationAnnotation are the only 2 known value_types causing
1947       // ProcessAnnotationValue return false. For other value_types, we shouldn't need to iterate
1948       // over annotation_ptr and skip the value here.
1949       DCHECK(is_consumed) << StringPrintf(
1950           "consumed annotation element type 0x%02x of %s for the class %s",
1951           annotation_value.type_,
1952           element_name,
1953           klass.GetRealClass()->PrettyClass().c_str());
1954       if (UNLIKELY(!is_consumed)) {
1955         SkipAnnotationValue(dex_file, annotation_ptr);
1956       }
1957       break;
1958     }
1959   }
1960 
1961   return status;
1962 }
1963 
VisitClassAnnotations(Handle<mirror::Class> klass,AnnotationVisitor * visitor)1964 void VisitClassAnnotations(Handle<mirror::Class> klass, AnnotationVisitor* visitor) {
1965   ClassData data(klass);
1966   const AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1967   if (annotation_set == nullptr) {
1968     return;
1969   }
1970 
1971   const DexFile& dex_file = data.GetDexFile();
1972   for (uint32_t i = 0; i < annotation_set->size_; ++i) {
1973     const AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
1974     uint8_t visibility = annotation_item->visibility_;
1975     const uint8_t* annotation = annotation_item->annotation_;
1976     uint32_t type_index = DecodeUnsignedLeb128(&annotation);
1977     const char* annotation_descriptor = dex_file.StringByTypeIdx(dex::TypeIndex(type_index));
1978     VisitorStatus status = visitor->VisitAnnotation(annotation_descriptor, visibility);
1979     switch (status) {
1980       case VisitorStatus::kVisitBreak:
1981         return;
1982       case VisitorStatus::kVisitNext:
1983         continue;
1984       case VisitorStatus::kVisitInner:
1985         // Visit the annotation elements
1986         break;
1987     }
1988 
1989     uint32_t size = DecodeUnsignedLeb128(&annotation);
1990     while (size != 0) {
1991       uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
1992       const char* element_name =
1993           dex_file.GetStringData(dex_file.GetStringId(dex::StringIndex(element_name_index)));
1994 
1995       status = VisitEncodedValue(
1996           data, dex_file, &annotation, visitor, element_name, /*depth=*/0, /*ignored*/ 0);
1997       if (status == VisitorStatus::kVisitBreak) {
1998         break;
1999       }
2000       size--;
2001     }
2002   }
2003 }
2004 
2005 }  // namespace annotations
2006 
2007 }  // namespace art
2008