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/stringprintf.h"
22
23#include "art_field-inl.h"
24#include "art_method-inl.h"
25#include "class_linker-inl.h"
26#include "dex_file-inl.h"
27#include "jni_internal.h"
28#include "jvalue-inl.h"
29#include "mirror/field.h"
30#include "mirror/method.h"
31#include "reflection.h"
32#include "thread.h"
33
34namespace art {
35
36using android::base::StringPrintf;
37
38struct DexFile::AnnotationValue {
39  JValue value_;
40  uint8_t type_;
41};
42
43namespace {
44
45// A helper class that contains all the data needed to do annotation lookup.
46class ClassData {
47 public:
48  explicit ClassData(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
49    : ClassData(ScopedNullHandle<mirror::Class>(),  // klass
50                method,
51                *method->GetDexFile(),
52                &method->GetClassDef()) {}
53
54  // Requires Scope to be able to create at least 1 handles.
55  template <typename Scope>
56  ClassData(Scope& hs, ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_)
57    : ClassData(hs.NewHandle(field->GetDeclaringClass())) { }
58
59  explicit ClassData(Handle<mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_)
60    : ClassData(klass,  // klass
61                nullptr,  // method
62                klass->GetDexFile(),
63                klass->GetClassDef()) {}
64
65  const DexFile& GetDexFile() const REQUIRES_SHARED(Locks::mutator_lock_) {
66    return dex_file_;
67  }
68
69  const DexFile::ClassDef* GetClassDef() const REQUIRES_SHARED(Locks::mutator_lock_) {
70    return class_def_;
71  }
72
73  ObjPtr<mirror::DexCache> GetDexCache() const REQUIRES_SHARED(Locks::mutator_lock_) {
74    if (method_ != nullptr) {
75      return method_->GetDexCache();
76    } else {
77      return real_klass_->GetDexCache();
78    }
79  }
80
81  ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
82    if (method_ != nullptr) {
83      return method_->GetDeclaringClass()->GetClassLoader();
84    } else {
85      return real_klass_->GetClassLoader();
86    }
87  }
88
89  ObjPtr<mirror::Class> GetRealClass() const REQUIRES_SHARED(Locks::mutator_lock_) {
90    if (method_ != nullptr) {
91      return method_->GetDeclaringClass();
92    } else {
93      return real_klass_.Get();
94    }
95  }
96
97 private:
98  ClassData(Handle<mirror::Class> klass,
99            ArtMethod* method,
100            const DexFile& dex_file,
101            const DexFile::ClassDef* class_def) REQUIRES_SHARED(Locks::mutator_lock_)
102      : real_klass_(klass),
103        method_(method),
104        dex_file_(dex_file),
105        class_def_(class_def) {
106    DCHECK((method_ == nullptr) || real_klass_.IsNull());
107  }
108
109  Handle<mirror::Class> real_klass_;
110  ArtMethod* method_;
111  const DexFile& dex_file_;
112  const DexFile::ClassDef* class_def_;
113
114  DISALLOW_COPY_AND_ASSIGN(ClassData);
115};
116
117mirror::Object* CreateAnnotationMember(const ClassData& klass,
118                                       Handle<mirror::Class> annotation_class,
119                                       const uint8_t** annotation)
120    REQUIRES_SHARED(Locks::mutator_lock_);
121
122bool IsVisibilityCompatible(uint32_t actual, uint32_t expected) {
123  if (expected == DexFile::kDexVisibilityRuntime) {
124    int32_t sdk_version = Runtime::Current()->GetTargetSdkVersion();
125    if (sdk_version > 0 && sdk_version <= 23) {
126      return actual == DexFile::kDexVisibilityRuntime || actual == DexFile::kDexVisibilityBuild;
127    }
128  }
129  return actual == expected;
130}
131
132const DexFile::AnnotationSetItem* FindAnnotationSetForField(ArtField* field)
133    REQUIRES_SHARED(Locks::mutator_lock_) {
134  const DexFile* dex_file = field->GetDexFile();
135  ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
136  const DexFile::AnnotationsDirectoryItem* annotations_dir =
137      dex_file->GetAnnotationsDirectory(*klass->GetClassDef());
138  if (annotations_dir == nullptr) {
139    return nullptr;
140  }
141  const DexFile::FieldAnnotationsItem* field_annotations =
142      dex_file->GetFieldAnnotations(annotations_dir);
143  if (field_annotations == nullptr) {
144    return nullptr;
145  }
146  uint32_t field_index = field->GetDexFieldIndex();
147  uint32_t field_count = annotations_dir->fields_size_;
148  for (uint32_t i = 0; i < field_count; ++i) {
149    if (field_annotations[i].field_idx_ == field_index) {
150      return dex_file->GetFieldAnnotationSetItem(field_annotations[i]);
151    }
152  }
153  return nullptr;
154}
155
156const DexFile::AnnotationItem* SearchAnnotationSet(const DexFile& dex_file,
157                                                   const DexFile::AnnotationSetItem* annotation_set,
158                                                   const char* descriptor,
159                                                   uint32_t visibility)
160    REQUIRES_SHARED(Locks::mutator_lock_) {
161  const DexFile::AnnotationItem* result = nullptr;
162  for (uint32_t i = 0; i < annotation_set->size_; ++i) {
163    const DexFile::AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
164    if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
165      continue;
166    }
167    const uint8_t* annotation = annotation_item->annotation_;
168    uint32_t type_index = DecodeUnsignedLeb128(&annotation);
169
170    if (strcmp(descriptor, dex_file.StringByTypeIdx(dex::TypeIndex(type_index))) == 0) {
171      result = annotation_item;
172      break;
173    }
174  }
175  return result;
176}
177
178bool SkipAnnotationValue(const DexFile& dex_file, const uint8_t** annotation_ptr)
179    REQUIRES_SHARED(Locks::mutator_lock_) {
180  const uint8_t* annotation = *annotation_ptr;
181  uint8_t header_byte = *(annotation++);
182  uint8_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
183  uint8_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
184  int32_t width = value_arg + 1;
185
186  switch (value_type) {
187    case DexFile::kDexAnnotationByte:
188    case DexFile::kDexAnnotationShort:
189    case DexFile::kDexAnnotationChar:
190    case DexFile::kDexAnnotationInt:
191    case DexFile::kDexAnnotationLong:
192    case DexFile::kDexAnnotationFloat:
193    case DexFile::kDexAnnotationDouble:
194    case DexFile::kDexAnnotationString:
195    case DexFile::kDexAnnotationType:
196    case DexFile::kDexAnnotationMethod:
197    case DexFile::kDexAnnotationField:
198    case DexFile::kDexAnnotationEnum:
199      break;
200    case DexFile::kDexAnnotationArray:
201    {
202      uint32_t size = DecodeUnsignedLeb128(&annotation);
203      while (size--) {
204        if (!SkipAnnotationValue(dex_file, &annotation)) {
205          return false;
206        }
207      }
208      width = 0;
209      break;
210    }
211    case DexFile::kDexAnnotationAnnotation:
212    {
213      DecodeUnsignedLeb128(&annotation);  // unused type_index
214      uint32_t size = DecodeUnsignedLeb128(&annotation);
215      while (size--) {
216        DecodeUnsignedLeb128(&annotation);  // unused element_name_index
217        if (!SkipAnnotationValue(dex_file, &annotation)) {
218          return false;
219        }
220      }
221      width = 0;
222      break;
223    }
224    case DexFile::kDexAnnotationBoolean:
225    case DexFile::kDexAnnotationNull:
226      width = 0;
227      break;
228    default:
229      LOG(FATAL) << StringPrintf("Bad annotation element value byte 0x%02x", value_type);
230      return false;
231  }
232
233  annotation += width;
234  *annotation_ptr = annotation;
235  return true;
236}
237
238const uint8_t* SearchEncodedAnnotation(const DexFile& dex_file,
239                                       const uint8_t* annotation,
240                                       const char* name)
241    REQUIRES_SHARED(Locks::mutator_lock_) {
242  DecodeUnsignedLeb128(&annotation);  // unused type_index
243  uint32_t size = DecodeUnsignedLeb128(&annotation);
244
245  while (size != 0) {
246    uint32_t element_name_index = DecodeUnsignedLeb128(&annotation);
247    const char* element_name =
248        dex_file.GetStringData(dex_file.GetStringId(dex::StringIndex(element_name_index)));
249    if (strcmp(name, element_name) == 0) {
250      return annotation;
251    }
252    SkipAnnotationValue(dex_file, &annotation);
253    size--;
254  }
255  return nullptr;
256}
257
258const DexFile::AnnotationSetItem* FindAnnotationSetForMethod(ArtMethod* method)
259    REQUIRES_SHARED(Locks::mutator_lock_) {
260  const DexFile* dex_file = method->GetDexFile();
261  const DexFile::AnnotationsDirectoryItem* annotations_dir =
262      dex_file->GetAnnotationsDirectory(method->GetClassDef());
263  if (annotations_dir == nullptr) {
264    return nullptr;
265  }
266  const DexFile::MethodAnnotationsItem* method_annotations =
267      dex_file->GetMethodAnnotations(annotations_dir);
268  if (method_annotations == nullptr) {
269    return nullptr;
270  }
271  uint32_t method_index = method->GetDexMethodIndex();
272  uint32_t method_count = annotations_dir->methods_size_;
273  for (uint32_t i = 0; i < method_count; ++i) {
274    if (method_annotations[i].method_idx_ == method_index) {
275      return dex_file->GetMethodAnnotationSetItem(method_annotations[i]);
276    }
277  }
278  return nullptr;
279}
280
281const DexFile::ParameterAnnotationsItem* FindAnnotationsItemForMethod(ArtMethod* method)
282    REQUIRES_SHARED(Locks::mutator_lock_) {
283  const DexFile* dex_file = method->GetDexFile();
284  const DexFile::AnnotationsDirectoryItem* annotations_dir =
285      dex_file->GetAnnotationsDirectory(method->GetClassDef());
286  if (annotations_dir == nullptr) {
287    return nullptr;
288  }
289  const DexFile::ParameterAnnotationsItem* parameter_annotations =
290      dex_file->GetParameterAnnotations(annotations_dir);
291  if (parameter_annotations == nullptr) {
292    return nullptr;
293  }
294  uint32_t method_index = method->GetDexMethodIndex();
295  uint32_t parameter_count = annotations_dir->parameters_size_;
296  for (uint32_t i = 0; i < parameter_count; ++i) {
297    if (parameter_annotations[i].method_idx_ == method_index) {
298      return &parameter_annotations[i];
299    }
300  }
301  return nullptr;
302}
303
304const DexFile::AnnotationSetItem* FindAnnotationSetForClass(const ClassData& klass)
305    REQUIRES_SHARED(Locks::mutator_lock_) {
306  const DexFile& dex_file = klass.GetDexFile();
307  const DexFile::AnnotationsDirectoryItem* annotations_dir =
308      dex_file.GetAnnotationsDirectory(*klass.GetClassDef());
309  if (annotations_dir == nullptr) {
310    return nullptr;
311  }
312  return dex_file.GetClassAnnotationSet(annotations_dir);
313}
314
315mirror::Object* ProcessEncodedAnnotation(const ClassData& klass, const uint8_t** annotation)
316    REQUIRES_SHARED(Locks::mutator_lock_) {
317  uint32_t type_index = DecodeUnsignedLeb128(annotation);
318  uint32_t size = DecodeUnsignedLeb128(annotation);
319
320  Thread* self = Thread::Current();
321  ScopedObjectAccessUnchecked soa(self);
322  StackHandleScope<4> hs(self);
323  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
324  Handle<mirror::Class> annotation_class(hs.NewHandle(
325      class_linker->ResolveType(klass.GetDexFile(),
326                                dex::TypeIndex(type_index),
327                                hs.NewHandle(klass.GetDexCache()),
328                                hs.NewHandle(klass.GetClassLoader()))));
329  if (annotation_class == nullptr) {
330    LOG(INFO) << "Unable to resolve " << klass.GetRealClass()->PrettyClass()
331              << " annotation class " << type_index;
332    DCHECK(Thread::Current()->IsExceptionPending());
333    Thread::Current()->ClearException();
334    return nullptr;
335  }
336
337  ObjPtr<mirror::Class> annotation_member_class =
338      soa.Decode<mirror::Class>(WellKnownClasses::libcore_reflect_AnnotationMember).Ptr();
339  mirror::Class* annotation_member_array_class =
340      class_linker->FindArrayClass(self, &annotation_member_class);
341  if (annotation_member_array_class == nullptr) {
342    return nullptr;
343  }
344  mirror::ObjectArray<mirror::Object>* element_array = nullptr;
345  if (size > 0) {
346    element_array =
347        mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_member_array_class, size);
348    if (element_array == nullptr) {
349      LOG(ERROR) << "Failed to allocate annotation member array (" << size << " elements)";
350      return nullptr;
351    }
352  }
353
354  Handle<mirror::ObjectArray<mirror::Object>> h_element_array(hs.NewHandle(element_array));
355  for (uint32_t i = 0; i < size; ++i) {
356    mirror::Object* new_member = CreateAnnotationMember(klass, annotation_class, annotation);
357    if (new_member == nullptr) {
358      return nullptr;
359    }
360    h_element_array->SetWithoutChecks<false>(i, new_member);
361  }
362
363  JValue result;
364  ArtMethod* create_annotation_method =
365      jni::DecodeArtMethod(WellKnownClasses::libcore_reflect_AnnotationFactory_createAnnotation);
366  uint32_t args[2] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(annotation_class.Get())),
367                       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_element_array.Get())) };
368  create_annotation_method->Invoke(self, args, sizeof(args), &result, "LLL");
369  if (self->IsExceptionPending()) {
370    LOG(INFO) << "Exception in AnnotationFactory.createAnnotation";
371    return nullptr;
372  }
373
374  return result.GetL();
375}
376
377template <bool kTransactionActive>
378bool ProcessAnnotationValue(const ClassData& klass,
379                            const uint8_t** annotation_ptr,
380                            DexFile::AnnotationValue* annotation_value,
381                            Handle<mirror::Class> array_class,
382                            DexFile::AnnotationResultStyle result_style)
383    REQUIRES_SHARED(Locks::mutator_lock_) {
384  const DexFile& dex_file = klass.GetDexFile();
385  Thread* self = Thread::Current();
386  ObjPtr<mirror::Object> element_object = nullptr;
387  bool set_object = false;
388  Primitive::Type primitive_type = Primitive::kPrimVoid;
389  const uint8_t* annotation = *annotation_ptr;
390  uint8_t header_byte = *(annotation++);
391  uint8_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
392  uint8_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
393  int32_t width = value_arg + 1;
394  annotation_value->type_ = value_type;
395
396  switch (value_type) {
397    case DexFile::kDexAnnotationByte:
398      annotation_value->value_.SetB(
399          static_cast<int8_t>(DexFile::ReadSignedInt(annotation, value_arg)));
400      primitive_type = Primitive::kPrimByte;
401      break;
402    case DexFile::kDexAnnotationShort:
403      annotation_value->value_.SetS(
404          static_cast<int16_t>(DexFile::ReadSignedInt(annotation, value_arg)));
405      primitive_type = Primitive::kPrimShort;
406      break;
407    case DexFile::kDexAnnotationChar:
408      annotation_value->value_.SetC(
409          static_cast<uint16_t>(DexFile::ReadUnsignedInt(annotation, value_arg, false)));
410      primitive_type = Primitive::kPrimChar;
411      break;
412    case DexFile::kDexAnnotationInt:
413      annotation_value->value_.SetI(DexFile::ReadSignedInt(annotation, value_arg));
414      primitive_type = Primitive::kPrimInt;
415      break;
416    case DexFile::kDexAnnotationLong:
417      annotation_value->value_.SetJ(DexFile::ReadSignedLong(annotation, value_arg));
418      primitive_type = Primitive::kPrimLong;
419      break;
420    case DexFile::kDexAnnotationFloat:
421      annotation_value->value_.SetI(DexFile::ReadUnsignedInt(annotation, value_arg, true));
422      primitive_type = Primitive::kPrimFloat;
423      break;
424    case DexFile::kDexAnnotationDouble:
425      annotation_value->value_.SetJ(DexFile::ReadUnsignedLong(annotation, value_arg, true));
426      primitive_type = Primitive::kPrimDouble;
427      break;
428    case DexFile::kDexAnnotationBoolean:
429      annotation_value->value_.SetZ(value_arg != 0);
430      primitive_type = Primitive::kPrimBoolean;
431      width = 0;
432      break;
433    case DexFile::kDexAnnotationString: {
434      uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
435      if (result_style == DexFile::kAllRaw) {
436        annotation_value->value_.SetI(index);
437      } else {
438        StackHandleScope<1> hs(self);
439        element_object = Runtime::Current()->GetClassLinker()->ResolveString(
440            klass.GetDexFile(), dex::StringIndex(index), hs.NewHandle(klass.GetDexCache()));
441        set_object = true;
442        if (element_object == nullptr) {
443          return false;
444        }
445      }
446      break;
447    }
448    case DexFile::kDexAnnotationType: {
449      uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
450      if (result_style == DexFile::kAllRaw) {
451        annotation_value->value_.SetI(index);
452      } else {
453        dex::TypeIndex type_index(index);
454        StackHandleScope<2> hs(self);
455        element_object = Runtime::Current()->GetClassLinker()->ResolveType(
456            klass.GetDexFile(),
457            type_index,
458            hs.NewHandle(klass.GetDexCache()),
459            hs.NewHandle(klass.GetClassLoader()));
460        set_object = true;
461        if (element_object == nullptr) {
462          CHECK(self->IsExceptionPending());
463          if (result_style == DexFile::kAllObjects) {
464            const char* msg = dex_file.StringByTypeIdx(type_index);
465            self->ThrowNewWrappedException("Ljava/lang/TypeNotPresentException;", msg);
466            element_object = self->GetException();
467            self->ClearException();
468          } else {
469            return false;
470          }
471        }
472      }
473      break;
474    }
475    case DexFile::kDexAnnotationMethod: {
476      uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
477      if (result_style == DexFile::kAllRaw) {
478        annotation_value->value_.SetI(index);
479      } else {
480        ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
481        StackHandleScope<2> hs(self);
482        ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
483            klass.GetDexFile(),
484            index,
485            hs.NewHandle(klass.GetDexCache()),
486            hs.NewHandle(klass.GetClassLoader()));
487        if (method == nullptr) {
488          return false;
489        }
490        PointerSize pointer_size = class_linker->GetImagePointerSize();
491        set_object = true;
492        if (method->IsConstructor()) {
493          if (pointer_size == PointerSize::k64) {
494            element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k64,
495                kTransactionActive>(self, method);
496          } else {
497            element_object = mirror::Constructor::CreateFromArtMethod<PointerSize::k32,
498                kTransactionActive>(self, method);
499          }
500        } else {
501          if (pointer_size == PointerSize::k64) {
502            element_object = mirror::Method::CreateFromArtMethod<PointerSize::k64,
503                kTransactionActive>(self, method);
504          } else {
505            element_object = mirror::Method::CreateFromArtMethod<PointerSize::k32,
506                kTransactionActive>(self, method);
507          }
508        }
509        if (element_object == nullptr) {
510          return false;
511        }
512      }
513      break;
514    }
515    case DexFile::kDexAnnotationField: {
516      uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
517      if (result_style == DexFile::kAllRaw) {
518        annotation_value->value_.SetI(index);
519      } else {
520        StackHandleScope<2> hs(self);
521        ArtField* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(
522            klass.GetDexFile(),
523            index,
524            hs.NewHandle(klass.GetDexCache()),
525            hs.NewHandle(klass.GetClassLoader()));
526        if (field == nullptr) {
527          return false;
528        }
529        set_object = true;
530        PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
531        if (pointer_size == PointerSize::k64) {
532          element_object = mirror::Field::CreateFromArtField<PointerSize::k64,
533              kTransactionActive>(self, field, true);
534        } else {
535          element_object = mirror::Field::CreateFromArtField<PointerSize::k32,
536              kTransactionActive>(self, field, true);
537        }
538        if (element_object == nullptr) {
539          return false;
540        }
541      }
542      break;
543    }
544    case DexFile::kDexAnnotationEnum: {
545      uint32_t index = DexFile::ReadUnsignedInt(annotation, value_arg, false);
546      if (result_style == DexFile::kAllRaw) {
547        annotation_value->value_.SetI(index);
548      } else {
549        StackHandleScope<3> hs(self);
550        ArtField* enum_field = Runtime::Current()->GetClassLinker()->ResolveField(
551            klass.GetDexFile(),
552            index,
553            hs.NewHandle(klass.GetDexCache()),
554            hs.NewHandle(klass.GetClassLoader()),
555            true);
556        if (enum_field == nullptr) {
557          return false;
558        } else {
559          Handle<mirror::Class> field_class(hs.NewHandle(enum_field->GetDeclaringClass()));
560          Runtime::Current()->GetClassLinker()->EnsureInitialized(self, field_class, true, true);
561          element_object = enum_field->GetObject(field_class.Get());
562          set_object = true;
563        }
564      }
565      break;
566    }
567    case DexFile::kDexAnnotationArray:
568      if (result_style == DexFile::kAllRaw || array_class == nullptr) {
569        return false;
570      } else {
571        ScopedObjectAccessUnchecked soa(self);
572        StackHandleScope<2> hs(self);
573        uint32_t size = DecodeUnsignedLeb128(&annotation);
574        Handle<mirror::Class> component_type(hs.NewHandle(array_class->GetComponentType()));
575        Handle<mirror::Array> new_array(hs.NewHandle(mirror::Array::Alloc<true>(
576            self, array_class.Get(), size, array_class->GetComponentSizeShift(),
577            Runtime::Current()->GetHeap()->GetCurrentAllocator())));
578        if (new_array == nullptr) {
579          LOG(ERROR) << "Annotation element array allocation failed with size " << size;
580          return false;
581        }
582        DexFile::AnnotationValue new_annotation_value;
583        for (uint32_t i = 0; i < size; ++i) {
584          if (!ProcessAnnotationValue<kTransactionActive>(klass,
585                                                          &annotation,
586                                                          &new_annotation_value,
587                                                          component_type,
588                                                          DexFile::kPrimitivesOrObjects)) {
589            return false;
590          }
591          if (!component_type->IsPrimitive()) {
592            mirror::Object* obj = new_annotation_value.value_.GetL();
593            new_array->AsObjectArray<mirror::Object>()->
594                SetWithoutChecks<kTransactionActive>(i, obj);
595          } else {
596            switch (new_annotation_value.type_) {
597              case DexFile::kDexAnnotationByte:
598                new_array->AsByteArray()->SetWithoutChecks<kTransactionActive>(
599                    i, new_annotation_value.value_.GetB());
600                break;
601              case DexFile::kDexAnnotationShort:
602                new_array->AsShortArray()->SetWithoutChecks<kTransactionActive>(
603                    i, new_annotation_value.value_.GetS());
604                break;
605              case DexFile::kDexAnnotationChar:
606                new_array->AsCharArray()->SetWithoutChecks<kTransactionActive>(
607                    i, new_annotation_value.value_.GetC());
608                break;
609              case DexFile::kDexAnnotationInt:
610                new_array->AsIntArray()->SetWithoutChecks<kTransactionActive>(
611                    i, new_annotation_value.value_.GetI());
612                break;
613              case DexFile::kDexAnnotationLong:
614                new_array->AsLongArray()->SetWithoutChecks<kTransactionActive>(
615                    i, new_annotation_value.value_.GetJ());
616                break;
617              case DexFile::kDexAnnotationFloat:
618                new_array->AsFloatArray()->SetWithoutChecks<kTransactionActive>(
619                    i, new_annotation_value.value_.GetF());
620                break;
621              case DexFile::kDexAnnotationDouble:
622                new_array->AsDoubleArray()->SetWithoutChecks<kTransactionActive>(
623                    i, new_annotation_value.value_.GetD());
624                break;
625              case DexFile::kDexAnnotationBoolean:
626                new_array->AsBooleanArray()->SetWithoutChecks<kTransactionActive>(
627                    i, new_annotation_value.value_.GetZ());
628                break;
629              default:
630                LOG(FATAL) << "Found invalid annotation value type while building annotation array";
631                return false;
632            }
633          }
634        }
635        element_object = new_array.Get();
636        set_object = true;
637        width = 0;
638      }
639      break;
640    case DexFile::kDexAnnotationAnnotation:
641      if (result_style == DexFile::kAllRaw) {
642        return false;
643      }
644      element_object = ProcessEncodedAnnotation(klass, &annotation);
645      if (element_object == nullptr) {
646        return false;
647      }
648      set_object = true;
649      width = 0;
650      break;
651    case DexFile::kDexAnnotationNull:
652      if (result_style == DexFile::kAllRaw) {
653        annotation_value->value_.SetI(0);
654      } else {
655        CHECK(element_object == nullptr);
656        set_object = true;
657      }
658      width = 0;
659      break;
660    default:
661      LOG(ERROR) << StringPrintf("Bad annotation element value type 0x%02x", value_type);
662      return false;
663  }
664
665  annotation += width;
666  *annotation_ptr = annotation;
667
668  if (result_style == DexFile::kAllObjects && primitive_type != Primitive::kPrimVoid) {
669    element_object = BoxPrimitive(primitive_type, annotation_value->value_).Ptr();
670    set_object = true;
671  }
672
673  if (set_object) {
674    annotation_value->value_.SetL(element_object.Ptr());
675  }
676
677  return true;
678}
679
680mirror::Object* CreateAnnotationMember(const ClassData& klass,
681                                       Handle<mirror::Class> annotation_class,
682                                       const uint8_t** annotation) {
683  const DexFile& dex_file = klass.GetDexFile();
684  Thread* self = Thread::Current();
685  ScopedObjectAccessUnchecked soa(self);
686  StackHandleScope<5> hs(self);
687  uint32_t element_name_index = DecodeUnsignedLeb128(annotation);
688  const char* name = dex_file.StringDataByIdx(dex::StringIndex(element_name_index));
689  Handle<mirror::String> string_name(
690      hs.NewHandle(mirror::String::AllocFromModifiedUtf8(self, name)));
691
692  PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
693  ArtMethod* annotation_method =
694      annotation_class->FindDeclaredVirtualMethodByName(name, pointer_size);
695  if (annotation_method == nullptr) {
696    return nullptr;
697  }
698  Handle<mirror::Class> method_return(hs.NewHandle(
699      annotation_method->GetReturnType(true /* resolve */)));
700
701  DexFile::AnnotationValue annotation_value;
702  if (!ProcessAnnotationValue<false>(klass,
703                                     annotation,
704                                     &annotation_value,
705                                     method_return,
706                                     DexFile::kAllObjects)) {
707    return nullptr;
708  }
709  Handle<mirror::Object> value_object(hs.NewHandle(annotation_value.value_.GetL()));
710
711  ObjPtr<mirror::Class> annotation_member_class =
712      WellKnownClasses::ToClass(WellKnownClasses::libcore_reflect_AnnotationMember);
713  Handle<mirror::Object> new_member(hs.NewHandle(annotation_member_class->AllocObject(self)));
714  mirror::Method* method_obj_ptr;
715  DCHECK(!Runtime::Current()->IsActiveTransaction());
716  if (pointer_size == PointerSize::k64) {
717    method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k64, false>(
718        self, annotation_method);
719  } else {
720    method_obj_ptr = mirror::Method::CreateFromArtMethod<PointerSize::k32, false>(
721        self, annotation_method);
722  }
723  Handle<mirror::Method> method_object(hs.NewHandle(method_obj_ptr));
724
725  if (new_member == nullptr || string_name == nullptr ||
726      method_object == nullptr || method_return == nullptr) {
727    LOG(ERROR) << StringPrintf("Failed creating annotation element (m=%p n=%p a=%p r=%p",
728        new_member.Get(), string_name.Get(), method_object.Get(), method_return.Get());
729    return nullptr;
730  }
731
732  JValue result;
733  ArtMethod* annotation_member_init =
734      jni::DecodeArtMethod(WellKnownClasses::libcore_reflect_AnnotationMember_init);
735  uint32_t args[5] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(new_member.Get())),
736                       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(string_name.Get())),
737                       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(value_object.Get())),
738                       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_return.Get())),
739                       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method_object.Get()))
740  };
741  annotation_member_init->Invoke(self, args, sizeof(args), &result, "VLLLL");
742  if (self->IsExceptionPending()) {
743    LOG(INFO) << "Exception in AnnotationMember.<init>";
744    return nullptr;
745  }
746
747  return new_member.Get();
748}
749
750const DexFile::AnnotationItem* GetAnnotationItemFromAnnotationSet(
751    const ClassData& klass,
752    const DexFile::AnnotationSetItem* annotation_set,
753    uint32_t visibility,
754    Handle<mirror::Class> annotation_class,
755    bool lookup_in_resolved_boot_classes = false)
756    REQUIRES_SHARED(Locks::mutator_lock_) {
757  const DexFile& dex_file = klass.GetDexFile();
758  for (uint32_t i = 0; i < annotation_set->size_; ++i) {
759    const DexFile::AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
760    if (!IsVisibilityCompatible(annotation_item->visibility_, visibility)) {
761      continue;
762    }
763    const uint8_t* annotation = annotation_item->annotation_;
764    uint32_t type_index = DecodeUnsignedLeb128(&annotation);
765    mirror::Class* resolved_class;
766    if (lookup_in_resolved_boot_classes) {
767      ObjPtr<mirror::Class> looked_up_class =
768          Runtime::Current()->GetClassLinker()->LookupResolvedType(
769              klass.GetDexFile(),
770              dex::TypeIndex(type_index),
771              klass.GetDexCache(),
772              // Force the use of the bootstrap class loader.
773              static_cast<mirror::ClassLoader*>(nullptr));
774      resolved_class = looked_up_class.Ptr();
775      if (resolved_class == nullptr) {
776        // If `resolved_class` is null, this is fine: just ignore that
777        // annotation item. We expect this to happen, as we do not
778        // attempt to resolve the annotation's class in this code path.
779        continue;
780      }
781    } else {
782      StackHandleScope<2> hs(Thread::Current());
783      resolved_class = Runtime::Current()->GetClassLinker()->ResolveType(
784          klass.GetDexFile(),
785          dex::TypeIndex(type_index),
786          hs.NewHandle(klass.GetDexCache()),
787          hs.NewHandle(klass.GetClassLoader()));
788      if (resolved_class == nullptr) {
789        std::string temp;
790        LOG(WARNING) << StringPrintf("Unable to resolve %s annotation class %d",
791                                     klass.GetRealClass()->GetDescriptor(&temp), type_index);
792        CHECK(Thread::Current()->IsExceptionPending());
793        Thread::Current()->ClearException();
794        continue;
795      }
796    }
797    if (resolved_class == annotation_class.Get()) {
798      return annotation_item;
799    }
800  }
801
802  return nullptr;
803}
804
805mirror::Object* GetAnnotationObjectFromAnnotationSet(
806    const ClassData& klass,
807    const DexFile::AnnotationSetItem* annotation_set,
808    uint32_t visibility,
809    Handle<mirror::Class> annotation_class)
810    REQUIRES_SHARED(Locks::mutator_lock_) {
811  const DexFile::AnnotationItem* annotation_item =
812      GetAnnotationItemFromAnnotationSet(klass, annotation_set, visibility, annotation_class);
813  if (annotation_item == nullptr) {
814    return nullptr;
815  }
816  const uint8_t* annotation = annotation_item->annotation_;
817  return ProcessEncodedAnnotation(klass, &annotation);
818}
819
820mirror::Object* GetAnnotationValue(const ClassData& klass,
821                                   const DexFile::AnnotationItem* annotation_item,
822                                   const char* annotation_name,
823                                   Handle<mirror::Class> array_class,
824                                   uint32_t expected_type)
825    REQUIRES_SHARED(Locks::mutator_lock_) {
826  const DexFile& dex_file = klass.GetDexFile();
827  const uint8_t* annotation =
828      SearchEncodedAnnotation(dex_file, annotation_item->annotation_, annotation_name);
829  if (annotation == nullptr) {
830    return nullptr;
831  }
832  DexFile::AnnotationValue annotation_value;
833  bool result = Runtime::Current()->IsActiveTransaction()
834      ? ProcessAnnotationValue<true>(klass,
835                                     &annotation,
836                                     &annotation_value,
837                                     array_class,
838                                     DexFile::kAllObjects)
839      : ProcessAnnotationValue<false>(klass,
840                                      &annotation,
841                                      &annotation_value,
842                                      array_class,
843                                      DexFile::kAllObjects);
844  if (!result) {
845    return nullptr;
846  }
847  if (annotation_value.type_ != expected_type) {
848    return nullptr;
849  }
850  return annotation_value.value_.GetL();
851}
852
853mirror::ObjectArray<mirror::String>* GetSignatureValue(const ClassData& klass,
854    const DexFile::AnnotationSetItem* annotation_set)
855    REQUIRES_SHARED(Locks::mutator_lock_) {
856  const DexFile& dex_file = klass.GetDexFile();
857  StackHandleScope<1> hs(Thread::Current());
858  const DexFile::AnnotationItem* annotation_item =
859      SearchAnnotationSet(dex_file, annotation_set, "Ldalvik/annotation/Signature;",
860                          DexFile::kDexVisibilitySystem);
861  if (annotation_item == nullptr) {
862    return nullptr;
863  }
864  ObjPtr<mirror::Class> string_class = mirror::String::GetJavaLangString();
865  Handle<mirror::Class> string_array_class(hs.NewHandle(
866      Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
867  if (string_array_class == nullptr) {
868    return nullptr;
869  }
870  mirror::Object* obj =
871      GetAnnotationValue(klass, annotation_item, "value", string_array_class,
872                         DexFile::kDexAnnotationArray);
873  if (obj == nullptr) {
874    return nullptr;
875  }
876  return obj->AsObjectArray<mirror::String>();
877}
878
879mirror::ObjectArray<mirror::Class>* GetThrowsValue(const ClassData& klass,
880                                                   const DexFile::AnnotationSetItem* annotation_set)
881    REQUIRES_SHARED(Locks::mutator_lock_) {
882  const DexFile& dex_file = klass.GetDexFile();
883  StackHandleScope<1> hs(Thread::Current());
884  const DexFile::AnnotationItem* annotation_item =
885      SearchAnnotationSet(dex_file, annotation_set, "Ldalvik/annotation/Throws;",
886                          DexFile::kDexVisibilitySystem);
887  if (annotation_item == nullptr) {
888    return nullptr;
889  }
890  ObjPtr<mirror::Class> class_class = mirror::Class::GetJavaLangClass();
891  Handle<mirror::Class> class_array_class(hs.NewHandle(
892      Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &class_class)));
893  if (class_array_class == nullptr) {
894    return nullptr;
895  }
896  mirror::Object* obj =
897      GetAnnotationValue(klass, annotation_item, "value", class_array_class,
898                         DexFile::kDexAnnotationArray);
899  if (obj == nullptr) {
900    return nullptr;
901  }
902  return obj->AsObjectArray<mirror::Class>();
903}
904
905mirror::ObjectArray<mirror::Object>* ProcessAnnotationSet(
906    const ClassData& klass,
907    const DexFile::AnnotationSetItem* annotation_set,
908    uint32_t visibility)
909    REQUIRES_SHARED(Locks::mutator_lock_) {
910  const DexFile& dex_file = klass.GetDexFile();
911  Thread* self = Thread::Current();
912  ScopedObjectAccessUnchecked soa(self);
913  StackHandleScope<2> hs(self);
914  Handle<mirror::Class> annotation_array_class(hs.NewHandle(
915      soa.Decode<mirror::Class>(WellKnownClasses::java_lang_annotation_Annotation__array)));
916  if (annotation_set == nullptr) {
917    return mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), 0);
918  }
919
920  uint32_t size = annotation_set->size_;
921  Handle<mirror::ObjectArray<mirror::Object>> result(hs.NewHandle(
922      mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), size)));
923  if (result == nullptr) {
924    return nullptr;
925  }
926
927  uint32_t dest_index = 0;
928  for (uint32_t i = 0; i < size; ++i) {
929    const DexFile::AnnotationItem* annotation_item = dex_file.GetAnnotationItem(annotation_set, i);
930    // Note that we do not use IsVisibilityCompatible here because older code
931    // was correct for this case.
932    if (annotation_item->visibility_ != visibility) {
933      continue;
934    }
935    const uint8_t* annotation = annotation_item->annotation_;
936    mirror::Object* annotation_obj = ProcessEncodedAnnotation(klass, &annotation);
937    if (annotation_obj != nullptr) {
938      result->SetWithoutChecks<false>(dest_index, annotation_obj);
939      ++dest_index;
940    } else if (self->IsExceptionPending()) {
941      return nullptr;
942    }
943  }
944
945  if (dest_index == size) {
946    return result.Get();
947  }
948
949  mirror::ObjectArray<mirror::Object>* trimmed_result =
950      mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_class.Get(), dest_index);
951  if (trimmed_result == nullptr) {
952    return nullptr;
953  }
954
955  for (uint32_t i = 0; i < dest_index; ++i) {
956    mirror::Object* obj = result->GetWithoutChecks(i);
957    trimmed_result->SetWithoutChecks<false>(i, obj);
958  }
959
960  return trimmed_result;
961}
962
963mirror::ObjectArray<mirror::Object>* ProcessAnnotationSetRefList(
964    const ClassData& klass,
965    const DexFile::AnnotationSetRefList* set_ref_list,
966    uint32_t size)
967    REQUIRES_SHARED(Locks::mutator_lock_) {
968  const DexFile& dex_file = klass.GetDexFile();
969  Thread* self = Thread::Current();
970  ScopedObjectAccessUnchecked soa(self);
971  StackHandleScope<1> hs(self);
972  ObjPtr<mirror::Class> annotation_array_class =
973      soa.Decode<mirror::Class>(WellKnownClasses::java_lang_annotation_Annotation__array);
974  mirror::Class* annotation_array_array_class =
975      Runtime::Current()->GetClassLinker()->FindArrayClass(self, &annotation_array_class);
976  if (annotation_array_array_class == nullptr) {
977    return nullptr;
978  }
979  Handle<mirror::ObjectArray<mirror::Object>> annotation_array_array(hs.NewHandle(
980      mirror::ObjectArray<mirror::Object>::Alloc(self, annotation_array_array_class, size)));
981  if (annotation_array_array == nullptr) {
982    LOG(ERROR) << "Annotation set ref array allocation failed";
983    return nullptr;
984  }
985  for (uint32_t index = 0; index < size; ++index) {
986    const DexFile::AnnotationSetRefItem* set_ref_item = &set_ref_list->list_[index];
987    const DexFile::AnnotationSetItem* set_item = dex_file.GetSetRefItemItem(set_ref_item);
988    mirror::Object* annotation_set = ProcessAnnotationSet(klass, set_item,
989                                                          DexFile::kDexVisibilityRuntime);
990    if (annotation_set == nullptr) {
991      return nullptr;
992    }
993    annotation_array_array->SetWithoutChecks<false>(index, annotation_set);
994  }
995  return annotation_array_array.Get();
996}
997}  // namespace
998
999namespace annotations {
1000
1001mirror::Object* GetAnnotationForField(ArtField* field, Handle<mirror::Class> annotation_class) {
1002  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1003  if (annotation_set == nullptr) {
1004    return nullptr;
1005  }
1006  StackHandleScope<1> hs(Thread::Current());
1007  const ClassData field_class(hs, field);
1008  return GetAnnotationObjectFromAnnotationSet(field_class,
1009                                              annotation_set,
1010                                              DexFile::kDexVisibilityRuntime,
1011                                              annotation_class);
1012}
1013
1014mirror::ObjectArray<mirror::Object>* GetAnnotationsForField(ArtField* field) {
1015  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1016  StackHandleScope<1> hs(Thread::Current());
1017  const ClassData field_class(hs, field);
1018  return ProcessAnnotationSet(field_class, annotation_set, DexFile::kDexVisibilityRuntime);
1019}
1020
1021mirror::ObjectArray<mirror::String>* GetSignatureAnnotationForField(ArtField* field) {
1022  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1023  if (annotation_set == nullptr) {
1024    return nullptr;
1025  }
1026  StackHandleScope<1> hs(Thread::Current());
1027  const ClassData field_class(hs, field);
1028  return GetSignatureValue(field_class, annotation_set);
1029}
1030
1031bool IsFieldAnnotationPresent(ArtField* field, Handle<mirror::Class> annotation_class) {
1032  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForField(field);
1033  if (annotation_set == nullptr) {
1034    return false;
1035  }
1036  StackHandleScope<1> hs(Thread::Current());
1037  const ClassData field_class(hs, field);
1038  const DexFile::AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1039      field_class, annotation_set, DexFile::kDexVisibilityRuntime, annotation_class);
1040  return annotation_item != nullptr;
1041}
1042
1043mirror::Object* GetAnnotationDefaultValue(ArtMethod* method) {
1044  const ClassData klass(method);
1045  const DexFile* dex_file = &klass.GetDexFile();
1046  const DexFile::AnnotationsDirectoryItem* annotations_dir =
1047      dex_file->GetAnnotationsDirectory(*klass.GetClassDef());
1048  if (annotations_dir == nullptr) {
1049    return nullptr;
1050  }
1051  const DexFile::AnnotationSetItem* annotation_set =
1052      dex_file->GetClassAnnotationSet(annotations_dir);
1053  if (annotation_set == nullptr) {
1054    return nullptr;
1055  }
1056  const DexFile::AnnotationItem* annotation_item = SearchAnnotationSet(*dex_file, annotation_set,
1057      "Ldalvik/annotation/AnnotationDefault;", DexFile::kDexVisibilitySystem);
1058  if (annotation_item == nullptr) {
1059    return nullptr;
1060  }
1061  const uint8_t* annotation =
1062      SearchEncodedAnnotation(*dex_file, annotation_item->annotation_, "value");
1063  if (annotation == nullptr) {
1064    return nullptr;
1065  }
1066  uint8_t header_byte = *(annotation++);
1067  if ((header_byte & DexFile::kDexAnnotationValueTypeMask) != DexFile::kDexAnnotationAnnotation) {
1068    return nullptr;
1069  }
1070  annotation = SearchEncodedAnnotation(*dex_file, annotation, method->GetName());
1071  if (annotation == nullptr) {
1072    return nullptr;
1073  }
1074  DexFile::AnnotationValue annotation_value;
1075  StackHandleScope<1> hs(Thread::Current());
1076  Handle<mirror::Class> return_type(hs.NewHandle(method->GetReturnType(true /* resolve */)));
1077  if (!ProcessAnnotationValue<false>(klass,
1078                                     &annotation,
1079                                     &annotation_value,
1080                                     return_type,
1081                                     DexFile::kAllObjects)) {
1082    return nullptr;
1083  }
1084  return annotation_value.value_.GetL();
1085}
1086
1087mirror::Object* GetAnnotationForMethod(ArtMethod* method, Handle<mirror::Class> annotation_class) {
1088  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1089  if (annotation_set == nullptr) {
1090    return nullptr;
1091  }
1092  return GetAnnotationObjectFromAnnotationSet(ClassData(method), annotation_set,
1093                                              DexFile::kDexVisibilityRuntime, annotation_class);
1094}
1095
1096mirror::ObjectArray<mirror::Object>* GetAnnotationsForMethod(ArtMethod* method) {
1097  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1098  return ProcessAnnotationSet(ClassData(method),
1099                              annotation_set,
1100                              DexFile::kDexVisibilityRuntime);
1101}
1102
1103mirror::ObjectArray<mirror::Class>* GetExceptionTypesForMethod(ArtMethod* method) {
1104  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1105  if (annotation_set == nullptr) {
1106    return nullptr;
1107  }
1108  return GetThrowsValue(ClassData(method), annotation_set);
1109}
1110
1111mirror::ObjectArray<mirror::Object>* GetParameterAnnotations(ArtMethod* method) {
1112  const DexFile* dex_file = method->GetDexFile();
1113  const DexFile::ParameterAnnotationsItem* parameter_annotations =
1114      FindAnnotationsItemForMethod(method);
1115  if (parameter_annotations == nullptr) {
1116    return nullptr;
1117  }
1118  const DexFile::AnnotationSetRefList* set_ref_list =
1119      dex_file->GetParameterAnnotationSetRefList(parameter_annotations);
1120  if (set_ref_list == nullptr) {
1121    return nullptr;
1122  }
1123  uint32_t size = set_ref_list->size_;
1124  return ProcessAnnotationSetRefList(ClassData(method), set_ref_list, size);
1125}
1126
1127mirror::Object* GetAnnotationForMethodParameter(ArtMethod* method,
1128                                                uint32_t parameter_idx,
1129                                                Handle<mirror::Class> annotation_class) {
1130  const DexFile* dex_file = method->GetDexFile();
1131  const DexFile::ParameterAnnotationsItem* parameter_annotations =
1132      FindAnnotationsItemForMethod(method);
1133  if (parameter_annotations == nullptr) {
1134    return nullptr;
1135  }
1136  const DexFile::AnnotationSetRefList* set_ref_list =
1137      dex_file->GetParameterAnnotationSetRefList(parameter_annotations);
1138  if (set_ref_list == nullptr) {
1139    return nullptr;
1140  }
1141  if (parameter_idx >= set_ref_list->size_) {
1142    return nullptr;
1143  }
1144  const DexFile::AnnotationSetRefItem* annotation_set_ref = &set_ref_list->list_[parameter_idx];
1145  const DexFile::AnnotationSetItem* annotation_set =
1146     dex_file->GetSetRefItemItem(annotation_set_ref);
1147
1148  return GetAnnotationObjectFromAnnotationSet(ClassData(method),
1149                                              annotation_set,
1150                                              DexFile::kDexVisibilityRuntime,
1151                                              annotation_class);
1152}
1153
1154bool GetParametersMetadataForMethod(ArtMethod* method,
1155                                    MutableHandle<mirror::ObjectArray<mirror::String>>* names,
1156                                    MutableHandle<mirror::IntArray>* access_flags) {
1157  const DexFile::AnnotationSetItem::AnnotationSetItem* annotation_set =
1158      FindAnnotationSetForMethod(method);
1159  if (annotation_set == nullptr) {
1160    return false;
1161  }
1162
1163  const DexFile* dex_file = method->GetDexFile();
1164  const DexFile::AnnotationItem* annotation_item =
1165      SearchAnnotationSet(*dex_file,
1166                          annotation_set,
1167                          "Ldalvik/annotation/MethodParameters;",
1168                          DexFile::kDexVisibilitySystem);
1169  if (annotation_item == nullptr) {
1170    return false;
1171  }
1172
1173  StackHandleScope<4> hs(Thread::Current());
1174
1175  // Extract the parameters' names String[].
1176  ObjPtr<mirror::Class> string_class = mirror::String::GetJavaLangString();
1177  Handle<mirror::Class> string_array_class(hs.NewHandle(
1178      Runtime::Current()->GetClassLinker()->FindArrayClass(Thread::Current(), &string_class)));
1179  if (UNLIKELY(string_array_class == nullptr)) {
1180    return false;
1181  }
1182
1183  ClassData data(method);
1184  Handle<mirror::Object> names_obj =
1185      hs.NewHandle(GetAnnotationValue(data,
1186                                      annotation_item,
1187                                      "names",
1188                                      string_array_class,
1189                                      DexFile::kDexAnnotationArray));
1190  if (names_obj == nullptr) {
1191    return false;
1192  }
1193
1194  // Extract the parameters' access flags int[].
1195  Handle<mirror::Class> int_array_class(hs.NewHandle(mirror::IntArray::GetArrayClass()));
1196  if (UNLIKELY(int_array_class == nullptr)) {
1197    return false;
1198  }
1199  Handle<mirror::Object> access_flags_obj =
1200      hs.NewHandle(GetAnnotationValue(data,
1201                                      annotation_item,
1202                                      "accessFlags",
1203                                      int_array_class,
1204                                      DexFile::kDexAnnotationArray));
1205  if (access_flags_obj == nullptr) {
1206    return false;
1207  }
1208
1209  names->Assign(names_obj.Get()->AsObjectArray<mirror::String>());
1210  access_flags->Assign(access_flags_obj.Get()->AsIntArray());
1211  return true;
1212}
1213
1214mirror::ObjectArray<mirror::String>* GetSignatureAnnotationForMethod(ArtMethod* method) {
1215  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1216  if (annotation_set == nullptr) {
1217    return nullptr;
1218  }
1219  return GetSignatureValue(ClassData(method), annotation_set);
1220}
1221
1222bool IsMethodAnnotationPresent(ArtMethod* method,
1223                               Handle<mirror::Class> annotation_class,
1224                               uint32_t visibility /* = DexFile::kDexVisibilityRuntime */,
1225                               bool lookup_in_resolved_boot_classes /* = false */) {
1226  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForMethod(method);
1227  if (annotation_set == nullptr) {
1228    return false;
1229  }
1230  const DexFile::AnnotationItem* annotation_item =
1231      GetAnnotationItemFromAnnotationSet(ClassData(method),
1232                                         annotation_set,
1233                                         visibility,
1234                                         annotation_class,
1235                                         lookup_in_resolved_boot_classes);
1236  return annotation_item != nullptr;
1237}
1238
1239mirror::Object* GetAnnotationForClass(Handle<mirror::Class> klass,
1240                                      Handle<mirror::Class> annotation_class) {
1241  ClassData data(klass);
1242  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1243  if (annotation_set == nullptr) {
1244    return nullptr;
1245  }
1246  return GetAnnotationObjectFromAnnotationSet(data,
1247                                              annotation_set,
1248                                              DexFile::kDexVisibilityRuntime,
1249                                              annotation_class);
1250}
1251
1252mirror::ObjectArray<mirror::Object>* GetAnnotationsForClass(Handle<mirror::Class> klass) {
1253  ClassData data(klass);
1254  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1255  return ProcessAnnotationSet(data, annotation_set, DexFile::kDexVisibilityRuntime);
1256}
1257
1258mirror::ObjectArray<mirror::Class>* GetDeclaredClasses(Handle<mirror::Class> klass) {
1259  ClassData data(klass);
1260  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1261  if (annotation_set == nullptr) {
1262    return nullptr;
1263  }
1264  const DexFile::AnnotationItem* annotation_item =
1265      SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/MemberClasses;",
1266                          DexFile::kDexVisibilitySystem);
1267  if (annotation_item == nullptr) {
1268    return nullptr;
1269  }
1270  StackHandleScope<1> hs(Thread::Current());
1271  ObjPtr<mirror::Class> class_class = mirror::Class::GetJavaLangClass();
1272  Handle<mirror::Class> class_array_class(hs.NewHandle(
1273      Runtime::Current()->GetClassLinker()->FindArrayClass(hs.Self(), &class_class)));
1274  if (class_array_class == nullptr) {
1275    return nullptr;
1276  }
1277  mirror::Object* obj =
1278      GetAnnotationValue(data, annotation_item, "value", class_array_class,
1279                         DexFile::kDexAnnotationArray);
1280  if (obj == nullptr) {
1281    return nullptr;
1282  }
1283  return obj->AsObjectArray<mirror::Class>();
1284}
1285
1286mirror::Class* GetDeclaringClass(Handle<mirror::Class> klass) {
1287  ClassData data(klass);
1288  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1289  if (annotation_set == nullptr) {
1290    return nullptr;
1291  }
1292  const DexFile::AnnotationItem* annotation_item =
1293      SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/EnclosingClass;",
1294                          DexFile::kDexVisibilitySystem);
1295  if (annotation_item == nullptr) {
1296    return nullptr;
1297  }
1298  mirror::Object* obj = GetAnnotationValue(data, annotation_item, "value",
1299                                           ScopedNullHandle<mirror::Class>(),
1300                                           DexFile::kDexAnnotationType);
1301  if (obj == nullptr) {
1302    return nullptr;
1303  }
1304  return obj->AsClass();
1305}
1306
1307mirror::Class* GetEnclosingClass(Handle<mirror::Class> klass) {
1308  mirror::Class* declaring_class = GetDeclaringClass(klass);
1309  if (declaring_class != nullptr) {
1310    return declaring_class;
1311  }
1312  ClassData data(klass);
1313  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1314  if (annotation_set == nullptr) {
1315    return nullptr;
1316  }
1317  const DexFile::AnnotationItem* annotation_item =
1318      SearchAnnotationSet(data.GetDexFile(),
1319                          annotation_set,
1320                          "Ldalvik/annotation/EnclosingMethod;",
1321                          DexFile::kDexVisibilitySystem);
1322  if (annotation_item == nullptr) {
1323    return nullptr;
1324  }
1325  const uint8_t* annotation =
1326      SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "value");
1327  if (annotation == nullptr) {
1328    return nullptr;
1329  }
1330  DexFile::AnnotationValue annotation_value;
1331  if (!ProcessAnnotationValue<false>(data,
1332                                     &annotation,
1333                                     &annotation_value,
1334                                     ScopedNullHandle<mirror::Class>(),
1335                                     DexFile::kAllRaw)) {
1336    return nullptr;
1337  }
1338  if (annotation_value.type_ != DexFile::kDexAnnotationMethod) {
1339    return nullptr;
1340  }
1341  StackHandleScope<2> hs(Thread::Current());
1342  ArtMethod* method = Runtime::Current()->GetClassLinker()->ResolveMethodWithoutInvokeType(
1343      data.GetDexFile(),
1344      annotation_value.value_.GetI(),
1345      hs.NewHandle(data.GetDexCache()),
1346      hs.NewHandle(data.GetClassLoader()));
1347  if (method == nullptr) {
1348    return nullptr;
1349  }
1350  return method->GetDeclaringClass();
1351}
1352
1353mirror::Object* GetEnclosingMethod(Handle<mirror::Class> klass) {
1354  ClassData data(klass);
1355  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1356  if (annotation_set == nullptr) {
1357    return nullptr;
1358  }
1359  const DexFile::AnnotationItem* annotation_item =
1360      SearchAnnotationSet(data.GetDexFile(),
1361                          annotation_set,
1362                          "Ldalvik/annotation/EnclosingMethod;",
1363                          DexFile::kDexVisibilitySystem);
1364  if (annotation_item == nullptr) {
1365    return nullptr;
1366  }
1367  return GetAnnotationValue(data, annotation_item, "value", ScopedNullHandle<mirror::Class>(),
1368      DexFile::kDexAnnotationMethod);
1369}
1370
1371bool GetInnerClass(Handle<mirror::Class> klass, mirror::String** name) {
1372  ClassData data(klass);
1373  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1374  if (annotation_set == nullptr) {
1375    return false;
1376  }
1377  const DexFile::AnnotationItem* annotation_item = SearchAnnotationSet(
1378      data.GetDexFile(),
1379      annotation_set,
1380      "Ldalvik/annotation/InnerClass;",
1381      DexFile::kDexVisibilitySystem);
1382  if (annotation_item == nullptr) {
1383    return false;
1384  }
1385  const uint8_t* annotation =
1386      SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "name");
1387  if (annotation == nullptr) {
1388    return false;
1389  }
1390  DexFile::AnnotationValue annotation_value;
1391  if (!ProcessAnnotationValue<false>(data,
1392                                     &annotation,
1393                                     &annotation_value,
1394                                     ScopedNullHandle<mirror::Class>(),
1395                                     DexFile::kAllObjects)) {
1396    return false;
1397  }
1398  if (annotation_value.type_ != DexFile::kDexAnnotationNull &&
1399      annotation_value.type_ != DexFile::kDexAnnotationString) {
1400    return false;
1401  }
1402  *name = down_cast<mirror::String*>(annotation_value.value_.GetL());
1403  return true;
1404}
1405
1406bool GetInnerClassFlags(Handle<mirror::Class> klass, uint32_t* flags) {
1407  ClassData data(klass);
1408  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1409  if (annotation_set == nullptr) {
1410    return false;
1411  }
1412  const DexFile::AnnotationItem* annotation_item =
1413      SearchAnnotationSet(data.GetDexFile(), annotation_set, "Ldalvik/annotation/InnerClass;",
1414                          DexFile::kDexVisibilitySystem);
1415  if (annotation_item == nullptr) {
1416    return false;
1417  }
1418  const uint8_t* annotation =
1419      SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "accessFlags");
1420  if (annotation == nullptr) {
1421    return false;
1422  }
1423  DexFile::AnnotationValue annotation_value;
1424  if (!ProcessAnnotationValue<false>(data,
1425                                     &annotation,
1426                                     &annotation_value,
1427                                     ScopedNullHandle<mirror::Class>(),
1428                                     DexFile::kAllRaw)) {
1429    return false;
1430  }
1431  if (annotation_value.type_ != DexFile::kDexAnnotationInt) {
1432    return false;
1433  }
1434  *flags = annotation_value.value_.GetI();
1435  return true;
1436}
1437
1438mirror::ObjectArray<mirror::String>* GetSignatureAnnotationForClass(Handle<mirror::Class> klass) {
1439  ClassData data(klass);
1440  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1441  if (annotation_set == nullptr) {
1442    return nullptr;
1443  }
1444  return GetSignatureValue(data, annotation_set);
1445}
1446
1447const char* GetSourceDebugExtension(Handle<mirror::Class> klass) {
1448  // Before instantiating ClassData, check that klass has a DexCache
1449  // assigned.  The ClassData constructor indirectly dereferences it
1450  // when calling klass->GetDexFile().
1451  if (klass->GetDexCache() == nullptr) {
1452    DCHECK(klass->IsPrimitive() || klass->IsArrayClass());
1453    return nullptr;
1454  }
1455
1456  ClassData data(klass);
1457  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1458  if (annotation_set == nullptr) {
1459    return nullptr;
1460  }
1461
1462  const DexFile::AnnotationItem* annotation_item = SearchAnnotationSet(
1463      data.GetDexFile(),
1464      annotation_set,
1465      "Ldalvik/annotation/SourceDebugExtension;",
1466      DexFile::kDexVisibilitySystem);
1467  if (annotation_item == nullptr) {
1468    return nullptr;
1469  }
1470
1471  const uint8_t* annotation =
1472      SearchEncodedAnnotation(data.GetDexFile(), annotation_item->annotation_, "value");
1473  if (annotation == nullptr) {
1474    return nullptr;
1475  }
1476  DexFile::AnnotationValue annotation_value;
1477  if (!ProcessAnnotationValue<false>(data,
1478                                     &annotation,
1479                                     &annotation_value,
1480                                     ScopedNullHandle<mirror::Class>(),
1481                                     DexFile::kAllRaw)) {
1482    return nullptr;
1483  }
1484  if (annotation_value.type_ != DexFile::kDexAnnotationString) {
1485    return nullptr;
1486  }
1487  dex::StringIndex index(static_cast<uint32_t>(annotation_value.value_.GetI()));
1488  return data.GetDexFile().StringDataByIdx(index);
1489}
1490
1491bool IsClassAnnotationPresent(Handle<mirror::Class> klass, Handle<mirror::Class> annotation_class) {
1492  ClassData data(klass);
1493  const DexFile::AnnotationSetItem* annotation_set = FindAnnotationSetForClass(data);
1494  if (annotation_set == nullptr) {
1495    return false;
1496  }
1497  const DexFile::AnnotationItem* annotation_item = GetAnnotationItemFromAnnotationSet(
1498      data, annotation_set, DexFile::kDexVisibilityRuntime, annotation_class);
1499  return annotation_item != nullptr;
1500}
1501
1502int32_t GetLineNumFromPC(const DexFile* dex_file, ArtMethod* method, uint32_t rel_pc) {
1503  // For native method, lineno should be -2 to indicate it is native. Note that
1504  // "line number == -2" is how libcore tells from StackTraceElement.
1505  if (method->GetCodeItemOffset() == 0) {
1506    return -2;
1507  }
1508
1509  const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1510  DCHECK(code_item != nullptr) << method->PrettyMethod() << " " << dex_file->GetLocation();
1511
1512  // A method with no line number info should return -1
1513  DexFile::LineNumFromPcContext context(rel_pc, -1);
1514  dex_file->DecodeDebugPositionInfo(code_item, DexFile::LineNumForPcCb, &context);
1515  return context.line_num_;
1516}
1517
1518template<bool kTransactionActive>
1519void RuntimeEncodedStaticFieldValueIterator::ReadValueToField(ArtField* field) const {
1520  DCHECK(dex_cache_ != nullptr);
1521  DCHECK(class_loader_ != nullptr);
1522  switch (type_) {
1523    case kBoolean: field->SetBoolean<kTransactionActive>(field->GetDeclaringClass(), jval_.z);
1524        break;
1525    case kByte:    field->SetByte<kTransactionActive>(field->GetDeclaringClass(), jval_.b); break;
1526    case kShort:   field->SetShort<kTransactionActive>(field->GetDeclaringClass(), jval_.s); break;
1527    case kChar:    field->SetChar<kTransactionActive>(field->GetDeclaringClass(), jval_.c); break;
1528    case kInt:     field->SetInt<kTransactionActive>(field->GetDeclaringClass(), jval_.i); break;
1529    case kLong:    field->SetLong<kTransactionActive>(field->GetDeclaringClass(), jval_.j); break;
1530    case kFloat:   field->SetFloat<kTransactionActive>(field->GetDeclaringClass(), jval_.f); break;
1531    case kDouble:  field->SetDouble<kTransactionActive>(field->GetDeclaringClass(), jval_.d); break;
1532    case kNull:    field->SetObject<kTransactionActive>(field->GetDeclaringClass(), nullptr); break;
1533    case kString: {
1534      mirror::String* resolved = linker_->ResolveString(dex_file_,
1535                                                        dex::StringIndex(jval_.i),
1536                                                        *dex_cache_);
1537      field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
1538      break;
1539    }
1540    case kType: {
1541      mirror::Class* resolved = linker_->ResolveType(dex_file_,
1542                                                     dex::TypeIndex(jval_.i),
1543                                                     *dex_cache_,
1544                                                     *class_loader_);
1545      field->SetObject<kTransactionActive>(field->GetDeclaringClass(), resolved);
1546      break;
1547    }
1548    default: UNIMPLEMENTED(FATAL) << ": type " << type_;
1549  }
1550}
1551template
1552void RuntimeEncodedStaticFieldValueIterator::ReadValueToField<true>(ArtField* field) const;
1553template
1554void RuntimeEncodedStaticFieldValueIterator::ReadValueToField<false>(ArtField* field) const;
1555
1556}  // namespace annotations
1557
1558}  // namespace art
1559