• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 "hidden_api.h"
18 
19 #include <atomic>
20 
21 #include "art_field-inl.h"
22 #include "art_method-inl.h"
23 #include "base/dumpable.h"
24 #include "base/file_utils.h"
25 #include "class_root-inl.h"
26 #include "compat_framework.h"
27 #include "dex/class_accessor-inl.h"
28 #include "dex/dex_file_loader.h"
29 #include "mirror/class_ext.h"
30 #include "mirror/proxy.h"
31 #include "nativehelper/scoped_local_ref.h"
32 #include "oat_file.h"
33 #include "scoped_thread_state_change.h"
34 #include "stack.h"
35 #include "thread-inl.h"
36 #include "well_known_classes.h"
37 
38 namespace art {
39 namespace hiddenapi {
40 
41 // Should be the same as dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_P_HIDDEN_APIS,
42 // dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_Q_HIDDEN_APIS, and
43 // dalvik.system.VMRuntime.ALLOW_TEST_API_ACCESS.
44 // Corresponds to bug ids.
45 static constexpr uint64_t kHideMaxtargetsdkPHiddenApis = 149997251;
46 static constexpr uint64_t kHideMaxtargetsdkQHiddenApis = 149994052;
47 static constexpr uint64_t kAllowTestApiAccess = 166236554;
48 
49 static constexpr uint64_t kMaxLogWarnings = 100;
50 
51 // Should be the same as dalvik.system.VMRuntime.PREVENT_META_REFLECTION_BLOCKLIST_ACCESS.
52 // Corresponds to a bug id.
53 static constexpr uint64_t kPreventMetaReflectionBlocklistAccess = 142365358;
54 
55 // Set to true if we should always print a warning in logcat for all hidden API accesses, not just
56 // conditionally and unconditionally blocked. This can be set to true for developer preview / beta
57 // builds, but should be false for public release builds.
58 // Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
59 // as it affects whether or not we warn for unsupported APIs that have been added to the exemptions
60 // list.
61 static constexpr bool kLogAllAccesses = false;
62 
63 // Exemptions for logcat warning. Following signatures do not produce a warning as app developers
64 // should not be alerted on the usage of these unsupported APIs. See b/154851649.
65 static const std::vector<std::string> kWarningExemptions = {
66     "Ljava/nio/Buffer;",
67     "Llibcore/io/Memory;",
68     "Lsun/misc/Unsafe;",
69 };
70 
operator <<(std::ostream & os,AccessMethod value)71 static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
72   switch (value) {
73     case AccessMethod::kNone:
74       LOG(FATAL) << "Internal access to hidden API should not be logged";
75       UNREACHABLE();
76     case AccessMethod::kReflection:
77       os << "reflection";
78       break;
79     case AccessMethod::kJNI:
80       os << "JNI";
81       break;
82     case AccessMethod::kLinking:
83       os << "linking";
84       break;
85   }
86   return os;
87 }
88 
operator <<(std::ostream & os,const AccessContext & value)89 static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
90     REQUIRES_SHARED(Locks::mutator_lock_) {
91   if (!value.GetClass().IsNull()) {
92     std::string tmp;
93     os << value.GetClass()->GetDescriptor(&tmp);
94   } else if (value.GetDexFile() != nullptr) {
95     os << value.GetDexFile()->GetLocation();
96   } else {
97     os << "<unknown_caller>";
98   }
99   return os;
100 }
101 
DetermineDomainFromLocation(const std::string & dex_location,ObjPtr<mirror::ClassLoader> class_loader)102 static Domain DetermineDomainFromLocation(const std::string& dex_location,
103                                           ObjPtr<mirror::ClassLoader> class_loader) {
104   // If running with APEX, check `path` against known APEX locations.
105   // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
106   // is set to "/system".
107   if (ArtModuleRootDistinctFromAndroidRoot()) {
108     if (LocationIsOnArtModule(dex_location) || LocationIsOnConscryptModule(dex_location) ||
109         LocationIsOnI18nModule(dex_location)) {
110       return Domain::kCorePlatform;
111     }
112 
113     if (LocationIsOnApex(dex_location)) {
114       return Domain::kPlatform;
115     }
116   }
117 
118   if (LocationIsOnSystemFramework(dex_location)) {
119     return Domain::kPlatform;
120   }
121 
122   if (LocationIsOnSystemExtFramework(dex_location)) {
123     return Domain::kPlatform;
124   }
125 
126   if (class_loader.IsNull()) {
127     if (kIsTargetBuild && !kIsTargetLinux) {
128       // This is unexpected only when running on Android.
129       LOG(WARNING) << "DexFile " << dex_location
130                    << " is in boot class path but is not in a known location";
131     }
132     return Domain::kPlatform;
133   }
134 
135   return Domain::kApplication;
136 }
137 
InitializeDexFileDomain(const DexFile & dex_file,ObjPtr<mirror::ClassLoader> class_loader)138 void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
139   Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
140 
141   // Assign the domain unless a more permissive domain has already been assigned.
142   // This may happen when DexFile is initialized as trusted.
143   if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
144     dex_file.SetHiddenapiDomain(dex_domain);
145   }
146 }
147 
InitializeCorePlatformApiPrivateFields()148 void InitializeCorePlatformApiPrivateFields() {
149   // The following fields in WellKnownClasses correspond to private fields in the Core Platform
150   // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
151   ArtField* private_core_platform_api_fields[] = {
152       WellKnownClasses::java_io_FileDescriptor_descriptor,
153       WellKnownClasses::java_nio_Buffer_address,
154       WellKnownClasses::java_nio_Buffer_elementSizeShift,
155       WellKnownClasses::java_nio_Buffer_limit,
156       WellKnownClasses::java_nio_Buffer_position,
157   };
158 
159   ScopedObjectAccess soa(Thread::Current());
160   for (ArtField* field : private_core_platform_api_fields) {
161     const uint32_t access_flags = field->GetAccessFlags();
162     uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
163     DCHECK(new_access_flags != access_flags);
164     field->SetAccessFlags(new_access_flags);
165   }
166 }
167 
GetReflectionCallerAccessContext(Thread * self)168 hiddenapi::AccessContext GetReflectionCallerAccessContext(Thread* self)
169     REQUIRES_SHARED(Locks::mutator_lock_) {
170   // Walk the stack and find the first frame not from java.lang.Class,
171   // java.lang.invoke or java.lang.reflect. This is very expensive.
172   // Save this till the last.
173   struct FirstExternalCallerVisitor : public StackVisitor {
174     explicit FirstExternalCallerVisitor(Thread* thread)
175         : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
176           caller(nullptr) {}
177 
178     bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
179       ArtMethod* m = GetMethod();
180       if (m == nullptr) {
181         // Attached native thread. Assume this is *not* boot class path.
182         caller = nullptr;
183         return false;
184       } else if (m->IsRuntimeMethod()) {
185         // Internal runtime method, continue walking the stack.
186         return true;
187       }
188 
189       ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
190       if (declaring_class->IsBootStrapClassLoaded()) {
191         if (declaring_class->IsClassClass()) {
192           return true;
193         }
194         // Check classes in the java.lang.invoke package. At the time of writing, the
195         // classes of interest are MethodHandles and MethodHandles.Lookup, but this
196         // is subject to change so conservatively cover the entire package.
197         // NB Static initializers within java.lang.invoke are permitted and do not
198         // need further stack inspection.
199         ObjPtr<mirror::Class> lookup_class = GetClassRoot<mirror::MethodHandlesLookup>();
200         if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) &&
201             !m->IsClassInitializer()) {
202           return true;
203         }
204         // Check for classes in the java.lang.reflect package, except for java.lang.reflect.Proxy.
205         // java.lang.reflect.Proxy does its own hidden api checks (https://r.android.com/915496),
206         // and walking over this frame would cause a null pointer dereference
207         // (e.g. in 691-hiddenapi-proxy).
208         ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>();
209         CompatFramework& compat_framework = Runtime::Current()->GetCompatFramework();
210         if (declaring_class->IsInSamePackage(proxy_class) && declaring_class != proxy_class) {
211           if (compat_framework.IsChangeEnabled(kPreventMetaReflectionBlocklistAccess)) {
212             return true;
213           }
214         }
215       }
216 
217       caller = m;
218       return false;
219     }
220 
221     ArtMethod* caller;
222   };
223 
224   FirstExternalCallerVisitor visitor(self);
225   visitor.WalkStack();
226 
227   // Construct AccessContext from the calling class found on the stack.
228   // If the calling class cannot be determined, e.g. unattached threads,
229   // we conservatively assume the caller is trusted.
230   ObjPtr<mirror::Class> caller =
231       (visitor.caller == nullptr) ? nullptr : visitor.caller->GetDeclaringClass();
232   return caller.IsNull() ? AccessContext(/* is_trusted= */ true) : AccessContext(caller);
233 }
234 
235 namespace detail {
236 
237 // Do not change the values of items in this enum, as they are written to the
238 // event log for offline analysis. Any changes will interfere with that analysis.
239 enum AccessContextFlags {
240   // Accessed member is a field if this bit is set, else a method
241   kMemberIsField = 1 << 0,
242   // Indicates if access was denied to the member, instead of just printing a warning.
243   kAccessDenied = 1 << 1,
244 };
245 
MemberSignature(ArtField * field)246 MemberSignature::MemberSignature(ArtField* field) {
247   class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
248   member_name_ = field->GetName();
249   type_signature_ = field->GetTypeDescriptor();
250   type_ = kField;
251 }
252 
MemberSignature(ArtMethod * method)253 MemberSignature::MemberSignature(ArtMethod* method) {
254   DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
255       << "Caller should have replaced proxy method with interface method";
256   class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
257   member_name_ = method->GetName();
258   type_signature_ = method->GetSignature().ToString();
259   type_ = kMethod;
260 }
261 
MemberSignature(const ClassAccessor::Field & field)262 MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
263   const DexFile& dex_file = field.GetDexFile();
264   const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
265   class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
266   member_name_ = dex_file.GetFieldName(field_id);
267   type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
268   type_ = kField;
269 }
270 
MemberSignature(const ClassAccessor::Method & method)271 MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
272   const DexFile& dex_file = method.GetDexFile();
273   const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
274   class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
275   member_name_ = dex_file.GetMethodName(method_id);
276   type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
277   type_ = kMethod;
278 }
279 
GetSignatureParts() const280 inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
281   if (type_ == kField) {
282     return {class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str()};
283   } else {
284     DCHECK_EQ(type_, kMethod);
285     return {class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str()};
286   }
287 }
288 
DoesPrefixMatch(const std::string & prefix) const289 bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
290   size_t pos = 0;
291   for (const char* part : GetSignatureParts()) {
292     size_t count = std::min(prefix.length() - pos, strlen(part));
293     if (prefix.compare(pos, count, part, 0, count) == 0) {
294       pos += count;
295     } else {
296       return false;
297     }
298   }
299   // We have a complete match if all parts match (we exit the loop without
300   // returning) AND we've matched the whole prefix.
301   return pos == prefix.length();
302 }
303 
DoesPrefixMatchAny(const std::vector<std::string> & exemptions)304 bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
305   for (const std::string& exemption : exemptions) {
306     if (DoesPrefixMatch(exemption)) {
307       return true;
308     }
309   }
310   return false;
311 }
312 
Dump(std::ostream & os) const313 void MemberSignature::Dump(std::ostream& os) const {
314   for (const char* part : GetSignatureParts()) {
315     os << part;
316   }
317 }
318 
WarnAboutAccess(AccessMethod access_method,hiddenapi::ApiList list,bool access_denied)319 void MemberSignature::WarnAboutAccess(AccessMethod access_method,
320                                       hiddenapi::ApiList list,
321                                       bool access_denied) {
322   static std::atomic<uint64_t> log_warning_count_ = 0;
323   if (log_warning_count_ > kMaxLogWarnings) {
324     return;
325   }
326   LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
327                << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
328                << (access_denied ? ", denied)" : ", allowed)");
329   if (access_denied && list.IsTestApi()) {
330     // see b/177047045 for more details about test api access getting denied
331     LOG(WARNING) << "If this is a platform test consider enabling "
332                  << "VMRuntime.ALLOW_TEST_API_ACCESS change id for this package.";
333   }
334   if (log_warning_count_ >= kMaxLogWarnings) {
335     LOG(WARNING) << "Reached maximum number of hidden api access warnings.";
336   }
337   ++log_warning_count_;
338 }
339 
Equals(const MemberSignature & other)340 bool MemberSignature::Equals(const MemberSignature& other) {
341   return type_ == other.type_ && class_name_ == other.class_name_ &&
342          member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
343 }
344 
MemberNameAndTypeMatch(const MemberSignature & other)345 bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
346   return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
347 }
348 
LogAccessToEventLog(uint32_t sampled_value,AccessMethod access_method,bool access_denied)349 void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
350                                           AccessMethod access_method,
351                                           bool access_denied) {
352 #ifdef ART_TARGET_ANDROID
353   if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
354     // Linking warnings come from static analysis/compilation of the bytecode
355     // and can contain false positives (i.e. code that is never run). We choose
356     // not to log these in the event log.
357     // None does not correspond to actual access, so should also be ignored.
358     return;
359   }
360   Runtime* runtime = Runtime::Current();
361   if (runtime->IsAotCompiler()) {
362     return;
363   }
364 
365   const std::string& package_name = runtime->GetProcessPackageName();
366   std::ostringstream signature_str;
367   Dump(signature_str);
368 
369   ScopedObjectAccess soa(Thread::Current());
370   StackHandleScope<2u> hs(soa.Self());
371   Handle<mirror::String> package_str =
372       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), package_name.c_str()));
373   if (soa.Self()->IsExceptionPending()) {
374     soa.Self()->ClearException();
375     LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
376   }
377   Handle<mirror::String> signature_jstr =
378       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), signature_str.str().c_str()));
379   if (soa.Self()->IsExceptionPending()) {
380     soa.Self()->ClearException();
381     LOG(ERROR) << "Unable to allocate string for hidden api method signature";
382   }
383   WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed
384       ->InvokeStatic<'V', 'I', 'L', 'L', 'I', 'Z'>(soa.Self(),
385                                                    static_cast<jint>(sampled_value),
386                                                    package_str.Get(),
387                                                    signature_jstr.Get(),
388                                                    static_cast<jint>(access_method),
389                                                    access_denied);
390   if (soa.Self()->IsExceptionPending()) {
391     soa.Self()->ClearException();
392     LOG(ERROR) << "Unable to report hidden api usage";
393   }
394 #else
395   UNUSED(sampled_value);
396   UNUSED(access_method);
397   UNUSED(access_denied);
398 #endif
399 }
400 
NotifyHiddenApiListener(AccessMethod access_method)401 void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
402   if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
403     // We can only up-call into Java during reflection and JNI down-calls.
404     return;
405   }
406 
407   Runtime* runtime = Runtime::Current();
408   if (!runtime->IsAotCompiler()) {
409     ScopedObjectAccess soa(Thread::Current());
410     StackHandleScope<2u> hs(soa.Self());
411 
412     ArtField* consumer_field = WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer;
413     DCHECK(consumer_field->GetDeclaringClass()->IsInitialized());
414     Handle<mirror::Object> consumer_object =
415         hs.NewHandle(consumer_field->GetObject(consumer_field->GetDeclaringClass()));
416 
417     // If the consumer is non-null, we call back to it to let it know that we
418     // have encountered an API that's in one of our lists.
419     if (consumer_object != nullptr) {
420       std::ostringstream member_signature_str;
421       Dump(member_signature_str);
422 
423       Handle<mirror::String> signature_str = hs.NewHandle(
424           mirror::String::AllocFromModifiedUtf8(soa.Self(), member_signature_str.str().c_str()));
425       // FIXME: Handle OOME. For now, crash immediatelly (do not continue with a pending exception).
426       CHECK(signature_str != nullptr);
427 
428       // Call through to Consumer.accept(String memberSignature);
429       WellKnownClasses::java_util_function_Consumer_accept->InvokeInterface<'V', 'L'>(
430           soa.Self(), consumer_object.Get(), signature_str.Get());
431     }
432   }
433 }
434 
CanUpdateRuntimeFlags(ArtField *)435 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) { return true; }
436 
CanUpdateRuntimeFlags(ArtMethod * method)437 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
438   return !method->IsIntrinsic();
439 }
440 
441 template <typename T>
MaybeUpdateAccessFlags(Runtime * runtime,T * member,uint32_t flag)442 static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
443     REQUIRES_SHARED(Locks::mutator_lock_) {
444   // Update the access flags unless:
445   // (a) `member` is an intrinsic
446   // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
447   // (c) deduping warnings has been explicitly switched off.
448   if (CanUpdateRuntimeFlags(member) && !runtime->IsAotCompiler() &&
449       runtime->ShouldDedupeHiddenApiWarnings()) {
450     member->SetAccessFlags(member->GetAccessFlags() | flag);
451   }
452 }
453 
GetMemberDexIndex(ArtField * field)454 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
455   return field->GetDexFieldIndex();
456 }
457 
GetMemberDexIndex(ArtMethod * method)458 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
459     REQUIRES_SHARED(Locks::mutator_lock_) {
460   // Use the non-obsolete method to avoid DexFile mismatch between
461   // the method index and the declaring class.
462   return method->GetNonObsoleteMethod()->GetDexMethodIndex();
463 }
464 
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Field &)> & fn_visit)465 static void VisitMembers(const DexFile& dex_file,
466                          const dex::ClassDef& class_def,
467                          const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
468   ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
469   accessor.VisitFields(fn_visit, fn_visit);
470 }
471 
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Method &)> & fn_visit)472 static void VisitMembers(const DexFile& dex_file,
473                          const dex::ClassDef& class_def,
474                          const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
475   ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
476   accessor.VisitMethods(fn_visit, fn_visit);
477 }
478 
479 template <typename T>
GetDexFlags(T * member)480 uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
481   static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
482   constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
483   using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
484                                                  ClassAccessor::Field,
485                                                  ClassAccessor::Method>::type;
486 
487   ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
488   DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
489 
490   ApiList flags;
491   DCHECK(!flags.IsValid());
492 
493   // Check if the declaring class has ClassExt allocated. If it does, check if
494   // the pre-JVMTI redefine dex file has been set to determine if the declaring
495   // class has been JVMTI-redefined.
496   ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
497   const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
498   if (LIKELY(original_dex == nullptr)) {
499     // Class is not redefined. Find the class def, iterate over its members and
500     // find the entry corresponding to this `member`.
501     const dex::ClassDef* class_def = declaring_class->GetClassDef();
502     if (class_def == nullptr) {
503       // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
504       DCHECK(declaring_class->IsProxyClass())
505           << "Only proxy classes are expected not to have a class def";
506       DCHECK(kMemberIsField)
507           << "Interface methods should be inspected instead of proxy class methods";
508       flags = ApiList::Unsupported();
509     } else {
510       uint32_t member_index = GetMemberDexIndex(member);
511       auto fn_visit = [&](const AccessorType& dex_member) {
512         if (dex_member.GetIndex() == member_index) {
513           flags = ApiList(dex_member.GetHiddenapiFlags());
514         }
515       };
516       VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
517     }
518   } else {
519     // Class was redefined using JVMTI. We have a pointer to the original dex file
520     // and the class def index of this class in that dex file, but the field/method
521     // indices are lost. Iterate over all members of the class def and find the one
522     // corresponding to this `member` by name and type string comparison.
523     // This is obviously very slow, but it is only used when non-exempt code tries
524     // to access a hidden member of a JVMTI-redefined class.
525     uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
526     DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
527     const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
528     MemberSignature member_signature(member);
529     auto fn_visit = [&](const AccessorType& dex_member) {
530       MemberSignature cur_signature(dex_member);
531       if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
532         DCHECK(member_signature.Equals(cur_signature));
533         flags = ApiList(dex_member.GetHiddenapiFlags());
534       }
535     };
536     VisitMembers(*original_dex, original_class_def, fn_visit);
537   }
538 
539   CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
540                          << Dumpable<MemberSignature>(MemberSignature(member));
541   return flags.GetDexFlags();
542 }
543 
544 template <typename T>
HandleCorePlatformApiViolation(T * member,const AccessContext & caller_context,AccessMethod access_method,EnforcementPolicy policy)545 bool HandleCorePlatformApiViolation(T* member,
546                                     const AccessContext& caller_context,
547                                     AccessMethod access_method,
548                                     EnforcementPolicy policy) {
549   DCHECK(policy != EnforcementPolicy::kDisabled)
550       << "Should never enter this function when access checks are completely disabled";
551 
552   if (access_method != AccessMethod::kNone) {
553     LOG(WARNING) << "Core platform API violation: "
554                  << Dumpable<MemberSignature>(MemberSignature(member)) << " from " << caller_context
555                  << " using " << access_method;
556 
557     // If policy is set to just warn, add kAccCorePlatformApi to access flags of
558     // `member` to avoid reporting the violation again next time.
559     if (policy == EnforcementPolicy::kJustWarn) {
560       MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
561     }
562   }
563 
564   // Deny access if enforcement is enabled.
565   return policy == EnforcementPolicy::kEnabled;
566 }
567 
568 template <typename T>
ShouldDenyAccessToMemberImpl(T * member,ApiList api_list,AccessMethod access_method)569 bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
570   DCHECK(member != nullptr);
571   Runtime* runtime = Runtime::Current();
572   CompatFramework& compatFramework = runtime->GetCompatFramework();
573 
574   EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
575   DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
576       << "Should never enter this function when access checks are completely disabled";
577 
578   MemberSignature member_signature(member);
579 
580   // Check for an exemption first. Exempted APIs are treated as SDK.
581   if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
582     // Avoid re-examining the exemption list next time.
583     // Note this results in no warning for the member, which seems like what one would expect.
584     // Exemptions effectively adds new members to the public API list.
585     MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
586     return false;
587   }
588 
589   EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
590 
591   bool deny_access = false;
592   if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
593     if (api_list.IsTestApi() && (testApiPolicy == EnforcementPolicy::kDisabled ||
594                                  compatFramework.IsChangeEnabled(kAllowTestApiAccess))) {
595       deny_access = false;
596     } else {
597       switch (api_list.GetMaxAllowedSdkVersion()) {
598         case SdkVersion::kP:
599           deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkPHiddenApis);
600           break;
601         case SdkVersion::kQ:
602           deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkQHiddenApis);
603           break;
604         default:
605           deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
606                                                    api_list.GetMaxAllowedSdkVersion());
607       }
608     }
609   }
610 
611   if (access_method != AccessMethod::kNone) {
612     // Warn if blocked signature is being accessed or it is not exempted.
613     if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
614       // Print a log message with information about this class member access.
615       // We do this if we're about to deny access, or the app is debuggable.
616       if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
617         member_signature.WarnAboutAccess(access_method, api_list, deny_access);
618       }
619 
620       // If there is a StrictMode listener, notify it about this violation.
621       member_signature.NotifyHiddenApiListener(access_method);
622     }
623 
624     // If event log sampling is enabled, report this violation.
625     if (kIsTargetBuild && !kIsTargetLinux) {
626       uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
627       // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
628       static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
629       if (eventLogSampleRate != 0) {
630         const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
631         if (sampled_value < eventLogSampleRate) {
632           member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
633         }
634       }
635     }
636 
637     // If this access was not denied, flag member as SDK and skip
638     // the warning the next time the member is accessed. Don't update for
639     // non-debuggable apps as this has a memory cost.
640     if (!deny_access && runtime->IsJavaDebuggable()) {
641       MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
642     }
643   }
644 
645   return deny_access;
646 }
647 
648 // Need to instantiate these.
649 template uint32_t GetDexFlags<ArtField>(ArtField* member);
650 template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
651 template bool HandleCorePlatformApiViolation(ArtField* member,
652                                              const AccessContext& caller_context,
653                                              AccessMethod access_method,
654                                              EnforcementPolicy policy);
655 template bool HandleCorePlatformApiViolation(ArtMethod* member,
656                                              const AccessContext& caller_context,
657                                              AccessMethod access_method,
658                                              EnforcementPolicy policy);
659 template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
660                                                      ApiList api_list,
661                                                      AccessMethod access_method);
662 template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
663                                                       ApiList api_list,
664                                                       AccessMethod access_method);
665 }  // namespace detail
666 
667 template <typename T>
ShouldDenyAccessToMember(T * member,const std::function<AccessContext ()> & fn_get_access_context,AccessMethod access_method)668 bool ShouldDenyAccessToMember(T* member,
669                               const std::function<AccessContext()>& fn_get_access_context,
670                               AccessMethod access_method) {
671   DCHECK(member != nullptr);
672 
673   // First check if we have an explicit sdk checker installed that should be used to
674   // verify access. If so, make the decision based on it.
675   //
676   // This is used during off-device AOT compilation which may want to generate verification
677   // metadata only for a specific list of public SDKs. Note that the check here is made
678   // based on descriptor equality and it's aim to further restrict a symbol that would
679   // otherwise be resolved.
680   //
681   // The check only applies to boot classpaths dex files.
682   Runtime* runtime = Runtime::Current();
683   if (UNLIKELY(runtime->IsAotCompiler())) {
684     if (member->GetDeclaringClass()->IsBootStrapClassLoaded() &&
685         runtime->GetClassLinker()->DenyAccessBasedOnPublicSdk(member)) {
686       return true;
687     }
688   }
689 
690   // Get the runtime flags encoded in member's access flags.
691   // Note: this works for proxy methods because they inherit access flags from their
692   // respective interface methods.
693   const uint32_t runtime_flags = GetRuntimeFlags(member);
694 
695   // Exit early if member is public API. This flag is also set for non-boot class
696   // path fields/methods.
697   if ((runtime_flags & kAccPublicApi) != 0) {
698     return false;
699   }
700 
701   // Determine which domain the caller and callee belong to.
702   // This can be *very* expensive. This is why ShouldDenyAccessToMember
703   // should not be called on every individual access.
704   const AccessContext caller_context = fn_get_access_context();
705   const AccessContext callee_context(member->GetDeclaringClass());
706 
707   // Non-boot classpath callers should have exited early.
708   DCHECK(!callee_context.IsApplicationDomain());
709 
710   // Check if the caller is always allowed to access members in the callee context.
711   if (caller_context.CanAlwaysAccess(callee_context)) {
712     return false;
713   }
714 
715   // Check if this is platform accessing core platform. We may warn if `member` is
716   // not part of core platform API.
717   switch (caller_context.GetDomain()) {
718     case Domain::kApplication: {
719       DCHECK(!callee_context.IsApplicationDomain());
720 
721       // Exit early if access checks are completely disabled.
722       EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
723       if (policy == EnforcementPolicy::kDisabled) {
724         return false;
725       }
726 
727       // If this is a proxy method, look at the interface method instead.
728       member = detail::GetInterfaceMemberIfProxy(member);
729 
730       // Decode hidden API access flags from the dex file.
731       // This is an O(N) operation scaling with the number of fields/methods
732       // in the class. Only do this on slow path and only do it once.
733       ApiList api_list(detail::GetDexFlags(member));
734       DCHECK(api_list.IsValid());
735 
736       // Member is hidden and caller is not exempted. Enter slow path.
737       return detail::ShouldDenyAccessToMemberImpl(member, api_list, access_method);
738     }
739 
740     case Domain::kPlatform: {
741       DCHECK(callee_context.GetDomain() == Domain::kCorePlatform);
742 
743       // Member is part of core platform API. Accessing it is allowed.
744       if ((runtime_flags & kAccCorePlatformApi) != 0) {
745         return false;
746       }
747 
748       // Allow access if access checks are disabled.
749       EnforcementPolicy policy = Runtime::Current()->GetCorePlatformApiEnforcementPolicy();
750       if (policy == EnforcementPolicy::kDisabled) {
751         return false;
752       }
753 
754       // If this is a proxy method, look at the interface method instead.
755       member = detail::GetInterfaceMemberIfProxy(member);
756 
757       // Access checks are not disabled, report the violation.
758       // This may also add kAccCorePlatformApi to the access flags of `member`
759       // so as to not warn again on next access.
760       return detail::HandleCorePlatformApiViolation(member, caller_context, access_method, policy);
761     }
762 
763     case Domain::kCorePlatform: {
764       LOG(FATAL) << "CorePlatform domain should be allowed to access all domains";
765       UNREACHABLE();
766     }
767   }
768 }
769 
770 // Need to instantiate these.
771 template bool ShouldDenyAccessToMember<ArtField>(
772     ArtField* member,
773     const std::function<AccessContext()>& fn_get_access_context,
774     AccessMethod access_method);
775 template bool ShouldDenyAccessToMember<ArtMethod>(
776     ArtMethod* member,
777     const std::function<AccessContext()>& fn_get_access_context,
778     AccessMethod access_method);
779 
780 }  // namespace hiddenapi
781 }  // namespace art
782