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