blob: 188c5f353bf9c38c378d5eaccd1f89eecf6198a1 [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 Brazdil2bb2fbd2018-11-13 18:24:26 +000024#include "base/sdk_version.h"
David Brazdil85865692018-10-30 17:26:20 +000025#include "dex/class_accessor-inl.h"
26#include "scoped_thread_state_change.h"
27#include "thread-inl.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010028#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070029
Nicolas Geoffray8a229072018-05-10 16:34:14 +010030#ifdef ART_TARGET_ANDROID
31#include <metricslogger/metrics_logger.h>
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010032using android::metricslogger::ComplexEventLogger;
33using android::metricslogger::ACTION_HIDDEN_API_ACCESSED;
34using android::metricslogger::FIELD_HIDDEN_API_ACCESS_METHOD;
35using android::metricslogger::FIELD_HIDDEN_API_ACCESS_DENIED;
36using android::metricslogger::FIELD_HIDDEN_API_SIGNATURE;
Nicolas Geoffray8a229072018-05-10 16:34:14 +010037#endif
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010038
Andreas Gampe80f5fe52018-03-28 16:23:24 -070039namespace art {
40namespace hiddenapi {
41
Mathew Inwood27199e62018-04-11 16:08:21 +010042// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
43// dark grey and black. This can be set to true for developer preview / beta builds, but should be
44// false for public release builds.
Mathew Inwood6d6012e2018-04-12 15:43:11 +010045// Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
46// as it affects whether or not we warn for light grey APIs that have been added to the exemptions
47// list.
Mathew Inwood015a7ec2018-05-16 11:18:10 +010048static constexpr bool kLogAllAccesses = false;
Mathew Inwood27199e62018-04-11 16:08:21 +010049
Andreas Gampe80f5fe52018-03-28 16:23:24 -070050static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
51 switch (value) {
David Brazdilf50ac102018-10-17 18:00:06 +010052 case AccessMethod::kNone:
David Brazdil54a99cf2018-04-05 16:57:32 +010053 LOG(FATAL) << "Internal access to hidden API should not be logged";
54 UNREACHABLE();
David Brazdilf50ac102018-10-17 18:00:06 +010055 case AccessMethod::kReflection:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070056 os << "reflection";
57 break;
David Brazdilf50ac102018-10-17 18:00:06 +010058 case AccessMethod::kJNI:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070059 os << "JNI";
60 break;
David Brazdilf50ac102018-10-17 18:00:06 +010061 case AccessMethod::kLinking:
Andreas Gampe80f5fe52018-03-28 16:23:24 -070062 os << "linking";
63 break;
64 }
65 return os;
66}
67
Andreas Gampe80f5fe52018-03-28 16:23:24 -070068namespace detail {
69
David Brazdilf50ac102018-10-17 18:00:06 +010070// Do not change the values of items in this enum, as they are written to the
71// event log for offline analysis. Any changes will interfere with that analysis.
72enum AccessContextFlags {
73 // Accessed member is a field if this bit is set, else a method
74 kMemberIsField = 1 << 0,
75 // Indicates if access was denied to the member, instead of just printing a warning.
76 kAccessDenied = 1 << 1,
77};
78
David Brazdil2bb2fbd2018-11-13 18:24:26 +000079static SdkVersion GetMaxAllowedSdkVersionForApiList(ApiList api_list) {
David Brazdilf50ac102018-10-17 18:00:06 +010080 switch (api_list) {
81 case ApiList::kWhitelist:
82 case ApiList::kLightGreylist:
David Brazdil2bb2fbd2018-11-13 18:24:26 +000083 return SdkVersion::kMax;
David Brazdilf50ac102018-10-17 18:00:06 +010084 case ApiList::kDarkGreylist:
David Brazdil2bb2fbd2018-11-13 18:24:26 +000085 return SdkVersion::kO_MR1;
David Brazdilf50ac102018-10-17 18:00:06 +010086 case ApiList::kBlacklist:
David Brazdil2bb2fbd2018-11-13 18:24:26 +000087 return SdkVersion::kMin;
David Brazdilf50ac102018-10-17 18:00:06 +010088 case ApiList::kNoList:
89 LOG(FATAL) << "Unexpected value";
90 UNREACHABLE();
91 }
David Brazdilf50ac102018-10-17 18:00:06 +010092}
93
Andreas Gampe80f5fe52018-03-28 16:23:24 -070094MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010095 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
96 member_name_ = field->GetName();
97 type_signature_ = field->GetTypeDescriptor();
98 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -070099}
100
101MemberSignature::MemberSignature(ArtMethod* method) {
David Brazdil73a64f62018-05-02 16:53:06 +0100102 // If this is a proxy method, print the signature of the interface method.
103 method = method->GetInterfaceMethodIfProxy(
104 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
105
Mathew Inwood73ddda42018-04-03 15:32:32 +0100106 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
107 member_name_ = method->GetName();
108 type_signature_ = method->GetSignature().ToString();
109 type_ = kMethod;
110}
111
112inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
113 if (type_ == kField) {
114 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
115 } else {
116 DCHECK_EQ(type_, kMethod);
117 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
118 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700119}
120
121bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
122 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100123 for (const char* part : GetSignatureParts()) {
124 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700125 if (prefix.compare(pos, count, part, 0, count) == 0) {
126 pos += count;
127 } else {
128 return false;
129 }
130 }
131 // We have a complete match if all parts match (we exit the loop without
132 // returning) AND we've matched the whole prefix.
133 return pos == prefix.length();
134}
135
136bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
137 for (const std::string& exemption : exemptions) {
138 if (DoesPrefixMatch(exemption)) {
139 return true;
140 }
141 }
142 return false;
143}
144
145void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100146 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700147 os << part;
148 }
149}
150
David Brazdil47cd2722018-10-23 12:50:02 +0100151void MemberSignature::WarnAboutAccess(AccessMethod access_method, hiddenapi::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100152 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
153 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
154}
David Brazdilf50ac102018-10-17 18:00:06 +0100155
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100156#ifdef ART_TARGET_ANDROID
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100157// Convert an AccessMethod enum to a value for logging from the proto enum.
158// This method may look odd (the enum values are current the same), but it
159// prevents coupling the internal enum to the proto enum (which should never
160// be changed) so that we are free to change the internal one if necessary in
161// future.
162inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
163 switch (access_method) {
David Brazdilf50ac102018-10-17 18:00:06 +0100164 case AccessMethod::kNone:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100165 return android::metricslogger::ACCESS_METHOD_NONE;
David Brazdilf50ac102018-10-17 18:00:06 +0100166 case AccessMethod::kReflection:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100167 return android::metricslogger::ACCESS_METHOD_REFLECTION;
David Brazdilf50ac102018-10-17 18:00:06 +0100168 case AccessMethod::kJNI:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100169 return android::metricslogger::ACCESS_METHOD_JNI;
David Brazdilf50ac102018-10-17 18:00:06 +0100170 case AccessMethod::kLinking:
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100171 return android::metricslogger::ACCESS_METHOD_LINKING;
172 default:
173 DCHECK(false);
174 }
175}
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100176#endif
Mathew Inwood73ddda42018-04-03 15:32:32 +0100177
David Brazdilf50ac102018-10-17 18:00:06 +0100178void MemberSignature::LogAccessToEventLog(AccessMethod access_method, bool access_denied) {
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100179#ifdef ART_TARGET_ANDROID
David Brazdilf50ac102018-10-17 18:00:06 +0100180 if (access_method == AccessMethod::kLinking || access_method == AccessMethod::kNone) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100181 // Linking warnings come from static analysis/compilation of the bytecode
182 // and can contain false positives (i.e. code that is never run). We choose
183 // not to log these in the event log.
Mathew Inwoodf59ca612018-05-03 11:30:01 +0100184 // None does not correspond to actual access, so should also be ignored.
Mathew Inwood73ddda42018-04-03 15:32:32 +0100185 return;
186 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100187 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
188 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
David Brazdilf50ac102018-10-17 18:00:06 +0100189 if (access_denied) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100190 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100191 }
Mathew Inwood5bcef172018-05-01 14:40:12 +0100192 const std::string& package_name = Runtime::Current()->GetProcessPackageName();
193 if (!package_name.empty()) {
194 log_maker.SetPackageName(package_name);
195 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100196 std::ostringstream signature_str;
197 Dump(signature_str);
198 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
199 log_maker.Record();
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100200#else
201 UNUSED(access_method);
David Brazdilf50ac102018-10-17 18:00:06 +0100202 UNUSED(access_denied);
Nicolas Geoffray8a229072018-05-10 16:34:14 +0100203#endif
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700204}
205
David Brazdilf50ac102018-10-17 18:00:06 +0100206void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
207 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
208 // We can only up-call into Java during reflection and JNI down-calls.
209 return;
210 }
211
212 Runtime* runtime = Runtime::Current();
213 if (!runtime->IsAotCompiler()) {
214 ScopedObjectAccessUnchecked soa(Thread::Current());
215
216 ScopedLocalRef<jobject> consumer_object(soa.Env(),
217 soa.Env()->GetStaticObjectField(
218 WellKnownClasses::dalvik_system_VMRuntime,
219 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
220 // If the consumer is non-null, we call back to it to let it know that we
221 // have encountered an API that's in one of our lists.
222 if (consumer_object != nullptr) {
223 std::ostringstream member_signature_str;
224 Dump(member_signature_str);
225
226 ScopedLocalRef<jobject> signature_str(
227 soa.Env(),
228 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
229
230 // Call through to Consumer.accept(String memberSignature);
231 soa.Env()->CallVoidMethod(consumer_object.get(),
232 WellKnownClasses::java_util_function_Consumer_accept,
233 signature_str.get());
234 }
235 }
236}
237
David Brazdil85865692018-10-30 17:26:20 +0000238static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100239 return true;
240}
241
David Brazdil85865692018-10-30 17:26:20 +0000242static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
David Brazdil8a6b2f32018-04-26 16:52:11 +0100243 return !method->IsIntrinsic();
244}
245
246template<typename T>
247static ALWAYS_INLINE void MaybeWhitelistMember(Runtime* runtime, T* member)
248 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil85865692018-10-30 17:26:20 +0000249 if (CanUpdateRuntimeFlags(member) && runtime->ShouldDedupeHiddenApiWarnings()) {
250 member->SetAccessFlags(member->GetAccessFlags() | kAccPublicApi);
David Brazdil8a6b2f32018-04-26 16:52:11 +0100251 }
252}
253
David Brazdil85865692018-10-30 17:26:20 +0000254static constexpr uint32_t kNoDexFlags = 0u;
255static constexpr uint32_t kInvalidDexFlags = static_cast<uint32_t>(-1);
256
257uint32_t GetDexFlags(ArtField* field) REQUIRES_SHARED(Locks::mutator_lock_) {
258 ObjPtr<mirror::Class> declaring_class = field->GetDeclaringClass();
259 DCHECK(declaring_class != nullptr) << "Fields always have a declaring class";
260
261 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
262 if (class_def == nullptr) {
263 return kNoDexFlags;
264 }
265
266 uint32_t flags = kInvalidDexFlags;
267 DCHECK(!AreValidFlags(flags));
268
269 ClassAccessor accessor(declaring_class->GetDexFile(),
270 *class_def,
271 /* parse_hiddenapi_class_data= */ true);
272 auto fn_visit = [&](const ClassAccessor::Field& dex_field) {
273 if (dex_field.GetIndex() == field->GetDexFieldIndex()) {
274 flags = dex_field.GetHiddenapiFlags();
275 }
276 };
277 accessor.VisitFields(fn_visit, fn_visit);
278
279 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for field " << field->PrettyField();
280 DCHECK(AreValidFlags(flags));
281 return flags;
282}
283
284uint32_t GetDexFlags(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
285 ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
286 if (declaring_class.IsNull()) {
287 DCHECK(method->IsRuntimeMethod());
288 return kNoDexFlags;
289 }
290
291 const DexFile::ClassDef* class_def = declaring_class->GetClassDef();
292 if (class_def == nullptr) {
293 return kNoDexFlags;
294 }
295
296 uint32_t flags = kInvalidDexFlags;
297 DCHECK(!AreValidFlags(flags));
298
299 ClassAccessor accessor(declaring_class->GetDexFile(),
300 *class_def,
301 /* parse_hiddenapi_class_data= */ true);
302 auto fn_visit = [&](const ClassAccessor::Method& dex_method) {
303 if (dex_method.GetIndex() == method->GetDexMethodIndex()) {
304 flags = dex_method.GetHiddenapiFlags();
305 }
306 };
307 accessor.VisitMethods(fn_visit, fn_visit);
308
309 CHECK_NE(flags, kInvalidDexFlags) << "Could not find flags for method " << method->PrettyMethod();
310 DCHECK(AreValidFlags(flags));
311 return flags;
312}
313
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700314template<typename T>
David Brazdilf50ac102018-10-17 18:00:06 +0100315bool ShouldDenyAccessToMemberImpl(T* member,
316 hiddenapi::ApiList api_list,
317 AccessMethod access_method) {
318 DCHECK(member != nullptr);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700319
320 Runtime* runtime = Runtime::Current();
David Brazdilf50ac102018-10-17 18:00:06 +0100321 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
322
323 const bool deny_access =
324 (policy == EnforcementPolicy::kEnabled) &&
David Brazdil2bb2fbd2018-11-13 18:24:26 +0000325 IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
326 GetMaxAllowedSdkVersionForApiList(api_list));
David Brazdilf50ac102018-10-17 18:00:06 +0100327
328 MemberSignature member_signature(member);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700329
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100330 // Check for an exemption first. Exempted APIs are treated as white list.
David Brazdilf50ac102018-10-17 18:00:06 +0100331 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
332 // Avoid re-examining the exemption list next time.
333 // Note this results in no warning for the member, which seems like what one would expect.
334 // Exemptions effectively adds new members to the whitelist.
335 MaybeWhitelistMember(runtime, member);
336 return false;
337 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700338
David Brazdilf50ac102018-10-17 18:00:06 +0100339 if (access_method != AccessMethod::kNone) {
340 // Print a log message with information about this class member access.
341 // We do this if we're about to deny access, or the app is debuggable.
342 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
David Brazdilb8c66192018-04-23 13:51:16 +0100343 member_signature.WarnAboutAccess(access_method, api_list);
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100344 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700345
David Brazdilf50ac102018-10-17 18:00:06 +0100346 // If there is a StrictMode listener, notify it about this violation.
347 member_signature.NotifyHiddenApiListener(access_method);
348
349 // If event log sampling is enabled, report this violation.
350 if (kIsTargetBuild && !kIsTargetLinux) {
351 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
352 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
353 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
354 if (eventLogSampleRate != 0 &&
355 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
356 member_signature.LogAccessToEventLog(access_method, deny_access);
357 }
358 }
359
360 // If this access was not denied, move the member into whitelist and skip
361 // the warning the next time the member is accessed.
362 if (!deny_access) {
363 MaybeWhitelistMember(runtime, member);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100364 }
365 }
366
David Brazdilf50ac102018-10-17 18:00:06 +0100367 return deny_access;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700368}
369
370// Need to instantiate this.
David Brazdilf50ac102018-10-17 18:00:06 +0100371template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
372 hiddenapi::ApiList api_list,
373 AccessMethod access_method);
374template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
375 hiddenapi::ApiList api_list,
376 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700377} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100378
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700379} // namespace hiddenapi
380} // namespace art