blob: 5729800bb02c7b5ce16c8b3dc38b0a2e59c38af2 [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
63static constexpr bool EnumsEqual(EnforcementPolicy policy, HiddenApiAccessFlags::ApiList apiList) {
64 return static_cast<int>(policy) == static_cast<int>(apiList);
65}
66
67// GetMemberAction-related static_asserts.
68static_assert(
Andreas Gampe80f5fe52018-03-28 16:23:24 -070069 EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, HiddenApiAccessFlags::kDarkGreylist) &&
70 EnumsEqual(EnforcementPolicy::kBlacklistOnly, HiddenApiAccessFlags::kBlacklist),
71 "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
136void MemberSignature::WarnAboutAccess(AccessMethod access_method,
137 HiddenApiAccessFlags::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100138 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
139 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
140}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100141#ifdef ART_TARGET_ANDROID
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100142// Convert an AccessMethod enum to a value for logging from the proto enum.
143// This method may look odd (the enum values are current the same), but it
144// prevents coupling the internal enum to the proto enum (which should never
145// be changed) so that we are free to change the internal one if necessary in
146// future.
147inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
148 switch (access_method) {
149 case kNone:
150 return android::metricslogger::ACCESS_METHOD_NONE;
151 case kReflection:
152 return android::metricslogger::ACCESS_METHOD_REFLECTION;
153 case kJNI:
154 return android::metricslogger::ACCESS_METHOD_JNI;
155 case kLinking:
156 return android::metricslogger::ACCESS_METHOD_LINKING;
157 default:
158 DCHECK(false);
159 }
160}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100161#endif
Mathew Inwood73ddda42018-04-03 15:32:32 +0100162
163void MemberSignature::LogAccessToEventLog(AccessMethod access_method, Action action_taken) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100164#ifdef ART_TARGET_ANDROID
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100165 if (access_method == kLinking || access_method == kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100166 // Linking warnings come from static analysis/compilation of the bytecode
167 // and can contain false positives (i.e. code that is never run). We choose
168 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100169 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100170 return;
171 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100172 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
173 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
Mathew Inwood73ddda42018-04-03 15:32:32 +0100174 if (action_taken == kDeny) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100175 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100176 }
Mathew Inwood5bcef172018-05-01 14:40:12 +0100177 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
178 if (!package_name.empty()) {
179 log_maker.SetPackageName(package_name);
180 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100181 std::ostringstream signature_str;
182 Dump(signature_str);
183 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
184 log_maker.Record();
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100185#else
186 UNUSED(access_method);
187 UNUSED(action_taken);
188#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700189}
190
David Brazdil8a6b2f32018-04-26 16:52:11 +0100191static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtField*) {
192 return true;
193}
194
195static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtMethod* method) {
196 return !method->IsIntrinsic();
197}
198
199template<typename T>
200static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
201 REQUIRES_SHARED(Locks::mutator_lock_) {
202 if (CanUpdateMemberAccessFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
203 member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
204 member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
205 }
206}
207
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700208template<typename T>
David Brazdilb8c66192018-04-23 13:51:16 +0100209Action GetMemberActionImpl(T* member,
210 HiddenApiAccessFlags::ApiList api_list,
211 Action action,
212 AccessMethod access_method) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100213 DCHECK_NE(action, kAllow);
214
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700215 // Get the signature, we need it later.
216 MemberSignature member_signature(member);
217
218 Runtime* runtime = Runtime::Current();
219
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100220 // Check for an exemption first. Exempted APIs are treated as white list.
221 // We only do this if we're about to deny, or if the app is debuggable. This is because:
222 // - we only print a warning for light greylist violations for debuggable apps
223 // - for non-debuggable apps, there is no distinction between light grey & whitelisted APIs.
224 // - we want to avoid the overhead of checking for exemptions for light greylisted APIs whenever
225 // possible.
Mathew Inwood015a7ec2018-05-16 11:18:10 +0100226 const bool shouldWarn = kLogAllAccesses || runtime->IsJavaDebuggable();
227 if (shouldWarn || action == kDeny) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700228 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100229 action = kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700230 // Avoid re-examining the exemption list next time.
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100231 // Note this results in no warning for the member, which seems like what one would expect.
232 // Exemptions effectively adds new members to the whitelist.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100233 MaybeWhitelistMember(runtime, member);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100234 return kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700235 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700236
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100237 if (access_method != kNone) {
238 // Print a log message with information about this class member access.
239 // We do this if we're about to block access, or the app is debuggable.
David Brazdilb8c66192018-04-23 13:51:16 +0100240 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100241 }
David Brazdil54a99cf2018-04-05 16:57:32 +0100242 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700243
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100244 if (kIsTargetBuild && !kIsTargetLinux) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100245 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
246 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
247 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
248 if (eventLogSampleRate != 0 &&
249 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
250 member_signature.LogAccessToEventLog(access_method, action);
251 }
252 }
253
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700254 if (action == kDeny) {
255 // Block access
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100256 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700257 }
258
259 // Allow access to this member but print a warning.
260 DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
261
David Brazdil54a99cf2018-04-05 16:57:32 +0100262 if (access_method != kNone) {
263 // Depending on a runtime flag, we might move the member into whitelist and
264 // skip the warning the next time the member is accessed.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100265 MaybeWhitelistMember(runtime, member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700266
David Brazdil54a99cf2018-04-05 16:57:32 +0100267 // If this action requires a UI warning, set the appropriate flag.
Mathew Inwood015a7ec2018-05-16 11:18:10 +0100268 if (shouldWarn &&
269 (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag())) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100270 runtime->SetPendingHiddenApiWarning(true);
271 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700272 }
273
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100274 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700275}
276
277// Need to instantiate this.
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100278template Action GetMemberActionImpl<ArtField>(ArtField* member,
David Brazdilb8c66192018-04-23 13:51:16 +0100279 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100280 Action action,
281 AccessMethod access_method);
282template Action GetMemberActionImpl<ArtMethod>(ArtMethod* member,
David Brazdilb8c66192018-04-23 13:51:16 +0100283 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100284 Action action,
285 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700286} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100287
288template<typename T>
289void NotifyHiddenApiListener(T* member) {
290 Runtime* runtime = Runtime::Current();
291 if (!runtime->IsAotCompiler()) {
292 ScopedObjectAccessUnchecked soa(Thread::Current());
293
294 ScopedLocalRef<jobject> consumer_object(soa.Env(),
295 soa.Env()->GetStaticObjectField(
296 WellKnownClasses::dalvik_system_VMRuntime,
297 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
298 // If the consumer is non-null, we call back to it to let it know that we
299 // have encountered an API that's in one of our lists.
300 if (consumer_object != nullptr) {
301 detail::MemberSignature member_signature(member);
302 std::ostringstream member_signature_str;
303 member_signature.Dump(member_signature_str);
304
305 ScopedLocalRef<jobject> signature_str(
306 soa.Env(),
307 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
308
309 // Call through to Consumer.accept(String memberSignature);
310 soa.Env()->CallVoidMethod(consumer_object.get(),
311 WellKnownClasses::java_util_function_Consumer_accept,
312 signature_str.get());
313 }
314 }
315}
316
317template void NotifyHiddenApiListener<ArtMethod>(ArtMethod* member);
318template void NotifyHiddenApiListener<ArtField>(ArtField* member);
319
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700320} // namespace hiddenapi
321} // namespace art