blob: ab9e65c458e684754a378dd2a8142b302870b0cc [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 Brazdil85865692018-10-30 17:26:20 +000024#include "dex/class_accessor-inl.h"
25#include "scoped_thread_state_change.h"
26#include "thread-inl.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010027#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070028
Nicolas Geoffray8a229072018-05-10 16:34:14 +010029#ifdef ART_TARGET_ANDROID
30#include <metricslogger/metrics_logger.h>
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010031using android::metricslogger::ComplexEventLogger;
32using android::metricslogger::ACTION_HIDDEN_API_ACCESSED;
33using android::metricslogger::FIELD_HIDDEN_API_ACCESS_METHOD;
34using android::metricslogger::FIELD_HIDDEN_API_ACCESS_DENIED;
35using android::metricslogger::FIELD_HIDDEN_API_SIGNATURE;
Nicolas Geoffray8a229072018-05-10 16:34:14 +010036#endif
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010037
Andreas Gampe80f5fe52018-03-28 16:23:24 -070038namespace art {
39namespace hiddenapi {
40
Mathew Inwood27199e62018-04-11 16:08:21 +010041// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
42// dark grey and black. This can be set to true for developer preview / beta builds, but should be
43// false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010044// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
45// as it affects whether or not we warn for light grey APIs that have been added to the exemptions
46// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010047static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010048
Andreas Gampe80f5fe52018-03-28 16:23:24 -070049static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
50 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010051 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010052 LOG(FATAL) << "Internal access to hidden API should not be logged";
53 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010054 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070055 os << "reflection";
56 break;
David Brazdilf50ac102018-10-17 18:00:06 +010057 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070058 os << "JNI";
59 break;
David Brazdilf50ac102018-10-17 18:00:06 +010060 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070061 os << "linking";
62 break;
63 }
64 return os;
65}
66
Andreas Gampe80f5fe52018-03-28 16:23:24 -070067namespace detail {
68
David Brazdilf50ac102018-10-17 18:00:06 +010069// Do not change the values of items in this enum, as they are written to the
70// event log for offline analysis. Any changes will interfere with that analysis.
71enum AccessContextFlags {
72 // Accessed member is a field if this bit is set, else a method
73 kMemberIsField = 1 << 0,
74 // Indicates if access was denied to the member, instead of just printing a warning.
75 kAccessDenied = 1 << 1,
76};
77
78static int32_t GetMaxAllowedSdkVersionForApiList(ApiList api_list) {
79 SdkCodes sdk = SdkCodes::kVersionNone;
80 switch (api_list) {
81 case ApiList::kWhitelist:
82 case ApiList::kLightGreylist:
83 sdk = SdkCodes::kVersionUnlimited;
84 break;
85 case ApiList::kDarkGreylist:
86 sdk = SdkCodes::kVersionO_MR1;
87 break;
88 case ApiList::kBlacklist:
89 sdk = SdkCodes::kVersionNone;
90 break;
91 case ApiList::kNoList:
92 LOG(FATAL) << "Unexpected value";
93 UNREACHABLE();
94 }
95 return static_cast<int32_t>(sdk);
96}
97
Andreas Gampe80f5fe52018-03-28 16:23:24 -070098MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010099 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
100 member_name_ = field->GetName();
101 type_signature_ = field->GetTypeDescriptor();
102 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700103}
104
105MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil73a64f62018-05-02 16:53:06 +0100106 // If this is a proxy method, print the signature of the interface method.
107 method = method->GetInterfaceMethodIfProxy(
108 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
109
Mathew Inwood73ddda42018-04-03 15:32:32 +0100110 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
111 member_name_ = method->GetName();
112 type_signature_ = method->GetSignature().ToString();
113 type_ = kMethod;
114}
115
116inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
117 if (type_ == kField) {
118 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
119 } else {
120 DCHECK_EQ(type_, kMethod);
121 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
122 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700123}
124
125bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
126 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100127 for (const char* part : GetSignatureParts()) {
128 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700129 if (prefix.compare(pos, count, part, 0, count) == 0) {
130 pos += count;
131 } else {
132 return false;
133 }
134 }
135 // We have a complete match if all parts match (we exit the loop without
136 // returning) AND we've matched the whole prefix.
137 return pos == prefix.length();
138}
139
140bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
141 for (const std::string& exemption : exemptions) {
142 if (DoesPrefixMatch(exemption)) {
143 return true;
144 }
145 }
146 return false;
147}
148
149void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100150 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700151 os << part;
152 }
153}
154
David Brazdil47cd2722018-10-23 12:50:02 +0100155void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100156 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
157 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
158}
David Brazdilf50ac102018-10-17 18:00:06 +0100159
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100160#ifdef ART_TARGET_ANDROID
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100161// Convert an AccessMethod enum to a value for logging from the proto enum.
162// This method may look odd (the enum values are current the same), but it
163// prevents coupling the internal enum to the proto enum (which should never
164// be changed) so that we are free to change the internal one if necessary in
165// future.
166inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
167 switch (access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100168 case AccessMethod::kNone:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100169 return android::metricslogger::ACCESS_METHOD_NONE;
David Brazdilf50ac102018-10-17 18:00:06 +0100170 case AccessMethod::kReflection:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100171 return android::metricslogger::ACCESS_METHOD_REFLECTION;
David Brazdilf50ac102018-10-17 18:00:06 +0100172 case AccessMethod::kJNI:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100173 return android::metricslogger::ACCESS_METHOD_JNI;
David Brazdilf50ac102018-10-17 18:00:06 +0100174 case AccessMethod::kLinking:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100175 return android::metricslogger::ACCESS_METHOD_LINKING;
176 default:
177 DCHECK(false);
178 }
179}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100180#endif
Mathew Inwood73ddda42018-04-03 15:32:32 +0100181
David Brazdilf50ac102018-10-17 18:00:06 +0100182void MemberSignature::LogAccessToEventLog(AccessMethod access_method, bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100183#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100184 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100185 // Linking warnings come from static analysis/compilation of the bytecode
186 // and can contain false positives (i.e. code that is never run). We choose
187 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100188 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100189 return;
190 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100191 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
192 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
David Brazdilf50ac102018-10-17 18:00:06 +0100193 if (access_denied) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100194 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100195 }
Mathew Inwood5bcef172018-05-01 14:40:12 +0100196 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
197 if (!package_name.empty()) {
198 log_maker.SetPackageName(package_name);
199 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100200 std::ostringstream signature_str;
201 Dump(signature_str);
202 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
203 log_maker.Record();
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100204#else
205 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100206 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100207#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700208}
209
David Brazdilf50ac102018-10-17 18:00:06 +0100210void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
211 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
212 // We can only up-call into Java during reflection and JNI down-calls.
213 return;
214 }
215
216 Runtime* runtime = Runtime::Current();
217 if (!runtime->IsAotCompiler()) {
218 ScopedObjectAccessUnchecked soa(Thread::Current());
219
220 ScopedLocalRef<jobject> consumer_object(soa.Env(),
221 soa.Env()->GetStaticObjectField(
222 WellKnownClasses::dalvik_system_VMRuntime,
223 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
224 // If the consumer is non-null, we call back to it to let it know that we
225 // have encountered an API that's in one of our lists.
226 if (consumer_object != nullptr) {
227 std::ostringstream member_signature_str;
228 Dump(member_signature_str);
229
230 ScopedLocalRef<jobject> signature_str(
231 soa.Env(),
232 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
233
234 // Call through to Consumer.accept(String memberSignature);
235 soa.Env()->CallVoidMethod(consumer_object.get(),
236 WellKnownClasses::java_util_function_Consumer_accept,
237 signature_str.get());
238 }
239 }
240}
241
David Brazdil85865692018-10-30 17:26:20 +0000242static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100243 return true;
244}
245
David Brazdil85865692018-10-30 17:26:20 +0000246static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100247 return !method->IsIntrinsic();
248}
249
250template<typename T>
251static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
252 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil85865692018-10-30 17:26:20 +0000253 if (CanUpdateRuntimeFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
254 member->SetAccessFlags(member->GetAccessFlags() | kAccPublicApi);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100255 }
256}
257
David Brazdil85865692018-10-30 17:26:20 +0000258static constexpr uint32_t kNoDexFlags = 0u;
259static constexpr uint32_t kInvalidDexFlags = static_cast<uint32_t>(-1);
260
261uint32_t GetDexFlags(ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_) {
262 ObjPtr<mirror::Class> declaring_class = field->GetDeclaringClass();
263 DCHECK(declaring_class != nullptr) << "Fields always have a declaring class";
264
265 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
266 if (class_def == nullptr) {
267 return kNoDexFlags;
268 }
269
270 uint32_t flags = kInvalidDexFlags;
271 DCHECK(!AreValidFlags(flags));
272
273 ClassAccessor accessor(declaring_class->GetDexFile(),
274 *class_def,
275 /* parse_hiddenapi_class_data= */ true);
276 auto fn_visit = [&](const ClassAccessor::Field& dex_field) {
277 if (dex_field.GetIndex() == field->GetDexFieldIndex()) {
278 flags = dex_field.GetHiddenapiFlags();
279 }
280 };
281 accessor.VisitFields(fn_visit, fn_visit);
282
283 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for field " << field->PrettyField();
284 DCHECK(AreValidFlags(flags));
285 return flags;
286}
287
288uint32_t GetDexFlags(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
289 ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
290 if (declaring_class.IsNull()) {
291 DCHECK(method->IsRuntimeMethod());
292 return kNoDexFlags;
293 }
294
295 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
296 if (class_def == nullptr) {
297 return kNoDexFlags;
298 }
299
300 uint32_t flags = kInvalidDexFlags;
301 DCHECK(!AreValidFlags(flags));
302
303 ClassAccessor accessor(declaring_class->GetDexFile(),
304 *class_def,
305 /* parse_hiddenapi_class_data= */ true);
306 auto fn_visit = [&](const ClassAccessor::Method& dex_method) {
307 if (dex_method.GetIndex() == method->GetDexMethodIndex()) {
308 flags = dex_method.GetHiddenapiFlags();
309 }
310 };
311 accessor.VisitMethods(fn_visit, fn_visit);
312
313 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for method " << method->PrettyMethod();
314 DCHECK(AreValidFlags(flags));
315 return flags;
316}
317
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700318template<typename T>
David Brazdilf50ac102018-10-17 18:00:06 +0100319bool ShouldDenyAccessToMemberImpl(T* member,
320 hiddenapi::ApiList api_list,
321 AccessMethod access_method) {
322 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700323
324 Runtime* runtime = Runtime::Current();
David Brazdilf50ac102018-10-17 18:00:06 +0100325 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
326
327 const bool deny_access =
328 (policy == EnforcementPolicy::kEnabled) &&
329 (runtime->GetTargetSdkVersion() > GetMaxAllowedSdkVersionForApiList(api_list));
330
331 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700332
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100333 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100334 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
335 // Avoid re-examining the exemption list next time.
336 // Note this results in no warning for the member, which seems like what one would expect.
337 // Exemptions effectively adds new members to the whitelist.
338 MaybeWhitelistMember(runtime, member);
339 return false;
340 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700341
David Brazdilf50ac102018-10-17 18:00:06 +0100342 if (access_method != AccessMethod::kNone) {
343 // Print a log message with information about this class member access.
344 // We do this if we're about to deny access, or the app is debuggable.
345 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdilb8c66192018-04-23 13:51:16 +0100346 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100347 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700348
David Brazdilf50ac102018-10-17 18:00:06 +0100349 // If there is a StrictMode listener, notify it about this violation.
350 member_signature.NotifyHiddenApiListener(access_method);
351
352 // If event log sampling is enabled, report this violation.
353 if (kIsTargetBuild && !kIsTargetLinux) {
354 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
355 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
356 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
357 if (eventLogSampleRate != 0 &&
358 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
359 member_signature.LogAccessToEventLog(access_method, deny_access);
360 }
361 }
362
363 // If this access was not denied, move the member into whitelist and skip
364 // the warning the next time the member is accessed.
365 if (!deny_access) {
366 MaybeWhitelistMember(runtime, member);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100367 }
368 }
369
David Brazdilf50ac102018-10-17 18:00:06 +0100370 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700371}
372
373// Need to instantiate this.
David Brazdilf50ac102018-10-17 18:00:06 +0100374template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
375 hiddenapi::ApiList api_list,
376 AccessMethod access_method);
377template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
378 hiddenapi::ApiList api_list,
379 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700380} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100381
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700382} // namespace hiddenapi
383} // namespace art