blob: f42ed4914051d04455aced0bbb8f5e6d17089151 [file] [log] [blame]
Andreas Gampe80f5fe52018-03-28 16:23:24 -07001/*
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
Narayan Kamathe453a8d2018-04-03 15:23:46 +010019#include <nativehelper/scoped_local_ref.h>
Andrei Onea3098e362021-01-26 18:30:54 +000020#include <atomic>
Narayan Kamathe453a8d2018-04-03 15:23:46 +010021
David Brazdil85865692018-10-30 17:26:20 +000022#include "art_field-inl.h"
23#include "art_method-inl.h"
Andrei Onea037d2822020-11-19 00:20:04 +000024#include "compat_framework.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070025#include "base/dumpable.h"
David Brazdila5c3a802019-03-08 14:59:41 +000026#include "base/file_utils.h"
David Brazdil85865692018-10-30 17:26:20 +000027#include "dex/class_accessor-inl.h"
David Brazdil1a658632018-12-01 17:54:26 +000028#include "dex/dex_file_loader.h"
29#include "mirror/class_ext.h"
David Brazdila5c3a802019-03-08 14:59:41 +000030#include "oat_file.h"
David Brazdil85865692018-10-30 17:26:20 +000031#include "scoped_thread_state_change.h"
32#include "thread-inl.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010033#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070034
35namespace art {
36namespace hiddenapi {
37
Pedro Loureirof7fcb982020-11-24 16:44:12 +000038// Should be the same as dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_P_HIDDEN_APIS,
39// dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_Q_HIDDEN_APIS, and
Pedro Loureiro28078392021-01-21 17:09:55 +000040// dalvik.system.VMRuntime.ALLOW_TEST_API_ACCESS.
atrost2dea0792020-02-25 20:11:47 +000041// Corresponds to bug ids.
42static constexpr uint64_t kHideMaxtargetsdkPHiddenApis = 149997251;
43static constexpr uint64_t kHideMaxtargetsdkQHiddenApis = 149994052;
Pedro Loureirof7fcb982020-11-24 16:44:12 +000044static constexpr uint64_t kAllowTestApiAccess = 166236554;
atrost2dea0792020-02-25 20:11:47 +000045
Andrei Onea3098e362021-01-26 18:30:54 +000046static constexpr uint64_t kMaxLogWarnings = 100;
47
Mathew Inwood27199e62018-04-11 16:08:21 +010048// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
Andrei Oneafc12a6c2020-07-29 19:52:34 +010049// conditionally and unconditionally blocked. This can be set to true for developer preview / beta
50// builds, but should be false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010051// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
Andrei Oneafc12a6c2020-07-29 19:52:34 +010052// as it affects whether or not we warn for unsupported APIs that have been added to the exemptions
Mathew Inwood6d6012e2018-04-12 15:43:11 +010053// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010054static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010055
Artur Satayev4a1e4dd2020-04-23 22:28:59 +010056// Exemptions for logcat warning. Following signatures do not produce a warning as app developers
Andrei Oneafc12a6c2020-07-29 19:52:34 +010057// should not be alerted on the usage of these unsupported APIs. See b/154851649.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +010058static const std::vector<std::string> kWarningExemptions = {
59 "Ljava/nio/Buffer;",
60 "Llibcore/io/Memory;",
61 "Lsun/misc/Unsafe;",
62};
63
Andreas Gampe80f5fe52018-03-28 16:23:24 -070064static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
65 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010066 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010067 LOG(FATAL) << "Internal access to hidden API should not be logged";
68 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010069 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070070 os << "reflection";
71 break;
David Brazdilf50ac102018-10-17 18:00:06 +010072 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070073 os << "JNI";
74 break;
David Brazdilf50ac102018-10-17 18:00:06 +010075 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070076 os << "linking";
77 break;
78 }
79 return os;
80}
81
David Brazdile7681822018-12-14 16:25:33 +000082static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
83 REQUIRES_SHARED(Locks::mutator_lock_) {
84 if (!value.GetClass().IsNull()) {
85 std::string tmp;
86 os << value.GetClass()->GetDescriptor(&tmp);
87 } else if (value.GetDexFile() != nullptr) {
88 os << value.GetDexFile()->GetLocation();
89 } else {
90 os << "<unknown_caller>";
91 }
92 return os;
93}
94
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000095static Domain DetermineDomainFromLocation(const std::string& dex_location,
96 ObjPtr<mirror::ClassLoader> class_loader) {
David Brazdilbfaba282019-03-15 11:35:51 +000097 // If running with APEX, check `path` against known APEX locations.
Martin Stjernholme58624f2019-09-20 15:53:40 +010098 // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
David Brazdilbfaba282019-03-15 11:35:51 +000099 // is set to "/system".
Martin Stjernholme58624f2019-09-20 15:53:40 +0100100 if (ArtModuleRootDistinctFromAndroidRoot()) {
101 if (LocationIsOnArtModule(dex_location.c_str()) ||
Victor Changd20e51d2020-05-05 16:01:19 +0100102 LocationIsOnConscryptModule(dex_location.c_str()) ||
103 LocationIsOnI18nModule(dex_location.c_str())) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000104 return Domain::kCorePlatform;
David Brazdilbfaba282019-03-15 11:35:51 +0000105 }
106
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000107 if (LocationIsOnApex(dex_location.c_str())) {
David Brazdilbfaba282019-03-15 11:35:51 +0000108 return Domain::kPlatform;
109 }
110 }
111
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000112 if (LocationIsOnSystemFramework(dex_location.c_str())) {
David Brazdila5c3a802019-03-08 14:59:41 +0000113 return Domain::kPlatform;
114 }
115
Chris Gross5477b8e2020-04-24 09:36:45 -0700116 if (LocationIsOnSystemExtFramework(dex_location.c_str())) {
117 return Domain::kPlatform;
118 }
119
David Brazdila5c3a802019-03-08 14:59:41 +0000120 if (class_loader.IsNull()) {
Nicolas Geoffray5158d4a2020-05-27 08:50:06 +0100121 if (kIsTargetBuild && !kIsTargetLinux) {
122 // This is unexpected only when running on Android.
123 LOG(WARNING) << "DexFile " << dex_location
124 << " is in boot class path but is not in a known location";
125 }
David Brazdila5c3a802019-03-08 14:59:41 +0000126 return Domain::kPlatform;
127 }
128
129 return Domain::kApplication;
130}
131
David Brazdila5c3a802019-03-08 14:59:41 +0000132void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000133 Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
David Brazdila5c3a802019-03-08 14:59:41 +0000134
135 // Assign the domain unless a more permissive domain has already been assigned.
136 // This may happen when DexFile is initialized as trusted.
137 if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
138 dex_file.SetHiddenapiDomain(dex_domain);
139 }
140}
141
Orion Hodson814b9282020-02-19 16:37:11 +0000142void InitializeCorePlatformApiPrivateFields() {
143 // The following fields in WellKnownClasses correspond to private fields in the Core Platform
144 // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
145 jfieldID private_core_platform_api_fields[] = {
Orion Hodsoneb070f02020-03-10 14:00:18 +0000146 WellKnownClasses::java_io_FileDescriptor_descriptor,
Orion Hodson814b9282020-02-19 16:37:11 +0000147 WellKnownClasses::java_nio_Buffer_address,
148 WellKnownClasses::java_nio_Buffer_elementSizeShift,
149 WellKnownClasses::java_nio_Buffer_limit,
150 WellKnownClasses::java_nio_Buffer_position,
151 };
152
153 ScopedObjectAccess soa(Thread::Current());
154 for (const auto private_core_platform_api_field : private_core_platform_api_fields) {
155 ArtField* field = jni::DecodeArtField(private_core_platform_api_field);
156 const uint32_t access_flags = field->GetAccessFlags();
157 uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
158 DCHECK(new_access_flags != access_flags);
159 field->SetAccessFlags(new_access_flags);
160 }
161}
162
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700163namespace detail {
164
David Brazdilf50ac102018-10-17 18:00:06 +0100165// Do not change the values of items in this enum, as they are written to the
166// event log for offline analysis. Any changes will interfere with that analysis.
167enum AccessContextFlags {
168 // Accessed member is a field if this bit is set, else a method
169 kMemberIsField = 1 << 0,
170 // Indicates if access was denied to the member, instead of just printing a warning.
171 kAccessDenied = 1 << 1,
172};
173
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700174MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100175 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
176 member_name_ = field->GetName();
177 type_signature_ = field->GetTypeDescriptor();
178 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700179}
180
181MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil6a1dab42019-02-28 18:45:15 +0000182 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
183 << "Caller should have replaced proxy method with interface method";
Mathew Inwood73ddda42018-04-03 15:32:32 +0100184 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
185 member_name_ = method->GetName();
186 type_signature_ = method->GetSignature().ToString();
187 type_ = kMethod;
188}
189
David Brazdil1a658632018-12-01 17:54:26 +0000190MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
191 const DexFile& dex_file = field.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800192 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000193 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
194 member_name_ = dex_file.GetFieldName(field_id);
195 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
196 type_ = kField;
197}
198
199MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
200 const DexFile& dex_file = method.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800201 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000202 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
203 member_name_ = dex_file.GetMethodName(method_id);
204 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
205 type_ = kMethod;
206}
207
Mathew Inwood73ddda42018-04-03 15:32:32 +0100208inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
209 if (type_ == kField) {
210 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
211 } else {
212 DCHECK_EQ(type_, kMethod);
213 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
214 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700215}
216
217bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
218 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100219 for (const char* part : GetSignatureParts()) {
220 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700221 if (prefix.compare(pos, count, part, 0, count) == 0) {
222 pos += count;
223 } else {
224 return false;
225 }
226 }
227 // We have a complete match if all parts match (we exit the loop without
228 // returning) AND we've matched the whole prefix.
229 return pos == prefix.length();
230}
231
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100232bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700233 for (const std::string& exemption : exemptions) {
234 if (DoesPrefixMatch(exemption)) {
235 return true;
236 }
237 }
238 return false;
239}
240
241void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100242 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700243 os << part;
244 }
245}
246
David Brazdil4de9bb62019-04-03 13:06:17 +0100247void MemberSignature::WarnAboutAccess(AccessMethod access_method,
248 hiddenapi::ApiList list,
249 bool access_denied) {
Andrei Onea3098e362021-01-26 18:30:54 +0000250 static std::atomic<uint64_t> log_warning_count_ = 0;
251 if (log_warning_count_ > kMaxLogWarnings) {
252 return;
253 }
Mathew Inwood73ddda42018-04-03 15:32:32 +0100254 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
David Brazdil4de9bb62019-04-03 13:06:17 +0100255 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
256 << (access_denied ? ", denied)" : ", allowed)");
Pedro Loureiro28078392021-01-21 17:09:55 +0000257 if (access_denied && list.IsTestApi()) {
258 // see b/177047045 for more details about test api access getting denied
259 LOG(WARNING) << "If this is a platform test consider enabling "
260 << "VMRuntime.ALLOW_TEST_API_ACCESS change id for this package.";
261 }
Andrei Onea3098e362021-01-26 18:30:54 +0000262 if (log_warning_count_ >= kMaxLogWarnings) {
263 LOG(WARNING) << "Reached maximum number of hidden api access warnings.";
264 }
265 ++log_warning_count_;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100266}
David Brazdilf50ac102018-10-17 18:00:06 +0100267
David Brazdil1a658632018-12-01 17:54:26 +0000268bool MemberSignature::Equals(const MemberSignature& other) {
269 return type_ == other.type_ &&
270 class_name_ == other.class_name_ &&
271 member_name_ == other.member_name_ &&
272 type_signature_ == other.type_signature_;
273}
274
275bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
276 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
277}
278
Andrei Onea6ad020d2019-02-18 12:15:51 +0000279void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
280 AccessMethod access_method,
281 bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100282#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100283 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100284 // Linking warnings come from static analysis/compilation of the bytecode
285 // and can contain false positives (i.e. code that is never run). We choose
286 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100287 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100288 return;
289 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000290 Runtime* runtime = Runtime::Current();
291 if (runtime->IsAotCompiler()) {
292 return;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100293 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000294 JNIEnvExt* env = Thread::Current()->GetJniEnv();
Mathew Inwood5bcef172018-05-01 14:40:12 +0100295 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000296 ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
297 if (env->ExceptionCheck()) {
298 env->ExceptionClear();
299 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
Mathew Inwood5bcef172018-05-01 14:40:12 +0100300 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100301 std::ostringstream signature_str;
302 Dump(signature_str);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000303 ScopedLocalRef<jstring> signature_jstr(env,
304 env->NewStringUTF(signature_str.str().c_str()));
305 if (env->ExceptionCheck()) {
306 env->ExceptionClear();
307 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
308 }
309 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
Andrei Onea6ad020d2019-02-18 12:15:51 +0000310 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
311 sampled_value,
312 package_str.get(),
313 signature_jstr.get(),
314 static_cast<jint>(access_method),
315 access_denied);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000316 if (env->ExceptionCheck()) {
317 env->ExceptionClear();
318 LOG(ERROR) << "Unable to report hidden api usage";
319 }
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100320#else
Andrei Onea6ad020d2019-02-18 12:15:51 +0000321 UNUSED(sampled_value);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100322 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100323 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100324#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700325}
326
David Brazdilf50ac102018-10-17 18:00:06 +0100327void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
328 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
329 // We can only up-call into Java during reflection and JNI down-calls.
330 return;
331 }
332
333 Runtime* runtime = Runtime::Current();
334 if (!runtime->IsAotCompiler()) {
335 ScopedObjectAccessUnchecked soa(Thread::Current());
336
337 ScopedLocalRef<jobject> consumer_object(soa.Env(),
338 soa.Env()->GetStaticObjectField(
339 WellKnownClasses::dalvik_system_VMRuntime,
340 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
341 // If the consumer is non-null, we call back to it to let it know that we
342 // have encountered an API that's in one of our lists.
343 if (consumer_object != nullptr) {
344 std::ostringstream member_signature_str;
345 Dump(member_signature_str);
346
347 ScopedLocalRef<jobject> signature_str(
348 soa.Env(),
349 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
350
351 // Call through to Consumer.accept(String memberSignature);
352 soa.Env()->CallVoidMethod(consumer_object.get(),
353 WellKnownClasses::java_util_function_Consumer_accept,
354 signature_str.get());
355 }
356 }
357}
358
David Brazdil85865692018-10-30 17:26:20 +0000359static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100360 return true;
361}
362
David Brazdil85865692018-10-30 17:26:20 +0000363static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100364 return !method->IsIntrinsic();
365}
366
367template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000368static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
David Brazdil8a6b2f32018-04-26 16:52:11 +0100369 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil0039bc52019-04-10 10:22:26 +0100370 // Update the access flags unless:
371 // (a) `member` is an intrinsic
372 // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
373 // (c) deduping warnings has been explicitly switched off.
374 if (CanUpdateRuntimeFlags(member) &&
375 !runtime->IsAotCompiler() &&
376 runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdild51e5742019-02-28 14:47:32 +0000377 member->SetAccessFlags(member->GetAccessFlags() | flag);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100378 }
379}
380
David Brazdil1a658632018-12-01 17:54:26 +0000381static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
382 return field->GetDexFieldIndex();
David Brazdil85865692018-10-30 17:26:20 +0000383}
384
David Brazdil1a658632018-12-01 17:54:26 +0000385static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
386 REQUIRES_SHARED(Locks::mutator_lock_) {
387 // Use the non-obsolete method to avoid DexFile mismatch between
388 // the method index and the declaring class.
389 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
390}
David Brazdil85865692018-10-30 17:26:20 +0000391
David Brazdil1a658632018-12-01 17:54:26 +0000392static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800393 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000394 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
395 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
396 accessor.VisitFields(fn_visit, fn_visit);
397}
398
399static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800400 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000401 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
402 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
403 accessor.VisitMethods(fn_visit, fn_visit);
404}
405
406template<typename T>
407uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
408 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
David Brazdil6a1dab42019-02-28 18:45:15 +0000409 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
David Brazdil1a658632018-12-01 17:54:26 +0000410 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
411 ClassAccessor::Field, ClassAccessor::Method>::type;
412
413 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
David Brazdil90faceb2018-12-14 14:36:15 +0000414 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
David Brazdil85865692018-10-30 17:26:20 +0000415
David Brazdil90faceb2018-12-14 14:36:15 +0000416 ApiList flags;
417 DCHECK(!flags.IsValid());
David Brazdil85865692018-10-30 17:26:20 +0000418
David Brazdil1a658632018-12-01 17:54:26 +0000419 // Check if the declaring class has ClassExt allocated. If it does, check if
420 // the pre-JVMTI redefine dex file has been set to determine if the declaring
421 // class has been JVMTI-redefined.
422 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
423 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
424 if (LIKELY(original_dex == nullptr)) {
425 // Class is not redefined. Find the class def, iterate over its members and
426 // find the entry corresponding to this `member`.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800427 const dex::ClassDef* class_def = declaring_class->GetClassDef();
David Brazdil6a1dab42019-02-28 18:45:15 +0000428 if (class_def == nullptr) {
429 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
430 DCHECK(declaring_class->IsProxyClass())
431 << "Only proxy classes are expected not to have a class def";
432 DCHECK(kMemberIsField)
433 << "Interface methods should be inspected instead of proxy class methods";
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100434 flags = ApiList::Unsupported();
David Brazdil6a1dab42019-02-28 18:45:15 +0000435 } else {
436 uint32_t member_index = GetMemberDexIndex(member);
437 auto fn_visit = [&](const AccessorType& dex_member) {
438 if (dex_member.GetIndex() == member_index) {
439 flags = ApiList(dex_member.GetHiddenapiFlags());
440 }
441 };
442 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
443 }
David Brazdil1a658632018-12-01 17:54:26 +0000444 } else {
445 // Class was redefined using JVMTI. We have a pointer to the original dex file
446 // and the class def index of this class in that dex file, but the field/method
447 // indices are lost. Iterate over all members of the class def and find the one
448 // corresponding to this `member` by name and type string comparison.
449 // This is obviously very slow, but it is only used when non-exempt code tries
450 // to access a hidden member of a JVMTI-redefined class.
451 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
452 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800453 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
David Brazdil1a658632018-12-01 17:54:26 +0000454 MemberSignature member_signature(member);
455 auto fn_visit = [&](const AccessorType& dex_member) {
456 MemberSignature cur_signature(dex_member);
457 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
458 DCHECK(member_signature.Equals(cur_signature));
David Brazdil90faceb2018-12-14 14:36:15 +0000459 flags = ApiList(dex_member.GetHiddenapiFlags());
David Brazdil1a658632018-12-01 17:54:26 +0000460 }
461 };
462 VisitMembers(*original_dex, original_class_def, fn_visit);
463 }
David Brazdil85865692018-10-30 17:26:20 +0000464
David Brazdil90faceb2018-12-14 14:36:15 +0000465 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
David Brazdil1a658632018-12-01 17:54:26 +0000466 << Dumpable<MemberSignature>(MemberSignature(member));
David Brazdil90faceb2018-12-14 14:36:15 +0000467 return flags.GetDexFlags();
David Brazdil85865692018-10-30 17:26:20 +0000468}
469
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700470template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000471bool HandleCorePlatformApiViolation(T* member,
472 const AccessContext& caller_context,
473 AccessMethod access_method,
474 EnforcementPolicy policy) {
475 DCHECK(policy != EnforcementPolicy::kDisabled)
476 << "Should never enter this function when access checks are completely disabled";
477
David Brazdile7681822018-12-14 16:25:33 +0000478 if (access_method != AccessMethod::kNone) {
David Brazdild51e5742019-02-28 14:47:32 +0000479 LOG(WARNING) << "Core platform API violation: "
480 << Dumpable<MemberSignature>(MemberSignature(member))
481 << " from " << caller_context << " using " << access_method;
482
483 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
484 // `member` to avoid reporting the violation again next time.
485 if (policy == EnforcementPolicy::kJustWarn) {
486 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
487 }
David Brazdile7681822018-12-14 16:25:33 +0000488 }
David Brazdild51e5742019-02-28 14:47:32 +0000489
490 // Deny access if enforcement is enabled.
491 return policy == EnforcementPolicy::kEnabled;
David Brazdile7681822018-12-14 16:25:33 +0000492}
493
494template<typename T>
495bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100496 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700497 Runtime* runtime = Runtime::Current();
Andrei Onea037d2822020-11-19 00:20:04 +0000498 CompatFramework& compatFramework = runtime->GetCompatFramework();
David Brazdilc5a96e42019-01-09 10:04:45 +0000499
Artur Satayev267366c2019-10-31 14:59:26 +0000500 EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
501 DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
David Brazdilc5a96e42019-01-09 10:04:45 +0000502 << "Should never enter this function when access checks are completely disabled";
David Brazdilf50ac102018-10-17 18:00:06 +0100503
David Brazdilf50ac102018-10-17 18:00:06 +0100504 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700505
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100506 // Check for an exemption first. Exempted APIs are treated as SDK.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100507 if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
David Brazdilf50ac102018-10-17 18:00:06 +0100508 // Avoid re-examining the exemption list next time.
509 // Note this results in no warning for the member, which seems like what one would expect.
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100510 // Exemptions effectively adds new members to the public API list.
David Brazdild51e5742019-02-28 14:47:32 +0000511 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
David Brazdilf50ac102018-10-17 18:00:06 +0100512 return false;
513 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700514
satayev09efc162021-02-22 17:24:57 +0000515 EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
516
Artur Satayev267366c2019-10-31 14:59:26 +0000517 bool deny_access = false;
518 if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
satayev09efc162021-02-22 17:24:57 +0000519 if (api_list.IsTestApi() &&
520 (testApiPolicy == EnforcementPolicy::kDisabled ||
521 compatFramework.IsChangeEnabled(kAllowTestApiAccess))) {
Artur Satayev267366c2019-10-31 14:59:26 +0000522 deny_access = false;
523 } else {
atrost2dea0792020-02-25 20:11:47 +0000524 switch (api_list.GetMaxAllowedSdkVersion()) {
525 case SdkVersion::kP:
Andrei Onea037d2822020-11-19 00:20:04 +0000526 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkPHiddenApis);
atrost2dea0792020-02-25 20:11:47 +0000527 break;
528 case SdkVersion::kQ:
Andrei Onea037d2822020-11-19 00:20:04 +0000529 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkQHiddenApis);
atrost2dea0792020-02-25 20:11:47 +0000530 break;
531 default:
532 deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +0000533 api_list.GetMaxAllowedSdkVersion());
atrost2dea0792020-02-25 20:11:47 +0000534 }
Artur Satayev267366c2019-10-31 14:59:26 +0000535 }
536 }
537
David Brazdilf50ac102018-10-17 18:00:06 +0100538 if (access_method != AccessMethod::kNone) {
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100539 // Warn if blocked signature is being accessed or it is not exempted.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100540 if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
541 // Print a log message with information about this class member access.
542 // We do this if we're about to deny access, or the app is debuggable.
543 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
544 member_signature.WarnAboutAccess(access_method, api_list, deny_access);
545 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700546
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100547 // If there is a StrictMode listener, notify it about this violation.
548 member_signature.NotifyHiddenApiListener(access_method);
549 }
David Brazdilf50ac102018-10-17 18:00:06 +0100550
551 // If event log sampling is enabled, report this violation.
552 if (kIsTargetBuild && !kIsTargetLinux) {
553 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
554 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
555 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
Andrei Onea6ad020d2019-02-18 12:15:51 +0000556 if (eventLogSampleRate != 0) {
557 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
558 if (sampled_value < eventLogSampleRate) {
559 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
560 }
David Brazdilf50ac102018-10-17 18:00:06 +0100561 }
562 }
563
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100564 // If this access was not denied, flag member as SDK and skip
David Brazdilf50ac102018-10-17 18:00:06 +0100565 // the warning the next time the member is accessed.
566 if (!deny_access) {
David Brazdild51e5742019-02-28 14:47:32 +0000567 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100568 }
569 }
570
David Brazdilf50ac102018-10-17 18:00:06 +0100571 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700572}
573
David Brazdile7681822018-12-14 16:25:33 +0000574// Need to instantiate these.
David Brazdil1a658632018-12-01 17:54:26 +0000575template uint32_t GetDexFlags<ArtField>(ArtField* member);
576template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
David Brazdild51e5742019-02-28 14:47:32 +0000577template bool HandleCorePlatformApiViolation(ArtField* member,
578 const AccessContext& caller_context,
579 AccessMethod access_method,
580 EnforcementPolicy policy);
581template bool HandleCorePlatformApiViolation(ArtMethod* member,
582 const AccessContext& caller_context,
583 AccessMethod access_method,
584 EnforcementPolicy policy);
David Brazdilf50ac102018-10-17 18:00:06 +0100585template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
David Brazdile7681822018-12-14 16:25:33 +0000586 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100587 AccessMethod access_method);
588template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
David Brazdile7681822018-12-14 16:25:33 +0000589 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100590 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700591} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100592
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700593} // namespace hiddenapi
594} // namespace art