blob: 2480eba3f0bd789b61af22aecf7b216086463a55 [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
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010017#include <metricslogger/metrics_logger.h>
Mathew Inwood73ddda42018-04-03 15:32:32 +010018
Andreas Gampe80f5fe52018-03-28 16:23:24 -070019#include "hidden_api.h"
20
Narayan Kamathe453a8d2018-04-03 15:23:46 +010021#include <nativehelper/scoped_local_ref.h>
22
Andreas Gampe80f5fe52018-03-28 16:23:24 -070023#include "base/dumpable.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010024#include "thread-current-inl.h"
25#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070026
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;
32
Andreas Gampe80f5fe52018-03-28 16:23:24 -070033namespace art {
34namespace hiddenapi {
35
Mathew Inwood27199e62018-04-11 16:08:21 +010036// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
37// dark grey and black. This can be set to true for developer preview / beta builds, but should be
38// false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010039// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
40// as it affects whether or not we warn for light grey APIs that have been added to the exemptions
41// list.
Mathew Inwood27199e62018-04-11 16:08:21 +010042static constexpr bool kLogAllAccesses = true;
43
Andreas Gampe80f5fe52018-03-28 16:23:24 -070044static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
45 switch (value) {
David Brazdil54a99cf2018-04-05 16:57:32 +010046 case kNone:
47 LOG(FATAL) << "Internal access to hidden API should not be logged";
48 UNREACHABLE();
Andreas Gampe80f5fe52018-03-28 16:23:24 -070049 case kReflection:
50 os << "reflection";
51 break;
52 case kJNI:
53 os << "JNI";
54 break;
55 case kLinking:
56 os << "linking";
57 break;
58 }
59 return os;
60}
61
62static constexpr bool EnumsEqual(EnforcementPolicy policy, HiddenApiAccessFlags::ApiList apiList) {
63 return static_cast<int>(policy) == static_cast<int>(apiList);
64}
65
66// GetMemberAction-related static_asserts.
67static_assert(
Andreas Gampe80f5fe52018-03-28 16:23:24 -070068 EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, HiddenApiAccessFlags::kDarkGreylist) &&
69 EnumsEqual(EnforcementPolicy::kBlacklistOnly, HiddenApiAccessFlags::kBlacklist),
70 "Mismatch between EnforcementPolicy and ApiList enums");
71static_assert(
Mathew Inwood68693692018-04-05 16:10:25 +010072 EnforcementPolicy::kJustWarn < EnforcementPolicy::kDarkGreyAndBlackList &&
Andreas Gampe80f5fe52018-03-28 16:23:24 -070073 EnforcementPolicy::kDarkGreyAndBlackList < EnforcementPolicy::kBlacklistOnly,
74 "EnforcementPolicy values ordering not correct");
75
76namespace detail {
77
78MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010079 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
80 member_name_ = field->GetName();
81 type_signature_ = field->GetTypeDescriptor();
82 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -070083}
84
85MemberSignature::MemberSignature(ArtMethod* method) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010086 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
87 member_name_ = method->GetName();
88 type_signature_ = method->GetSignature().ToString();
89 type_ = kMethod;
90}
91
92inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
93 if (type_ == kField) {
94 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
95 } else {
96 DCHECK_EQ(type_, kMethod);
97 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
98 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -070099}
100
101bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
102 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100103 for (const char* part : GetSignatureParts()) {
104 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700105 if (prefix.compare(pos, count, part, 0, count) == 0) {
106 pos += count;
107 } else {
108 return false;
109 }
110 }
111 // We have a complete match if all parts match (we exit the loop without
112 // returning) AND we've matched the whole prefix.
113 return pos == prefix.length();
114}
115
116bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
117 for (const std::string& exemption : exemptions) {
118 if (DoesPrefixMatch(exemption)) {
119 return true;
120 }
121 }
122 return false;
123}
124
125void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100126 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700127 os << part;
128 }
129}
130
131void MemberSignature::WarnAboutAccess(AccessMethod access_method,
132 HiddenApiAccessFlags::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100133 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
134 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
135}
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100136// Convert an AccessMethod enum to a value for logging from the proto enum.
137// This method may look odd (the enum values are current the same), but it
138// prevents coupling the internal enum to the proto enum (which should never
139// be changed) so that we are free to change the internal one if necessary in
140// future.
141inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
142 switch (access_method) {
143 case kNone:
144 return android::metricslogger::ACCESS_METHOD_NONE;
145 case kReflection:
146 return android::metricslogger::ACCESS_METHOD_REFLECTION;
147 case kJNI:
148 return android::metricslogger::ACCESS_METHOD_JNI;
149 case kLinking:
150 return android::metricslogger::ACCESS_METHOD_LINKING;
151 default:
152 DCHECK(false);
153 }
154}
Mathew Inwood73ddda42018-04-03 15:32:32 +0100155
156void MemberSignature::LogAccessToEventLog(AccessMethod access_method, Action action_taken) {
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100157 if (access_method == kLinking || access_method == kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100158 // Linking warnings come from static analysis/compilation of the bytecode
159 // and can contain false positives (i.e. code that is never run). We choose
160 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100161 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100162 return;
163 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100164 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
165 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
Mathew Inwood73ddda42018-04-03 15:32:32 +0100166 if (action_taken == kDeny) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100167 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100168 }
Mathew Inwood5bcef172018-05-01 14:40:12 +0100169 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
170 if (!package_name.empty()) {
171 log_maker.SetPackageName(package_name);
172 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100173 std::ostringstream signature_str;
174 Dump(signature_str);
175 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
176 log_maker.Record();
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700177}
178
David Brazdil8a6b2f32018-04-26 16:52:11 +0100179static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtField*) {
180 return true;
181}
182
183static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtMethod* method) {
184 return !method->IsIntrinsic();
185}
186
187template<typename T>
188static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
189 REQUIRES_SHARED(Locks::mutator_lock_) {
190 if (CanUpdateMemberAccessFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
191 member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
192 member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
193 }
194}
195
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700196template<typename T>
David Brazdilb8c66192018-04-23 13:51:16 +0100197Action GetMemberActionImpl(T* member,
198 HiddenApiAccessFlags::ApiList api_list,
199 Action action,
200 AccessMethod access_method) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100201 DCHECK_NE(action, kAllow);
202
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700203 // Get the signature, we need it later.
204 MemberSignature member_signature(member);
205
206 Runtime* runtime = Runtime::Current();
207
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100208 // Check for an exemption first. Exempted APIs are treated as white list.
209 // We only do this if we're about to deny, or if the app is debuggable. This is because:
210 // - we only print a warning for light greylist violations for debuggable apps
211 // - for non-debuggable apps, there is no distinction between light grey & whitelisted APIs.
212 // - we want to avoid the overhead of checking for exemptions for light greylisted APIs whenever
213 // possible.
Mathew Inwood27199e62018-04-11 16:08:21 +0100214 if (kLogAllAccesses || action == kDeny || runtime->IsJavaDebuggable()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700215 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100216 action = kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700217 // Avoid re-examining the exemption list next time.
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100218 // Note this results in no warning for the member, which seems like what one would expect.
219 // Exemptions effectively adds new members to the whitelist.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100220 MaybeWhitelistMember(runtime, member);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100221 return kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700222 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700223
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100224 if (access_method != kNone) {
225 // Print a log message with information about this class member access.
226 // We do this if we're about to block access, or the app is debuggable.
David Brazdilb8c66192018-04-23 13:51:16 +0100227 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100228 }
David Brazdil54a99cf2018-04-05 16:57:32 +0100229 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700230
Mathew Inwood73ddda42018-04-03 15:32:32 +0100231 if (kIsTargetBuild) {
232 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
233 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
234 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
235 if (eventLogSampleRate != 0 &&
236 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
237 member_signature.LogAccessToEventLog(access_method, action);
238 }
239 }
240
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700241 if (action == kDeny) {
242 // Block access
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100243 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700244 }
245
246 // Allow access to this member but print a warning.
247 DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
248
David Brazdil54a99cf2018-04-05 16:57:32 +0100249 if (access_method != kNone) {
250 // Depending on a runtime flag, we might move the member into whitelist and
251 // skip the warning the next time the member is accessed.
David Brazdil8a6b2f32018-04-26 16:52:11 +0100252 MaybeWhitelistMember(runtime, member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700253
David Brazdil54a99cf2018-04-05 16:57:32 +0100254 // If this action requires a UI warning, set the appropriate flag.
255 if (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag()) {
256 runtime->SetPendingHiddenApiWarning(true);
257 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700258 }
259
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100260 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700261}
262
263// Need to instantiate this.
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100264template Action GetMemberActionImpl<ArtField>(ArtField* member,
David Brazdilb8c66192018-04-23 13:51:16 +0100265 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100266 Action action,
267 AccessMethod access_method);
268template Action GetMemberActionImpl<ArtMethod>(ArtMethod* member,
David Brazdilb8c66192018-04-23 13:51:16 +0100269 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100270 Action action,
271 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700272} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100273
274template<typename T>
275void NotifyHiddenApiListener(T* member) {
276 Runtime* runtime = Runtime::Current();
277 if (!runtime->IsAotCompiler()) {
278 ScopedObjectAccessUnchecked soa(Thread::Current());
279
280 ScopedLocalRef<jobject> consumer_object(soa.Env(),
281 soa.Env()->GetStaticObjectField(
282 WellKnownClasses::dalvik_system_VMRuntime,
283 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
284 // If the consumer is non-null, we call back to it to let it know that we
285 // have encountered an API that's in one of our lists.
286 if (consumer_object != nullptr) {
287 detail::MemberSignature member_signature(member);
288 std::ostringstream member_signature_str;
289 member_signature.Dump(member_signature_str);
290
291 ScopedLocalRef<jobject> signature_str(
292 soa.Env(),
293 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
294
295 // Call through to Consumer.accept(String memberSignature);
296 soa.Env()->CallVoidMethod(consumer_object.get(),
297 WellKnownClasses::java_util_function_Consumer_accept,
298 signature_str.get());
299 }
300 }
301}
302
303template void NotifyHiddenApiListener<ArtMethod>(ArtMethod* member);
304template void NotifyHiddenApiListener<ArtField>(ArtField* member);
305
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700306} // namespace hiddenapi
307} // namespace art