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/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 HIDDEN {
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
195 // MethodHandles.makeIdentity is doing findStatic to find hidden methods,
196 // where reflection is used.
197 if (m == WellKnownClasses::java_lang_invoke_MethodHandles_makeIdentity) {
198 return false;
199 }
200
201 // Check classes in the java.lang.invoke package. At the time of writing, the
202 // classes of interest are MethodHandles and MethodHandles.Lookup, but this
203 // is subject to change so conservatively cover the entire package.
204 // NB Static initializers within java.lang.invoke are permitted and do not
205 // need further stack inspection.
206 ObjPtr<mirror::Class> lookup_class = GetClassRoot<mirror::MethodHandlesLookup>();
207 if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) &&
208 !m->IsClassInitializer()) {
209 return true;
210 }
211 // Check for classes in the java.lang.reflect package, except for java.lang.reflect.Proxy.
212 // java.lang.reflect.Proxy does its own hidden api checks (https://r.android.com/915496),
213 // and walking over this frame would cause a null pointer dereference
214 // (e.g. in 691-hiddenapi-proxy).
215 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>();
216 CompatFramework& compat_framework = Runtime::Current()->GetCompatFramework();
217 if (declaring_class->IsInSamePackage(proxy_class) && declaring_class != proxy_class) {
218 if (compat_framework.IsChangeEnabled(kPreventMetaReflectionBlocklistAccess)) {
219 return true;
220 }
221 }
222 }
223
224 caller = m;
225 return false;
226 }
227
228 ArtMethod* caller;
229 };
230
231 FirstExternalCallerVisitor visitor(self);
232 visitor.WalkStack();
233
234 // Construct AccessContext from the calling class found on the stack.
235 // If the calling class cannot be determined, e.g. unattached threads,
236 // we conservatively assume the caller is trusted.
237 ObjPtr<mirror::Class> caller =
238 (visitor.caller == nullptr) ? nullptr : visitor.caller->GetDeclaringClass();
239 return caller.IsNull() ? AccessContext(/* is_trusted= */ true) : AccessContext(caller);
240 }
241
242 namespace detail {
243
244 // Do not change the values of items in this enum, as they are written to the
245 // event log for offline analysis. Any changes will interfere with that analysis.
246 enum AccessContextFlags {
247 // Accessed member is a field if this bit is set, else a method
248 kMemberIsField = 1 << 0,
249 // Indicates if access was denied to the member, instead of just printing a warning.
250 kAccessDenied = 1 << 1,
251 };
252
MemberSignature(ArtField * field)253 MemberSignature::MemberSignature(ArtField* field) {
254 // Note: `ArtField::GetDeclaringClassDescriptor()` does not support proxy classes.
255 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
256 member_name_ = field->GetNameView();
257 type_signature_ = field->GetTypeDescriptorView();
258 type_ = kField;
259 }
260
MemberSignature(ArtMethod * method)261 MemberSignature::MemberSignature(ArtMethod* method) {
262 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
263 << "Caller should have replaced proxy method with interface method";
264 class_name_ = method->GetDeclaringClassDescriptorView();
265 member_name_ = method->GetNameView();
266 type_signature_ = method->GetSignature().ToString();
267 type_ = kMethod;
268 }
269
MemberSignature(const ClassAccessor::Field & field)270 MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
271 const DexFile& dex_file = field.GetDexFile();
272 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
273 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
274 member_name_ = dex_file.GetFieldName(field_id);
275 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
276 type_ = kField;
277 }
278
MemberSignature(const ClassAccessor::Method & method)279 MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
280 const DexFile& dex_file = method.GetDexFile();
281 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
282 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
283 member_name_ = dex_file.GetMethodName(method_id);
284 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
285 type_ = kMethod;
286 }
287
GetSignatureParts() const288 inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
289 if (type_ == kField) {
290 return {class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str()};
291 } else {
292 DCHECK_EQ(type_, kMethod);
293 return {class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str()};
294 }
295 }
296
DoesPrefixMatch(const std::string & prefix) const297 bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
298 size_t pos = 0;
299 for (const char* part : GetSignatureParts()) {
300 size_t count = std::min(prefix.length() - pos, strlen(part));
301 if (prefix.compare(pos, count, part, 0, count) == 0) {
302 pos += count;
303 } else {
304 return false;
305 }
306 }
307 // We have a complete match if all parts match (we exit the loop without
308 // returning) AND we've matched the whole prefix.
309 return pos == prefix.length();
310 }
311
DoesPrefixMatchAny(const std::vector<std::string> & exemptions)312 bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
313 for (const std::string& exemption : exemptions) {
314 if (DoesPrefixMatch(exemption)) {
315 return true;
316 }
317 }
318 return false;
319 }
320
Dump(std::ostream & os) const321 void MemberSignature::Dump(std::ostream& os) const {
322 for (const char* part : GetSignatureParts()) {
323 os << part;
324 }
325 }
326
WarnAboutAccess(AccessMethod access_method,hiddenapi::ApiList list,bool access_denied)327 void MemberSignature::WarnAboutAccess(AccessMethod access_method,
328 hiddenapi::ApiList list,
329 bool access_denied) {
330 static std::atomic<uint64_t> log_warning_count_ = 0;
331 if (log_warning_count_ > kMaxLogWarnings) {
332 return;
333 }
334 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
335 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
336 << (access_denied ? ", denied)" : ", allowed)");
337 if (access_denied && list.IsTestApi()) {
338 // see b/177047045 for more details about test api access getting denied
339 LOG(WARNING) << "If this is a platform test consider enabling "
340 << "VMRuntime.ALLOW_TEST_API_ACCESS change id for this package.";
341 }
342 if (log_warning_count_ >= kMaxLogWarnings) {
343 LOG(WARNING) << "Reached maximum number of hidden api access warnings.";
344 }
345 ++log_warning_count_;
346 }
347
Equals(const MemberSignature & other)348 bool MemberSignature::Equals(const MemberSignature& other) {
349 return type_ == other.type_ && class_name_ == other.class_name_ &&
350 member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
351 }
352
MemberNameAndTypeMatch(const MemberSignature & other)353 bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
354 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
355 }
356
LogAccessToEventLog(uint32_t sampled_value,AccessMethod access_method,bool access_denied)357 void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
358 AccessMethod access_method,
359 bool access_denied) {
360 #ifdef ART_TARGET_ANDROID
361 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
362 // Linking warnings come from static analysis/compilation of the bytecode
363 // and can contain false positives (i.e. code that is never run). We choose
364 // not to log these in the event log.
365 // None does not correspond to actual access, so should also be ignored.
366 return;
367 }
368 Runtime* runtime = Runtime::Current();
369 if (runtime->IsAotCompiler()) {
370 return;
371 }
372
373 const std::string& package_name = runtime->GetProcessPackageName();
374 std::ostringstream signature_str;
375 Dump(signature_str);
376
377 ScopedObjectAccess soa(Thread::Current());
378 StackHandleScope<2u> hs(soa.Self());
379 Handle<mirror::String> package_str =
380 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), package_name.c_str()));
381 if (soa.Self()->IsExceptionPending()) {
382 soa.Self()->ClearException();
383 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
384 }
385 Handle<mirror::String> signature_jstr =
386 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), signature_str.str().c_str()));
387 if (soa.Self()->IsExceptionPending()) {
388 soa.Self()->ClearException();
389 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
390 }
391 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed
392 ->InvokeStatic<'V', 'I', 'L', 'L', 'I', 'Z'>(soa.Self(),
393 static_cast<jint>(sampled_value),
394 package_str.Get(),
395 signature_jstr.Get(),
396 static_cast<jint>(access_method),
397 access_denied);
398 if (soa.Self()->IsExceptionPending()) {
399 soa.Self()->ClearException();
400 LOG(ERROR) << "Unable to report hidden api usage";
401 }
402 #else
403 UNUSED(sampled_value);
404 UNUSED(access_method);
405 UNUSED(access_denied);
406 #endif
407 }
408
NotifyHiddenApiListener(AccessMethod access_method)409 void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
410 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
411 // We can only up-call into Java during reflection and JNI down-calls.
412 return;
413 }
414
415 Runtime* runtime = Runtime::Current();
416 if (!runtime->IsAotCompiler()) {
417 ScopedObjectAccess soa(Thread::Current());
418 StackHandleScope<2u> hs(soa.Self());
419
420 ArtField* consumer_field = WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer;
421 DCHECK(consumer_field->GetDeclaringClass()->IsInitialized());
422 Handle<mirror::Object> consumer_object =
423 hs.NewHandle(consumer_field->GetObject(consumer_field->GetDeclaringClass()));
424
425 // If the consumer is non-null, we call back to it to let it know that we
426 // have encountered an API that's in one of our lists.
427 if (consumer_object != nullptr) {
428 std::ostringstream member_signature_str;
429 Dump(member_signature_str);
430
431 Handle<mirror::String> signature_str = hs.NewHandle(
432 mirror::String::AllocFromModifiedUtf8(soa.Self(), member_signature_str.str().c_str()));
433 // FIXME: Handle OOME. For now, crash immediatelly (do not continue with a pending exception).
434 CHECK(signature_str != nullptr);
435
436 // Call through to Consumer.accept(String memberSignature);
437 WellKnownClasses::java_util_function_Consumer_accept->InvokeInterface<'V', 'L'>(
438 soa.Self(), consumer_object.Get(), signature_str.Get());
439 }
440 }
441 }
442
CanUpdateRuntimeFlags(ArtField *)443 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) { return true; }
444
CanUpdateRuntimeFlags(ArtMethod * method)445 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
446 return !method->IsIntrinsic();
447 }
448
449 template <typename T>
MaybeUpdateAccessFlags(Runtime * runtime,T * member,uint32_t flag)450 static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
451 REQUIRES_SHARED(Locks::mutator_lock_) {
452 // Update the access flags unless:
453 // (a) `member` is an intrinsic
454 // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
455 // (c) deduping warnings has been explicitly switched off.
456 if (CanUpdateRuntimeFlags(member) && !runtime->IsAotCompiler() &&
457 runtime->ShouldDedupeHiddenApiWarnings()) {
458 member->SetAccessFlags(member->GetAccessFlags() | flag);
459 }
460 }
461
GetMemberDexIndex(ArtField * field)462 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
463 return field->GetDexFieldIndex();
464 }
465
GetMemberDexIndex(ArtMethod * method)466 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
467 REQUIRES_SHARED(Locks::mutator_lock_) {
468 // Use the non-obsolete method to avoid DexFile mismatch between
469 // the method index and the declaring class.
470 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
471 }
472
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Field &)> & fn_visit)473 static void VisitMembers(const DexFile& dex_file,
474 const dex::ClassDef& class_def,
475 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
476 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
477 accessor.VisitFields(fn_visit, fn_visit);
478 }
479
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Method &)> & fn_visit)480 static void VisitMembers(const DexFile& dex_file,
481 const dex::ClassDef& class_def,
482 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
483 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
484 accessor.VisitMethods(fn_visit, fn_visit);
485 }
486
487 template <typename T>
GetDexFlags(T * member)488 uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
489 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
490 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
491 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
492 ClassAccessor::Field,
493 ClassAccessor::Method>::type;
494
495 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
496 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
497
498 ApiList flags;
499 DCHECK(!flags.IsValid());
500
501 // Check if the declaring class has ClassExt allocated. If it does, check if
502 // the pre-JVMTI redefine dex file has been set to determine if the declaring
503 // class has been JVMTI-redefined.
504 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
505 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
506 if (LIKELY(original_dex == nullptr)) {
507 // Class is not redefined. Find the class def, iterate over its members and
508 // find the entry corresponding to this `member`.
509 const dex::ClassDef* class_def = declaring_class->GetClassDef();
510 if (class_def == nullptr) {
511 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
512 DCHECK(declaring_class->IsProxyClass())
513 << "Only proxy classes are expected not to have a class def";
514 DCHECK(kMemberIsField)
515 << "Interface methods should be inspected instead of proxy class methods";
516 flags = ApiList::Unsupported();
517 } else {
518 uint32_t member_index = GetMemberDexIndex(member);
519 auto fn_visit = [&](const AccessorType& dex_member) {
520 if (dex_member.GetIndex() == member_index) {
521 flags = ApiList(dex_member.GetHiddenapiFlags());
522 }
523 };
524 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
525 }
526 } else {
527 // Class was redefined using JVMTI. We have a pointer to the original dex file
528 // and the class def index of this class in that dex file, but the field/method
529 // indices are lost. Iterate over all members of the class def and find the one
530 // corresponding to this `member` by name and type string comparison.
531 // This is obviously very slow, but it is only used when non-exempt code tries
532 // to access a hidden member of a JVMTI-redefined class.
533 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
534 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
535 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
536 MemberSignature member_signature(member);
537 auto fn_visit = [&](const AccessorType& dex_member) {
538 MemberSignature cur_signature(dex_member);
539 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
540 DCHECK(member_signature.Equals(cur_signature));
541 flags = ApiList(dex_member.GetHiddenapiFlags());
542 }
543 };
544 VisitMembers(*original_dex, original_class_def, fn_visit);
545 }
546
547 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
548 << Dumpable<MemberSignature>(MemberSignature(member));
549 return flags.GetDexFlags();
550 }
551
552 template <typename T>
HandleCorePlatformApiViolation(T * member,const AccessContext & caller_context,AccessMethod access_method,EnforcementPolicy policy)553 bool HandleCorePlatformApiViolation(T* member,
554 const AccessContext& caller_context,
555 AccessMethod access_method,
556 EnforcementPolicy policy) {
557 DCHECK(policy != EnforcementPolicy::kDisabled)
558 << "Should never enter this function when access checks are completely disabled";
559
560 if (access_method != AccessMethod::kNone) {
561 LOG(WARNING) << "Core platform API violation: "
562 << Dumpable<MemberSignature>(MemberSignature(member)) << " from " << caller_context
563 << " using " << access_method;
564
565 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
566 // `member` to avoid reporting the violation again next time.
567 if (policy == EnforcementPolicy::kJustWarn) {
568 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
569 }
570 }
571
572 // Deny access if enforcement is enabled.
573 return policy == EnforcementPolicy::kEnabled;
574 }
575
576 template <typename T>
ShouldDenyAccessToMemberImpl(T * member,ApiList api_list,AccessMethod access_method)577 bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
578 DCHECK(member != nullptr);
579 Runtime* runtime = Runtime::Current();
580 CompatFramework& compatFramework = runtime->GetCompatFramework();
581
582 EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
583 DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
584 << "Should never enter this function when access checks are completely disabled";
585
586 MemberSignature member_signature(member);
587
588 // Check for an exemption first. Exempted APIs are treated as SDK.
589 if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
590 // Avoid re-examining the exemption list next time.
591 // Note this results in no warning for the member, which seems like what one would expect.
592 // Exemptions effectively adds new members to the public API list.
593 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
594 return false;
595 }
596
597 EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
598
599 bool deny_access = false;
600 if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
601 if (api_list.IsTestApi() && (testApiPolicy == EnforcementPolicy::kDisabled ||
602 compatFramework.IsChangeEnabled(kAllowTestApiAccess))) {
603 deny_access = false;
604 } else {
605 switch (api_list.GetMaxAllowedSdkVersion()) {
606 case SdkVersion::kP:
607 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkPHiddenApis);
608 break;
609 case SdkVersion::kQ:
610 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkQHiddenApis);
611 break;
612 default:
613 deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
614 api_list.GetMaxAllowedSdkVersion());
615 }
616 }
617 }
618
619 if (access_method != AccessMethod::kNone) {
620 // Warn if blocked signature is being accessed or it is not exempted.
621 if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
622 // Print a log message with information about this class member access.
623 // We do this if we're about to deny access, or the app is debuggable.
624 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
625 member_signature.WarnAboutAccess(access_method, api_list, deny_access);
626 }
627
628 // If there is a StrictMode listener, notify it about this violation.
629 member_signature.NotifyHiddenApiListener(access_method);
630 }
631
632 // If event log sampling is enabled, report this violation.
633 if (kIsTargetBuild && !kIsTargetLinux) {
634 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
635 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
636 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
637 if (eventLogSampleRate != 0) {
638 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
639 if (sampled_value <= eventLogSampleRate) {
640 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
641 }
642 }
643 }
644
645 // If this access was not denied, flag member as SDK and skip
646 // the warning the next time the member is accessed. Don't update for
647 // non-debuggable apps as this has a memory cost.
648 if (!deny_access && runtime->IsJavaDebuggable()) {
649 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
650 }
651 }
652
653 return deny_access;
654 }
655
656 // Need to instantiate these.
657 template uint32_t GetDexFlags<ArtField>(ArtField* member);
658 template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
659 template bool HandleCorePlatformApiViolation(ArtField* member,
660 const AccessContext& caller_context,
661 AccessMethod access_method,
662 EnforcementPolicy policy);
663 template bool HandleCorePlatformApiViolation(ArtMethod* member,
664 const AccessContext& caller_context,
665 AccessMethod access_method,
666 EnforcementPolicy policy);
667 template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
668 ApiList api_list,
669 AccessMethod access_method);
670 template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
671 ApiList api_list,
672 AccessMethod access_method);
673 } // namespace detail
674
675 template <typename T>
ShouldDenyAccessToMember(T * member,const std::function<AccessContext ()> & fn_get_access_context,AccessMethod access_method)676 bool ShouldDenyAccessToMember(T* member,
677 const std::function<AccessContext()>& fn_get_access_context,
678 AccessMethod access_method) {
679 DCHECK(member != nullptr);
680
681 // First check if we have an explicit sdk checker installed that should be used to
682 // verify access. If so, make the decision based on it.
683 //
684 // This is used during off-device AOT compilation which may want to generate verification
685 // metadata only for a specific list of public SDKs. Note that the check here is made
686 // based on descriptor equality and it's aim to further restrict a symbol that would
687 // otherwise be resolved.
688 //
689 // The check only applies to boot classpaths dex files.
690 Runtime* runtime = Runtime::Current();
691 if (UNLIKELY(runtime->IsAotCompiler())) {
692 if (member->GetDeclaringClass()->IsBootStrapClassLoaded() &&
693 runtime->GetClassLinker()->DenyAccessBasedOnPublicSdk(member)) {
694 return true;
695 }
696 }
697
698 // Get the runtime flags encoded in member's access flags.
699 // Note: this works for proxy methods because they inherit access flags from their
700 // respective interface methods.
701 const uint32_t runtime_flags = GetRuntimeFlags(member);
702
703 // Exit early if member is public API. This flag is also set for non-boot class
704 // path fields/methods.
705 if ((runtime_flags & kAccPublicApi) != 0) {
706 return false;
707 }
708
709 // Determine which domain the caller and callee belong to.
710 // This can be *very* expensive. This is why ShouldDenyAccessToMember
711 // should not be called on every individual access.
712 const AccessContext caller_context = fn_get_access_context();
713 const AccessContext callee_context(member->GetDeclaringClass());
714
715 // Non-boot classpath callers should have exited early.
716 DCHECK(!callee_context.IsApplicationDomain());
717
718 // Check if the caller is always allowed to access members in the callee context.
719 if (caller_context.CanAlwaysAccess(callee_context)) {
720 return false;
721 }
722
723 // Check if this is platform accessing core platform. We may warn if `member` is
724 // not part of core platform API.
725 switch (caller_context.GetDomain()) {
726 case Domain::kApplication: {
727 DCHECK(!callee_context.IsApplicationDomain());
728
729 // Exit early if access checks are completely disabled.
730 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
731 if (policy == EnforcementPolicy::kDisabled) {
732 return false;
733 }
734
735 // If this is a proxy method, look at the interface method instead.
736 member = detail::GetInterfaceMemberIfProxy(member);
737
738 // Decode hidden API access flags from the dex file.
739 // This is an O(N) operation scaling with the number of fields/methods
740 // in the class. Only do this on slow path and only do it once.
741 ApiList api_list(detail::GetDexFlags(member));
742 DCHECK(api_list.IsValid());
743
744 // Member is hidden and caller is not exempted. Enter slow path.
745 return detail::ShouldDenyAccessToMemberImpl(member, api_list, access_method);
746 }
747
748 case Domain::kPlatform: {
749 DCHECK(callee_context.GetDomain() == Domain::kCorePlatform);
750
751 // Member is part of core platform API. Accessing it is allowed.
752 if ((runtime_flags & kAccCorePlatformApi) != 0) {
753 return false;
754 }
755
756 // Allow access if access checks are disabled.
757 EnforcementPolicy policy = Runtime::Current()->GetCorePlatformApiEnforcementPolicy();
758 if (policy == EnforcementPolicy::kDisabled) {
759 return false;
760 }
761
762 // If this is a proxy method, look at the interface method instead.
763 member = detail::GetInterfaceMemberIfProxy(member);
764
765 // Access checks are not disabled, report the violation.
766 // This may also add kAccCorePlatformApi to the access flags of `member`
767 // so as to not warn again on next access.
768 return detail::HandleCorePlatformApiViolation(member, caller_context, access_method, policy);
769 }
770
771 case Domain::kCorePlatform: {
772 LOG(FATAL) << "CorePlatform domain should be allowed to access all domains";
773 UNREACHABLE();
774 }
775 }
776 }
777
778 // Need to instantiate these.
779 template bool ShouldDenyAccessToMember<ArtField>(
780 ArtField* member,
781 const std::function<AccessContext()>& fn_get_access_context,
782 AccessMethod access_method);
783 template bool ShouldDenyAccessToMember<ArtMethod>(
784 ArtMethod* member,
785 const std::function<AccessContext()>& fn_get_access_context,
786 AccessMethod access_method);
787
788 } // namespace hiddenapi
789 } // namespace art
790