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 <nativehelper/scoped_local_ref.h>
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.h"
26 #include "dex/class_accessor-inl.h"
27 #include "dex/dex_file_loader.h"
28 #include "mirror/class_ext.h"
29 #include "oat_file.h"
30 #include "scoped_thread_state_change.h"
31 #include "thread-inl.h"
32 #include "well_known_classes.h"
33 
34 namespace art {
35 namespace hiddenapi {
36 
37 // Should be the same as dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_P_HIDDEN_APIS and
38 // dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_Q_HIDDEN_APIS.
39 // Corresponds to bug ids.
40 static constexpr uint64_t kHideMaxtargetsdkPHiddenApis = 149997251;
41 static constexpr uint64_t kHideMaxtargetsdkQHiddenApis = 149994052;
42 
43 // Set to true if we should always print a warning in logcat for all hidden API accesses, not just
44 // dark grey and black. This can be set to true for developer preview / beta builds, but should be
45 // false for public release builds.
46 // Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
47 // as it affects whether or not we warn for light grey APIs that have been added to the exemptions
48 // list.
49 static constexpr bool kLogAllAccesses = false;
50 
51 // Exemptions for logcat warning. Following signatures do not produce a warning as app developers
52 // should not be alerted on the usage of these greylised APIs. See b/154851649.
53 static const std::vector<std::string> kWarningExemptions = {
54     "Ljava/nio/Buffer;",
55     "Llibcore/io/Memory;",
56     "Lsun/misc/Unsafe;",
57 };
58 
operator <<(std::ostream & os,AccessMethod value)59 static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
60   switch (value) {
61     case AccessMethod::kNone:
62       LOG(FATAL) << "Internal access to hidden API should not be logged";
63       UNREACHABLE();
64     case AccessMethod::kReflection:
65       os << "reflection";
66       break;
67     case AccessMethod::kJNI:
68       os << "JNI";
69       break;
70     case AccessMethod::kLinking:
71       os << "linking";
72       break;
73   }
74   return os;
75 }
76 
operator <<(std::ostream & os,const AccessContext & value)77 static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
78     REQUIRES_SHARED(Locks::mutator_lock_) {
79   if (!value.GetClass().IsNull()) {
80     std::string tmp;
81     os << value.GetClass()->GetDescriptor(&tmp);
82   } else if (value.GetDexFile() != nullptr) {
83     os << value.GetDexFile()->GetLocation();
84   } else {
85     os << "<unknown_caller>";
86   }
87   return os;
88 }
89 
DetermineDomainFromLocation(const std::string & dex_location,ObjPtr<mirror::ClassLoader> class_loader)90 static Domain DetermineDomainFromLocation(const std::string& dex_location,
91                                           ObjPtr<mirror::ClassLoader> class_loader) {
92   // If running with APEX, check `path` against known APEX locations.
93   // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
94   // is set to "/system".
95   if (ArtModuleRootDistinctFromAndroidRoot()) {
96     if (LocationIsOnArtModule(dex_location.c_str()) ||
97         LocationIsOnConscryptModule(dex_location.c_str())) {
98       return Domain::kCorePlatform;
99     }
100 
101     if (LocationIsOnApex(dex_location.c_str())) {
102       return Domain::kPlatform;
103     }
104   }
105 
106   if (LocationIsOnSystemFramework(dex_location.c_str())) {
107     return Domain::kPlatform;
108   }
109 
110   if (class_loader.IsNull()) {
111     LOG(WARNING) << "DexFile " << dex_location
112         << " is in boot class path but is not in a known location";
113     return Domain::kPlatform;
114   }
115 
116   return Domain::kApplication;
117 }
118 
InitializeDexFileDomain(const DexFile & dex_file,ObjPtr<mirror::ClassLoader> class_loader)119 void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
120   Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
121 
122   // Assign the domain unless a more permissive domain has already been assigned.
123   // This may happen when DexFile is initialized as trusted.
124   if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
125     dex_file.SetHiddenapiDomain(dex_domain);
126   }
127 }
128 
InitializeCorePlatformApiPrivateFields()129 void InitializeCorePlatformApiPrivateFields() {
130   // The following fields in WellKnownClasses correspond to private fields in the Core Platform
131   // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
132   jfieldID private_core_platform_api_fields[] = {
133     WellKnownClasses::java_io_FileDescriptor_descriptor,
134     WellKnownClasses::java_io_FileDescriptor_ownerId,
135     WellKnownClasses::java_nio_Buffer_address,
136     WellKnownClasses::java_nio_Buffer_elementSizeShift,
137     WellKnownClasses::java_nio_Buffer_limit,
138     WellKnownClasses::java_nio_Buffer_position,
139   };
140 
141   ScopedObjectAccess soa(Thread::Current());
142   for (const auto private_core_platform_api_field : private_core_platform_api_fields) {
143     ArtField* field = jni::DecodeArtField(private_core_platform_api_field);
144     const uint32_t access_flags = field->GetAccessFlags();
145     uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
146     DCHECK(new_access_flags != access_flags);
147     field->SetAccessFlags(new_access_flags);
148   }
149 }
150 
151 namespace detail {
152 
153 // Do not change the values of items in this enum, as they are written to the
154 // event log for offline analysis. Any changes will interfere with that analysis.
155 enum AccessContextFlags {
156   // Accessed member is a field if this bit is set, else a method
157   kMemberIsField = 1 << 0,
158   // Indicates if access was denied to the member, instead of just printing a warning.
159   kAccessDenied  = 1 << 1,
160 };
161 
MemberSignature(ArtField * field)162 MemberSignature::MemberSignature(ArtField* field) {
163   class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
164   member_name_ = field->GetName();
165   type_signature_ = field->GetTypeDescriptor();
166   type_ = kField;
167 }
168 
MemberSignature(ArtMethod * method)169 MemberSignature::MemberSignature(ArtMethod* method) {
170   DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
171       << "Caller should have replaced proxy method with interface method";
172   class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
173   member_name_ = method->GetName();
174   type_signature_ = method->GetSignature().ToString();
175   type_ = kMethod;
176 }
177 
MemberSignature(const ClassAccessor::Field & field)178 MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
179   const DexFile& dex_file = field.GetDexFile();
180   const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
181   class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
182   member_name_ = dex_file.GetFieldName(field_id);
183   type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
184   type_ = kField;
185 }
186 
MemberSignature(const ClassAccessor::Method & method)187 MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
188   const DexFile& dex_file = method.GetDexFile();
189   const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
190   class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
191   member_name_ = dex_file.GetMethodName(method_id);
192   type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
193   type_ = kMethod;
194 }
195 
GetSignatureParts() const196 inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
197   if (type_ == kField) {
198     return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
199   } else {
200     DCHECK_EQ(type_, kMethod);
201     return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
202   }
203 }
204 
DoesPrefixMatch(const std::string & prefix) const205 bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
206   size_t pos = 0;
207   for (const char* part : GetSignatureParts()) {
208     size_t count = std::min(prefix.length() - pos, strlen(part));
209     if (prefix.compare(pos, count, part, 0, count) == 0) {
210       pos += count;
211     } else {
212       return false;
213     }
214   }
215   // We have a complete match if all parts match (we exit the loop without
216   // returning) AND we've matched the whole prefix.
217   return pos == prefix.length();
218 }
219 
DoesPrefixMatchAny(const std::vector<std::string> & exemptions)220 bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
221   for (const std::string& exemption : exemptions) {
222     if (DoesPrefixMatch(exemption)) {
223       return true;
224     }
225   }
226   return false;
227 }
228 
Dump(std::ostream & os) const229 void MemberSignature::Dump(std::ostream& os) const {
230   for (const char* part : GetSignatureParts()) {
231     os << part;
232   }
233 }
234 
WarnAboutAccess(AccessMethod access_method,hiddenapi::ApiList list,bool access_denied)235 void MemberSignature::WarnAboutAccess(AccessMethod access_method,
236                                       hiddenapi::ApiList list,
237                                       bool access_denied) {
238   LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
239                << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
240                << (access_denied ? ", denied)" : ", allowed)");
241 }
242 
Equals(const MemberSignature & other)243 bool MemberSignature::Equals(const MemberSignature& other) {
244   return type_ == other.type_ &&
245          class_name_ == other.class_name_ &&
246          member_name_ == other.member_name_ &&
247          type_signature_ == other.type_signature_;
248 }
249 
MemberNameAndTypeMatch(const MemberSignature & other)250 bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
251   return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
252 }
253 
LogAccessToEventLog(uint32_t sampled_value,AccessMethod access_method,bool access_denied)254 void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
255                                           AccessMethod access_method,
256                                           bool access_denied) {
257 #ifdef ART_TARGET_ANDROID
258   if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
259     // Linking warnings come from static analysis/compilation of the bytecode
260     // and can contain false positives (i.e. code that is never run). We choose
261     // not to log these in the event log.
262     // None does not correspond to actual access, so should also be ignored.
263     return;
264   }
265   Runtime* runtime = Runtime::Current();
266   if (runtime->IsAotCompiler()) {
267     return;
268   }
269   JNIEnvExt* env = Thread::Current()->GetJniEnv();
270   const std::string& package_name = Runtime::Current()->GetProcessPackageName();
271   ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
272   if (env->ExceptionCheck()) {
273     env->ExceptionClear();
274     LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
275   }
276   std::ostringstream signature_str;
277   Dump(signature_str);
278   ScopedLocalRef<jstring> signature_jstr(env,
279       env->NewStringUTF(signature_str.str().c_str()));
280   if (env->ExceptionCheck()) {
281     env->ExceptionClear();
282     LOG(ERROR) << "Unable to allocate string for hidden api method signature";
283   }
284   env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
285       WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
286       sampled_value,
287       package_str.get(),
288       signature_jstr.get(),
289       static_cast<jint>(access_method),
290       access_denied);
291   if (env->ExceptionCheck()) {
292     env->ExceptionClear();
293     LOG(ERROR) << "Unable to report hidden api usage";
294   }
295 #else
296   UNUSED(sampled_value);
297   UNUSED(access_method);
298   UNUSED(access_denied);
299 #endif
300 }
301 
NotifyHiddenApiListener(AccessMethod access_method)302 void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
303   if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
304     // We can only up-call into Java during reflection and JNI down-calls.
305     return;
306   }
307 
308   Runtime* runtime = Runtime::Current();
309   if (!runtime->IsAotCompiler()) {
310     ScopedObjectAccessUnchecked soa(Thread::Current());
311 
312     ScopedLocalRef<jobject> consumer_object(soa.Env(),
313         soa.Env()->GetStaticObjectField(
314             WellKnownClasses::dalvik_system_VMRuntime,
315             WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
316     // If the consumer is non-null, we call back to it to let it know that we
317     // have encountered an API that's in one of our lists.
318     if (consumer_object != nullptr) {
319       std::ostringstream member_signature_str;
320       Dump(member_signature_str);
321 
322       ScopedLocalRef<jobject> signature_str(
323           soa.Env(),
324           soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
325 
326       // Call through to Consumer.accept(String memberSignature);
327       soa.Env()->CallVoidMethod(consumer_object.get(),
328                                 WellKnownClasses::java_util_function_Consumer_accept,
329                                 signature_str.get());
330     }
331   }
332 }
333 
CanUpdateRuntimeFlags(ArtField *)334 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
335   return true;
336 }
337 
CanUpdateRuntimeFlags(ArtMethod * method)338 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
339   return !method->IsIntrinsic();
340 }
341 
342 template<typename T>
MaybeUpdateAccessFlags(Runtime * runtime,T * member,uint32_t flag)343 static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
344     REQUIRES_SHARED(Locks::mutator_lock_) {
345   // Update the access flags unless:
346   // (a) `member` is an intrinsic
347   // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
348   // (c) deduping warnings has been explicitly switched off.
349   if (CanUpdateRuntimeFlags(member) &&
350       !runtime->IsAotCompiler() &&
351       runtime->ShouldDedupeHiddenApiWarnings()) {
352     member->SetAccessFlags(member->GetAccessFlags() | flag);
353   }
354 }
355 
GetMemberDexIndex(ArtField * field)356 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
357   return field->GetDexFieldIndex();
358 }
359 
GetMemberDexIndex(ArtMethod * method)360 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
361     REQUIRES_SHARED(Locks::mutator_lock_) {
362   // Use the non-obsolete method to avoid DexFile mismatch between
363   // the method index and the declaring class.
364   return method->GetNonObsoleteMethod()->GetDexMethodIndex();
365 }
366 
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Field &)> & fn_visit)367 static void VisitMembers(const DexFile& dex_file,
368                          const dex::ClassDef& class_def,
369                          const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
370   ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
371   accessor.VisitFields(fn_visit, fn_visit);
372 }
373 
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Method &)> & fn_visit)374 static void VisitMembers(const DexFile& dex_file,
375                          const dex::ClassDef& class_def,
376                          const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
377   ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
378   accessor.VisitMethods(fn_visit, fn_visit);
379 }
380 
381 template<typename T>
GetDexFlags(T * member)382 uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
383   static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
384   constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
385   using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
386       ClassAccessor::Field, ClassAccessor::Method>::type;
387 
388   ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
389   DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
390 
391   ApiList flags;
392   DCHECK(!flags.IsValid());
393 
394   // Check if the declaring class has ClassExt allocated. If it does, check if
395   // the pre-JVMTI redefine dex file has been set to determine if the declaring
396   // class has been JVMTI-redefined.
397   ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
398   const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
399   if (LIKELY(original_dex == nullptr)) {
400     // Class is not redefined. Find the class def, iterate over its members and
401     // find the entry corresponding to this `member`.
402     const dex::ClassDef* class_def = declaring_class->GetClassDef();
403     if (class_def == nullptr) {
404       // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
405       DCHECK(declaring_class->IsProxyClass())
406           << "Only proxy classes are expected not to have a class def";
407       DCHECK(kMemberIsField)
408           << "Interface methods should be inspected instead of proxy class methods";
409       flags = ApiList::Greylist();
410     } else {
411       uint32_t member_index = GetMemberDexIndex(member);
412       auto fn_visit = [&](const AccessorType& dex_member) {
413         if (dex_member.GetIndex() == member_index) {
414           flags = ApiList(dex_member.GetHiddenapiFlags());
415         }
416       };
417       VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
418     }
419   } else {
420     // Class was redefined using JVMTI. We have a pointer to the original dex file
421     // and the class def index of this class in that dex file, but the field/method
422     // indices are lost. Iterate over all members of the class def and find the one
423     // corresponding to this `member` by name and type string comparison.
424     // This is obviously very slow, but it is only used when non-exempt code tries
425     // to access a hidden member of a JVMTI-redefined class.
426     uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
427     DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
428     const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
429     MemberSignature member_signature(member);
430     auto fn_visit = [&](const AccessorType& dex_member) {
431       MemberSignature cur_signature(dex_member);
432       if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
433         DCHECK(member_signature.Equals(cur_signature));
434         flags = ApiList(dex_member.GetHiddenapiFlags());
435       }
436     };
437     VisitMembers(*original_dex, original_class_def, fn_visit);
438   }
439 
440   CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
441       << Dumpable<MemberSignature>(MemberSignature(member));
442   return flags.GetDexFlags();
443 }
444 
445 template<typename T>
HandleCorePlatformApiViolation(T * member,const AccessContext & caller_context,AccessMethod access_method,EnforcementPolicy policy)446 bool HandleCorePlatformApiViolation(T* member,
447                                     const AccessContext& caller_context,
448                                     AccessMethod access_method,
449                                     EnforcementPolicy policy) {
450   DCHECK(policy != EnforcementPolicy::kDisabled)
451       << "Should never enter this function when access checks are completely disabled";
452 
453   if (access_method != AccessMethod::kNone) {
454     LOG(WARNING) << "Core platform API violation: "
455         << Dumpable<MemberSignature>(MemberSignature(member))
456         << " from " << caller_context << " using " << access_method;
457 
458     // If policy is set to just warn, add kAccCorePlatformApi to access flags of
459     // `member` to avoid reporting the violation again next time.
460     if (policy == EnforcementPolicy::kJustWarn) {
461       MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
462     }
463   }
464 
465   // Deny access if enforcement is enabled.
466   return policy == EnforcementPolicy::kEnabled;
467 }
468 
469 template<typename T>
ShouldDenyAccessToMemberImpl(T * member,ApiList api_list,AccessMethod access_method)470 bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
471   DCHECK(member != nullptr);
472   Runtime* runtime = Runtime::Current();
473 
474   EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
475   DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
476       << "Should never enter this function when access checks are completely disabled";
477 
478   MemberSignature member_signature(member);
479 
480   // Check for an exemption first. Exempted APIs are treated as white list.
481   if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
482     // Avoid re-examining the exemption list next time.
483     // Note this results in no warning for the member, which seems like what one would expect.
484     // Exemptions effectively adds new members to the whitelist.
485     MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
486     return false;
487   }
488 
489   EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
490 
491   bool deny_access = false;
492   if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
493     if (testApiPolicy == EnforcementPolicy::kDisabled && api_list.IsTestApi()) {
494       deny_access = false;
495     } else {
496       switch (api_list.GetMaxAllowedSdkVersion()) {
497         case SdkVersion::kP:
498           deny_access = runtime->isChangeEnabled(kHideMaxtargetsdkPHiddenApis);
499           break;
500         case SdkVersion::kQ:
501           deny_access = runtime->isChangeEnabled(kHideMaxtargetsdkQHiddenApis);
502           break;
503         default:
504           deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
505                                                          api_list.GetMaxAllowedSdkVersion());
506       }
507     }
508   }
509 
510   if (access_method != AccessMethod::kNone) {
511     // Warn if non-greylisted signature is being accessed or it is not exempted.
512     if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
513       // Print a log message with information about this class member access.
514       // We do this if we're about to deny access, or the app is debuggable.
515       if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
516         member_signature.WarnAboutAccess(access_method, api_list, deny_access);
517       }
518 
519       // If there is a StrictMode listener, notify it about this violation.
520       member_signature.NotifyHiddenApiListener(access_method);
521     }
522 
523     // If event log sampling is enabled, report this violation.
524     if (kIsTargetBuild && !kIsTargetLinux) {
525       uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
526       // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
527       static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
528       if (eventLogSampleRate != 0) {
529         const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
530         if (sampled_value < eventLogSampleRate) {
531           member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
532         }
533       }
534     }
535 
536     // If this access was not denied, move the member into whitelist and skip
537     // the warning the next time the member is accessed.
538     if (!deny_access) {
539       MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
540     }
541   }
542 
543   return deny_access;
544 }
545 
546 // Need to instantiate these.
547 template uint32_t GetDexFlags<ArtField>(ArtField* member);
548 template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
549 template bool HandleCorePlatformApiViolation(ArtField* member,
550                                              const AccessContext& caller_context,
551                                              AccessMethod access_method,
552                                              EnforcementPolicy policy);
553 template bool HandleCorePlatformApiViolation(ArtMethod* member,
554                                              const AccessContext& caller_context,
555                                              AccessMethod access_method,
556                                              EnforcementPolicy policy);
557 template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
558                                                      ApiList api_list,
559                                                      AccessMethod access_method);
560 template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
561                                                       ApiList api_list,
562                                                       AccessMethod access_method);
563 }  // namespace detail
564 
565 }  // namespace hiddenapi
566 }  // namespace art
567