blob: 371fbe5ff7f0ad347458ef7b518e4c003accdd1b [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
Mathew Inwood27199e62018-04-11 16:08:21 +010037// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
38// dark grey and black. This can be set to true for developer preview / beta builds, but should be
39// false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010040// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
41// as it affects whether or not we warn for light grey APIs that have been added to the exemptions
42// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010043static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010044
Andreas Gampe80f5fe52018-03-28 16:23:24 -070045static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
46 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010047 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010048 LOG(FATAL) << "Internal access to hidden API should not be logged";
49 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010050 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070051 os << "reflection";
52 break;
David Brazdilf50ac102018-10-17 18:00:06 +010053 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070054 os << "JNI";
55 break;
David Brazdilf50ac102018-10-17 18:00:06 +010056 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070057 os << "linking";
58 break;
59 }
60 return os;
61}
62
David Brazdile7681822018-12-14 16:25:33 +000063static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
64 REQUIRES_SHARED(Locks::mutator_lock_) {
65 if (!value.GetClass().IsNull()) {
66 std::string tmp;
67 os << value.GetClass()->GetDescriptor(&tmp);
68 } else if (value.GetDexFile() != nullptr) {
69 os << value.GetDexFile()->GetLocation();
70 } else {
71 os << "<unknown_caller>";
72 }
73 return os;
74}
75
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000076static Domain DetermineDomainFromLocation(const std::string& dex_location,
77 ObjPtr<mirror::ClassLoader> class_loader) {
David Brazdilbfaba282019-03-15 11:35:51 +000078 // If running with APEX, check `path` against known APEX locations.
79 // These checks will be skipped on target buildbots where ANDROID_RUNTIME_ROOT
80 // is set to "/system".
81 if (RuntimeModuleRootDistinctFromAndroidRoot()) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000082 if (LocationIsOnRuntimeModule(dex_location.c_str()) ||
83 LocationIsOnConscryptModule(dex_location.c_str())) {
84 return Domain::kCorePlatform;
David Brazdilbfaba282019-03-15 11:35:51 +000085 }
86
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000087 if (LocationIsOnApex(dex_location.c_str())) {
David Brazdilbfaba282019-03-15 11:35:51 +000088 return Domain::kPlatform;
89 }
90 }
91
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000092 if (LocationIsOnSystemFramework(dex_location.c_str())) {
David Brazdila5c3a802019-03-08 14:59:41 +000093 return Domain::kPlatform;
94 }
95
David Brazdila5c3a802019-03-08 14:59:41 +000096 if (class_loader.IsNull()) {
97 LOG(WARNING) << "DexFile " << dex_location
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +000098 << " is in boot class path but is not in a known location";
David Brazdila5c3a802019-03-08 14:59:41 +000099 return Domain::kPlatform;
100 }
101
102 return Domain::kApplication;
103}
104
David Brazdila5c3a802019-03-08 14:59:41 +0000105void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000106 Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
David Brazdila5c3a802019-03-08 14:59:41 +0000107
108 // Assign the domain unless a more permissive domain has already been assigned.
109 // This may happen when DexFile is initialized as trusted.
110 if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
111 dex_file.SetHiddenapiDomain(dex_domain);
112 }
113}
114
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700115namespace detail {
116
David Brazdilf50ac102018-10-17 18:00:06 +0100117// Do not change the values of items in this enum, as they are written to the
118// event log for offline analysis. Any changes will interfere with that analysis.
119enum AccessContextFlags {
120 // Accessed member is a field if this bit is set, else a method
121 kMemberIsField = 1 << 0,
122 // Indicates if access was denied to the member, instead of just printing a warning.
123 kAccessDenied = 1 << 1,
124};
125
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700126MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100127 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
128 member_name_ = field->GetName();
129 type_signature_ = field->GetTypeDescriptor();
130 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700131}
132
133MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil6a1dab42019-02-28 18:45:15 +0000134 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
135 << "Caller should have replaced proxy method with interface method";
Mathew Inwood73ddda42018-04-03 15:32:32 +0100136 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
137 member_name_ = method->GetName();
138 type_signature_ = method->GetSignature().ToString();
139 type_ = kMethod;
140}
141
David Brazdil1a658632018-12-01 17:54:26 +0000142MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
143 const DexFile& dex_file = field.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800144 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000145 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
146 member_name_ = dex_file.GetFieldName(field_id);
147 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
148 type_ = kField;
149}
150
151MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
152 const DexFile& dex_file = method.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800153 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000154 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
155 member_name_ = dex_file.GetMethodName(method_id);
156 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
157 type_ = kMethod;
158}
159
Mathew Inwood73ddda42018-04-03 15:32:32 +0100160inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
161 if (type_ == kField) {
162 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
163 } else {
164 DCHECK_EQ(type_, kMethod);
165 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
166 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700167}
168
169bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
170 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100171 for (const char* part : GetSignatureParts()) {
172 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700173 if (prefix.compare(pos, count, part, 0, count) == 0) {
174 pos += count;
175 } else {
176 return false;
177 }
178 }
179 // We have a complete match if all parts match (we exit the loop without
180 // returning) AND we've matched the whole prefix.
181 return pos == prefix.length();
182}
183
184bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
185 for (const std::string& exemption : exemptions) {
186 if (DoesPrefixMatch(exemption)) {
187 return true;
188 }
189 }
190 return false;
191}
192
193void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100194 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700195 os << part;
196 }
197}
198
David Brazdil47cd2722018-10-23 12:50:02 +0100199void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100200 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
201 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
202}
David Brazdilf50ac102018-10-17 18:00:06 +0100203
David Brazdil1a658632018-12-01 17:54:26 +0000204bool MemberSignature::Equals(const MemberSignature& other) {
205 return type_ == other.type_ &&
206 class_name_ == other.class_name_ &&
207 member_name_ == other.member_name_ &&
208 type_signature_ == other.type_signature_;
209}
210
211bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
212 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
213}
214
Andrei Onea6ad020d2019-02-18 12:15:51 +0000215void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
216 AccessMethod access_method,
217 bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100218#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100219 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100220 // Linking warnings come from static analysis/compilation of the bytecode
221 // and can contain false positives (i.e. code that is never run). We choose
222 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100223 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100224 return;
225 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000226 Runtime* runtime = Runtime::Current();
227 if (runtime->IsAotCompiler()) {
228 return;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100229 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000230 JNIEnvExt* env = Thread::Current()->GetJniEnv();
Mathew Inwood5bcef172018-05-01 14:40:12 +0100231 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000232 ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
233 if (env->ExceptionCheck()) {
234 env->ExceptionClear();
235 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
Mathew Inwood5bcef172018-05-01 14:40:12 +0100236 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100237 std::ostringstream signature_str;
238 Dump(signature_str);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000239 ScopedLocalRef<jstring> signature_jstr(env,
240 env->NewStringUTF(signature_str.str().c_str()));
241 if (env->ExceptionCheck()) {
242 env->ExceptionClear();
243 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
244 }
245 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
Andrei Onea6ad020d2019-02-18 12:15:51 +0000246 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
247 sampled_value,
248 package_str.get(),
249 signature_jstr.get(),
250 static_cast<jint>(access_method),
251 access_denied);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000252 if (env->ExceptionCheck()) {
253 env->ExceptionClear();
254 LOG(ERROR) << "Unable to report hidden api usage";
255 }
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100256#else
Andrei Onea6ad020d2019-02-18 12:15:51 +0000257 UNUSED(sampled_value);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100258 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100259 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100260#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700261}
262
David Brazdilf50ac102018-10-17 18:00:06 +0100263void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
264 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
265 // We can only up-call into Java during reflection and JNI down-calls.
266 return;
267 }
268
269 Runtime* runtime = Runtime::Current();
270 if (!runtime->IsAotCompiler()) {
271 ScopedObjectAccessUnchecked soa(Thread::Current());
272
273 ScopedLocalRef<jobject> consumer_object(soa.Env(),
274 soa.Env()->GetStaticObjectField(
275 WellKnownClasses::dalvik_system_VMRuntime,
276 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
277 // If the consumer is non-null, we call back to it to let it know that we
278 // have encountered an API that's in one of our lists.
279 if (consumer_object != nullptr) {
280 std::ostringstream member_signature_str;
281 Dump(member_signature_str);
282
283 ScopedLocalRef<jobject> signature_str(
284 soa.Env(),
285 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
286
287 // Call through to Consumer.accept(String memberSignature);
288 soa.Env()->CallVoidMethod(consumer_object.get(),
289 WellKnownClasses::java_util_function_Consumer_accept,
290 signature_str.get());
291 }
292 }
293}
294
David Brazdil85865692018-10-30 17:26:20 +0000295static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100296 return true;
297}
298
David Brazdil85865692018-10-30 17:26:20 +0000299static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100300 return !method->IsIntrinsic();
301}
302
303template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000304static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
David Brazdil8a6b2f32018-04-26 16:52:11 +0100305 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil85865692018-10-30 17:26:20 +0000306 if (CanUpdateRuntimeFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdild51e5742019-02-28 14:47:32 +0000307 member->SetAccessFlags(member->GetAccessFlags() | flag);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100308 }
309}
310
David Brazdil1a658632018-12-01 17:54:26 +0000311static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
312 return field->GetDexFieldIndex();
David Brazdil85865692018-10-30 17:26:20 +0000313}
314
David Brazdil1a658632018-12-01 17:54:26 +0000315static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
316 REQUIRES_SHARED(Locks::mutator_lock_) {
317 // Use the non-obsolete method to avoid DexFile mismatch between
318 // the method index and the declaring class.
319 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
320}
David Brazdil85865692018-10-30 17:26:20 +0000321
David Brazdil1a658632018-12-01 17:54:26 +0000322static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800323 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000324 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
325 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
326 accessor.VisitFields(fn_visit, fn_visit);
327}
328
329static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800330 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000331 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
332 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
333 accessor.VisitMethods(fn_visit, fn_visit);
334}
335
336template<typename T>
337uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
338 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
David Brazdil6a1dab42019-02-28 18:45:15 +0000339 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
David Brazdil1a658632018-12-01 17:54:26 +0000340 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
341 ClassAccessor::Field, ClassAccessor::Method>::type;
342
343 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
David Brazdil90faceb2018-12-14 14:36:15 +0000344 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
David Brazdil85865692018-10-30 17:26:20 +0000345
David Brazdil90faceb2018-12-14 14:36:15 +0000346 ApiList flags;
347 DCHECK(!flags.IsValid());
David Brazdil85865692018-10-30 17:26:20 +0000348
David Brazdil1a658632018-12-01 17:54:26 +0000349 // Check if the declaring class has ClassExt allocated. If it does, check if
350 // the pre-JVMTI redefine dex file has been set to determine if the declaring
351 // class has been JVMTI-redefined.
352 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
353 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
354 if (LIKELY(original_dex == nullptr)) {
355 // Class is not redefined. Find the class def, iterate over its members and
356 // find the entry corresponding to this `member`.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800357 const dex::ClassDef* class_def = declaring_class->GetClassDef();
David Brazdil6a1dab42019-02-28 18:45:15 +0000358 if (class_def == nullptr) {
359 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
360 DCHECK(declaring_class->IsProxyClass())
361 << "Only proxy classes are expected not to have a class def";
362 DCHECK(kMemberIsField)
363 << "Interface methods should be inspected instead of proxy class methods";
364 flags = ApiList::Greylist();
365 } else {
366 uint32_t member_index = GetMemberDexIndex(member);
367 auto fn_visit = [&](const AccessorType& dex_member) {
368 if (dex_member.GetIndex() == member_index) {
369 flags = ApiList(dex_member.GetHiddenapiFlags());
370 }
371 };
372 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
373 }
David Brazdil1a658632018-12-01 17:54:26 +0000374 } else {
375 // Class was redefined using JVMTI. We have a pointer to the original dex file
376 // and the class def index of this class in that dex file, but the field/method
377 // indices are lost. Iterate over all members of the class def and find the one
378 // corresponding to this `member` by name and type string comparison.
379 // This is obviously very slow, but it is only used when non-exempt code tries
380 // to access a hidden member of a JVMTI-redefined class.
381 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
382 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800383 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
David Brazdil1a658632018-12-01 17:54:26 +0000384 MemberSignature member_signature(member);
385 auto fn_visit = [&](const AccessorType& dex_member) {
386 MemberSignature cur_signature(dex_member);
387 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
388 DCHECK(member_signature.Equals(cur_signature));
David Brazdil90faceb2018-12-14 14:36:15 +0000389 flags = ApiList(dex_member.GetHiddenapiFlags());
David Brazdil1a658632018-12-01 17:54:26 +0000390 }
391 };
392 VisitMembers(*original_dex, original_class_def, fn_visit);
393 }
David Brazdil85865692018-10-30 17:26:20 +0000394
David Brazdil90faceb2018-12-14 14:36:15 +0000395 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
David Brazdil1a658632018-12-01 17:54:26 +0000396 << Dumpable<MemberSignature>(MemberSignature(member));
David Brazdil90faceb2018-12-14 14:36:15 +0000397 return flags.GetDexFlags();
David Brazdil85865692018-10-30 17:26:20 +0000398}
399
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700400template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000401bool HandleCorePlatformApiViolation(T* member,
402 const AccessContext& caller_context,
403 AccessMethod access_method,
404 EnforcementPolicy policy) {
405 DCHECK(policy != EnforcementPolicy::kDisabled)
406 << "Should never enter this function when access checks are completely disabled";
407
David Brazdile7681822018-12-14 16:25:33 +0000408 if (access_method != AccessMethod::kNone) {
David Brazdild51e5742019-02-28 14:47:32 +0000409 LOG(WARNING) << "Core platform API violation: "
410 << Dumpable<MemberSignature>(MemberSignature(member))
411 << " from " << caller_context << " using " << access_method;
412
413 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
414 // `member` to avoid reporting the violation again next time.
415 if (policy == EnforcementPolicy::kJustWarn) {
416 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
417 }
David Brazdile7681822018-12-14 16:25:33 +0000418 }
David Brazdild51e5742019-02-28 14:47:32 +0000419
420 // Deny access if enforcement is enabled.
421 return policy == EnforcementPolicy::kEnabled;
David Brazdile7681822018-12-14 16:25:33 +0000422}
423
424template<typename T>
425bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100426 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700427 Runtime* runtime = Runtime::Current();
David Brazdilc5a96e42019-01-09 10:04:45 +0000428
David Brazdilf50ac102018-10-17 18:00:06 +0100429 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
David Brazdilc5a96e42019-01-09 10:04:45 +0000430 DCHECK(policy != EnforcementPolicy::kDisabled)
431 << "Should never enter this function when access checks are completely disabled";
David Brazdilf50ac102018-10-17 18:00:06 +0100432
433 const bool deny_access =
434 (policy == EnforcementPolicy::kEnabled) &&
David Brazdil2bb2fbd2018-11-13 18:24:26 +0000435 IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
David Brazdildcfa89b2018-10-31 11:04:10 +0000436 api_list.GetMaxAllowedSdkVersion());
David Brazdilf50ac102018-10-17 18:00:06 +0100437
438 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700439
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100440 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100441 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
442 // Avoid re-examining the exemption list next time.
443 // Note this results in no warning for the member, which seems like what one would expect.
444 // Exemptions effectively adds new members to the whitelist.
David Brazdild51e5742019-02-28 14:47:32 +0000445 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
David Brazdilf50ac102018-10-17 18:00:06 +0100446 return false;
447 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700448
David Brazdilf50ac102018-10-17 18:00:06 +0100449 if (access_method != AccessMethod::kNone) {
450 // Print a log message with information about this class member access.
451 // We do this if we're about to deny access, or the app is debuggable.
452 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdilb8c66192018-04-23 13:51:16 +0100453 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100454 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700455
David Brazdilf50ac102018-10-17 18:00:06 +0100456 // If there is a StrictMode listener, notify it about this violation.
457 member_signature.NotifyHiddenApiListener(access_method);
458
459 // If event log sampling is enabled, report this violation.
460 if (kIsTargetBuild && !kIsTargetLinux) {
461 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
462 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
463 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
Andrei Onea6ad020d2019-02-18 12:15:51 +0000464 if (eventLogSampleRate != 0) {
465 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
466 if (sampled_value < eventLogSampleRate) {
467 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
468 }
David Brazdilf50ac102018-10-17 18:00:06 +0100469 }
470 }
471
472 // If this access was not denied, move the member into whitelist and skip
473 // the warning the next time the member is accessed.
474 if (!deny_access) {
David Brazdild51e5742019-02-28 14:47:32 +0000475 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100476 }
477 }
478
David Brazdilf50ac102018-10-17 18:00:06 +0100479 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700480}
481
David Brazdile7681822018-12-14 16:25:33 +0000482// Need to instantiate these.
David Brazdil1a658632018-12-01 17:54:26 +0000483template uint32_t GetDexFlags<ArtField>(ArtField* member);
484template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
David Brazdild51e5742019-02-28 14:47:32 +0000485template bool HandleCorePlatformApiViolation(ArtField* member,
486 const AccessContext& caller_context,
487 AccessMethod access_method,
488 EnforcementPolicy policy);
489template bool HandleCorePlatformApiViolation(ArtMethod* member,
490 const AccessContext& caller_context,
491 AccessMethod access_method,
492 EnforcementPolicy policy);
David Brazdilf50ac102018-10-17 18:00:06 +0100493template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
David Brazdile7681822018-12-14 16:25:33 +0000494 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100495 AccessMethod access_method);
496template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
David Brazdile7681822018-12-14 16:25:33 +0000497 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100498 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700499} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100500
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700501} // namespace hiddenapi
502} // namespace art