blob: 4ef38426829f044e86734173f155d63b3fe1b934 [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
David Brazdila5c3a802019-03-08 14:59:41 +000076static Domain DetermineDomainFromPath_Impl(const std::string& path,
77 const std::string& dex_location,
78 ObjPtr<mirror::ClassLoader> class_loader) {
David Brazdilbfaba282019-03-15 11:35:51 +000079 // If running with APEX, check `path` against known APEX locations.
80 // These checks will be skipped on target buildbots where ANDROID_RUNTIME_ROOT
81 // is set to "/system".
82 if (RuntimeModuleRootDistinctFromAndroidRoot()) {
83 if (LocationIsOnRuntimeModule(path.c_str()) || LocationIsOnConscryptModule(path.c_str())) {
84 return Domain::kCorePlatform;
85 }
86
87 if (LocationIsOnApex(path.c_str())) {
88 return Domain::kPlatform;
89 }
90 }
91
David Brazdila5c3a802019-03-08 14:59:41 +000092 if (LocationIsOnSystemFramework(path.c_str())) {
93 return Domain::kPlatform;
94 }
95
David Brazdila5c3a802019-03-08 14:59:41 +000096 if (class_loader.IsNull()) {
97 LOG(WARNING) << "DexFile " << dex_location
98 << " is in boot class path but its path " << path << " is not in a known location";
99 return Domain::kPlatform;
100 }
101
102 return Domain::kApplication;
103}
104
105static bool IsAbsoluteLocation(const std::string& str) {
106 return !str.empty() && str[0] == '/';
107}
108
109void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
110 // TODO(dbrazdil): Fix when preopting on host for target. In that case, the dex location
111 // is the target path and functions in file_utils.h check against host system paths.
112
113 const std::string& dex_location = dex_file.GetLocation();
114 const OatDexFile* const oat_dex_file = dex_file.GetOatDexFile();
115
116 Domain dex_domain = Domain::kApplication;
117 if (IsAbsoluteLocation(dex_location)) {
118 // Resolve realpath() of the dex location.
119 dex_domain = DetermineDomainFromPath_Impl(
120 DexFileLoader::GetDexCanonicalLocation(dex_location.c_str()),
121 dex_location,
122 class_loader);
123 } else if (oat_dex_file != nullptr && !oat_dex_file->GetCanonicalDexFileLocation().empty()) {
124 // If the path is relative, we might find the canonical path in the OatDexFile.
125 dex_domain = DetermineDomainFromPath_Impl(
126 oat_dex_file->GetCanonicalDexFileLocation(),
127 dex_location,
128 class_loader);
129 } else if (class_loader.IsNull()) {
130 LOG(WARNING) << "DexFile " << dex_location
131 << " is in boot class path but has no canonical location";
132 dex_domain = Domain::kPlatform;
133 } else {
134 // No canonical path available, not in boot class path. Conservatively
135 // assign application domain.
136 dex_domain = Domain::kApplication;
137 }
138
139 // Assign the domain unless a more permissive domain has already been assigned.
140 // This may happen when DexFile is initialized as trusted.
141 if (IsDomainMoreTrustedThan(dex_domain, dex_file.GetHiddenapiDomain())) {
142 dex_file.SetHiddenapiDomain(dex_domain);
143 }
144}
145
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700146namespace detail {
147
David Brazdilf50ac102018-10-17 18:00:06 +0100148// Do not change the values of items in this enum, as they are written to the
149// event log for offline analysis. Any changes will interfere with that analysis.
150enum AccessContextFlags {
151 // Accessed member is a field if this bit is set, else a method
152 kMemberIsField = 1 << 0,
153 // Indicates if access was denied to the member, instead of just printing a warning.
154 kAccessDenied = 1 << 1,
155};
156
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700157MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100158 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
159 member_name_ = field->GetName();
160 type_signature_ = field->GetTypeDescriptor();
161 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700162}
163
164MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil6a1dab42019-02-28 18:45:15 +0000165 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
166 << "Caller should have replaced proxy method with interface method";
Mathew Inwood73ddda42018-04-03 15:32:32 +0100167 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
168 member_name_ = method->GetName();
169 type_signature_ = method->GetSignature().ToString();
170 type_ = kMethod;
171}
172
David Brazdil1a658632018-12-01 17:54:26 +0000173MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
174 const DexFile& dex_file = field.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800175 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000176 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
177 member_name_ = dex_file.GetFieldName(field_id);
178 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
179 type_ = kField;
180}
181
182MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
183 const DexFile& dex_file = method.GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800184 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
David Brazdil1a658632018-12-01 17:54:26 +0000185 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
186 member_name_ = dex_file.GetMethodName(method_id);
187 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
188 type_ = kMethod;
189}
190
Mathew Inwood73ddda42018-04-03 15:32:32 +0100191inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
192 if (type_ == kField) {
193 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
194 } else {
195 DCHECK_EQ(type_, kMethod);
196 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
197 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700198}
199
200bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
201 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100202 for (const char* part : GetSignatureParts()) {
203 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700204 if (prefix.compare(pos, count, part, 0, count) == 0) {
205 pos += count;
206 } else {
207 return false;
208 }
209 }
210 // We have a complete match if all parts match (we exit the loop without
211 // returning) AND we've matched the whole prefix.
212 return pos == prefix.length();
213}
214
215bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
216 for (const std::string& exemption : exemptions) {
217 if (DoesPrefixMatch(exemption)) {
218 return true;
219 }
220 }
221 return false;
222}
223
224void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100225 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700226 os << part;
227 }
228}
229
David Brazdil47cd2722018-10-23 12:50:02 +0100230void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100231 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
232 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
233}
David Brazdilf50ac102018-10-17 18:00:06 +0100234
David Brazdil1a658632018-12-01 17:54:26 +0000235bool MemberSignature::Equals(const MemberSignature& other) {
236 return type_ == other.type_ &&
237 class_name_ == other.class_name_ &&
238 member_name_ == other.member_name_ &&
239 type_signature_ == other.type_signature_;
240}
241
242bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
243 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
244}
245
Andrei Onea6ad020d2019-02-18 12:15:51 +0000246void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
247 AccessMethod access_method,
248 bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100249#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100250 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100251 // Linking warnings come from static analysis/compilation of the bytecode
252 // and can contain false positives (i.e. code that is never run). We choose
253 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100254 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100255 return;
256 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000257 Runtime* runtime = Runtime::Current();
258 if (runtime->IsAotCompiler()) {
259 return;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100260 }
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000261 JNIEnvExt* env = Thread::Current()->GetJniEnv();
Mathew Inwood5bcef172018-05-01 14:40:12 +0100262 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000263 ScopedLocalRef<jstring> package_str(env, env->NewStringUTF(package_name.c_str()));
264 if (env->ExceptionCheck()) {
265 env->ExceptionClear();
266 LOG(ERROR) << "Unable to allocate string for package name which called hidden api";
Mathew Inwood5bcef172018-05-01 14:40:12 +0100267 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100268 std::ostringstream signature_str;
269 Dump(signature_str);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000270 ScopedLocalRef<jstring> signature_jstr(env,
271 env->NewStringUTF(signature_str.str().c_str()));
272 if (env->ExceptionCheck()) {
273 env->ExceptionClear();
274 LOG(ERROR) << "Unable to allocate string for hidden api method signature";
275 }
276 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
Andrei Onea6ad020d2019-02-18 12:15:51 +0000277 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed,
278 sampled_value,
279 package_str.get(),
280 signature_jstr.get(),
281 static_cast<jint>(access_method),
282 access_denied);
Andrei Oneaa2d2bc22019-01-25 16:18:53 +0000283 if (env->ExceptionCheck()) {
284 env->ExceptionClear();
285 LOG(ERROR) << "Unable to report hidden api usage";
286 }
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100287#else
Andrei Onea6ad020d2019-02-18 12:15:51 +0000288 UNUSED(sampled_value);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100289 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100290 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100291#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700292}
293
David Brazdilf50ac102018-10-17 18:00:06 +0100294void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
295 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
296 // We can only up-call into Java during reflection and JNI down-calls.
297 return;
298 }
299
300 Runtime* runtime = Runtime::Current();
301 if (!runtime->IsAotCompiler()) {
302 ScopedObjectAccessUnchecked soa(Thread::Current());
303
304 ScopedLocalRef<jobject> consumer_object(soa.Env(),
305 soa.Env()->GetStaticObjectField(
306 WellKnownClasses::dalvik_system_VMRuntime,
307 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
308 // If the consumer is non-null, we call back to it to let it know that we
309 // have encountered an API that's in one of our lists.
310 if (consumer_object != nullptr) {
311 std::ostringstream member_signature_str;
312 Dump(member_signature_str);
313
314 ScopedLocalRef<jobject> signature_str(
315 soa.Env(),
316 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
317
318 // Call through to Consumer.accept(String memberSignature);
319 soa.Env()->CallVoidMethod(consumer_object.get(),
320 WellKnownClasses::java_util_function_Consumer_accept,
321 signature_str.get());
322 }
323 }
324}
325
David Brazdil85865692018-10-30 17:26:20 +0000326static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100327 return true;
328}
329
David Brazdil85865692018-10-30 17:26:20 +0000330static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100331 return !method->IsIntrinsic();
332}
333
334template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000335static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
David Brazdil8a6b2f32018-04-26 16:52:11 +0100336 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil85865692018-10-30 17:26:20 +0000337 if (CanUpdateRuntimeFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdild51e5742019-02-28 14:47:32 +0000338 member->SetAccessFlags(member->GetAccessFlags() | flag);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100339 }
340}
341
David Brazdil1a658632018-12-01 17:54:26 +0000342static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
343 return field->GetDexFieldIndex();
David Brazdil85865692018-10-30 17:26:20 +0000344}
345
David Brazdil1a658632018-12-01 17:54:26 +0000346static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
347 REQUIRES_SHARED(Locks::mutator_lock_) {
348 // Use the non-obsolete method to avoid DexFile mismatch between
349 // the method index and the declaring class.
350 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
351}
David Brazdil85865692018-10-30 17:26:20 +0000352
David Brazdil1a658632018-12-01 17:54:26 +0000353static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800354 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000355 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
356 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
357 accessor.VisitFields(fn_visit, fn_visit);
358}
359
360static void VisitMembers(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800361 const dex::ClassDef& class_def,
David Brazdil1a658632018-12-01 17:54:26 +0000362 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
363 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
364 accessor.VisitMethods(fn_visit, fn_visit);
365}
366
367template<typename T>
368uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
369 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
David Brazdil6a1dab42019-02-28 18:45:15 +0000370 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
David Brazdil1a658632018-12-01 17:54:26 +0000371 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
372 ClassAccessor::Field, ClassAccessor::Method>::type;
373
374 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
David Brazdil90faceb2018-12-14 14:36:15 +0000375 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
David Brazdil85865692018-10-30 17:26:20 +0000376
David Brazdil90faceb2018-12-14 14:36:15 +0000377 ApiList flags;
378 DCHECK(!flags.IsValid());
David Brazdil85865692018-10-30 17:26:20 +0000379
David Brazdil1a658632018-12-01 17:54:26 +0000380 // Check if the declaring class has ClassExt allocated. If it does, check if
381 // the pre-JVMTI redefine dex file has been set to determine if the declaring
382 // class has been JVMTI-redefined.
383 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
384 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
385 if (LIKELY(original_dex == nullptr)) {
386 // Class is not redefined. Find the class def, iterate over its members and
387 // find the entry corresponding to this `member`.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800388 const dex::ClassDef* class_def = declaring_class->GetClassDef();
David Brazdil6a1dab42019-02-28 18:45:15 +0000389 if (class_def == nullptr) {
390 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
391 DCHECK(declaring_class->IsProxyClass())
392 << "Only proxy classes are expected not to have a class def";
393 DCHECK(kMemberIsField)
394 << "Interface methods should be inspected instead of proxy class methods";
395 flags = ApiList::Greylist();
396 } else {
397 uint32_t member_index = GetMemberDexIndex(member);
398 auto fn_visit = [&](const AccessorType& dex_member) {
399 if (dex_member.GetIndex() == member_index) {
400 flags = ApiList(dex_member.GetHiddenapiFlags());
401 }
402 };
403 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
404 }
David Brazdil1a658632018-12-01 17:54:26 +0000405 } else {
406 // Class was redefined using JVMTI. We have a pointer to the original dex file
407 // and the class def index of this class in that dex file, but the field/method
408 // indices are lost. Iterate over all members of the class def and find the one
409 // corresponding to this `member` by name and type string comparison.
410 // This is obviously very slow, but it is only used when non-exempt code tries
411 // to access a hidden member of a JVMTI-redefined class.
412 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
413 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800414 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
David Brazdil1a658632018-12-01 17:54:26 +0000415 MemberSignature member_signature(member);
416 auto fn_visit = [&](const AccessorType& dex_member) {
417 MemberSignature cur_signature(dex_member);
418 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
419 DCHECK(member_signature.Equals(cur_signature));
David Brazdil90faceb2018-12-14 14:36:15 +0000420 flags = ApiList(dex_member.GetHiddenapiFlags());
David Brazdil1a658632018-12-01 17:54:26 +0000421 }
422 };
423 VisitMembers(*original_dex, original_class_def, fn_visit);
424 }
David Brazdil85865692018-10-30 17:26:20 +0000425
David Brazdil90faceb2018-12-14 14:36:15 +0000426 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
David Brazdil1a658632018-12-01 17:54:26 +0000427 << Dumpable<MemberSignature>(MemberSignature(member));
David Brazdil90faceb2018-12-14 14:36:15 +0000428 return flags.GetDexFlags();
David Brazdil85865692018-10-30 17:26:20 +0000429}
430
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700431template<typename T>
David Brazdild51e5742019-02-28 14:47:32 +0000432bool HandleCorePlatformApiViolation(T* member,
433 const AccessContext& caller_context,
434 AccessMethod access_method,
435 EnforcementPolicy policy) {
436 DCHECK(policy != EnforcementPolicy::kDisabled)
437 << "Should never enter this function when access checks are completely disabled";
438
David Brazdile7681822018-12-14 16:25:33 +0000439 if (access_method != AccessMethod::kNone) {
David Brazdild51e5742019-02-28 14:47:32 +0000440 LOG(WARNING) << "Core platform API violation: "
441 << Dumpable<MemberSignature>(MemberSignature(member))
442 << " from " << caller_context << " using " << access_method;
443
444 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
445 // `member` to avoid reporting the violation again next time.
446 if (policy == EnforcementPolicy::kJustWarn) {
447 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
448 }
David Brazdile7681822018-12-14 16:25:33 +0000449 }
David Brazdild51e5742019-02-28 14:47:32 +0000450
451 // Deny access if enforcement is enabled.
452 return policy == EnforcementPolicy::kEnabled;
David Brazdile7681822018-12-14 16:25:33 +0000453}
454
455template<typename T>
456bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100457 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700458 Runtime* runtime = Runtime::Current();
David Brazdilc5a96e42019-01-09 10:04:45 +0000459
David Brazdilf50ac102018-10-17 18:00:06 +0100460 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
David Brazdilc5a96e42019-01-09 10:04:45 +0000461 DCHECK(policy != EnforcementPolicy::kDisabled)
462 << "Should never enter this function when access checks are completely disabled";
David Brazdilf50ac102018-10-17 18:00:06 +0100463
464 const bool deny_access =
465 (policy == EnforcementPolicy::kEnabled) &&
David Brazdil2bb2fbd2018-11-13 18:24:26 +0000466 IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
David Brazdildcfa89b2018-10-31 11:04:10 +0000467 api_list.GetMaxAllowedSdkVersion());
David Brazdilf50ac102018-10-17 18:00:06 +0100468
469 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700470
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100471 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100472 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
473 // Avoid re-examining the exemption list next time.
474 // Note this results in no warning for the member, which seems like what one would expect.
475 // Exemptions effectively adds new members to the whitelist.
David Brazdild51e5742019-02-28 14:47:32 +0000476 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
David Brazdilf50ac102018-10-17 18:00:06 +0100477 return false;
478 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700479
David Brazdilf50ac102018-10-17 18:00:06 +0100480 if (access_method != AccessMethod::kNone) {
481 // Print a log message with information about this class member access.
482 // We do this if we're about to deny access, or the app is debuggable.
483 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdilb8c66192018-04-23 13:51:16 +0100484 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100485 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700486
David Brazdilf50ac102018-10-17 18:00:06 +0100487 // If there is a StrictMode listener, notify it about this violation.
488 member_signature.NotifyHiddenApiListener(access_method);
489
490 // If event log sampling is enabled, report this violation.
491 if (kIsTargetBuild && !kIsTargetLinux) {
492 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
493 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
494 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
Andrei Onea6ad020d2019-02-18 12:15:51 +0000495 if (eventLogSampleRate != 0) {
496 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
497 if (sampled_value < eventLogSampleRate) {
498 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
499 }
David Brazdilf50ac102018-10-17 18:00:06 +0100500 }
501 }
502
503 // If this access was not denied, move the member into whitelist and skip
504 // the warning the next time the member is accessed.
505 if (!deny_access) {
David Brazdild51e5742019-02-28 14:47:32 +0000506 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100507 }
508 }
509
David Brazdilf50ac102018-10-17 18:00:06 +0100510 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700511}
512
David Brazdile7681822018-12-14 16:25:33 +0000513// Need to instantiate these.
David Brazdil1a658632018-12-01 17:54:26 +0000514template uint32_t GetDexFlags<ArtField>(ArtField* member);
515template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
David Brazdild51e5742019-02-28 14:47:32 +0000516template bool HandleCorePlatformApiViolation(ArtField* member,
517 const AccessContext& caller_context,
518 AccessMethod access_method,
519 EnforcementPolicy policy);
520template bool HandleCorePlatformApiViolation(ArtMethod* member,
521 const AccessContext& caller_context,
522 AccessMethod access_method,
523 EnforcementPolicy policy);
David Brazdilf50ac102018-10-17 18:00:06 +0100524template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
David Brazdile7681822018-12-14 16:25:33 +0000525 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100526 AccessMethod access_method);
527template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
David Brazdile7681822018-12-14 16:25:33 +0000528 ApiList api_list,
David Brazdilf50ac102018-10-17 18:00:06 +0100529 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700530} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100531
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700532} // namespace hiddenapi
533} // namespace art