blob: d3df7fd38dcea3c7a99ad753c19ae775d66f4012 [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
Andreas Gampe80f5fe52018-03-28 16:23:24 -070078MemberSignature::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) {
David Brazdil73a64f62018-05-02 16:53:06 +010086 // If this is a proxy method, print the signature of the interface method.
87 method = method->GetInterfaceMethodIfProxy(
88 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
89
Mathew Inwood73ddda42018-04-03 15:32:32 +010090 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
91 member_name_ = method->GetName();
92 type_signature_ = method->GetSignature().ToString();
93 type_ = kMethod;
94}
95
96inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
97 if (type_ == kField) {
98 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
99 } else {
100 DCHECK_EQ(type_, kMethod);
101 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
102 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700103}
104
105bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
106 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100107 for (const char* part : GetSignatureParts()) {
108 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700109 if (prefix.compare(pos, count, part, 0, count) == 0) {
110 pos += count;
111 } else {
112 return false;
113 }
114 }
115 // We have a complete match if all parts match (we exit the loop without
116 // returning) AND we've matched the whole prefix.
117 return pos == prefix.length();
118}
119
120bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
121 for (const std::string& exemption : exemptions) {
122 if (DoesPrefixMatch(exemption)) {
123 return true;
124 }
125 }
126 return false;
127}
128
129void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100130 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700131 os << part;
132 }
133}
134
David Brazdil47cd2722018-10-23 12:50:02 +0100135void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100136 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
137 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
138}
David Brazdilf50ac102018-10-17 18:00:06 +0100139
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) {
David Brazdilf50ac102018-10-17 18:00:06 +0100148 case AccessMethod::kNone:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100149 return android::metricslogger::ACCESS_METHOD_NONE;
David Brazdilf50ac102018-10-17 18:00:06 +0100150 case AccessMethod::kReflection:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100151 return android::metricslogger::ACCESS_METHOD_REFLECTION;
David Brazdilf50ac102018-10-17 18:00:06 +0100152 case AccessMethod::kJNI:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100153 return android::metricslogger::ACCESS_METHOD_JNI;
David Brazdilf50ac102018-10-17 18:00:06 +0100154 case AccessMethod::kLinking:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100155 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
David Brazdilf50ac102018-10-17 18:00:06 +0100162void MemberSignature::LogAccessToEventLog(AccessMethod access_method, bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100163#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100164 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::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));
David Brazdilf50ac102018-10-17 18:00:06 +0100173 if (access_denied) {
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);
David Brazdilf50ac102018-10-17 18:00:06 +0100186 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100187#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700188}
189
David Brazdilf50ac102018-10-17 18:00:06 +0100190void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
191 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
192 // We can only up-call into Java during reflection and JNI down-calls.
193 return;
194 }
195
196 Runtime* runtime = Runtime::Current();
197 if (!runtime->IsAotCompiler()) {
198 ScopedObjectAccessUnchecked soa(Thread::Current());
199
200 ScopedLocalRef<jobject> consumer_object(soa.Env(),
201 soa.Env()->GetStaticObjectField(
202 WellKnownClasses::dalvik_system_VMRuntime,
203 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
204 // If the consumer is non-null, we call back to it to let it know that we
205 // have encountered an API that's in one of our lists.
206 if (consumer_object != nullptr) {
207 std::ostringstream member_signature_str;
208 Dump(member_signature_str);
209
210 ScopedLocalRef<jobject> signature_str(
211 soa.Env(),
212 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
213
214 // Call through to Consumer.accept(String memberSignature);
215 soa.Env()->CallVoidMethod(consumer_object.get(),
216 WellKnownClasses::java_util_function_Consumer_accept,
217 signature_str.get());
218 }
219 }
220}
221
David Brazdil85865692018-10-30 17:26:20 +0000222static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100223 return true;
224}
225
David Brazdil85865692018-10-30 17:26:20 +0000226static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100227 return !method->IsIntrinsic();
228}
229
230template<typename T>
231static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
232 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil85865692018-10-30 17:26:20 +0000233 if (CanUpdateRuntimeFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
234 member->SetAccessFlags(member->GetAccessFlags() | kAccPublicApi);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100235 }
236}
237
David Brazdil85865692018-10-30 17:26:20 +0000238static constexpr uint32_t kNoDexFlags = 0u;
239static constexpr uint32_t kInvalidDexFlags = static_cast<uint32_t>(-1);
240
241uint32_t GetDexFlags(ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_) {
242 ObjPtr<mirror::Class> declaring_class = field->GetDeclaringClass();
243 DCHECK(declaring_class != nullptr) << "Fields always have a declaring class";
244
245 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
246 if (class_def == nullptr) {
247 return kNoDexFlags;
248 }
249
250 uint32_t flags = kInvalidDexFlags;
David Brazdildcfa89b2018-10-31 11:04:10 +0000251 DCHECK(!AreValidDexFlags(flags));
David Brazdil85865692018-10-30 17:26:20 +0000252
253 ClassAccessor accessor(declaring_class->GetDexFile(),
254 *class_def,
255 /* parse_hiddenapi_class_data= */ true);
256 auto fn_visit = [&](const ClassAccessor::Field& dex_field) {
257 if (dex_field.GetIndex() == field->GetDexFieldIndex()) {
258 flags = dex_field.GetHiddenapiFlags();
259 }
260 };
261 accessor.VisitFields(fn_visit, fn_visit);
262
263 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for field " << field->PrettyField();
David Brazdildcfa89b2018-10-31 11:04:10 +0000264 DCHECK(AreValidDexFlags(flags));
David Brazdil85865692018-10-30 17:26:20 +0000265 return flags;
266}
267
268uint32_t GetDexFlags(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
269 ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
270 if (declaring_class.IsNull()) {
271 DCHECK(method->IsRuntimeMethod());
272 return kNoDexFlags;
273 }
274
275 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
276 if (class_def == nullptr) {
277 return kNoDexFlags;
278 }
279
280 uint32_t flags = kInvalidDexFlags;
David Brazdildcfa89b2018-10-31 11:04:10 +0000281 DCHECK(!AreValidDexFlags(flags));
David Brazdil85865692018-10-30 17:26:20 +0000282
283 ClassAccessor accessor(declaring_class->GetDexFile(),
284 *class_def,
285 /* parse_hiddenapi_class_data= */ true);
286 auto fn_visit = [&](const ClassAccessor::Method& dex_method) {
287 if (dex_method.GetIndex() == method->GetDexMethodIndex()) {
288 flags = dex_method.GetHiddenapiFlags();
289 }
290 };
291 accessor.VisitMethods(fn_visit, fn_visit);
292
293 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for method " << method->PrettyMethod();
David Brazdildcfa89b2018-10-31 11:04:10 +0000294 DCHECK(AreValidDexFlags(flags));
David Brazdil85865692018-10-30 17:26:20 +0000295 return flags;
296}
297
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700298template<typename T>
David Brazdilf50ac102018-10-17 18:00:06 +0100299bool ShouldDenyAccessToMemberImpl(T* member,
300 hiddenapi::ApiList api_list,
301 AccessMethod access_method) {
302 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700303
304 Runtime* runtime = Runtime::Current();
David Brazdilf50ac102018-10-17 18:00:06 +0100305 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
306
307 const bool deny_access =
308 (policy == EnforcementPolicy::kEnabled) &&
David Brazdil2bb2fbd2018-11-13 18:24:26 +0000309 IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
David Brazdildcfa89b2018-10-31 11:04:10 +0000310 api_list.GetMaxAllowedSdkVersion());
David Brazdilf50ac102018-10-17 18:00:06 +0100311
312 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700313
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100314 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100315 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
316 // Avoid re-examining the exemption list next time.
317 // Note this results in no warning for the member, which seems like what one would expect.
318 // Exemptions effectively adds new members to the whitelist.
319 MaybeWhitelistMember(runtime, member);
320 return false;
321 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700322
David Brazdilf50ac102018-10-17 18:00:06 +0100323 if (access_method != AccessMethod::kNone) {
324 // Print a log message with information about this class member access.
325 // We do this if we're about to deny access, or the app is debuggable.
326 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdilb8c66192018-04-23 13:51:16 +0100327 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100328 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700329
David Brazdilf50ac102018-10-17 18:00:06 +0100330 // If there is a StrictMode listener, notify it about this violation.
331 member_signature.NotifyHiddenApiListener(access_method);
332
333 // If event log sampling is enabled, report this violation.
334 if (kIsTargetBuild && !kIsTargetLinux) {
335 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
336 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
337 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
338 if (eventLogSampleRate != 0 &&
339 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
340 member_signature.LogAccessToEventLog(access_method, deny_access);
341 }
342 }
343
344 // If this access was not denied, move the member into whitelist and skip
345 // the warning the next time the member is accessed.
346 if (!deny_access) {
347 MaybeWhitelistMember(runtime, member);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100348 }
349 }
350
David Brazdilf50ac102018-10-17 18:00:06 +0100351 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700352}
353
354// Need to instantiate this.
David Brazdilf50ac102018-10-17 18:00:06 +0100355template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
356 hiddenapi::ApiList api_list,
357 AccessMethod access_method);
358template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
359 hiddenapi::ApiList api_list,
360 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700361} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100362
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700363} // namespace hiddenapi
364} // namespace art