blob: c55a134cf6d37e693cc6b886484a5c73df1c5a2f [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"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070023#include "base/dumpable.h"
David Brazdila5c3a802019-03-08 14:59:41 +000024#include "base/file_utils.h"
David Brazdil1a658632018-12-01 17:54:26 +000025#include "class_root.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
44// dark grey and black. This can be set to true for developer preview / beta builds, but should be
45// false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010046// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
47// as it affects whether or not we warn for light grey APIs that have been added to the exemptions
48// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010049static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010050
Andreas Gampe80f5fe52018-03-28 16:23:24 -070051static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
52 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010053 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010054 LOG(FATAL) << "Internal access to hidden API should not be logged";
55 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010056 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070057 os << "reflection";
58 break;
David Brazdilf50ac102018-10-17 18:00:06 +010059 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070060 os << "JNI";
61 break;
David Brazdilf50ac102018-10-17 18:00:06 +010062 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070063 os << "linking";
64 break;
65 }
66 return os;
67}
68
David Brazdile7681822018-12-14 16:25:33 +000069static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
70 REQUIRES_SHARED(Locks::mutator_lock_) {
71 if (!value.GetClass().IsNull()) {
72 std::string tmp;
73 os << value.GetClass()->GetDescriptor(&tmp);
74 } else if (value.GetDexFile() != nullptr) {
75 os << value.GetDexFile()->GetLocation();
76 } else {
77 os << "<unknown_caller>";
78 }
79 return os;
80}
81
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000082static Domain DetermineDomainFromLocation(const std::string& dex_location,
83 ObjPtr<mirror::ClassLoader> class_loader) {
David Brazdilbfaba282019-03-15 11:35:51 +000084 // If running with APEX, check `path` against known APEX locations.
Martin Stjernholme58624f2019-09-20 15:53:40 +010085 // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
David Brazdilbfaba282019-03-15 11:35:51 +000086 // is set to "/system".
Martin Stjernholme58624f2019-09-20 15:53:40 +010087 if (ArtModuleRootDistinctFromAndroidRoot()) {
88 if (LocationIsOnArtModule(dex_location.c_str()) ||
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000089 LocationIsOnConscryptModule(dex_location.c_str())) {
90 return Domain::kCorePlatform;
David Brazdilbfaba282019-03-15 11:35:51 +000091 }
92
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000093 if (LocationIsOnApex(dex_location.c_str())) {
David Brazdilbfaba282019-03-15 11:35:51 +000094 return Domain::kPlatform;
95 }
96 }
97
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000098 if (LocationIsOnSystemFramework(dex_location.c_str())) {
David Brazdila5c3a802019-03-08 14:59:41 +000099 return Domain::kPlatform;
100 }
101
David Brazdila5c3a802019-03-08 14:59:41 +0000102 if (class_loader.IsNull()) {
103 LOG(WARNING) << "DexFile " << dex_location
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000104 << " is in boot class path but is not in a known location";
David Brazdila5c3a802019-03-08 14:59:41 +0000105 return Domain::kPlatform;
106 }
107
108 return Domain::kApplication;
109}
110
David Brazdila5c3a802019-03-08 14:59:41 +0000111void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000112 Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
David Brazdila5c3a802019-03-08 14:59:41 +0000113
114 // Assign the domain unless a more permissive domain has already been assigned.
115 // This may happen when DexFile is initialized as trusted.
116 if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
117 dex_file.SetHiddenapiDomain(dex_domain);
118 }
119}
120
Orion Hodson814b9282020-02-19 16:37:11 +0000121void InitializeCorePlatformApiPrivateFields() {
122 // The following fields in WellKnownClasses correspond to private fields in the Core Platform
123 // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
124 jfieldID private_core_platform_api_fields[] = {
125 WellKnownClasses::java_nio_Buffer_address,
126 WellKnownClasses::java_nio_Buffer_elementSizeShift,
127 WellKnownClasses::java_nio_Buffer_limit,
128 WellKnownClasses::java_nio_Buffer_position,
129 };
130
131 ScopedObjectAccess soa(Thread::Current());
132 for (const auto private_core_platform_api_field : private_core_platform_api_fields) {
133 ArtField* field = jni::DecodeArtField(private_core_platform_api_field);
134 const uint32_t access_flags = field->GetAccessFlags();
135 uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
136 DCHECK(new_access_flags != access_flags);
137 field->SetAccessFlags(new_access_flags);
138 }
139}
140
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700141namespace detail {
142
David Brazdilf50ac102018-10-17 18:00:06 +0100143// Do not change the values of items in this enum, as they are written to the
144// event log for offline analysis. Any changes will interfere with that analysis.
145enum AccessContextFlags {
146 // Accessed member is a field if this bit is set, else a method
147 kMemberIsField = 1 << 0,
148 // Indicates if access was denied to the member, instead of just printing a warning.
149 kAccessDenied = 1 << 1,
150};
151
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700152MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100153 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
154 member_name_ = field->GetName();
155 type_signature_ = field->GetTypeDescriptor();
156 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700157}
158
159MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil6a1dab42019-02-28 18:45:15 +0000160 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
161 << "Caller should have replaced proxy method with interface method";
Mathew Inwood73ddda42018-04-03 15:32:32 +0100162 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
163 member_name_ = method->GetName();
164 type_signature_ = method->GetSignature().ToString();
165 type_ = kMethod;
166}
167
David Brazdil1a658632018-12-01 17:54:26 +0000168MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
169 const DexFile& dex_file = field.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800170 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000171 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
172 member_name_ = dex_file.GetFieldName(field_id);
173 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
174 type_ = kField;
175}
176
177MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
178 const DexFile& dex_file = method.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800179 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000180 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
181 member_name_ = dex_file.GetMethodName(method_id);
182 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
183 type_ = kMethod;
184}
185
Mathew Inwood73ddda42018-04-03 15:32:32 +0100186inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
187 if (type_ == kField) {
188 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
189 } else {
190 DCHECK_EQ(type_, kMethod);
191 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
192 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700193}
194
195bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
196 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100197 for (const char* part : GetSignatureParts()) {
198 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700199 if (prefix.compare(pos, count, part, 0, count) == 0) {
200 pos += count;
201 } else {
202 return false;
203 }
204 }
205 // We have a complete match if all parts match (we exit the loop without
206 // returning) AND we've matched the whole prefix.
207 return pos == prefix.length();
208}
209
210bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
211 for (const std::string& exemption : exemptions) {
212 if (DoesPrefixMatch(exemption)) {
213 return true;
214 }
215 }
216 return false;
217}
218
219void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100220 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700221 os << part;
222 }
223}
224
David Brazdil4de9bb62019-04-03 13:06:17 +0100225void MemberSignature::WarnAboutAccess(AccessMethod access_method,
226 hiddenapi::ApiList list,
227 bool access_denied) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100228 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
David Brazdil4de9bb62019-04-03 13:06:17 +0100229 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method
230 << (access_denied ? ", denied)" : ", allowed)");
Mathew Inwood73ddda42018-04-03 15:32:32 +0100231}
David Brazdilf50ac102018-10-17 18:00:06 +0100232
David Brazdil1a658632018-12-01 17:54:26 +0000233bool MemberSignature::Equals(const MemberSignature& other) {
234 return type_ == other.type_ &&
235 class_name_ == other.class_name_ &&
236 member_name_ == other.member_name_ &&
237 type_signature_ == other.type_signature_;
238}
239
240bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
241 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
242}
243
Andrei Onea6ad020d2019-02-18 12:15:51 +0000244void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
245 AccessMethod access_method,
246 bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100247#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100248 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100249 // Linking warnings come from static analysis/compilation of the bytecode
250 // and can contain false positives (i.e. code that is never run). We choose
251 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100252 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100253 return;
254 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000255 Runtime* runtime = Runtime::Current();
256 if (runtime->IsAotCompiler()) {
257 return;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100258 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000259 JNIEnvExt* env = Thread::Current()->GetJniEnv();
Mathew Inwood5bcef172018-05-01 14:40:12 +0100260 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000261 ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
262 if (env->ExceptionCheck()) {
263 env->ExceptionClear();
264 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
Mathew Inwood5bcef172018-05-01 14:40:12 +0100265 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100266 std::ostringstream signature_str;
267 Dump(signature_str);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000268 ScopedLocalRef<jstring> signature_jstr(env,
269 env->NewStringUTF(signature_str.str().c_str()));
270 if (env->ExceptionCheck()) {
271 env->ExceptionClear();
272 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
273 }
274 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
Andrei Onea6ad020d2019-02-18 12:15:51 +0000275 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
276 sampled_value,
277 package_str.get(),
278 signature_jstr.get(),
279 static_cast<jint>(access_method),
280 access_denied);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000281 if (env->ExceptionCheck()) {
282 env->ExceptionClear();
283 LOG(ERROR) << "Unable to report hidden api usage";
284 }
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100285#else
Andrei Onea6ad020d2019-02-18 12:15:51 +0000286 UNUSED(sampled_value);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100287 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100288 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100289#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700290}
291
David Brazdilf50ac102018-10-17 18:00:06 +0100292void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
293 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
294 // We can only up-call into Java during reflection and JNI down-calls.
295 return;
296 }
297
298 Runtime* runtime = Runtime::Current();
299 if (!runtime->IsAotCompiler()) {
300 ScopedObjectAccessUnchecked soa(Thread::Current());
301
302 ScopedLocalRef<jobject> consumer_object(soa.Env(),
303 soa.Env()->GetStaticObjectField(
304 WellKnownClasses::dalvik_system_VMRuntime,
305 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
306 // If the consumer is non-null, we call back to it to let it know that we
307 // have encountered an API that's in one of our lists.
308 if (consumer_object != nullptr) {
309 std::ostringstream member_signature_str;
310 Dump(member_signature_str);
311
312 ScopedLocalRef<jobject> signature_str(
313 soa.Env(),
314 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
315
316 // Call through to Consumer.accept(String memberSignature);
317 soa.Env()->CallVoidMethod(consumer_object.get(),
318 WellKnownClasses::java_util_function_Consumer_accept,
319 signature_str.get());
320 }
321 }
322}
323
David Brazdil85865692018-10-30 17:26:20 +0000324static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100325 return true;
326}
327
David Brazdil85865692018-10-30 17:26:20 +0000328static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100329 return !method->IsIntrinsic();
330}
331
332template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000333static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
David Brazdil8a6b2f32018-04-26 16:52:11 +0100334 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil0039bc52019-04-10 10:22:26 +0100335 // Update the access flags unless:
336 // (a) `member` is an intrinsic
337 // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
338 // (c) deduping warnings has been explicitly switched off.
339 if (CanUpdateRuntimeFlags(member) &&
340 !runtime->IsAotCompiler() &&
341 runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdild51e5742019-02-28 14:47:32 +0000342 member->SetAccessFlags(member->GetAccessFlags() | flag);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100343 }
344}
345
David Brazdil1a658632018-12-01 17:54:26 +0000346static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
347 return field->GetDexFieldIndex();
David Brazdil85865692018-10-30 17:26:20 +0000348}
349
David Brazdil1a658632018-12-01 17:54:26 +0000350static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
351 REQUIRES_SHARED(Locks::mutator_lock_) {
352 // Use the non-obsolete method to avoid DexFile mismatch between
353 // the method index and the declaring class.
354 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
355}
David Brazdil85865692018-10-30 17:26:20 +0000356
David Brazdil1a658632018-12-01 17:54:26 +0000357static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800358 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000359 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
360 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
361 accessor.VisitFields(fn_visit, fn_visit);
362}
363
364static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800365 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000366 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
367 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
368 accessor.VisitMethods(fn_visit, fn_visit);
369}
370
371template<typename T>
372uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
373 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
David Brazdil6a1dab42019-02-28 18:45:15 +0000374 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
David Brazdil1a658632018-12-01 17:54:26 +0000375 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
376 ClassAccessor::Field, ClassAccessor::Method>::type;
377
378 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
David Brazdil90faceb2018-12-14 14:36:15 +0000379 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
David Brazdil85865692018-10-30 17:26:20 +0000380
David Brazdil90faceb2018-12-14 14:36:15 +0000381 ApiList flags;
382 DCHECK(!flags.IsValid());
David Brazdil85865692018-10-30 17:26:20 +0000383
David Brazdil1a658632018-12-01 17:54:26 +0000384 // Check if the declaring class has ClassExt allocated. If it does, check if
385 // the pre-JVMTI redefine dex file has been set to determine if the declaring
386 // class has been JVMTI-redefined.
387 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
388 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
389 if (LIKELY(original_dex == nullptr)) {
390 // Class is not redefined. Find the class def, iterate over its members and
391 // find the entry corresponding to this `member`.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800392 const dex::ClassDef* class_def = declaring_class->GetClassDef();
David Brazdil6a1dab42019-02-28 18:45:15 +0000393 if (class_def == nullptr) {
394 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
395 DCHECK(declaring_class->IsProxyClass())
396 << "Only proxy classes are expected not to have a class def";
397 DCHECK(kMemberIsField)
398 << "Interface methods should be inspected instead of proxy class methods";
399 flags = ApiList::Greylist();
400 } else {
401 uint32_t member_index = GetMemberDexIndex(member);
402 auto fn_visit = [&](const AccessorType& dex_member) {
403 if (dex_member.GetIndex() == member_index) {
404 flags = ApiList(dex_member.GetHiddenapiFlags());
405 }
406 };
407 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
408 }
David Brazdil1a658632018-12-01 17:54:26 +0000409 } else {
410 // Class was redefined using JVMTI. We have a pointer to the original dex file
411 // and the class def index of this class in that dex file, but the field/method
412 // indices are lost. Iterate over all members of the class def and find the one
413 // corresponding to this `member` by name and type string comparison.
414 // This is obviously very slow, but it is only used when non-exempt code tries
415 // to access a hidden member of a JVMTI-redefined class.
416 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
417 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800418 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
David Brazdil1a658632018-12-01 17:54:26 +0000419 MemberSignature member_signature(member);
420 auto fn_visit = [&](const AccessorType& dex_member) {
421 MemberSignature cur_signature(dex_member);
422 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
423 DCHECK(member_signature.Equals(cur_signature));
David Brazdil90faceb2018-12-14 14:36:15 +0000424 flags = ApiList(dex_member.GetHiddenapiFlags());
David Brazdil1a658632018-12-01 17:54:26 +0000425 }
426 };
427 VisitMembers(*original_dex, original_class_def, fn_visit);
428 }
David Brazdil85865692018-10-30 17:26:20 +0000429
David Brazdil90faceb2018-12-14 14:36:15 +0000430 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
David Brazdil1a658632018-12-01 17:54:26 +0000431 << Dumpable<MemberSignature>(MemberSignature(member));
David Brazdil90faceb2018-12-14 14:36:15 +0000432 return flags.GetDexFlags();
David Brazdil85865692018-10-30 17:26:20 +0000433}
434
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700435template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000436bool HandleCorePlatformApiViolation(T* member,
437 const AccessContext& caller_context,
438 AccessMethod access_method,
439 EnforcementPolicy policy) {
440 DCHECK(policy != EnforcementPolicy::kDisabled)
441 << "Should never enter this function when access checks are completely disabled";
442
David Brazdile7681822018-12-14 16:25:33 +0000443 if (access_method != AccessMethod::kNone) {
David Brazdild51e5742019-02-28 14:47:32 +0000444 LOG(WARNING) << "Core platform API violation: "
445 << Dumpable<MemberSignature>(MemberSignature(member))
446 << " from " << caller_context << " using " << access_method;
447
448 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
449 // `member` to avoid reporting the violation again next time.
450 if (policy == EnforcementPolicy::kJustWarn) {
451 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
452 }
David Brazdile7681822018-12-14 16:25:33 +0000453 }
David Brazdild51e5742019-02-28 14:47:32 +0000454
455 // Deny access if enforcement is enabled.
456 return policy == EnforcementPolicy::kEnabled;
David Brazdile7681822018-12-14 16:25:33 +0000457}
458
459template<typename T>
460bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100461 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700462 Runtime* runtime = Runtime::Current();
David Brazdilc5a96e42019-01-09 10:04:45 +0000463
Artur Satayev267366c2019-10-31 14:59:26 +0000464 EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
465 DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
David Brazdilc5a96e42019-01-09 10:04:45 +0000466 << "Should never enter this function when access checks are completely disabled";
David Brazdilf50ac102018-10-17 18:00:06 +0100467
David Brazdilf50ac102018-10-17 18:00:06 +0100468 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700469
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100470 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100471 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
472 // Avoid re-examining the exemption list next time.
473 // Note this results in no warning for the member, which seems like what one would expect.
474 // Exemptions effectively adds new members to the whitelist.
David Brazdild51e5742019-02-28 14:47:32 +0000475 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
David Brazdilf50ac102018-10-17 18:00:06 +0100476 return false;
477 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700478
Artur Satayev267366c2019-10-31 14:59:26 +0000479 EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
480
481 bool deny_access = false;
482 if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
483 if (testApiPolicy == EnforcementPolicy::kDisabled && api_list.IsTestApi()) {
484 deny_access = false;
485 } else {
atrost2dea0792020-02-25 20:11:47 +0000486 switch (api_list.GetMaxAllowedSdkVersion()) {
487 case SdkVersion::kP:
488 deny_access = runtime->isChangeEnabled(kHideMaxtargetsdkPHiddenApis);
489 break;
490 case SdkVersion::kQ:
491 deny_access = runtime->isChangeEnabled(kHideMaxtargetsdkQHiddenApis);
492 break;
493 default:
494 deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
495 api_list.GetMaxAllowedSdkVersion());
496 }
Artur Satayev267366c2019-10-31 14:59:26 +0000497 }
498 }
499
David Brazdilf50ac102018-10-17 18:00:06 +0100500 if (access_method != AccessMethod::kNone) {
501 // Print a log message with information about this class member access.
502 // We do this if we're about to deny access, or the app is debuggable.
503 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdil4de9bb62019-04-03 13:06:17 +0100504 member_signature.WarnAboutAccess(access_method, api_list, deny_access);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100505 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700506
David Brazdilf50ac102018-10-17 18:00:06 +0100507 // If there is a StrictMode listener, notify it about this violation.
508 member_signature.NotifyHiddenApiListener(access_method);
509
510 // If event log sampling is enabled, report this violation.
511 if (kIsTargetBuild && !kIsTargetLinux) {
512 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
513 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
514 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
Andrei Onea6ad020d2019-02-18 12:15:51 +0000515 if (eventLogSampleRate != 0) {
516 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
517 if (sampled_value < eventLogSampleRate) {
518 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
519 }
David Brazdilf50ac102018-10-17 18:00:06 +0100520 }
521 }
522
523 // If this access was not denied, move the member into whitelist and skip
524 // the warning the next time the member is accessed.
525 if (!deny_access) {
David Brazdild51e5742019-02-28 14:47:32 +0000526 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100527 }
528 }
529
David Brazdilf50ac102018-10-17 18:00:06 +0100530 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700531}
532
David Brazdile7681822018-12-14 16:25:33 +0000533// Need to instantiate these.
David Brazdil1a658632018-12-01 17:54:26 +0000534template uint32_t GetDexFlags<ArtField>(ArtField* member);
535template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
David Brazdild51e5742019-02-28 14:47:32 +0000536template bool HandleCorePlatformApiViolation(ArtField* member,
537 const AccessContext& caller_context,
538 AccessMethod access_method,
539 EnforcementPolicy policy);
540template bool HandleCorePlatformApiViolation(ArtMethod* member,
541 const AccessContext& caller_context,
542 AccessMethod access_method,
543 EnforcementPolicy policy);
David Brazdilf50ac102018-10-17 18:00:06 +0100544template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
David Brazdile7681822018-12-14 16:25:33 +0000545 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100546 AccessMethod access_method);
547template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
David Brazdile7681822018-12-14 16:25:33 +0000548 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100549 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700550} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100551
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700552} // namespace hiddenapi
553} // namespace art