blob: 62ff3ffee6a541eebdb5d01d05610673b270d889 [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>
20
David Brazdil85865692018-10-30 17:26:20 +000021#include "art_field-inl.h"
22#include "art_method-inl.h"
Andrei Onea037d2822020-11-19 00:20:04 +000023#include "compat_framework.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070024#include "base/dumpable.h"
David Brazdila5c3a802019-03-08 14:59:41 +000025#include "base/file_utils.h"
David Brazdil85865692018-10-30 17:26:20 +000026#include "dex/class_accessor-inl.h"
David Brazdil1a658632018-12-01 17:54:26 +000027#include "dex/dex_file_loader.h"
28#include "mirror/class_ext.h"
David Brazdila5c3a802019-03-08 14:59:41 +000029#include "oat_file.h"
David Brazdil85865692018-10-30 17:26:20 +000030#include "scoped_thread_state_change.h"
31#include "thread-inl.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010032#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070033
34namespace art {
35namespace hiddenapi {
36
atrost2dea0792020-02-25 20:11:47 +000037// 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.
40static constexpr uint64_t kHideMaxtargetsdkPHiddenApis = 149997251;
41static constexpr uint64_t kHideMaxtargetsdkQHiddenApis = 149994052;
42
Mathew Inwood27199e62018-04-11 16:08:21 +010043// 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 +010044// conditionally and unconditionally blocked. This can be set to true for developer preview / beta
45// builds, but should be false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010046// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
Andrei Oneafc12a6c2020-07-29 19:52:34 +010047// 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 +010048// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010049static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010050
Artur Satayev4a1e4dd2020-04-23 22:28:59 +010051// Exemptions for logcat warning. Following signatures do not produce a warning as app developers
Andrei Oneafc12a6c2020-07-29 19:52:34 +010052// should not be alerted on the usage of these unsupported APIs. See b/154851649.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +010053static const std::vector<std::string> kWarningExemptions = {
54 "Ljava/nio/Buffer;",
55 "Llibcore/io/Memory;",
56 "Lsun/misc/Unsafe;",
57};
58
Andreas Gampe80f5fe52018-03-28 16:23:24 -070059static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
60 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010061 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010062 LOG(FATAL) << "Internal access to hidden API should not be logged";
63 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010064 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070065 os << "reflection";
66 break;
David Brazdilf50ac102018-10-17 18:00:06 +010067 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070068 os << "JNI";
69 break;
David Brazdilf50ac102018-10-17 18:00:06 +010070 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070071 os << "linking";
72 break;
73 }
74 return os;
75}
76
David Brazdile7681822018-12-14 16:25:33 +000077static 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
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000090static Domain DetermineDomainFromLocation(const std::string& dex_location,
91 ObjPtr<mirror::ClassLoader> class_loader) {
David Brazdilbfaba282019-03-15 11:35:51 +000092 // If running with APEX, check `path` against known APEX locations.
Martin Stjernholme58624f2019-09-20 15:53:40 +010093 // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
David Brazdilbfaba282019-03-15 11:35:51 +000094 // is set to "/system".
Martin Stjernholme58624f2019-09-20 15:53:40 +010095 if (ArtModuleRootDistinctFromAndroidRoot()) {
96 if (LocationIsOnArtModule(dex_location.c_str()) ||
Victor Changd20e51d2020-05-05 16:01:19 +010097 LocationIsOnConscryptModule(dex_location.c_str()) ||
98 LocationIsOnI18nModule(dex_location.c_str())) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000099 return Domain::kCorePlatform;
David Brazdilbfaba282019-03-15 11:35:51 +0000100 }
101
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000102 if (LocationIsOnApex(dex_location.c_str())) {
David Brazdilbfaba282019-03-15 11:35:51 +0000103 return Domain::kPlatform;
104 }
105 }
106
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000107 if (LocationIsOnSystemFramework(dex_location.c_str())) {
David Brazdila5c3a802019-03-08 14:59:41 +0000108 return Domain::kPlatform;
109 }
110
Chris Gross5477b8e2020-04-24 09:36:45 -0700111 if (LocationIsOnSystemExtFramework(dex_location.c_str())) {
112 return Domain::kPlatform;
113 }
114
David Brazdila5c3a802019-03-08 14:59:41 +0000115 if (class_loader.IsNull()) {
Nicolas Geoffray5158d4a2020-05-27 08:50:06 +0100116 if (kIsTargetBuild && !kIsTargetLinux) {
117 // This is unexpected only when running on Android.
118 LOG(WARNING) << "DexFile " << dex_location
119 << " is in boot class path but is not in a known location";
120 }
David Brazdila5c3a802019-03-08 14:59:41 +0000121 return Domain::kPlatform;
122 }
123
124 return Domain::kApplication;
125}
126
David Brazdila5c3a802019-03-08 14:59:41 +0000127void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000128 Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
David Brazdila5c3a802019-03-08 14:59:41 +0000129
130 // Assign the domain unless a more permissive domain has already been assigned.
131 // This may happen when DexFile is initialized as trusted.
132 if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
133 dex_file.SetHiddenapiDomain(dex_domain);
134 }
135}
136
Orion Hodson814b9282020-02-19 16:37:11 +0000137void InitializeCorePlatformApiPrivateFields() {
138 // The following fields in WellKnownClasses correspond to private fields in the Core Platform
139 // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
140 jfieldID private_core_platform_api_fields[] = {
Orion Hodsoneb070f02020-03-10 14:00:18 +0000141 WellKnownClasses::java_io_FileDescriptor_descriptor,
Orion Hodson814b9282020-02-19 16:37:11 +0000142 WellKnownClasses::java_nio_Buffer_address,
143 WellKnownClasses::java_nio_Buffer_elementSizeShift,
144 WellKnownClasses::java_nio_Buffer_limit,
145 WellKnownClasses::java_nio_Buffer_position,
146 };
147
148 ScopedObjectAccess soa(Thread::Current());
149 for (const auto private_core_platform_api_field : private_core_platform_api_fields) {
150 ArtField* field = jni::DecodeArtField(private_core_platform_api_field);
151 const uint32_t access_flags = field->GetAccessFlags();
152 uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
153 DCHECK(new_access_flags != access_flags);
154 field->SetAccessFlags(new_access_flags);
155 }
156}
157
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700158namespace detail {
159
David Brazdilf50ac102018-10-17 18:00:06 +0100160// Do not change the values of items in this enum, as they are written to the
161// event log for offline analysis. Any changes will interfere with that analysis.
162enum AccessContextFlags {
163 // Accessed member is a field if this bit is set, else a method
164 kMemberIsField = 1 << 0,
165 // Indicates if access was denied to the member, instead of just printing a warning.
166 kAccessDenied = 1 << 1,
167};
168
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700169MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100170 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
171 member_name_ = field->GetName();
172 type_signature_ = field->GetTypeDescriptor();
173 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700174}
175
176MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil6a1dab42019-02-28 18:45:15 +0000177 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
178 << "Caller should have replaced proxy method with interface method";
Mathew Inwood73ddda42018-04-03 15:32:32 +0100179 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
180 member_name_ = method->GetName();
181 type_signature_ = method->GetSignature().ToString();
182 type_ = kMethod;
183}
184
David Brazdil1a658632018-12-01 17:54:26 +0000185MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
186 const DexFile& dex_file = field.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800187 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000188 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
189 member_name_ = dex_file.GetFieldName(field_id);
190 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
191 type_ = kField;
192}
193
194MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
195 const DexFile& dex_file = method.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800196 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000197 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
198 member_name_ = dex_file.GetMethodName(method_id);
199 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
200 type_ = kMethod;
201}
202
Mathew Inwood73ddda42018-04-03 15:32:32 +0100203inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
204 if (type_ == kField) {
205 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
206 } else {
207 DCHECK_EQ(type_, kMethod);
208 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
209 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700210}
211
212bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
213 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100214 for (const char* part : GetSignatureParts()) {
215 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700216 if (prefix.compare(pos, count, part, 0, count) == 0) {
217 pos += count;
218 } else {
219 return false;
220 }
221 }
222 // We have a complete match if all parts match (we exit the loop without
223 // returning) AND we've matched the whole prefix.
224 return pos == prefix.length();
225}
226
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100227bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700228 for (const std::string& exemption : exemptions) {
229 if (DoesPrefixMatch(exemption)) {
230 return true;
231 }
232 }
233 return false;
234}
235
236void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100237 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700238 os << part;
239 }
240}
241
David Brazdil4de9bb62019-04-03 13:06:17 +0100242void MemberSignature::WarnAboutAccess(AccessMethod access_method,
243 hiddenapi::ApiList list,
244 bool access_denied) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100245 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
David Brazdil4de9bb62019-04-03 13:06:17 +0100246 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
247 << (access_denied ? ", denied)" : ", allowed)");
Mathew Inwood73ddda42018-04-03 15:32:32 +0100248}
David Brazdilf50ac102018-10-17 18:00:06 +0100249
David Brazdil1a658632018-12-01 17:54:26 +0000250bool MemberSignature::Equals(const MemberSignature& other) {
251 return type_ == other.type_ &&
252 class_name_ == other.class_name_ &&
253 member_name_ == other.member_name_ &&
254 type_signature_ == other.type_signature_;
255}
256
257bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
258 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
259}
260
Andrei Onea6ad020d2019-02-18 12:15:51 +0000261void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
262 AccessMethod access_method,
263 bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100264#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100265 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100266 // Linking warnings come from static analysis/compilation of the bytecode
267 // and can contain false positives (i.e. code that is never run). We choose
268 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100269 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100270 return;
271 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000272 Runtime* runtime = Runtime::Current();
273 if (runtime->IsAotCompiler()) {
274 return;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100275 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000276 JNIEnvExt* env = Thread::Current()->GetJniEnv();
Mathew Inwood5bcef172018-05-01 14:40:12 +0100277 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000278 ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
279 if (env->ExceptionCheck()) {
280 env->ExceptionClear();
281 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
Mathew Inwood5bcef172018-05-01 14:40:12 +0100282 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100283 std::ostringstream signature_str;
284 Dump(signature_str);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000285 ScopedLocalRef<jstring> signature_jstr(env,
286 env->NewStringUTF(signature_str.str().c_str()));
287 if (env->ExceptionCheck()) {
288 env->ExceptionClear();
289 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
290 }
291 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
Andrei Onea6ad020d2019-02-18 12:15:51 +0000292 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
293 sampled_value,
294 package_str.get(),
295 signature_jstr.get(),
296 static_cast<jint>(access_method),
297 access_denied);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000298 if (env->ExceptionCheck()) {
299 env->ExceptionClear();
300 LOG(ERROR) << "Unable to report hidden api usage";
301 }
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100302#else
Andrei Onea6ad020d2019-02-18 12:15:51 +0000303 UNUSED(sampled_value);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100304 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100305 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100306#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700307}
308
David Brazdilf50ac102018-10-17 18:00:06 +0100309void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
310 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
311 // We can only up-call into Java during reflection and JNI down-calls.
312 return;
313 }
314
315 Runtime* runtime = Runtime::Current();
316 if (!runtime->IsAotCompiler()) {
317 ScopedObjectAccessUnchecked soa(Thread::Current());
318
319 ScopedLocalRef<jobject> consumer_object(soa.Env(),
320 soa.Env()->GetStaticObjectField(
321 WellKnownClasses::dalvik_system_VMRuntime,
322 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
323 // If the consumer is non-null, we call back to it to let it know that we
324 // have encountered an API that's in one of our lists.
325 if (consumer_object != nullptr) {
326 std::ostringstream member_signature_str;
327 Dump(member_signature_str);
328
329 ScopedLocalRef<jobject> signature_str(
330 soa.Env(),
331 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
332
333 // Call through to Consumer.accept(String memberSignature);
334 soa.Env()->CallVoidMethod(consumer_object.get(),
335 WellKnownClasses::java_util_function_Consumer_accept,
336 signature_str.get());
337 }
338 }
339}
340
David Brazdil85865692018-10-30 17:26:20 +0000341static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100342 return true;
343}
344
David Brazdil85865692018-10-30 17:26:20 +0000345static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100346 return !method->IsIntrinsic();
347}
348
349template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000350static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
David Brazdil8a6b2f32018-04-26 16:52:11 +0100351 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil0039bc52019-04-10 10:22:26 +0100352 // Update the access flags unless:
353 // (a) `member` is an intrinsic
354 // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
355 // (c) deduping warnings has been explicitly switched off.
356 if (CanUpdateRuntimeFlags(member) &&
357 !runtime->IsAotCompiler() &&
358 runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdild51e5742019-02-28 14:47:32 +0000359 member->SetAccessFlags(member->GetAccessFlags() | flag);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100360 }
361}
362
David Brazdil1a658632018-12-01 17:54:26 +0000363static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
364 return field->GetDexFieldIndex();
David Brazdil85865692018-10-30 17:26:20 +0000365}
366
David Brazdil1a658632018-12-01 17:54:26 +0000367static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
368 REQUIRES_SHARED(Locks::mutator_lock_) {
369 // Use the non-obsolete method to avoid DexFile mismatch between
370 // the method index and the declaring class.
371 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
372}
David Brazdil85865692018-10-30 17:26:20 +0000373
David Brazdil1a658632018-12-01 17:54:26 +0000374static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800375 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000376 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
377 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
378 accessor.VisitFields(fn_visit, fn_visit);
379}
380
381static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800382 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000383 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
384 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
385 accessor.VisitMethods(fn_visit, fn_visit);
386}
387
388template<typename T>
389uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
390 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
David Brazdil6a1dab42019-02-28 18:45:15 +0000391 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
David Brazdil1a658632018-12-01 17:54:26 +0000392 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
393 ClassAccessor::Field, ClassAccessor::Method>::type;
394
395 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
David Brazdil90faceb2018-12-14 14:36:15 +0000396 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
David Brazdil85865692018-10-30 17:26:20 +0000397
David Brazdil90faceb2018-12-14 14:36:15 +0000398 ApiList flags;
399 DCHECK(!flags.IsValid());
David Brazdil85865692018-10-30 17:26:20 +0000400
David Brazdil1a658632018-12-01 17:54:26 +0000401 // Check if the declaring class has ClassExt allocated. If it does, check if
402 // the pre-JVMTI redefine dex file has been set to determine if the declaring
403 // class has been JVMTI-redefined.
404 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
405 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
406 if (LIKELY(original_dex == nullptr)) {
407 // Class is not redefined. Find the class def, iterate over its members and
408 // find the entry corresponding to this `member`.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800409 const dex::ClassDef* class_def = declaring_class->GetClassDef();
David Brazdil6a1dab42019-02-28 18:45:15 +0000410 if (class_def == nullptr) {
411 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
412 DCHECK(declaring_class->IsProxyClass())
413 << "Only proxy classes are expected not to have a class def";
414 DCHECK(kMemberIsField)
415 << "Interface methods should be inspected instead of proxy class methods";
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100416 flags = ApiList::Unsupported();
David Brazdil6a1dab42019-02-28 18:45:15 +0000417 } else {
418 uint32_t member_index = GetMemberDexIndex(member);
419 auto fn_visit = [&](const AccessorType& dex_member) {
420 if (dex_member.GetIndex() == member_index) {
421 flags = ApiList(dex_member.GetHiddenapiFlags());
422 }
423 };
424 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
425 }
David Brazdil1a658632018-12-01 17:54:26 +0000426 } else {
427 // Class was redefined using JVMTI. We have a pointer to the original dex file
428 // and the class def index of this class in that dex file, but the field/method
429 // indices are lost. Iterate over all members of the class def and find the one
430 // corresponding to this `member` by name and type string comparison.
431 // This is obviously very slow, but it is only used when non-exempt code tries
432 // to access a hidden member of a JVMTI-redefined class.
433 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
434 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800435 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
David Brazdil1a658632018-12-01 17:54:26 +0000436 MemberSignature member_signature(member);
437 auto fn_visit = [&](const AccessorType& dex_member) {
438 MemberSignature cur_signature(dex_member);
439 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
440 DCHECK(member_signature.Equals(cur_signature));
David Brazdil90faceb2018-12-14 14:36:15 +0000441 flags = ApiList(dex_member.GetHiddenapiFlags());
David Brazdil1a658632018-12-01 17:54:26 +0000442 }
443 };
444 VisitMembers(*original_dex, original_class_def, fn_visit);
445 }
David Brazdil85865692018-10-30 17:26:20 +0000446
David Brazdil90faceb2018-12-14 14:36:15 +0000447 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
David Brazdil1a658632018-12-01 17:54:26 +0000448 << Dumpable<MemberSignature>(MemberSignature(member));
David Brazdil90faceb2018-12-14 14:36:15 +0000449 return flags.GetDexFlags();
David Brazdil85865692018-10-30 17:26:20 +0000450}
451
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700452template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000453bool HandleCorePlatformApiViolation(T* member,
454 const AccessContext& caller_context,
455 AccessMethod access_method,
456 EnforcementPolicy policy) {
457 DCHECK(policy != EnforcementPolicy::kDisabled)
458 << "Should never enter this function when access checks are completely disabled";
459
David Brazdile7681822018-12-14 16:25:33 +0000460 if (access_method != AccessMethod::kNone) {
David Brazdild51e5742019-02-28 14:47:32 +0000461 LOG(WARNING) << "Core platform API violation: "
462 << Dumpable<MemberSignature>(MemberSignature(member))
463 << " from " << caller_context << " using " << access_method;
464
465 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
466 // `member` to avoid reporting the violation again next time.
467 if (policy == EnforcementPolicy::kJustWarn) {
468 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
469 }
David Brazdile7681822018-12-14 16:25:33 +0000470 }
David Brazdild51e5742019-02-28 14:47:32 +0000471
472 // Deny access if enforcement is enabled.
473 return policy == EnforcementPolicy::kEnabled;
David Brazdile7681822018-12-14 16:25:33 +0000474}
475
476template<typename T>
477bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100478 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700479 Runtime* runtime = Runtime::Current();
Andrei Onea037d2822020-11-19 00:20:04 +0000480 CompatFramework& compatFramework = runtime->GetCompatFramework();
David Brazdilc5a96e42019-01-09 10:04:45 +0000481
Artur Satayev267366c2019-10-31 14:59:26 +0000482 EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
483 DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
David Brazdilc5a96e42019-01-09 10:04:45 +0000484 << "Should never enter this function when access checks are completely disabled";
David Brazdilf50ac102018-10-17 18:00:06 +0100485
David Brazdilf50ac102018-10-17 18:00:06 +0100486 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700487
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100488 // Check for an exemption first. Exempted APIs are treated as SDK.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100489 if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
David Brazdilf50ac102018-10-17 18:00:06 +0100490 // Avoid re-examining the exemption list next time.
491 // Note this results in no warning for the member, which seems like what one would expect.
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100492 // Exemptions effectively adds new members to the public API list.
David Brazdild51e5742019-02-28 14:47:32 +0000493 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
David Brazdilf50ac102018-10-17 18:00:06 +0100494 return false;
495 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700496
Artur Satayev267366c2019-10-31 14:59:26 +0000497 EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
498
499 bool deny_access = false;
500 if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
501 if (testApiPolicy == EnforcementPolicy::kDisabled && api_list.IsTestApi()) {
502 deny_access = false;
503 } else {
atrost2dea0792020-02-25 20:11:47 +0000504 switch (api_list.GetMaxAllowedSdkVersion()) {
505 case SdkVersion::kP:
Andrei Onea037d2822020-11-19 00:20:04 +0000506 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkPHiddenApis);
atrost2dea0792020-02-25 20:11:47 +0000507 break;
508 case SdkVersion::kQ:
Andrei Onea037d2822020-11-19 00:20:04 +0000509 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkQHiddenApis);
atrost2dea0792020-02-25 20:11:47 +0000510 break;
511 default:
512 deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
513 api_list.GetMaxAllowedSdkVersion());
514 }
Artur Satayev267366c2019-10-31 14:59:26 +0000515 }
516 }
517
David Brazdilf50ac102018-10-17 18:00:06 +0100518 if (access_method != AccessMethod::kNone) {
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100519 // Warn if blocked signature is being accessed or it is not exempted.
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100520 if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
521 // Print a log message with information about this class member access.
522 // We do this if we're about to deny access, or the app is debuggable.
523 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
524 member_signature.WarnAboutAccess(access_method, api_list, deny_access);
525 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700526
Artur Satayev4a1e4dd2020-04-23 22:28:59 +0100527 // If there is a StrictMode listener, notify it about this violation.
528 member_signature.NotifyHiddenApiListener(access_method);
529 }
David Brazdilf50ac102018-10-17 18:00:06 +0100530
531 // If event log sampling is enabled, report this violation.
532 if (kIsTargetBuild && !kIsTargetLinux) {
533 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
534 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
535 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
Andrei Onea6ad020d2019-02-18 12:15:51 +0000536 if (eventLogSampleRate != 0) {
537 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
538 if (sampled_value < eventLogSampleRate) {
539 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
540 }
David Brazdilf50ac102018-10-17 18:00:06 +0100541 }
542 }
543
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100544 // If this access was not denied, flag member as SDK and skip
David Brazdilf50ac102018-10-17 18:00:06 +0100545 // the warning the next time the member is accessed.
546 if (!deny_access) {
David Brazdild51e5742019-02-28 14:47:32 +0000547 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100548 }
549 }
550
David Brazdilf50ac102018-10-17 18:00:06 +0100551 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700552}
553
David Brazdile7681822018-12-14 16:25:33 +0000554// Need to instantiate these.
David Brazdil1a658632018-12-01 17:54:26 +0000555template uint32_t GetDexFlags<ArtField>(ArtField* member);
556template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
David Brazdild51e5742019-02-28 14:47:32 +0000557template bool HandleCorePlatformApiViolation(ArtField* member,
558 const AccessContext& caller_context,
559 AccessMethod access_method,
560 EnforcementPolicy policy);
561template bool HandleCorePlatformApiViolation(ArtMethod* member,
562 const AccessContext& caller_context,
563 AccessMethod access_method,
564 EnforcementPolicy policy);
David Brazdilf50ac102018-10-17 18:00:06 +0100565template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
David Brazdile7681822018-12-14 16:25:33 +0000566 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100567 AccessMethod access_method);
568template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
David Brazdile7681822018-12-14 16:25:33 +0000569 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100570 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700571} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100572
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700573} // namespace hiddenapi
574} // namespace art