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