blob: ee518ae1ea539d72118030f0759eadb684fa9a1f [file] [log] [blame]
Andreas Gampeaa120012018-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 Kamathf5f1f802018-04-03 15:23:46 +010019#include <nativehelper/scoped_local_ref.h>
20
Andreas Gampeaa120012018-03-28 16:23:24 -070021#include "base/dumpable.h"
Narayan Kamathf5f1f802018-04-03 15:23:46 +010022#include "thread-current-inl.h"
23#include "well_known_classes.h"
Andreas Gampeaa120012018-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 Inwood17245202018-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 Inwood17245202018-04-12 13:56:37 +010033
Andreas Gampeaa120012018-03-28 16:23:24 -070034namespace art {
35namespace hiddenapi {
36
Mathew Inwood85b5a572018-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 Inwood0a054d32018-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 Inwood85b5a572018-04-11 16:08:21 +010043static constexpr bool kLogAllAccesses = true;
44
Andreas Gampeaa120012018-03-28 16:23:24 -070045static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
46 switch (value) {
David Brazdil4525e0b2018-04-05 16:57:32 +010047 case kNone:
48 LOG(FATAL) << "Internal access to hidden API should not be logged";
49 UNREACHABLE();
Andreas Gampeaa120012018-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 Gampeaa120012018-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 Inwooda8503d92018-04-05 16:10:25 +010073 EnforcementPolicy::kJustWarn < EnforcementPolicy::kDarkGreyAndBlackList &&
Andreas Gampeaa120012018-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 Inwood1fd97f22018-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 Gampeaa120012018-03-28 16:23:24 -070084}
85
86MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil1f9d3c32018-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 Inwood1fd97f22018-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 Gampeaa120012018-03-28 16:23:24 -0700104}
105
106bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
107 size_t pos = 0;
Mathew Inwood1fd97f22018-04-03 15:32:32 +0100108 for (const char* part : GetSignatureParts()) {
109 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampeaa120012018-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 Inwood1fd97f22018-04-03 15:32:32 +0100131 for (const char* part : GetSignatureParts()) {
Andreas Gampeaa120012018-03-28 16:23:24 -0700132 os << part;
133 }
134}
135
136void MemberSignature::WarnAboutAccess(AccessMethod access_method,
137 HiddenApiAccessFlags::ApiList list) {
Mathew Inwood1fd97f22018-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 Inwood17245202018-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 Inwood1fd97f22018-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 Inwoode9c3bbb2018-05-03 11:30:01 +0100165 if (access_method == kLinking || access_method == kNone) {
Mathew Inwood1fd97f22018-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 Inwoode9c3bbb2018-05-03 11:30:01 +0100169 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood1fd97f22018-04-03 15:32:32 +0100170 return;
171 }
Mathew Inwood17245202018-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 Inwood1fd97f22018-04-03 15:32:32 +0100174 if (action_taken == kDeny) {
Mathew Inwood17245202018-04-12 13:56:37 +0100175 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood1fd97f22018-04-03 15:32:32 +0100176 }
Mathew Inwood17245202018-04-12 13:56:37 +0100177 std::ostringstream signature_str;
178 Dump(signature_str);
179 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
180 log_maker.Record();
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100181#else
182 UNUSED(access_method);
183 UNUSED(action_taken);
184#endif
Andreas Gampeaa120012018-03-28 16:23:24 -0700185}
186
David Brazdilbb0454a2018-04-26 16:52:11 +0100187static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtField*) {
188 return true;
189}
190
191static ALWAYS_INLINE bool CanUpdateMemberAccessFlags(ArtMethod* method) {
192 return !method->IsIntrinsic();
193}
194
195template<typename T>
196static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
197 REQUIRES_SHARED(Locks::mutator_lock_) {
198 if (CanUpdateMemberAccessFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
199 member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
200 member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
201 }
202}
203
Andreas Gampeaa120012018-03-28 16:23:24 -0700204template<typename T>
David Brazdil39512f52018-04-23 13:51:16 +0100205Action GetMemberActionImpl(T* member,
206 HiddenApiAccessFlags::ApiList api_list,
207 Action action,
208 AccessMethod access_method) {
David Brazdil4525e0b2018-04-05 16:57:32 +0100209 DCHECK_NE(action, kAllow);
210
Andreas Gampeaa120012018-03-28 16:23:24 -0700211 // Get the signature, we need it later.
212 MemberSignature member_signature(member);
213
214 Runtime* runtime = Runtime::Current();
215
Mathew Inwood9a819452018-04-05 13:58:55 +0100216 // Check for an exemption first. Exempted APIs are treated as white list.
217 // We only do this if we're about to deny, or if the app is debuggable. This is because:
218 // - we only print a warning for light greylist violations for debuggable apps
219 // - for non-debuggable apps, there is no distinction between light grey & whitelisted APIs.
220 // - we want to avoid the overhead of checking for exemptions for light greylisted APIs whenever
221 // possible.
Mathew Inwood85b5a572018-04-11 16:08:21 +0100222 if (kLogAllAccesses || action == kDeny || runtime->IsJavaDebuggable()) {
Andreas Gampeaa120012018-03-28 16:23:24 -0700223 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
Mathew Inwood9a819452018-04-05 13:58:55 +0100224 action = kAllow;
Andreas Gampeaa120012018-03-28 16:23:24 -0700225 // Avoid re-examining the exemption list next time.
Mathew Inwood9a819452018-04-05 13:58:55 +0100226 // Note this results in no warning for the member, which seems like what one would expect.
227 // Exemptions effectively adds new members to the whitelist.
David Brazdilbb0454a2018-04-26 16:52:11 +0100228 MaybeWhitelistMember(runtime, member);
Mathew Inwood9a819452018-04-05 13:58:55 +0100229 return kAllow;
Andreas Gampeaa120012018-03-28 16:23:24 -0700230 }
Andreas Gampeaa120012018-03-28 16:23:24 -0700231
Mathew Inwood9a819452018-04-05 13:58:55 +0100232 if (access_method != kNone) {
233 // Print a log message with information about this class member access.
234 // We do this if we're about to block access, or the app is debuggable.
David Brazdil39512f52018-04-23 13:51:16 +0100235 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwood9a819452018-04-05 13:58:55 +0100236 }
David Brazdil4525e0b2018-04-05 16:57:32 +0100237 }
Andreas Gampeaa120012018-03-28 16:23:24 -0700238
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100239 if (kIsTargetBuild && !kIsTargetLinux) {
Mathew Inwood1fd97f22018-04-03 15:32:32 +0100240 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
241 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
242 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
243 if (eventLogSampleRate != 0 &&
244 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
245 member_signature.LogAccessToEventLog(access_method, action);
246 }
247 }
248
Andreas Gampeaa120012018-03-28 16:23:24 -0700249 if (action == kDeny) {
250 // Block access
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100251 return action;
Andreas Gampeaa120012018-03-28 16:23:24 -0700252 }
253
254 // Allow access to this member but print a warning.
255 DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
256
David Brazdil4525e0b2018-04-05 16:57:32 +0100257 if (access_method != kNone) {
258 // Depending on a runtime flag, we might move the member into whitelist and
259 // skip the warning the next time the member is accessed.
David Brazdilbb0454a2018-04-26 16:52:11 +0100260 MaybeWhitelistMember(runtime, member);
Andreas Gampeaa120012018-03-28 16:23:24 -0700261
David Brazdil4525e0b2018-04-05 16:57:32 +0100262 // If this action requires a UI warning, set the appropriate flag.
263 if (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag()) {
264 runtime->SetPendingHiddenApiWarning(true);
265 }
Andreas Gampeaa120012018-03-28 16:23:24 -0700266 }
267
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100268 return action;
Andreas Gampeaa120012018-03-28 16:23:24 -0700269}
270
271// Need to instantiate this.
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100272template Action GetMemberActionImpl<ArtField>(ArtField* member,
David Brazdil39512f52018-04-23 13:51:16 +0100273 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100274 Action action,
275 AccessMethod access_method);
276template Action GetMemberActionImpl<ArtMethod>(ArtMethod* member,
David Brazdil39512f52018-04-23 13:51:16 +0100277 HiddenApiAccessFlags::ApiList api_list,
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100278 Action action,
279 AccessMethod access_method);
Andreas Gampeaa120012018-03-28 16:23:24 -0700280} // namespace detail
Narayan Kamathf5f1f802018-04-03 15:23:46 +0100281
282template<typename T>
283void NotifyHiddenApiListener(T* member) {
284 Runtime* runtime = Runtime::Current();
285 if (!runtime->IsAotCompiler()) {
286 ScopedObjectAccessUnchecked soa(Thread::Current());
287
288 ScopedLocalRef<jobject> consumer_object(soa.Env(),
289 soa.Env()->GetStaticObjectField(
290 WellKnownClasses::dalvik_system_VMRuntime,
291 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
292 // If the consumer is non-null, we call back to it to let it know that we
293 // have encountered an API that's in one of our lists.
294 if (consumer_object != nullptr) {
295 detail::MemberSignature member_signature(member);
296 std::ostringstream member_signature_str;
297 member_signature.Dump(member_signature_str);
298
299 ScopedLocalRef<jobject> signature_str(
300 soa.Env(),
301 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
302
303 // Call through to Consumer.accept(String memberSignature);
304 soa.Env()->CallVoidMethod(consumer_object.get(),
305 WellKnownClasses::java_util_function_Consumer_accept,
306 signature_str.get());
307 }
308 }
309}
310
311template void NotifyHiddenApiListener<ArtMethod>(ArtMethod* member);
312template void NotifyHiddenApiListener<ArtField>(ArtField* member);
313
Andreas Gampeaa120012018-03-28 16:23:24 -0700314} // namespace hiddenapi
315} // namespace art