blob: f3552765c5f8e205ff77208dfc83ad3806ee673b [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
Andreas Gampe80f5fe52018-03-28 16:23:24 -070021#include "base/dumpable.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010022#include "thread-current-inl.h"
23#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070024
Nicolas Geoffray8a229072018-05-10 16:34:14 +010025#ifdef ART_TARGET_ANDROID
26#include <metricslogger/metrics_logger.h>
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010027using android::metricslogger::ComplexEventLogger;
28using android::metricslogger::ACTION_HIDDEN_API_ACCESSED;
29using android::metricslogger::FIELD_HIDDEN_API_ACCESS_METHOD;
30using android::metricslogger::FIELD_HIDDEN_API_ACCESS_DENIED;
31using android::metricslogger::FIELD_HIDDEN_API_SIGNATURE;
Nicolas Geoffray8a229072018-05-10 16:34:14 +010032#endif
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010033
Andreas Gampe80f5fe52018-03-28 16:23:24 -070034namespace 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 Brazdil54a99cf2018-04-05 16:57:32 +010047 case kNone:
48 LOG(FATAL) << "Internal access to hidden API should not be logged";
49 UNREACHABLE();
Andreas Gampe80f5fe52018-03-28 16:23:24 -070050 case kReflection:
51 os << "reflection";
52 break;
53 case kJNI:
54 os << "JNI";
55 break;
56 case kLinking:
57 os << "linking";
58 break;
59 }
60 return os;
61}
62
David Brazdil47cd2722018-10-23 12:50:02 +010063static constexpr bool EnumsEqual(EnforcementPolicy policy, hiddenapi::ApiList apiList) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -070064 return static_cast<int>(policy) == static_cast<int>(apiList);
65}
66
67// GetMemberAction-related static_asserts.
68static_assert(
David Brazdil47cd2722018-10-23 12:50:02 +010069 EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, hiddenapi::ApiList::kDarkGreylist) &&
70 EnumsEqual(EnforcementPolicy::kBlacklistOnly, hiddenapi::ApiList::kBlacklist),
Andreas Gampe80f5fe52018-03-28 16:23:24 -070071 "Mismatch between EnforcementPolicy and ApiList enums");
72static_assert(
Mathew Inwood68693692018-04-05 16:10:25 +010073 EnforcementPolicy::kJustWarn < EnforcementPolicy::kDarkGreyAndBlackList &&
Andreas Gampe80f5fe52018-03-28 16:23:24 -070074 EnforcementPolicy::kDarkGreyAndBlackList < EnforcementPolicy::kBlacklistOnly,
75 "EnforcementPolicy values ordering not correct");
76
77namespace detail {
78
79MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010080 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
81 member_name_ = field->GetName();
82 type_signature_ = field->GetTypeDescriptor();
83 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -070084}
85
86MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil73a64f62018-05-02 16:53:06 +010087 // If this is a proxy method, print the signature of the interface method.
88 method = method->GetInterfaceMethodIfProxy(
89 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
90
Mathew Inwood73ddda42018-04-03 15:32:32 +010091 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
92 member_name_ = method->GetName();
93 type_signature_ = method->GetSignature().ToString();
94 type_ = kMethod;
95}
96
97inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
98 if (type_ == kField) {
99 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
100 } else {
101 DCHECK_EQ(type_, kMethod);
102 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
103 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700104}
105
106bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
107 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100108 for (const char* part : GetSignatureParts()) {
109 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700110 if (prefix.compare(pos, count, part, 0, count) == 0) {
111 pos += count;
112 } else {
113 return false;
114 }
115 }
116 // We have a complete match if all parts match (we exit the loop without
117 // returning) AND we've matched the whole prefix.
118 return pos == prefix.length();
119}
120
121bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
122 for (const std::string& exemption : exemptions) {
123 if (DoesPrefixMatch(exemption)) {
124 return true;
125 }
126 }
127 return false;
128}
129
130void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100131 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700132 os << part;
133 }
134}
135
David Brazdil47cd2722018-10-23 12:50:02 +0100136void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100137 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
138 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
139}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100140#ifdef ART_TARGET_ANDROID
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100141// Convert an AccessMethod enum to a value for logging from the proto enum.
142// This method may look odd (the enum values are current the same), but it
143// prevents coupling the internal enum to the proto enum (which should never
144// be changed) so that we are free to change the internal one if necessary in
145// future.
146inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
147 switch (access_method) {
148 case kNone:
149 return android::metricslogger::ACCESS_METHOD_NONE;
150 case kReflection:
151 return android::metricslogger::ACCESS_METHOD_REFLECTION;
152 case kJNI:
153 return android::metricslogger::ACCESS_METHOD_JNI;
154 case kLinking:
155 return android::metricslogger::ACCESS_METHOD_LINKING;
156 default:
157 DCHECK(false);
158 }
159}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100160#endif
Mathew Inwood73ddda42018-04-03 15:32:32 +0100161
162void MemberSignature::LogAccessToEventLog(AccessMethod access_method, Action action_taken) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100163#ifdef ART_TARGET_ANDROID
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100164 if (access_method == kLinking || access_method == kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100165 // Linking warnings come from static analysis/compilation of the bytecode
166 // and can contain false positives (i.e. code that is never run). We choose
167 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100168 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100169 return;
170 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100171 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
172 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
Mathew Inwood73ddda42018-04-03 15:32:32 +0100173 if (action_taken == kDeny) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100174 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100175 }
Mathew Inwood5bcef172018-05-01 14:40:12 +0100176 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
177 if (!package_name.empty()) {
178 log_maker.SetPackageName(package_name);
179 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100180 std::ostringstream signature_str;
181 Dump(signature_str);
182 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
183 log_maker.Record();
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100184#else
185 UNUSED(access_method);
186 UNUSED(action_taken);
187#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700188}
189
David Brazdil8a6b2f32018-04-26 16:52:11 +0100190static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtField*) {
191 return true;
192}
193
194static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtMethod* method) {
195 return !method->IsIntrinsic();
196}
197
198template<typename T>
199static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
200 REQUIRES_SHARED(Locks::mutator_lock_) {
201 if (CanUpdateMemberAccessFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
David Brazdil47cd2722018-10-23 12:50:02 +0100202 member->SetAccessFlags(hiddenapi::EncodeForRuntime(
203 member->GetAccessFlags(), hiddenapi::ApiList::kWhitelist));
David Brazdil8a6b2f32018-04-26 16:52:11 +0100204 }
205}
206
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700207template<typename T>
David Brazdilb8c66192018-04-23 13:51:16 +0100208Action GetMemberActionImpl(T* member,
David Brazdil47cd2722018-10-23 12:50:02 +0100209 hiddenapi::ApiList api_list,
David Brazdilb8c66192018-04-23 13:51:16 +0100210 Action action,
211 AccessMethod access_method) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100212 DCHECK_NE(action, kAllow);
213
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700214 // Get the signature, we need it later.
215 MemberSignature member_signature(member);
216
217 Runtime* runtime = Runtime::Current();
218
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100219 // Check for an exemption first. Exempted APIs are treated as white list.
220 // We only do this if we're about to deny, or if the app is debuggable. This is because:
221 // - we only print a warning for light greylist violations for debuggable apps
222 // - for non-debuggable apps, there is no distinction between light grey & whitelisted APIs.
223 // - we want to avoid the overhead of checking for exemptions for light greylisted APIs whenever
224 // possible.
Mathew Inwood015a7ec2018-05-16 11:18:10 +0100225 const bool shouldWarn = kLogAllAccesses || runtime->IsJavaDebuggable();
226 if (shouldWarn || action == kDeny) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700227 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100228 action = kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700229 // Avoid re-examining the exemption list next time.
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100230 // Note this results in no warning for the member, which seems like what one would expect.
231 // Exemptions effectively adds new members to the whitelist.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100232 MaybeWhitelistMember(runtime, member);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100233 return kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700234 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700235
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100236 if (access_method != kNone) {
237 // Print a log message with information about this class member access.
238 // We do this if we're about to block access, or the app is debuggable.
David Brazdilb8c66192018-04-23 13:51:16 +0100239 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100240 }
David Brazdil54a99cf2018-04-05 16:57:32 +0100241 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700242
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100243 if (kIsTargetBuild && !kIsTargetLinux) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100244 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
245 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
246 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
247 if (eventLogSampleRate != 0 &&
248 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
249 member_signature.LogAccessToEventLog(access_method, action);
250 }
251 }
252
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700253 if (action == kDeny) {
254 // Block access
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100255 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700256 }
257
258 // Allow access to this member but print a warning.
259 DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
260
David Brazdil54a99cf2018-04-05 16:57:32 +0100261 if (access_method != kNone) {
262 // Depending on a runtime flag, we might move the member into whitelist and
263 // skip the warning the next time the member is accessed.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100264 MaybeWhitelistMember(runtime, member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700265
David Brazdil54a99cf2018-04-05 16:57:32 +0100266 // If this action requires a UI warning, set the appropriate flag.
Mathew Inwood015a7ec2018-05-16 11:18:10 +0100267 if (shouldWarn &&
268 (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag())) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100269 runtime->SetPendingHiddenApiWarning(true);
270 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700271 }
272
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100273 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700274}
275
276// Need to instantiate this.
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100277template Action GetMemberActionImpl<ArtField>(ArtField* member,
David Brazdil47cd2722018-10-23 12:50:02 +0100278 hiddenapi::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100279 Action action,
280 AccessMethod access_method);
281template Action GetMemberActionImpl<ArtMethod>(ArtMethod* member,
David Brazdil47cd2722018-10-23 12:50:02 +0100282 hiddenapi::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100283 Action action,
284 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700285} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100286
287template<typename T>
288void NotifyHiddenApiListener(T* member) {
289 Runtime* runtime = Runtime::Current();
290 if (!runtime->IsAotCompiler()) {
291 ScopedObjectAccessUnchecked soa(Thread::Current());
292
293 ScopedLocalRef<jobject> consumer_object(soa.Env(),
294 soa.Env()->GetStaticObjectField(
295 WellKnownClasses::dalvik_system_VMRuntime,
296 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
297 // If the consumer is non-null, we call back to it to let it know that we
298 // have encountered an API that's in one of our lists.
299 if (consumer_object != nullptr) {
300 detail::MemberSignature member_signature(member);
301 std::ostringstream member_signature_str;
302 member_signature.Dump(member_signature_str);
303
304 ScopedLocalRef<jobject> signature_str(
305 soa.Env(),
306 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
307
308 // Call through to Consumer.accept(String memberSignature);
309 soa.Env()->CallVoidMethod(consumer_object.get(),
310 WellKnownClasses::java_util_function_Consumer_accept,
311 signature_str.get());
312 }
313 }
314}
315
316template void NotifyHiddenApiListener<ArtMethod>(ArtMethod* member);
317template void NotifyHiddenApiListener<ArtField>(ArtField* member);
318
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700319} // namespace hiddenapi
320} // namespace art