Debian Codegraph @

core/java/android/os/StrictMode.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2010 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 package android.os;
17
18 import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
19
20 import android.animation.ValueAnimator;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.SystemApi;
25 import android.annotation.TestApi;
26 import android.app.ActivityManager;
27 import android.app.ActivityThread;
28 import android.app.IActivityManager;
29 import android.app.compat.CompatChanges;
30 import android.compat.annotation.ChangeId;
31 import android.compat.annotation.EnabledSince;
32 import android.compat.annotation.UnsupportedAppUsage;
33 import android.content.BroadcastReceiver;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.ServiceConnection;
37 import android.content.pm.ApplicationInfo;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.net.TrafficStats;
41 import android.net.Uri;
42 import android.os.storage.IStorageManager;
43 import android.os.strictmode.CleartextNetworkViolation;
44 import android.os.strictmode.ContentUriWithoutPermissionViolation;
45 import android.os.strictmode.CredentialProtectedWhileLockedViolation;
46 import android.os.strictmode.CustomViolation;
47 import android.os.strictmode.DiskReadViolation;
48 import android.os.strictmode.DiskWriteViolation;
49 import android.os.strictmode.ExplicitGcViolation;
50 import android.os.strictmode.FileUriExposedViolation;
51 import android.os.strictmode.ImplicitDirectBootViolation;
52 import android.os.strictmode.IncorrectContextUseViolation;
53 import android.os.strictmode.InstanceCountViolation;
54 import android.os.strictmode.IntentReceiverLeakedViolation;
55 import android.os.strictmode.LeakedClosableViolation;
56 import android.os.strictmode.NetworkViolation;
57 import android.os.strictmode.NonSdkApiUsedViolation;
58 import android.os.strictmode.ResourceMismatchViolation;
59 import android.os.strictmode.ServiceConnectionLeakedViolation;
60 import android.os.strictmode.SqliteObjectLeakedViolation;
61 import android.os.strictmode.UnbufferedIoViolation;
62 import android.os.strictmode.UnsafeIntentLaunchViolation;
63 import android.os.strictmode.UntaggedSocketViolation;
64 import android.os.strictmode.Violation;
65 import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation;
66 import android.util.ArrayMap;
67 import android.util.Log;
68 import android.util.Printer;
69 import android.util.Singleton;
70 import android.util.Slog;
71 import android.util.SparseLongArray;
72 import android.view.IWindowManager;
73
74 import com.android.internal.annotations.GuardedBy;
75 import com.android.internal.os.BackgroundThread;
76 import com.android.internal.os.RuntimeInit;
77 import com.android.internal.util.FastPrintWriter;
78 import com.android.internal.util.HexDump;
79
80 import dalvik.system.BlockGuard;
81 import dalvik.system.CloseGuard;
82 import dalvik.system.VMDebug;
83 import dalvik.system.VMRuntime;
84
85 import java.io.PrintWriter;
86 import java.io.StringWriter;
87 import java.lang.annotation.Retention;
88 import java.lang.annotation.RetentionPolicy;
89 import java.net.InetAddress;
90 import java.net.UnknownHostException;
91 import java.util.ArrayDeque;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.Deque;
95 import java.util.HashMap;
96 import java.util.concurrent.Executor;
97 import java.util.concurrent.RejectedExecutionException;
98 import java.util.concurrent.atomic.AtomicInteger;
99 import java.util.function.Consumer;
100
101 /**
102 * StrictMode is a developer tool which detects things you might be doing by accident and brings
103 * them to your attention so you can fix them.
104 *
105 * <p>StrictMode is most commonly used to catch accidental disk or network access on the
106 * application's main thread, where UI operations are received and animations take place. Keeping
107 * disk and network operations off the main thread makes for much smoother, more responsive
108 * applications. By keeping your application's main thread responsive, you also prevent <a
109 * href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a> from being shown to
110 * users.
111 *
112 * <p class="note">Note that even though an Android device's disk is often on flash memory, many
113 * devices run a filesystem on top of that memory with very limited concurrency. It's often the case
114 * that almost all disk accesses are fast, but may in individual cases be dramatically slower when
115 * certain I/O is happening in the background from other processes. If possible, it's best to assume
116 * that such things are not fast.
117 *
118 * <p>Example code to enable from early in your {@link android.app.Application}, {@link
119 * android.app.Activity}, or other application component's {@link android.app.Application#onCreate}
120 * method:
121 *
122 * <pre>
123 * public void onCreate() {
124 * StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
125 * .detectDiskReads()
126 * .detectDiskWrites()
127 * .detectNetwork() // or .detectAll() for all detectable problems
128 * .penaltyLog()
129 * .build());
130 * StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
131 * .detectLeakedSqlLiteObjects()
132 * .detectLeakedClosableObjects()
133 * .penaltyLog()
134 * .penaltyDeath()
135 * .build());
136 * super.onCreate();
137 * }
138 * </pre>
139 *
140 * <p>You can decide what should happen when a violation is detected. For example, using {@link
141 * ThreadPolicy.Builder#penaltyLog} you can watch the output of <code>adb logcat</code> while you
142 * use your application to see the violations as they happen.
143 *
144 * <p>If you find violations that you feel are problematic, there are a variety of tools to help
145 * solve them: threads, {@link android.os.Handler}, {@link android.os.AsyncTask}, {@link
146 * android.app.IntentService}, etc. But don't feel compelled to fix everything that StrictMode
147 * finds. In particular, many cases of disk access are often necessary during the normal activity
148 * lifecycle. Use StrictMode to find things you did by accident. Network requests on the UI thread
149 * are almost always a problem, though.
150 *
151 * <p class="note">StrictMode is not a security mechanism and is not guaranteed to find all disk or
152 * network accesses. While it does propagate its state across process boundaries when doing {@link
153 * android.os.Binder} calls, it's still ultimately a best effort mechanism. Notably, disk or network
154 * access from JNI calls won't necessarily trigger it.
155 */
156 public final class StrictMode {
157 private static final String TAG = "StrictMode";
158 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
159
160 /**
161 * Boolean system property to disable strict mode checks outright. Set this to 'true' to force
162 * disable; 'false' has no effect on other enable/disable policy.
163 *
164 * @hide
165 */
166 public static final String DISABLE_PROPERTY = "persist.sys.strictmode.disable";
167
168 /**
169 * The boolean system property to control screen flashes on violations.
170 *
171 * @hide
172 */
173 public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
174
175 /**
176 * Temporary property used to include {@link #DETECT_VM_CLEARTEXT_NETWORK} in {@link
177 * VmPolicy.Builder#detectAll()}. Apps can still always opt-into detection using {@link
178 * VmPolicy.Builder#detectCleartextNetwork()}.
179 */
180 private static final String CLEARTEXT_PROPERTY = "persist.sys.strictmode.clear";
181
182 /**
183 * Quick feature-flag that can be used to disable the defaults provided by {@link
184 * #initThreadDefaults(ApplicationInfo)} and {@link #initVmDefaults(ApplicationInfo)}.
185 */
186 private static final boolean DISABLE = false;
187
188 // Only apply VM penalties for the same violation at this interval.
189 private static final long MIN_VM_INTERVAL_MS = 1000;
190
191 // Only log a duplicate stack trace to the logs every second.
192 private static final long MIN_LOG_INTERVAL_MS = 1000;
193
194 // Only show an annoying dialog at most every 30 seconds
195 private static final long MIN_DIALOG_INTERVAL_MS = 30000;
196
197 // Only log a dropbox entry at most every 30 seconds
198 private static final long MIN_DROPBOX_INTERVAL_MS = 3000;
199
200 // How many Span tags (e.g. animations) to report.
201 private static final int MAX_SPAN_TAGS = 20;
202
203 // How many offending stacks to keep track of (and time) per loop
204 // of the Looper.
205 private static final int MAX_OFFENSES_PER_LOOP = 10;
206
207 /** @hide */
208 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
209 DETECT_THREAD_DISK_WRITE,
210 DETECT_THREAD_DISK_READ,
211 DETECT_THREAD_NETWORK,
212 DETECT_THREAD_CUSTOM,
213 DETECT_THREAD_RESOURCE_MISMATCH,
214 DETECT_THREAD_UNBUFFERED_IO,
215 DETECT_THREAD_EXPLICIT_GC,
216 PENALTY_GATHER,
217 PENALTY_LOG,
218 PENALTY_DIALOG,
219 PENALTY_DEATH,
220 PENALTY_FLASH,
221 PENALTY_DROPBOX,
222 PENALTY_DEATH_ON_NETWORK,
223 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
224 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
225 })
226 @Retention(RetentionPolicy.SOURCE)
227 public @interface ThreadPolicyMask {}
228
229 // Thread policy: bits 0-15
230
231 /** @hide */
232 private static final int DETECT_THREAD_DISK_WRITE = 1 << 0;
233 /** @hide */
234 private static final int DETECT_THREAD_DISK_READ = 1 << 1;
235 /** @hide */
236 private static final int DETECT_THREAD_NETWORK = 1 << 2;
237 /** @hide */
238 private static final int DETECT_THREAD_CUSTOM = 1 << 3;
239 /** @hide */
240 private static final int DETECT_THREAD_RESOURCE_MISMATCH = 1 << 4;
241 /** @hide */
242 private static final int DETECT_THREAD_UNBUFFERED_IO = 1 << 5;
243 /** @hide */
244 private static final int DETECT_THREAD_EXPLICIT_GC = 1 << 6;
245
246 /** @hide */
247 private static final int DETECT_THREAD_ALL = 0x0000ffff;
248
249 /** @hide */
250 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
251 DETECT_VM_CURSOR_LEAKS,
252 DETECT_VM_CLOSABLE_LEAKS,
253 DETECT_VM_ACTIVITY_LEAKS,
254 DETECT_VM_INSTANCE_LEAKS,
255 DETECT_VM_REGISTRATION_LEAKS,
256 DETECT_VM_FILE_URI_EXPOSURE,
257 DETECT_VM_CLEARTEXT_NETWORK,
258 DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION,
259 DETECT_VM_UNTAGGED_SOCKET,
260 DETECT_VM_NON_SDK_API_USAGE,
261 DETECT_VM_IMPLICIT_DIRECT_BOOT,
262 DETECT_VM_INCORRECT_CONTEXT_USE,
263 DETECT_VM_UNSAFE_INTENT_LAUNCH,
264 PENALTY_GATHER,
265 PENALTY_LOG,
266 PENALTY_DIALOG,
267 PENALTY_DEATH,
268 PENALTY_FLASH,
269 PENALTY_DROPBOX,
270 PENALTY_DEATH_ON_NETWORK,
271 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
272 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
273 })
274 @Retention(RetentionPolicy.SOURCE)
275 public @interface VmPolicyMask {}
276
277 // VM policy: bits 0-15
278
279 /** @hide */
280 private static final int DETECT_VM_CURSOR_LEAKS = 1 << 0;
281 /** @hide */
282 private static final int DETECT_VM_CLOSABLE_LEAKS = 1 << 1;
283 /** @hide */
284 private static final int DETECT_VM_ACTIVITY_LEAKS = 1 << 2;
285 /** @hide */
286 private static final int DETECT_VM_INSTANCE_LEAKS = 1 << 3;
287 /** @hide */
288 private static final int DETECT_VM_REGISTRATION_LEAKS = 1 << 4;
289 /** @hide */
290 private static final int DETECT_VM_FILE_URI_EXPOSURE = 1 << 5;
291 /** @hide */
292 private static final int DETECT_VM_CLEARTEXT_NETWORK = 1 << 6;
293 /** @hide */
294 private static final int DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION = 1 << 7;
295 /** @hide */
296 private static final int DETECT_VM_UNTAGGED_SOCKET = 1 << 8;
297 /** @hide */
298 private static final int DETECT_VM_NON_SDK_API_USAGE = 1 << 9;
299 /** @hide */
300 private static final int DETECT_VM_IMPLICIT_DIRECT_BOOT = 1 << 10;
301 /** @hide */
302 private static final int DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED = 1 << 11;
303 /** @hide */
304 private static final int DETECT_VM_INCORRECT_CONTEXT_USE = 1 << 12;
305 /** @hide */
306 private static final int DETECT_VM_UNSAFE_INTENT_LAUNCH = 1 << 13;
307
308 /** @hide */
309 private static final int DETECT_VM_ALL = 0x0000ffff;
310
311 // Penalty policy: bits 16-31
312
313 /**
314 * Non-public penalty mode which overrides all the other penalty bits and signals that we're in
315 * a Binder call and we should ignore the other penalty bits and instead serialize back all our
316 * offending stack traces to the caller to ultimately handle in the originating process.
317 *
318 * <p>This must be kept in sync with the constant in libs/binder/Parcel.cpp
319 *
320 * @hide
321 */
322 public static final int PENALTY_GATHER = 1 << 31;
323
324 /** {@hide} */
325 public static final int PENALTY_LOG = 1 << 30;
326 /** {@hide} */
327 public static final int PENALTY_DIALOG = 1 << 29;
328 /** {@hide} */
329 public static final int PENALTY_DEATH = 1 << 28;
330 /** {@hide} */
331 public static final int PENALTY_FLASH = 1 << 27;
332 /** {@hide} */
333 public static final int PENALTY_DROPBOX = 1 << 26;
334 /** {@hide} */
335 public static final int PENALTY_DEATH_ON_NETWORK = 1 << 25;
336 /** {@hide} */
337 public static final int PENALTY_DEATH_ON_CLEARTEXT_NETWORK = 1 << 24;
338 /** {@hide} */
339 public static final int PENALTY_DEATH_ON_FILE_URI_EXPOSURE = 1 << 23;
340
341 /** @hide */
342 public static final int PENALTY_ALL = 0xffff0000;
343
344 /** {@hide} */
345 public static final int NETWORK_POLICY_ACCEPT = 0;
346 /** {@hide} */
347 public static final int NETWORK_POLICY_LOG = 1;
348 /** {@hide} */
349 public static final int NETWORK_POLICY_REJECT = 2;
350
351 /**
352 * Detect explicit calls to {@link Runtime#gc()}.
353 */
354 @ChangeId
355 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
356 static final long DETECT_EXPLICIT_GC = 3400644L;
357
358 // TODO: wrap in some ImmutableHashMap thing.
359 // Note: must be before static initialization of sVmPolicy.
360 private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP =
361 new HashMap<Class, Integer>();
362
363 /** The current VmPolicy in effect. */
364 private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
365
366 /** {@hide} */
367 @TestApi
368 public interface ViolationLogger {
369
370 /** Called when penaltyLog is enabled and a violation needs logging. */
371 void log(ViolationInfo info);
372 }
373
374 private static final ViolationLogger LOGCAT_LOGGER =
375 info -> {
376 String msg;
377 if (info.durationMillis != -1) {
378 msg = "StrictMode policy violation; ~duration=" + info.durationMillis + " ms:";
379 } else {
380 msg = "StrictMode policy violation:";
381 }
382 Log.d(TAG, msg + " " + info.getStackTrace());
383 };
384
385 private static volatile ViolationLogger sLogger = LOGCAT_LOGGER;
386
387 private static final ThreadLocal<OnThreadViolationListener> sThreadViolationListener =
388 new ThreadLocal<>();
389 private static final ThreadLocal<Executor> sThreadViolationExecutor = new ThreadLocal<>();
390
391 /**
392 * When #{@link ThreadPolicy.Builder#penaltyListener} is enabled, the listener is called on the
393 * provided executor when a Thread violation occurs.
394 */
395 public interface OnThreadViolationListener {
396 /** Called on a thread policy violation. */
397 void onThreadViolation(Violation v);
398 }
399
400 /**
401 * When #{@link VmPolicy.Builder#penaltyListener} is enabled, the listener is called on the
402 * provided executor when a VM violation occurs.
403 */
404 public interface OnVmViolationListener {
405 /** Called on a VM policy violation. */
406 void onVmViolation(Violation v);
407 }
408
409 /** {@hide} */
410 @TestApi
411 public static void setViolationLogger(ViolationLogger listener) {
412 if (listener == null) {
413 listener = LOGCAT_LOGGER;
414 }
415 sLogger = listener;
416 }
417
418 /**
419 * The number of threads trying to do an async dropbox write. Just to limit ourselves out of
420 * paranoia.
421 */
422 private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
423
424 /**
425 * Callback supplied to dalvik / libcore to get informed of usages of java API that are not
426 * a part of the public SDK.
427 */
428 private static final Consumer<String> sNonSdkApiUsageConsumer =
429 message -> onVmPolicyViolation(new NonSdkApiUsedViolation(message));
430
431 private StrictMode() {}
432
433 /**
434 * {@link StrictMode} policy applied to a certain thread.
435 *
436 * <p>The policy is enabled by {@link #setThreadPolicy}. The current policy can be retrieved
437 * with {@link #getThreadPolicy}.
438 *
439 * <p>Note that multiple penalties may be provided and they're run in order from least to most
440 * severe (logging before process death, for example). There's currently no mechanism to choose
441 * different penalties for different detected actions.
442 */
443 public static final class ThreadPolicy {
444 /** The default, lax policy which doesn't catch anything. */
445 public static final ThreadPolicy LAX = new ThreadPolicy(0, null, null);
446
447 @UnsupportedAppUsage
448 final @ThreadPolicyMask int mask;
449 final OnThreadViolationListener mListener;
450 final Executor mCallbackExecutor;
451
452 private ThreadPolicy(@ThreadPolicyMask int mask, OnThreadViolationListener listener,
453 Executor executor) {
454 this.mask = mask;
455 mListener = listener;
456 mCallbackExecutor = executor;
457 }
458
459 @Override
460 public String toString() {
461 return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
462 }
463
464 /**
465 * Creates {@link ThreadPolicy} instances. Methods whose names start with {@code detect}
466 * specify what problems we should look for. Methods whose names start with {@code penalty}
467 * specify what we should do when we detect a problem.
468 *
469 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
470 * order is insignificant: all penalties apply to all detected problems.
471 *
472 * <p>For example, detect everything and log anything that's found:
473 *
474 * <pre>
475 * StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
476 * .detectAll()
477 * .penaltyLog()
478 * .build();
479 * StrictMode.setThreadPolicy(policy);
480 * </pre>
481 */
482 public static final class Builder {
483 private @ThreadPolicyMask int mMask = 0;
484 private OnThreadViolationListener mListener;
485 private Executor mExecutor;
486
487 /**
488 * Create a Builder that detects nothing and has no violations. (but note that {@link
489 * #build} will default to enabling {@link #penaltyLog} if no other penalties are
490 * specified)
491 */
492 public Builder() {
493 mMask = 0;
494 }
495
496 /** Initialize a Builder from an existing ThreadPolicy. */
497 public Builder(ThreadPolicy policy) {
498 mMask = policy.mask;
499 mListener = policy.mListener;
500 mExecutor = policy.mCallbackExecutor;
501 }
502
503 /**
504 * Detect everything that's potentially suspect.
505 *
506 * <p>As of the Gingerbread release this includes network and disk operations but will
507 * likely expand in future releases.
508 */
509 @SuppressWarnings("AndroidFrameworkCompatChange")
510 public @NonNull Builder detectAll() {
511 detectDiskReads();
512 detectDiskWrites();
513 detectNetwork();
514
515 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
516 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
517 detectCustomSlowCalls();
518 }
519 if (targetSdk >= Build.VERSION_CODES.M) {
520 detectResourceMismatches();
521 }
522 if (targetSdk >= Build.VERSION_CODES.O) {
523 detectUnbufferedIo();
524 }
525 if (CompatChanges.isChangeEnabled(DETECT_EXPLICIT_GC)) {
526 detectExplicitGc();
527 }
528 return this;
529 }
530
531 /** Disable the detection of everything. */
532 public @NonNull Builder permitAll() {
533 return disable(DETECT_THREAD_ALL);
534 }
535
536 /** Enable detection of network operations. */
537 public @NonNull Builder detectNetwork() {
538 return enable(DETECT_THREAD_NETWORK);
539 }
540
541 /** Disable detection of network operations. */
542 public @NonNull Builder permitNetwork() {
543 return disable(DETECT_THREAD_NETWORK);
544 }
545
546 /** Enable detection of disk reads. */
547 public @NonNull Builder detectDiskReads() {
548 return enable(DETECT_THREAD_DISK_READ);
549 }
550
551 /** Disable detection of disk reads. */
552 public @NonNull Builder permitDiskReads() {
553 return disable(DETECT_THREAD_DISK_READ);
554 }
555
556 /** Enable detection of slow calls. */
557 public @NonNull Builder detectCustomSlowCalls() {
558 return enable(DETECT_THREAD_CUSTOM);
559 }
560
561 /** Disable detection of slow calls. */
562 public @NonNull Builder permitCustomSlowCalls() {
563 return disable(DETECT_THREAD_CUSTOM);
564 }
565
566 /** Disable detection of mismatches between defined resource types and getter calls. */
567 public @NonNull Builder permitResourceMismatches() {
568 return disable(DETECT_THREAD_RESOURCE_MISMATCH);
569 }
570
571 /** Detect unbuffered input/output operations. */
572 public @NonNull Builder detectUnbufferedIo() {
573 return enable(DETECT_THREAD_UNBUFFERED_IO);
574 }
575
576 /** Disable detection of unbuffered input/output operations. */
577 public @NonNull Builder permitUnbufferedIo() {
578 return disable(DETECT_THREAD_UNBUFFERED_IO);
579 }
580
581 /**
582 * Enables detection of mismatches between defined resource types and getter calls.
583 *
584 * <p>This helps detect accidental type mismatches and potentially expensive type
585 * conversions when obtaining typed resources.
586 *
587 * <p>For example, a strict mode violation would be thrown when calling {@link
588 * android.content.res.TypedArray#getInt(int, int)} on an index that contains a
589 * String-type resource. If the string value can be parsed as an integer, this method
590 * call will return a value without crashing; however, the developer should format the
591 * resource as an integer to avoid unnecessary type conversion.
592 */
593 public @NonNull Builder detectResourceMismatches() {
594 return enable(DETECT_THREAD_RESOURCE_MISMATCH);
595 }
596
597 /** Enable detection of disk writes. */
598 public @NonNull Builder detectDiskWrites() {
599 return enable(DETECT_THREAD_DISK_WRITE);
600 }
601
602 /** Disable detection of disk writes. */
603 public @NonNull Builder permitDiskWrites() {
604 return disable(DETECT_THREAD_DISK_WRITE);
605 }
606
607 /**
608 * Detect calls to {@link Runtime#gc()}.
609 */
610 public @NonNull Builder detectExplicitGc() {
611 return enable(DETECT_THREAD_EXPLICIT_GC);
612 }
613
614 /**
615 * Disable detection of calls to {@link Runtime#gc()}.
616 */
617 public @NonNull Builder permitExplicitGc() {
618 return disable(DETECT_THREAD_EXPLICIT_GC);
619 }
620
621 /**
622 * Show an annoying dialog to the developer on detected violations, rate-limited to be
623 * only a little annoying.
624 */
625 public @NonNull Builder penaltyDialog() {
626 return enable(PENALTY_DIALOG);
627 }
628
629 /**
630 * Crash the whole process on violation. This penalty runs at the end of all enabled
631 * penalties so you'll still get see logging or other violations before the process
632 * dies.
633 *
634 * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies to disk reads, disk writes,
635 * and network usage if their corresponding detect flags are set.
636 */
637 public @NonNull Builder penaltyDeath() {
638 return enable(PENALTY_DEATH);
639 }
640
641 /**
642 * Crash the whole process on any network usage. Unlike {@link #penaltyDeath}, this
643 * penalty runs <em>before</em> anything else. You must still have called {@link
644 * #detectNetwork} to enable this.
645 *
646 * <p>In the Honeycomb or later SDKs, this is on by default.
647 */
648 public @NonNull Builder penaltyDeathOnNetwork() {
649 return enable(PENALTY_DEATH_ON_NETWORK);
650 }
651
652 /** Flash the screen during a violation. */
653 public @NonNull Builder penaltyFlashScreen() {
654 return enable(PENALTY_FLASH);
655 }
656
657 /** Log detected violations to the system log. */
658 public @NonNull Builder penaltyLog() {
659 return enable(PENALTY_LOG);
660 }
661
662 /**
663 * Enable detected violations log a stacktrace and timing data to the {@link
664 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
665 * integrators doing beta user field data collection.
666 */
667 public @NonNull Builder penaltyDropBox() {
668 return enable(PENALTY_DROPBOX);
669 }
670
671 /**
672 * Call #{@link OnThreadViolationListener#onThreadViolation(Violation)} on specified
673 * executor every violation.
674 */
675 public @NonNull Builder penaltyListener(
676 @NonNull Executor executor, @NonNull OnThreadViolationListener listener) {
677 if (executor == null) {
678 throw new NullPointerException("executor must not be null");
679 }
680 mListener = listener;
681 mExecutor = executor;
682 return this;
683 }
684
685 /** @removed */
686 public @NonNull Builder penaltyListener(
687 @NonNull OnThreadViolationListener listener, @NonNull Executor executor) {
688 return penaltyListener(executor, listener);
689 }
690
691 private Builder enable(@ThreadPolicyMask int mask) {
692 mMask |= mask;
693 return this;
694 }
695
696 private Builder disable(@ThreadPolicyMask int mask) {
697 mMask &= ~mask;
698 return this;
699 }
700
701 /**
702 * Construct the ThreadPolicy instance.
703 *
704 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
705 * #penaltyLog} is implicitly set.
706 */
707 public ThreadPolicy build() {
708 // If there are detection bits set but no violation bits
709 // set, enable simple logging.
710 if (mListener == null
711 && mMask != 0
712 && (mMask
713 & (PENALTY_DEATH
714 | PENALTY_LOG
715 | PENALTY_DROPBOX
716 | PENALTY_DIALOG))
717 == 0) {
718 penaltyLog();
719 }
720 return new ThreadPolicy(mMask, mListener, mExecutor);
721 }
722 }
723 }
724
725 /**
726 * {@link StrictMode} policy applied to all threads in the virtual machine's process.
727 *
728 * <p>The policy is enabled by {@link #setVmPolicy}.
729 */
730 public static final class VmPolicy {
731 /** The default, lax policy which doesn't catch anything. */
732 public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP, null, null);
733
734 @UnsupportedAppUsage
735 final @VmPolicyMask int mask;
736 final OnVmViolationListener mListener;
737 final Executor mCallbackExecutor;
738
739 // Map from class to max number of allowed instances in memory.
740 final HashMap<Class, Integer> classInstanceLimit;
741
742 private VmPolicy(
743 @VmPolicyMask int mask,
744 HashMap<Class, Integer> classInstanceLimit,
745 OnVmViolationListener listener,
746 Executor executor) {
747 if (classInstanceLimit == null) {
748 throw new NullPointerException("classInstanceLimit == null");
749 }
750 this.mask = mask;
751 this.classInstanceLimit = classInstanceLimit;
752 mListener = listener;
753 mCallbackExecutor = executor;
754 }
755
756 @Override
757 public String toString() {
758 return "[StrictMode.VmPolicy; mask=" + mask + "]";
759 }
760
761 /**
762 * Creates {@link VmPolicy} instances. Methods whose names start with {@code detect} specify
763 * what problems we should look for. Methods whose names start with {@code penalty} specify
764 * what we should do when we detect a problem.
765 *
766 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
767 * order is insignificant: all penalties apply to all detected problems.
768 *
769 * <p>For example, detect everything and log anything that's found:
770 *
771 * <pre>
772 * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
773 * .detectAll()
774 * .penaltyLog()
775 * .build();
776 * StrictMode.setVmPolicy(policy);
777 * </pre>
778 */
779 public static final class Builder {
780 @UnsupportedAppUsage
781 private @VmPolicyMask int mMask;
782 private OnVmViolationListener mListener;
783 private Executor mExecutor;
784
785 private HashMap<Class, Integer> mClassInstanceLimit; // null until needed
786 private boolean mClassInstanceLimitNeedCow = false; // need copy-on-write
787
788 public Builder() {
789 mMask = 0;
790 }
791
792 /** Build upon an existing VmPolicy. */
793 public Builder(VmPolicy base) {
794 mMask = base.mask;
795 mClassInstanceLimitNeedCow = true;
796 mClassInstanceLimit = base.classInstanceLimit;
797 mListener = base.mListener;
798 mExecutor = base.mCallbackExecutor;
799 }
800
801 /**
802 * Set an upper bound on how many instances of a class can be in memory at once. Helps
803 * to prevent object leaks.
804 */
805 public @NonNull Builder setClassInstanceLimit(Class klass, int instanceLimit) {
806 if (klass == null) {
807 throw new NullPointerException("klass == null");
808 }
809 if (mClassInstanceLimitNeedCow) {
810 if (mClassInstanceLimit.containsKey(klass)
811 && mClassInstanceLimit.get(klass) == instanceLimit) {
812 // no-op; don't break COW
813 return this;
814 }
815 mClassInstanceLimitNeedCow = false;
816 mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
817 } else if (mClassInstanceLimit == null) {
818 mClassInstanceLimit = new HashMap<Class, Integer>();
819 }
820 mMask |= DETECT_VM_INSTANCE_LEAKS;
821 mClassInstanceLimit.put(klass, instanceLimit);
822 return this;
823 }
824
825 /** Detect leaks of {@link android.app.Activity} subclasses. */
826 public @NonNull Builder detectActivityLeaks() {
827 return enable(DETECT_VM_ACTIVITY_LEAKS);
828 }
829
830 /** @hide */
831 public @NonNull Builder permitActivityLeaks() {
832 synchronized (StrictMode.class) {
833 sExpectedActivityInstanceCount.clear();
834 }
835 return disable(DETECT_VM_ACTIVITY_LEAKS);
836 }
837
838 /**
839 * Detect reflective usage of APIs that are not part of the public Android SDK.
840 *
841 * <p>Note that any non-SDK APIs that this processes accesses before this detection is
842 * enabled may not be detected. To ensure that all such API accesses are detected,
843 * you should apply this policy as early as possible after process creation.
844 */
845 public @NonNull Builder detectNonSdkApiUsage() {
846 return enable(DETECT_VM_NON_SDK_API_USAGE);
847 }
848
849 /**
850 * Permit reflective usage of APIs that are not part of the public Android SDK. Note
851 * that this <b>only</b> affects {@code StrictMode}, the underlying runtime may
852 * continue to restrict or warn on access to methods that are not part of the
853 * public SDK.
854 */
855 public @NonNull Builder permitNonSdkApiUsage() {
856 return disable(DETECT_VM_NON_SDK_API_USAGE);
857 }
858
859 /**
860 * Detect everything that's potentially suspect.
861 *
862 * <p>In the Honeycomb release this includes leaks of SQLite cursors, Activities, and
863 * other closable objects but will likely expand in future releases.
864 */
865 @SuppressWarnings("AndroidFrameworkCompatChange")
866 public @NonNull Builder detectAll() {
867 detectLeakedSqlLiteObjects();
868
869 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
870 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
871 detectActivityLeaks();
872 detectLeakedClosableObjects();
873 }
874 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN) {
875 detectLeakedRegistrationObjects();
876 }
877 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
878 detectFileUriExposure();
879 }
880 if (targetSdk >= Build.VERSION_CODES.M) {
881 // TODO: always add DETECT_VM_CLEARTEXT_NETWORK once we have
882 // facility for apps to mark sockets that should be ignored
883 if (SystemProperties.getBoolean(CLEARTEXT_PROPERTY, false)) {
884 detectCleartextNetwork();
885 }
886 }
887 if (targetSdk >= Build.VERSION_CODES.O) {
888 detectContentUriWithoutPermission();
889 detectUntaggedSockets();
890 }
891 if (targetSdk >= Build.VERSION_CODES.Q) {
892 detectCredentialProtectedWhileLocked();
893 }
894 if (targetSdk >= Build.VERSION_CODES.R) {
895 detectIncorrectContextUse();
896 }
897 if (targetSdk >= Build.VERSION_CODES.S) {
898 detectUnsafeIntentLaunch();
899 }
900
901 // TODO: Decide whether to detect non SDK API usage beyond a certain API level.
902 // TODO: enable detectImplicitDirectBoot() once system is less noisy
903
904 return this;
905 }
906
907 /**
908 * Detect when an {@link android.database.sqlite.SQLiteCursor} or other SQLite object is
909 * finalized without having been closed.
910 *
911 * <p>You always want to explicitly close your SQLite cursors to avoid unnecessary
912 * database contention and temporary memory leaks.
913 */
914 public @NonNull Builder detectLeakedSqlLiteObjects() {
915 return enable(DETECT_VM_CURSOR_LEAKS);
916 }
917
918 /**
919 * Detect when an {@link java.io.Closeable} or other object with an explicit termination
920 * method is finalized without having been closed.
921 *
922 * <p>You always want to explicitly close such objects to avoid unnecessary resources
923 * leaks.
924 */
925 public @NonNull Builder detectLeakedClosableObjects() {
926 return enable(DETECT_VM_CLOSABLE_LEAKS);
927 }
928
929 /**
930 * Detect when a {@link BroadcastReceiver} or {@link ServiceConnection} is leaked during
931 * {@link Context} teardown.
932 */
933 public @NonNull Builder detectLeakedRegistrationObjects() {
934 return enable(DETECT_VM_REGISTRATION_LEAKS);
935 }
936
937 /**
938 * Detect when the calling application exposes a {@code file://} {@link android.net.Uri}
939 * to another app.
940 *
941 * <p>This exposure is discouraged since the receiving app may not have access to the
942 * shared path. For example, the receiving app may not have requested the {@link
943 * android.Manifest.permission#READ_EXTERNAL_STORAGE} runtime permission, or the
944 * platform may be sharing the {@link android.net.Uri} across user profile boundaries.
945 *
946 * <p>Instead, apps should use {@code content://} Uris so the platform can extend
947 * temporary permission for the receiving app to access the resource.
948 *
949 * @see androidx.core.content.FileProvider
950 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
951 */
952 public @NonNull Builder detectFileUriExposure() {
953 return enable(DETECT_VM_FILE_URI_EXPOSURE);
954 }
955
956 /**
957 * Detect any network traffic from the calling app which is not wrapped in SSL/TLS. This
958 * can help you detect places that your app is inadvertently sending cleartext data
959 * across the network.
960 *
961 * <p>Using {@link #penaltyDeath()} or {@link #penaltyDeathOnCleartextNetwork()} will
962 * block further traffic on that socket to prevent accidental data leakage, in addition
963 * to crashing your process.
964 *
965 * <p>Using {@link #penaltyDropBox()} will log the raw contents of the packet that
966 * triggered the violation.
967 *
968 * <p>This inspects both IPv4/IPv6 and TCP/UDP network traffic, but it may be subject to
969 * false positives, such as when STARTTLS protocols or HTTP proxies are used.
970 */
971 public @NonNull Builder detectCleartextNetwork() {
972 return enable(DETECT_VM_CLEARTEXT_NETWORK);
973 }
974
975 /**
976 * Detect when the calling application sends a {@code content://} {@link
977 * android.net.Uri} to another app without setting {@link
978 * Intent#FLAG_GRANT_READ_URI_PERMISSION} or {@link
979 * Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
980 *
981 * <p>Forgetting to include one or more of these flags when sending an intent is
982 * typically an app bug.
983 *
984 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
985 * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
986 */
987 public @NonNull Builder detectContentUriWithoutPermission() {
988 return enable(DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION);
989 }
990
991 /**
992 * Detect any sockets in the calling app which have not been tagged using {@link
993 * TrafficStats}. Tagging sockets can help you investigate network usage inside your
994 * app, such as a narrowing down heavy usage to a specific library or component.
995 *
996 * <p>This currently does not detect sockets created in native code.
997 *
998 * @see TrafficStats#setThreadStatsTag(int)
999 * @see TrafficStats#tagSocket(java.net.Socket)
1000 * @see TrafficStats#tagDatagramSocket(java.net.DatagramSocket)
1001 */
1002 public @NonNull Builder detectUntaggedSockets() {
1003 return enable(DETECT_VM_UNTAGGED_SOCKET);
1004 }
1005
1006 /** @hide */
1007 public @NonNull Builder permitUntaggedSockets() {
1008 return disable(DETECT_VM_UNTAGGED_SOCKET);
1009 }
1010
1011 /**
1012 * Detect any implicit reliance on Direct Boot automatic filtering
1013 * of {@link PackageManager} values. Violations are only triggered
1014 * when implicit calls are made while the user is locked.
1015 * <p>
1016 * Apps becoming Direct Boot aware need to carefully inspect each
1017 * query site and explicitly decide which combination of flags they
1018 * want to use:
1019 * <ul>
1020 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AWARE}
1021 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_UNAWARE}
1022 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AUTO}
1023 * </ul>
1024 */
1025 public @NonNull Builder detectImplicitDirectBoot() {
1026 return enable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
1027 }
1028
1029 /** @hide */
1030 public @NonNull Builder permitImplicitDirectBoot() {
1031 return disable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
1032 }
1033
1034 /**
1035 * Detect access to filesystem paths stored in credential protected
1036 * storage areas while the user is locked.
1037 * <p>
1038 * When a user is locked, credential protected storage is
1039 * unavailable, and files stored in these locations appear to not
1040 * exist, which can result in subtle app bugs if they assume default
1041 * behaviors or empty states. Instead, apps should store data needed
1042 * while a user is locked under device protected storage areas.
1043 *
1044 * @see Context#createDeviceProtectedStorageContext()
1045 */
1046 public @NonNull Builder detectCredentialProtectedWhileLocked() {
1047 return enable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1048 }
1049
1050 /** @hide */
1051 public @NonNull Builder permitCredentialProtectedWhileLocked() {
1052 return disable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1053 }
1054
1055 /**
1056 * Detect attempts to invoke a method on a {@link Context} that is not suited for such
1057 * operation.
1058 * <p>An example of this is trying to obtain an instance of UI service (e.g.
1059 * {@link android.view.WindowManager}) from a non-visual {@link Context}. This is not
1060 * allowed, since a non-visual {@link Context} is not adjusted to any visual area, and
1061 * therefore can report incorrect metrics or resources.
1062 * @see Context#getDisplay()
1063 * @see Context#getSystemService(String)
1064 */
1065 public @NonNull Builder detectIncorrectContextUse() {
1066 return enable(DETECT_VM_INCORRECT_CONTEXT_USE);
1067 }
1068
1069 /**
1070 * Disable detection of incorrect context use.
1071 *
1072 * @see #detectIncorrectContextUse()
1073 *
1074 * @hide
1075 */
1076 @TestApi
1077 public @NonNull Builder permitIncorrectContextUse() {
1078 return disable(DETECT_VM_INCORRECT_CONTEXT_USE);
1079 }
1080
1081 /**
1082 * Detect when your app launches an {@link Intent} which originated
1083 * from outside your app.
1084 * <p>
1085 * Violations may indicate security vulnerabilities in the design of
1086 * your app, where a malicious app could trick you into granting
1087 * {@link Uri} permissions or launching unexported components. Here
1088 * are some typical design patterns that can be used to safely
1089 * resolve these violations:
1090 * <ul>
1091 * <li>The ideal approach is to migrate to using a
1092 * {@link android.app.PendingIntent}, which ensures that your launch is
1093 * performed using the identity of the original creator, completely
1094 * avoiding the security issues described above.
1095 * <li>If using a {@link android.app.PendingIntent} isn't feasible, an
1096 * alternative approach is to create a brand new {@link Intent} and
1097 * carefully copy only specific values from the original
1098 * {@link Intent} after careful validation.
1099 * </ul>
1100 * <p>
1101 * Note that this <em>may</em> detect false-positives if your app
1102 * sends itself an {@link Intent} which is first routed through the
1103 * OS, such as using {@link Intent#createChooser}. In these cases,
1104 * careful inspection is required to determine if the return point
1105 * into your app is appropriately protected with a signature
1106 * permission or marked as unexported. If the return point is not
1107 * protected, your app is likely vulnerable to malicious apps.
1108 *
1109 * @see Context#startActivity(Intent)
1110 * @see Context#startService(Intent)
1111 * @see Context#bindService(Intent, ServiceConnection, int)
1112 * @see Context#sendBroadcast(Intent)
1113 * @see android.app.Activity#setResult(int, Intent)
1114 */
1115 public @NonNull Builder detectUnsafeIntentLaunch() {
1116 return enable(DETECT_VM_UNSAFE_INTENT_LAUNCH);
1117 }
1118
1119 /**
1120 * Permit your app to launch any {@link Intent} which originated
1121 * from outside your app.
1122 * <p>
1123 * Disabling this check is <em>strongly discouraged</em>, as
1124 * violations may indicate security vulnerabilities in the design of
1125 * your app, where a malicious app could trick you into granting
1126 * {@link Uri} permissions or launching unexported components.
1127 *
1128 * @see #detectUnsafeIntentLaunch()
1129 */
1130 public @NonNull Builder permitUnsafeIntentLaunch() {
1131 return disable(DETECT_VM_UNSAFE_INTENT_LAUNCH);
1132 }
1133
1134 /**
1135 * Crashes the whole process on violation. This penalty runs at the end of all enabled
1136 * penalties so you'll still get your logging or other violations before the process
1137 * dies.
1138 */
1139 public @NonNull Builder penaltyDeath() {
1140 return enable(PENALTY_DEATH);
1141 }
1142
1143 /**
1144 * Crashes the whole process when cleartext network traffic is detected.
1145 *
1146 * @see #detectCleartextNetwork()
1147 */
1148 public @NonNull Builder penaltyDeathOnCleartextNetwork() {
1149 return enable(PENALTY_DEATH_ON_CLEARTEXT_NETWORK);
1150 }
1151
1152 /**
1153 * Crashes the whole process when a {@code file://} {@link android.net.Uri} is exposed
1154 * beyond this app.
1155 *
1156 * @see #detectFileUriExposure()
1157 */
1158 public @NonNull Builder penaltyDeathOnFileUriExposure() {
1159 return enable(PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
1160 }
1161
1162 /** Log detected violations to the system log. */
1163 public @NonNull Builder penaltyLog() {
1164 return enable(PENALTY_LOG);
1165 }
1166
1167 /**
1168 * Enable detected violations log a stacktrace and timing data to the {@link
1169 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
1170 * integrators doing beta user field data collection.
1171 */
1172 public @NonNull Builder penaltyDropBox() {
1173 return enable(PENALTY_DROPBOX);
1174 }
1175
1176 /**
1177 * Call #{@link OnVmViolationListener#onVmViolation(Violation)} on every violation.
1178 */
1179 public @NonNull Builder penaltyListener(
1180 @NonNull Executor executor, @NonNull OnVmViolationListener listener) {
1181 if (executor == null) {
1182 throw new NullPointerException("executor must not be null");
1183 }
1184 mListener = listener;
1185 mExecutor = executor;
1186 return this;
1187 }
1188
1189 /** @removed */
1190 public @NonNull Builder penaltyListener(
1191 @NonNull OnVmViolationListener listener, @NonNull Executor executor) {
1192 return penaltyListener(executor, listener);
1193 }
1194
1195 private Builder enable(@VmPolicyMask int mask) {
1196 mMask |= mask;
1197 return this;
1198 }
1199
1200 Builder disable(@VmPolicyMask int mask) {
1201 mMask &= ~mask;
1202 return this;
1203 }
1204
1205 /**
1206 * Construct the VmPolicy instance.
1207 *
1208 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
1209 * #penaltyLog} is implicitly set.
1210 */
1211 public VmPolicy build() {
1212 // If there are detection bits set but no violation bits
1213 // set, enable simple logging.
1214 if (mListener == null
1215 && mMask != 0
1216 && (mMask
1217 & (PENALTY_DEATH
1218 | PENALTY_LOG
1219 | PENALTY_DROPBOX
1220 | PENALTY_DIALOG))
1221 == 0) {
1222 penaltyLog();
1223 }
1224 return new VmPolicy(
1225 mMask,
1226 mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP,
1227 mListener,
1228 mExecutor);
1229 }
1230 }
1231 }
1232
1233 /**
1234 * Log of strict mode violation stack traces that have occurred during a Binder call, to be
1235 * serialized back later to the caller via Parcel.writeNoException() (amusingly) where the
1236 * caller can choose how to react.
1237 */
1238 private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
1239 new ThreadLocal<ArrayList<ViolationInfo>>() {
1240 @Override
1241 protected ArrayList<ViolationInfo> initialValue() {
1242 // Starts null to avoid unnecessary allocations when
1243 // checking whether there are any violations or not in
1244 // hasGatheredViolations() below.
1245 return null;
1246 }
1247 };
1248
1249 /**
1250 * Sets the policy for what actions on the current thread should be detected, as well as the
1251 * penalty if such actions occur.
1252 *
1253 * <p>Internally this sets a thread-local variable which is propagated across cross-process IPC
1254 * calls, meaning you can catch violations when a system service or another process accesses the
1255 * disk or network on your behalf.
1256 *
1257 * @param policy the policy to put into place
1258 */
1259 public static void setThreadPolicy(final ThreadPolicy policy) {
1260 setThreadPolicyMask(policy.mask);
1261 sThreadViolationListener.set(policy.mListener);
1262 sThreadViolationExecutor.set(policy.mCallbackExecutor);
1263 }
1264
1265 /** @hide */
1266 public static void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
1267 // In addition to the Java-level thread-local in Dalvik's
1268 // BlockGuard, we also need to keep a native thread-local in
1269 // Binder in order to propagate the value across Binder calls,
1270 // even across native-only processes. The two are kept in
1271 // sync via the callback to onStrictModePolicyChange, below.
1272 setBlockGuardPolicy(threadPolicyMask);
1273
1274 // And set the Android native version...
1275 Binder.setThreadStrictModePolicy(threadPolicyMask);
1276 }
1277
1278 // Sets the policy in Dalvik/libcore (BlockGuard)
1279 private static void setBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1280 if (threadPolicyMask == 0) {
1281 BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
1282 return;
1283 }
1284 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1285 final AndroidBlockGuardPolicy androidPolicy;
1286 if (policy instanceof AndroidBlockGuardPolicy) {
1287 androidPolicy = (AndroidBlockGuardPolicy) policy;
1288 } else {
1289 androidPolicy = THREAD_ANDROID_POLICY.get();
1290 BlockGuard.setThreadPolicy(androidPolicy);
1291 }
1292 androidPolicy.setThreadPolicyMask(threadPolicyMask);
1293 }
1294
1295 private static void setBlockGuardVmPolicy(@VmPolicyMask int vmPolicyMask) {
1296 // We only need to install BlockGuard for a small subset of VM policies
1297 vmPolicyMask &= DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED;
1298 if (vmPolicyMask != 0) {
1299 BlockGuard.setVmPolicy(VM_ANDROID_POLICY);
1300 } else {
1301 BlockGuard.setVmPolicy(BlockGuard.LAX_VM_POLICY);
1302 }
1303 }
1304
1305 // Sets up CloseGuard in Dalvik/libcore
1306 private static void setCloseGuardEnabled(boolean enabled) {
1307 if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
1308 CloseGuard.setReporter(new AndroidCloseGuardReporter());
1309 }
1310 CloseGuard.setEnabled(enabled);
1311 }
1312
1313 /**
1314 * Returns the bitmask of the current thread's policy.
1315 *
1316 * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
1317 * @hide
1318 */
1319 @UnsupportedAppUsage
1320 public static @ThreadPolicyMask int getThreadPolicyMask() {
1321 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1322 if (policy instanceof AndroidBlockGuardPolicy) {
1323 return ((AndroidBlockGuardPolicy) policy).getThreadPolicyMask();
1324 } else {
1325 return 0;
1326 }
1327 }
1328
1329 /** Returns the current thread's policy. */
1330 public static ThreadPolicy getThreadPolicy() {
1331 // TODO: this was a last minute Gingerbread API change (to
1332 // introduce VmPolicy cleanly) but this isn't particularly
1333 // optimal for users who might call this method often. This
1334 // should be in a thread-local and not allocate on each call.
1335 return new ThreadPolicy(
1336 getThreadPolicyMask(),
1337 sThreadViolationListener.get(),
1338 sThreadViolationExecutor.get());
1339 }
1340
1341 /**
1342 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1343 * #getThreadPolicy}, modifies it to permit both disk reads &amp; writes, and sets the new
1344 * policy with {@link #setThreadPolicy}, returning the old policy so you can restore it at the
1345 * end of a block.
1346 *
1347 * @return the old policy, to be passed to {@link #setThreadPolicy} to restore the policy at the
1348 * end of a block
1349 */
1350 public static ThreadPolicy allowThreadDiskWrites() {
1351 return new ThreadPolicy(
1352 allowThreadDiskWritesMask(),
1353 sThreadViolationListener.get(),
1354 sThreadViolationExecutor.get());
1355 }
1356
1357 /** @hide */
1358 public static @ThreadPolicyMask int allowThreadDiskWritesMask() {
1359 int oldPolicyMask = getThreadPolicyMask();
1360 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_WRITE | DETECT_THREAD_DISK_READ);
1361 if (newPolicyMask != oldPolicyMask) {
1362 setThreadPolicyMask(newPolicyMask);
1363 }
1364 return oldPolicyMask;
1365 }
1366
1367 /**
1368 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1369 * #getThreadPolicy}, modifies it to permit disk reads, and sets the new policy with {@link
1370 * #setThreadPolicy}, returning the old policy so you can restore it at the end of a block.
1371 *
1372 * @return the old policy, to be passed to setThreadPolicy to restore the policy.
1373 */
1374 public static ThreadPolicy allowThreadDiskReads() {
1375 return new ThreadPolicy(
1376 allowThreadDiskReadsMask(),
1377 sThreadViolationListener.get(),
1378 sThreadViolationExecutor.get());
1379 }
1380
1381 /** @hide */
1382 public static @ThreadPolicyMask int allowThreadDiskReadsMask() {
1383 int oldPolicyMask = getThreadPolicyMask();
1384 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_READ);
1385 if (newPolicyMask != oldPolicyMask) {
1386 setThreadPolicyMask(newPolicyMask);
1387 }
1388 return oldPolicyMask;
1389 }
1390
1391 /** @hide */
1392 public static ThreadPolicy allowThreadViolations() {
1393 ThreadPolicy oldPolicy = getThreadPolicy();
1394 setThreadPolicyMask(0);
1395 return oldPolicy;
1396 }
1397
1398 /** @hide */
1399 public static VmPolicy allowVmViolations() {
1400 VmPolicy oldPolicy = getVmPolicy();
1401 sVmPolicy = VmPolicy.LAX;
1402 return oldPolicy;
1403 }
1404
1405 /**
1406 * Determine if the given app is "bundled" as part of the system image. These bundled apps are
1407 * developed in lock-step with the OS, and they aren't updated outside of an OTA, so we want to
1408 * chase any {@link StrictMode} regressions by enabling detection when running on {@link
1409 * Build#IS_USERDEBUG} or {@link Build#IS_ENG} builds.
1410 *
1411 * <p>Unbundled apps included in the system image are expected to detect and triage their own
1412 * {@link StrictMode} issues separate from the OS release process, which is why we don't enable
1413 * them here.
1414 *
1415 * @hide
1416 */
1417 public static boolean isBundledSystemApp(ApplicationInfo ai) {
1418 if (ai == null || ai.packageName == null) {
1419 // Probably system server
1420 return true;
1421 } else if (ai.isSystemApp()) {
1422 // Ignore unbundled apps living in the wrong namespace
1423 if (ai.packageName.equals("com.android.vending")
1424 || ai.packageName.equals("com.android.chrome")) {
1425 return false;
1426 }
1427
1428 // Ignore bundled apps that are way too spammy
1429 // STOPSHIP: burn this list down to zero
1430 if (ai.packageName.equals("com.android.phone")) {
1431 return false;
1432 }
1433
1434 if (ai.packageName.equals("android")
1435 || ai.packageName.startsWith("android.")
1436 || ai.packageName.startsWith("com.android.")) {
1437 return true;
1438 }
1439 }
1440 return false;
1441 }
1442
1443 /**
1444 * Initialize default {@link ThreadPolicy} for the current thread.
1445 *
1446 * @hide
1447 */
1448 public static void initThreadDefaults(ApplicationInfo ai) {
1449 final ThreadPolicy.Builder builder = new ThreadPolicy.Builder();
1450 final int targetSdkVersion =
1451 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
1452
1453 // Starting in HC, we don't allow network usage on the main thread
1454 if (targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
1455 builder.detectNetwork();
1456 builder.penaltyDeathOnNetwork();
1457 }
1458
1459 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1460 // Detect nothing extra
1461 } else if (Build.IS_USERDEBUG) {
1462 // Detect everything in bundled apps
1463 if (isBundledSystemApp(ai)) {
1464 builder.detectAll();
1465 builder.penaltyDropBox();
1466 if (SystemProperties.getBoolean(VISUAL_PROPERTY, false)) {
1467 builder.penaltyFlashScreen();
1468 }
1469 }
1470 } else if (Build.IS_ENG) {
1471 // Detect everything in bundled apps
1472 if (isBundledSystemApp(ai)) {
1473 builder.detectAll();
1474 builder.penaltyDropBox();
1475 builder.penaltyLog();
1476 builder.penaltyFlashScreen();
1477 }
1478 }
1479
1480 setThreadPolicy(builder.build());
1481 }
1482
1483 /**
1484 * Initialize default {@link VmPolicy} for the current VM.
1485 *
1486 * @hide
1487 */
1488 public static void initVmDefaults(ApplicationInfo ai) {
1489 final VmPolicy.Builder builder = new VmPolicy.Builder();
1490 final int targetSdkVersion =
1491 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
1492
1493 // Starting in N, we don't allow file:// Uri exposure
1494 if (targetSdkVersion >= Build.VERSION_CODES.N) {
1495 builder.detectFileUriExposure();
1496 builder.penaltyDeathOnFileUriExposure();
1497 }
1498
1499 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1500 // Detect nothing extra
1501 } else if (Build.IS_USERDEBUG) {
1502 // Detect everything in bundled apps (except activity leaks, which
1503 // are expensive to track)
1504 if (isBundledSystemApp(ai)) {
1505 builder.detectAll();
1506 builder.permitActivityLeaks();
1507 builder.penaltyDropBox();
1508 }
1509 } else if (Build.IS_ENG) {
1510 // Detect everything in bundled apps
1511 if (isBundledSystemApp(ai)) {
1512 builder.detectAll();
1513 builder.penaltyDropBox();
1514 builder.penaltyLog();
1515 }
1516 }
1517
1518 setVmPolicy(builder.build());
1519 }
1520
1521 /**
1522 * Used by the framework to make file usage a fatal error.
1523 *
1524 * @hide
1525 */
1526 @UnsupportedAppUsage
1527 public static void enableDeathOnFileUriExposure() {
1528 sVmPolicy =
1529 new VmPolicy(
1530 sVmPolicy.mask
1531 | DETECT_VM_FILE_URI_EXPOSURE
1532 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
1533 sVmPolicy.classInstanceLimit,
1534 sVmPolicy.mListener,
1535 sVmPolicy.mCallbackExecutor);
1536 }
1537
1538 /**
1539 * Used by lame internal apps that haven't done the hard work to get themselves off file:// Uris
1540 * yet.
1541 *
1542 * @hide
1543 */
1544 @UnsupportedAppUsage
1545 public static void disableDeathOnFileUriExposure() {
1546 sVmPolicy =
1547 new VmPolicy(
1548 sVmPolicy.mask
1549 & ~(DETECT_VM_FILE_URI_EXPOSURE
1550 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE),
1551 sVmPolicy.classInstanceLimit,
1552 sVmPolicy.mListener,
1553 sVmPolicy.mCallbackExecutor);
1554 }
1555
1556 @UnsupportedAppUsage
1557 private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
1558 new ThreadLocal<ArrayList<ViolationInfo>>() {
1559 @Override
1560 protected ArrayList<ViolationInfo> initialValue() {
1561 return new ArrayList<ViolationInfo>();
1562 }
1563 };
1564
1565 // Note: only access this once verifying the thread has a Looper.
1566 private static final ThreadLocal<Handler> THREAD_HANDLER =
1567 new ThreadLocal<Handler>() {
1568 @Override
1569 protected Handler initialValue() {
1570 return new Handler();
1571 }
1572 };
1573
1574 private static final ThreadLocal<AndroidBlockGuardPolicy> THREAD_ANDROID_POLICY =
1575 new ThreadLocal<AndroidBlockGuardPolicy>() {
1576 @Override
1577 protected AndroidBlockGuardPolicy initialValue() {
1578 return new AndroidBlockGuardPolicy(0);
1579 }
1580 };
1581
1582 private static boolean tooManyViolationsThisLoop() {
1583 return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
1584 }
1585
1586 private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
1587 private @ThreadPolicyMask int mThreadPolicyMask;
1588
1589 // Map from violation stacktrace hashcode -> uptimeMillis of
1590 // last violation. No locking needed, as this is only
1591 // accessed by the same thread.
1592 /** Temporarily retained; appears to be missing UnsupportedAppUsage annotation */
1593 private ArrayMap<Integer, Long> mLastViolationTime;
1594 private SparseLongArray mRealLastViolationTime;
1595
1596 public AndroidBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1597 mThreadPolicyMask = threadPolicyMask;
1598 }
1599
1600 @Override
1601 public String toString() {
1602 return "AndroidBlockGuardPolicy; mPolicyMask=" + mThreadPolicyMask;
1603 }
1604
1605 // Part of BlockGuard.Policy interface:
1606 public int getPolicyMask() {
1607 return mThreadPolicyMask;
1608 }
1609
1610 // Part of BlockGuard.Policy interface:
1611 public void onWriteToDisk() {
1612 if ((mThreadPolicyMask & DETECT_THREAD_DISK_WRITE) == 0) {
1613 return;
1614 }
1615 if (tooManyViolationsThisLoop()) {
1616 return;
1617 }
1618 startHandlingViolationException(new DiskWriteViolation());
1619 }
1620
1621 // Not part of BlockGuard.Policy; just part of StrictMode:
1622 void onCustomSlowCall(String name) {
1623 if ((mThreadPolicyMask & DETECT_THREAD_CUSTOM) == 0) {
1624 return;
1625 }
1626 if (tooManyViolationsThisLoop()) {
1627 return;
1628 }
1629 startHandlingViolationException(new CustomViolation(name));
1630 }
1631
1632 // Not part of BlockGuard.Policy; just part of StrictMode:
1633 void onResourceMismatch(Object tag) {
1634 if ((mThreadPolicyMask & DETECT_THREAD_RESOURCE_MISMATCH) == 0) {
1635 return;
1636 }
1637 if (tooManyViolationsThisLoop()) {
1638 return;
1639 }
1640 startHandlingViolationException(new ResourceMismatchViolation(tag));
1641 }
1642
1643 // Not part of BlockGuard.Policy; just part of StrictMode:
1644 public void onUnbufferedIO() {
1645 if ((mThreadPolicyMask & DETECT_THREAD_UNBUFFERED_IO) == 0) {
1646 return;
1647 }
1648 if (tooManyViolationsThisLoop()) {
1649 return;
1650 }
1651 startHandlingViolationException(new UnbufferedIoViolation());
1652 }
1653
1654 // Part of BlockGuard.Policy interface:
1655 public void onReadFromDisk() {
1656 if ((mThreadPolicyMask & DETECT_THREAD_DISK_READ) == 0) {
1657 return;
1658 }
1659 if (tooManyViolationsThisLoop()) {
1660 return;
1661 }
1662 startHandlingViolationException(new DiskReadViolation());
1663 }
1664
1665 // Part of BlockGuard.Policy interface:
1666 public void onNetwork() {
1667 if ((mThreadPolicyMask & DETECT_THREAD_NETWORK) == 0) {
1668 return;
1669 }
1670 if ((mThreadPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
1671 throw new NetworkOnMainThreadException();
1672 }
1673 if (tooManyViolationsThisLoop()) {
1674 return;
1675 }
1676 startHandlingViolationException(new NetworkViolation());
1677 }
1678
1679 // Part of BlockGuard.Policy interface:
1680 public void onExplicitGc() {
1681 if ((mThreadPolicyMask & DETECT_THREAD_EXPLICIT_GC) == 0) {
1682 return;
1683 }
1684 if (tooManyViolationsThisLoop()) {
1685 return;
1686 }
1687 startHandlingViolationException(new ExplicitGcViolation());
1688 }
1689
1690 public @ThreadPolicyMask int getThreadPolicyMask() {
1691 return mThreadPolicyMask;
1692 }
1693
1694 public void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
1695 mThreadPolicyMask = threadPolicyMask;
1696 }
1697
1698 // Start handling a violation that just started and hasn't
1699 // actually run yet (e.g. no disk write or network operation
1700 // has yet occurred). This sees if we're in an event loop
1701 // thread and, if so, uses it to roughly measure how long the
1702 // violation took.
1703 void startHandlingViolationException(Violation e) {
1704 final int penaltyMask = (mThreadPolicyMask & PENALTY_ALL);
1705 final ViolationInfo info = new ViolationInfo(e, penaltyMask);
1706 info.violationUptimeMillis = SystemClock.uptimeMillis();
1707 handleViolationWithTimingAttempt(info);
1708 }
1709
1710 // Attempts to fill in the provided ViolationInfo's
1711 // durationMillis field if this thread has a Looper we can use
1712 // to measure with. We measure from the time of violation
1713 // until the time the looper is idle again (right before
1714 // the next epoll_wait)
1715 void handleViolationWithTimingAttempt(final ViolationInfo info) {
1716 Looper looper = Looper.myLooper();
1717
1718 // Without a Looper, we're unable to time how long the
1719 // violation takes place. This case should be rare, as
1720 // most users will care about timing violations that
1721 // happen on their main UI thread. Note that this case is
1722 // also hit when a violation takes place in a Binder
1723 // thread, in "gather" mode. In this case, the duration
1724 // of the violation is computed by the ultimate caller and
1725 // its Looper, if any.
1726 //
1727 // Also, as a special short-cut case when the only penalty
1728 // bit is death, we die immediately, rather than timing
1729 // the violation's duration. This makes it convenient to
1730 // use in unit tests too, rather than waiting on a Looper.
1731 //
1732 // TODO: if in gather mode, ignore Looper.myLooper() and always
1733 // go into this immediate mode?
1734 if (looper == null || (info.mPenaltyMask == PENALTY_DEATH)) {
1735 info.durationMillis = -1; // unknown (redundant, already set)
1736 onThreadPolicyViolation(info);
1737 return;
1738 }
1739
1740 final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
1741 if (records.size() >= MAX_OFFENSES_PER_LOOP) {
1742 // Not worth measuring. Too many offenses in one loop.
1743 return;
1744 }
1745 records.add(info);
1746 if (records.size() > 1) {
1747 // There's already been a violation this loop, so we've already
1748 // registered an idle handler to process the list of violations
1749 // at the end of this Looper's loop.
1750 return;
1751 }
1752
1753 final IWindowManager windowManager =
1754 info.penaltyEnabled(PENALTY_FLASH) ? sWindowManager.get() : null;
1755 if (windowManager != null) {
1756 try {
1757 windowManager.showStrictModeViolation(true);
1758 } catch (RemoteException unused) {
1759 }
1760 }
1761
1762 // We post a runnable to a Handler (== delay 0 ms) for
1763 // measuring the end time of a violation instead of using
1764 // an IdleHandler (as was previously used) because an
1765 // IdleHandler may not run for quite a long period of time
1766 // if an ongoing animation is happening and continually
1767 // posting ASAP (0 ms) animation steps. Animations are
1768 // throttled back to 60fps via SurfaceFlinger/View
1769 // invalidates, _not_ by posting frame updates every 16
1770 // milliseconds.
1771 THREAD_HANDLER
1772 .get()
1773 .postAtFrontOfQueue(
1774 () -> {
1775 long loopFinishTime = SystemClock.uptimeMillis();
1776
1777 // Note: we do this early, before handling the
1778 // violation below, as handling the violation
1779 // may include PENALTY_DEATH and we don't want
1780 // to keep the red border on.
1781 if (windowManager != null) {
1782 try {
1783 windowManager.showStrictModeViolation(false);
1784 } catch (RemoteException unused) {
1785 }
1786 }
1787
1788 for (int n = 0; n < records.size(); ++n) {
1789 ViolationInfo v = records.get(n);
1790 v.violationNumThisLoop = n + 1;
1791 v.durationMillis =
1792 (int) (loopFinishTime - v.violationUptimeMillis);
1793 onThreadPolicyViolation(v);
1794 }
1795 records.clear();
1796 });
1797 }
1798
1799 // Note: It's possible (even quite likely) that the
1800 // thread-local policy mask has changed from the time the
1801 // violation fired and now (after the violating code ran) due
1802 // to people who push/pop temporary policy in regions of code,
1803 // hence the policy being passed around.
1804 void onThreadPolicyViolation(final ViolationInfo info) {
1805 if (LOG_V) Log.d(TAG, "onThreadPolicyViolation; penalty=" + info.mPenaltyMask);
1806
1807 if (info.penaltyEnabled(PENALTY_GATHER)) {
1808 ArrayList<ViolationInfo> violations = gatheredViolations.get();
1809 if (violations == null) {
1810 violations = new ArrayList<>(1);
1811 gatheredViolations.set(violations);
1812 }
1813 for (ViolationInfo previous : violations) {
1814 if (info.getStackTrace().equals(previous.getStackTrace())) {
1815 // Duplicate. Don't log.
1816 return;
1817 }
1818 }
1819 violations.add(info);
1820 return;
1821 }
1822
1823 // Not perfect, but fast and good enough for dup suppression.
1824 Integer crashFingerprint = info.hashCode();
1825 long lastViolationTime = 0;
1826 long now = SystemClock.uptimeMillis();
1827 if (sLogger == LOGCAT_LOGGER) { // Don't throttle it if there is a non-default logger
1828 if (mRealLastViolationTime != null) {
1829 Long vtime = mRealLastViolationTime.get(crashFingerprint);
1830 if (vtime != null) {
1831 lastViolationTime = vtime;
1832 }
1833 clampViolationTimeMap(mRealLastViolationTime, Math.max(MIN_LOG_INTERVAL_MS,
1834 Math.max(MIN_DIALOG_INTERVAL_MS, MIN_DROPBOX_INTERVAL_MS)));
1835 } else {
1836 mRealLastViolationTime = new SparseLongArray(1);
1837 }
1838 mRealLastViolationTime.put(crashFingerprint, now);
1839 }
1840 long timeSinceLastViolationMillis =
1841 lastViolationTime == 0 ? Long.MAX_VALUE : (now - lastViolationTime);
1842
1843 if (info.penaltyEnabled(PENALTY_LOG)
1844 && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1845 sLogger.log(info);
1846 }
1847
1848 final Violation violation = info.mViolation;
1849
1850 // Penalties that ActivityManager should execute on our behalf.
1851 int penaltyMask = 0;
1852
1853 if (info.penaltyEnabled(PENALTY_DIALOG)
1854 && timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
1855 penaltyMask |= PENALTY_DIALOG;
1856 }
1857
1858 if (info.penaltyEnabled(PENALTY_DROPBOX)
1859 && timeSinceLastViolationMillis > MIN_DROPBOX_INTERVAL_MS) {
1860 penaltyMask |= PENALTY_DROPBOX;
1861 }
1862
1863 if (penaltyMask != 0) {
1864 final boolean justDropBox = (info.mPenaltyMask == PENALTY_DROPBOX);
1865 if (justDropBox) {
1866 // If all we're going to ask the activity manager
1867 // to do is dropbox it (the common case during
1868 // platform development), we can avoid doing this
1869 // call synchronously which Binder data suggests
1870 // isn't always super fast, despite the implementation
1871 // in the ActivityManager trying to be mostly async.
1872 dropboxViolationAsync(penaltyMask, info);
1873 } else {
1874 handleApplicationStrictModeViolation(penaltyMask, info);
1875 }
1876 }
1877
1878 if (info.penaltyEnabled(PENALTY_DEATH)) {
1879 throw new RuntimeException("StrictMode ThreadPolicy violation", violation);
1880 }
1881
1882 // penaltyDeath will cause penaltyCallback to no-op since we cannot guarantee the
1883 // executor finishes before crashing.
1884 final OnThreadViolationListener listener = sThreadViolationListener.get();
1885 final Executor executor = sThreadViolationExecutor.get();
1886 if (listener != null && executor != null) {
1887 try {
1888 executor.execute(
1889 () -> {
1890 // Lift violated policy to prevent infinite recursion.
1891 ThreadPolicy oldPolicy = StrictMode.allowThreadViolations();
1892 try {
1893 listener.onThreadViolation(violation);
1894 } finally {
1895 StrictMode.setThreadPolicy(oldPolicy);
1896 }
1897 });
1898 } catch (RejectedExecutionException e) {
1899 Log.e(TAG, "ThreadPolicy penaltyCallback failed", e);
1900 }
1901 }
1902 }
1903 }
1904
1905 private static final BlockGuard.VmPolicy VM_ANDROID_POLICY = new BlockGuard.VmPolicy() {
1906 @Override
1907 public void onPathAccess(String path) {
1908 if (path == null) return;
1909
1910 // NOTE: keep credential-protected paths in sync with Environment.java
1911 if (path.startsWith("/data/user/")
1912 || path.startsWith("/data/media/")
1913 || path.startsWith("/data/system_ce/")
1914 || path.startsWith("/data/misc_ce/")
1915 || path.startsWith("/data/vendor_ce/")
1916 || path.startsWith("/storage/emulated/")) {
1917 final int second = path.indexOf('/', 1);
1918 final int third = path.indexOf('/', second + 1);
1919 final int fourth = path.indexOf('/', third + 1);
1920 if (fourth == -1) return;
1921
1922 try {
1923 final int userId = Integer.parseInt(path.substring(third + 1, fourth));
1924 onCredentialProtectedPathAccess(path, userId);
1925 } catch (NumberFormatException ignored) {
1926 }
1927 } else if (path.startsWith("/data/data/")) {
1928 onCredentialProtectedPathAccess(path, UserHandle.USER_SYSTEM);
1929 }
1930 }
1931 };
1932
1933 /**
1934 * In the common case, as set by conditionallyEnableDebugLogging, we're just dropboxing any
1935 * violations but not showing a dialog, not loggging, and not killing the process. In these
1936 * cases we don't need to do a synchronous call to the ActivityManager. This is used by both
1937 * per-thread and vm-wide violations when applicable.
1938 */
1939 private static void dropboxViolationAsync(
1940 final int penaltyMask, final ViolationInfo info) {
1941 int outstanding = sDropboxCallsInFlight.incrementAndGet();
1942 if (outstanding > 20) {
1943 // What's going on? Let's not make make the situation
1944 // worse and just not log.
1945 sDropboxCallsInFlight.decrementAndGet();
1946 return;
1947 }
1948
1949 if (LOG_V) Log.d(TAG, "Dropboxing async; in-flight=" + outstanding);
1950
1951 BackgroundThread.getHandler().post(() -> {
1952 handleApplicationStrictModeViolation(penaltyMask, info);
1953 int outstandingInner = sDropboxCallsInFlight.decrementAndGet();
1954 if (LOG_V) Log.d(TAG, "Dropbox complete; in-flight=" + outstandingInner);
1955 });
1956 }
1957
1958 private static void handleApplicationStrictModeViolation(int penaltyMask,
1959 ViolationInfo info) {
1960 final int oldMask = getThreadPolicyMask();
1961 try {
1962 // First, remove any policy before we call into the Activity Manager,
1963 // otherwise we'll infinite recurse as we try to log policy violations
1964 // to disk, thus violating policy, thus requiring logging, etc...
1965 // We restore the current policy below, in the finally block.
1966 setThreadPolicyMask(0);
1967
1968 IActivityManager am = ActivityManager.getService();
1969 if (am == null) {
1970 Log.w(TAG, "No activity manager; failed to Dropbox violation.");
1971 } else {
1972 am.handleApplicationStrictModeViolation(
1973 RuntimeInit.getApplicationObject(), penaltyMask, info);
1974 }
1975 } catch (RemoteException e) {
1976 if (e instanceof DeadObjectException) {
1977 // System process is dead; ignore
1978 } else {
1979 Log.e(TAG, "RemoteException handling StrictMode violation", e);
1980 }
1981 } finally {
1982 setThreadPolicyMask(oldMask);
1983 }
1984 }
1985
1986 private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
1987
1988 @Override
1989 public void report(String message, Throwable allocationSite) {
1990 onVmPolicyViolation(new LeakedClosableViolation(message, allocationSite));
1991 }
1992
1993 @Override
1994 public void report(String message) {
1995 onVmPolicyViolation(new LeakedClosableViolation(message));
1996 }
1997 }
1998
1999 /** Called from Parcel.writeNoException() */
2000 /* package */ static boolean hasGatheredViolations() {
2001 return gatheredViolations.get() != null;
2002 }
2003
2004 /**
2005 * Called from Parcel.writeException(), so we drop this memory and don't incorrectly attribute
2006 * it to the wrong caller on the next Binder call on this thread.
2007 */
2008 /* package */ static void clearGatheredViolations() {
2009 gatheredViolations.set(null);
2010 }
2011
2012 /** @hide */
2013 @UnsupportedAppUsage
2014 @TestApi
2015 public static void conditionallyCheckInstanceCounts() {
2016 VmPolicy policy = getVmPolicy();
2017 int policySize = policy.classInstanceLimit.size();
2018 if (policySize == 0) {
2019 return;
2020 }
2021
2022 System.gc();
2023 System.runFinalization();
2024 System.gc();
2025
2026 // Note: classInstanceLimit is immutable, so this is lock-free
2027 // Create the classes array.
2028 Class[] classes = policy.classInstanceLimit.keySet().toArray(new Class[policySize]);
2029 long[] instanceCounts = VMDebug.countInstancesOfClasses(classes, false);
2030 for (int i = 0; i < classes.length; ++i) {
2031 Class klass = classes[i];
2032 int limit = policy.classInstanceLimit.get(klass);
2033 long instances = instanceCounts[i];
2034 if (instances > limit) {
2035 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
2036 }
2037 }
2038 }
2039
2040 private static long sLastInstanceCountCheckMillis = 0;
2041 private static boolean sIsIdlerRegistered = false; // guarded by StrictMode.class
2042 private static final MessageQueue.IdleHandler sProcessIdleHandler =
2043 new MessageQueue.IdleHandler() {
2044 public boolean queueIdle() {
2045 long now = SystemClock.uptimeMillis();
2046 if (now - sLastInstanceCountCheckMillis > 30 * 1000) {
2047 sLastInstanceCountCheckMillis = now;
2048 conditionallyCheckInstanceCounts();
2049 }
2050 return true;
2051 }
2052 };
2053
2054 /**
2055 * Sets the policy for what actions in the VM process (on any thread) should be detected, as
2056 * well as the penalty if such actions occur.
2057 *
2058 * @param policy the policy to put into place
2059 */
2060 public static void setVmPolicy(final VmPolicy policy) {
2061 synchronized (StrictMode.class) {
2062 sVmPolicy = policy;
2063 setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
2064
2065 Looper looper = Looper.getMainLooper();
2066 if (looper != null) {
2067 MessageQueue mq = looper.mQueue;
2068 if (policy.classInstanceLimit.size() == 0
2069 || (sVmPolicy.mask & PENALTY_ALL) == 0) {
2070 mq.removeIdleHandler(sProcessIdleHandler);
2071 sIsIdlerRegistered = false;
2072 } else if (!sIsIdlerRegistered) {
2073 mq.addIdleHandler(sProcessIdleHandler);
2074 sIsIdlerRegistered = true;
2075 }
2076 }
2077
2078 int networkPolicy = NETWORK_POLICY_ACCEPT;
2079 if ((sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0) {
2080 if ((sVmPolicy.mask & PENALTY_DEATH) != 0
2081 || (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0) {
2082 networkPolicy = NETWORK_POLICY_REJECT;
2083 } else {
2084 networkPolicy = NETWORK_POLICY_LOG;
2085 }
2086 }
2087
2088 final INetworkManagementService netd =
2089 INetworkManagementService.Stub.asInterface(
2090 ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
2091 if (netd != null) {
2092 try {
2093 netd.setUidCleartextNetworkPolicy(android.os.Process.myUid(), networkPolicy);
2094 } catch (RemoteException ignored) {
2095 }
2096 } else if (networkPolicy != NETWORK_POLICY_ACCEPT) {
2097 Log.w(TAG, "Dropping requested network policy due to missing service!");
2098 }
2099
2100
2101 if ((sVmPolicy.mask & DETECT_VM_NON_SDK_API_USAGE) != 0) {
2102 VMRuntime.setNonSdkApiUsageConsumer(sNonSdkApiUsageConsumer);
2103 VMRuntime.setDedupeHiddenApiWarnings(false);
2104 } else {
2105 VMRuntime.setNonSdkApiUsageConsumer(null);
2106 VMRuntime.setDedupeHiddenApiWarnings(true);
2107 }
2108
2109 setBlockGuardVmPolicy(sVmPolicy.mask);
2110 }
2111 }
2112
2113 /** Gets the current VM policy. */
2114 public static VmPolicy getVmPolicy() {
2115 synchronized (StrictMode.class) {
2116 return sVmPolicy;
2117 }
2118 }
2119
2120 /**
2121 * Enable the recommended StrictMode defaults, with violations just being logged.
2122 *
2123 * <p>This catches disk and network access on the main thread, as well as leaked SQLite cursors
2124 * and unclosed resources. This is simply a wrapper around {@link #setVmPolicy} and {@link
2125 * #setThreadPolicy}.
2126 */
2127 public static void enableDefaults() {
2128 setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
2129 setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
2130 }
2131
2132 /** @hide */
2133 public static boolean vmSqliteObjectLeaksEnabled() {
2134 return (sVmPolicy.mask & DETECT_VM_CURSOR_LEAKS) != 0;
2135 }
2136
2137 /** @hide */
2138 public static boolean vmClosableObjectLeaksEnabled() {
2139 return (sVmPolicy.mask & DETECT_VM_CLOSABLE_LEAKS) != 0;
2140 }
2141
2142 /** @hide */
2143 public static boolean vmRegistrationLeaksEnabled() {
2144 return (sVmPolicy.mask & DETECT_VM_REGISTRATION_LEAKS) != 0;
2145 }
2146
2147 /** @hide */
2148 public static boolean vmFileUriExposureEnabled() {
2149 return (sVmPolicy.mask & DETECT_VM_FILE_URI_EXPOSURE) != 0;
2150 }
2151
2152 /** @hide */
2153 public static boolean vmCleartextNetworkEnabled() {
2154 return (sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0;
2155 }
2156
2157 /** @hide */
2158 public static boolean vmContentUriWithoutPermissionEnabled() {
2159 return (sVmPolicy.mask & DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION) != 0;
2160 }
2161
2162 /** @hide */
2163 public static boolean vmUntaggedSocketEnabled() {
2164 return (sVmPolicy.mask & DETECT_VM_UNTAGGED_SOCKET) != 0;
2165 }
2166
2167 /** @hide */
2168 public static boolean vmImplicitDirectBootEnabled() {
2169 return (sVmPolicy.mask & DETECT_VM_IMPLICIT_DIRECT_BOOT) != 0;
2170 }
2171
2172 /** @hide */
2173 public static boolean vmCredentialProtectedWhileLockedEnabled() {
2174 return (sVmPolicy.mask & DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED) != 0;
2175 }
2176
2177 /** @hide */
2178 public static boolean vmIncorrectContextUseEnabled() {
2179 return (sVmPolicy.mask & DETECT_VM_INCORRECT_CONTEXT_USE) != 0;
2180 }
2181
2182 /** @hide */
2183 public static boolean vmUnsafeIntentLaunchEnabled() {
2184 return (sVmPolicy.mask & DETECT_VM_UNSAFE_INTENT_LAUNCH) != 0;
2185 }
2186
2187 /** @hide */
2188 public static void onSqliteObjectLeaked(String message, Throwable originStack) {
2189 onVmPolicyViolation(new SqliteObjectLeakedViolation(message, originStack));
2190 }
2191
2192 /** @hide */
2193 @UnsupportedAppUsage
2194 public static void onWebViewMethodCalledOnWrongThread(Throwable originStack) {
2195 onVmPolicyViolation(new WebViewMethodCalledOnWrongThreadViolation(originStack));
2196 }
2197
2198 /** @hide */
2199 public static void onIntentReceiverLeaked(Throwable originStack) {
2200 onVmPolicyViolation(new IntentReceiverLeakedViolation(originStack));
2201 }
2202
2203 /** @hide */
2204 public static void onServiceConnectionLeaked(Throwable originStack) {
2205 onVmPolicyViolation(new ServiceConnectionLeakedViolation(originStack));
2206 }
2207
2208 /** @hide */
2209 public static void onFileUriExposed(Uri uri, String location) {
2210 final String message = uri + " exposed beyond app through " + location;
2211 if ((sVmPolicy.mask & PENALTY_DEATH_ON_FILE_URI_EXPOSURE) != 0) {
2212 throw new FileUriExposedException(message);
2213 } else {
2214 onVmPolicyViolation(new FileUriExposedViolation(message));
2215 }
2216 }
2217
2218 /** @hide */
2219 public static void onContentUriWithoutPermission(Uri uri, String location) {
2220 onVmPolicyViolation(new ContentUriWithoutPermissionViolation(uri, location));
2221 }
2222
2223 /** @hide */
2224 public static void onCleartextNetworkDetected(byte[] firstPacket) {
2225 byte[] rawAddr = null;
2226 if (firstPacket != null) {
2227 if (firstPacket.length >= 20 && (firstPacket[0] & 0xf0) == 0x40) {
2228 // IPv4
2229 rawAddr = new byte[4];
2230 System.arraycopy(firstPacket, 16, rawAddr, 0, 4);
2231 } else if (firstPacket.length >= 40 && (firstPacket[0] & 0xf0) == 0x60) {
2232 // IPv6
2233 rawAddr = new byte[16];
2234 System.arraycopy(firstPacket, 24, rawAddr, 0, 16);
2235 }
2236 }
2237
2238 final int uid = android.os.Process.myUid();
2239 final StringBuilder msg = new StringBuilder("Detected cleartext network traffic from UID ")
2240 .append(uid);
2241 if (rawAddr != null) {
2242 try {
2243 msg.append(" to ").append(InetAddress.getByAddress(rawAddr));
2244 } catch (UnknownHostException ignored) {
2245 }
2246 }
2247 msg.append(HexDump.dumpHexString(firstPacket).trim()).append(' ');
2248 final boolean forceDeath = (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0;
2249 onVmPolicyViolation(new CleartextNetworkViolation(msg.toString()), forceDeath);
2250 }
2251
2252 /** @hide */
2253 public static void onUntaggedSocket() {
2254 onVmPolicyViolation(new UntaggedSocketViolation());
2255 }
2256
2257 /** @hide */
2258 public static void onImplicitDirectBoot() {
2259 onVmPolicyViolation(new ImplicitDirectBootViolation());
2260 }
2261
2262 /** @hide */
2263 public static void onIncorrectContextUsed(String message, Throwable originStack) {
2264 onVmPolicyViolation(new IncorrectContextUseViolation(message, originStack));
2265 }
2266
2267 /**
2268 * A helper method to verify if the {@code context} has a proper {@link Configuration} to obtain
2269 * {@link android.view.LayoutInflater}, {@link android.view.ViewConfiguration} or
2270 * {@link android.view.GestureDetector}. Throw {@link IncorrectContextUseViolation} if the
2271 * {@code context} doesn't have a proper configuration.
2272 * <p>
2273 * Note that the context created via {@link Context#createConfigurationContext(Configuration)}
2274 * is also regarded as a context with a proper configuration because the {@link Configuration}
2275 * is handled by developers.
2276 * </p>
2277 * @param context The context to verify if it is a display associative context
2278 * @param methodName The asserted method name
2279 *
2280 * @see Context#isConfigurationContext()
2281 * @see Context#createConfigurationContext(Configuration)
2282 * @see Context#getSystemService(String)
2283 * @see Context#LAYOUT_INFLATER_SERVICE
2284 * @see android.view.ViewConfiguration#get(Context)
2285 * @see android.view.LayoutInflater#from(Context)
2286 * @see IncorrectContextUseViolation
2287 *
2288 * @hide
2289 */
2290 public static void assertConfigurationContext(@NonNull Context context,
2291 @NonNull String methodName) {
2292 if (vmIncorrectContextUseEnabled() && !context.isConfigurationContext()) {
2293 final String errorMessage = "Tried to access the API:" + methodName + " which needs to"
2294 + " have proper configuration from a non-UI Context:" + context;
2295 final String message = "The API:" + methodName + " needs a proper configuration."
2296 + " Use UI contexts such as an activity or a context created"
2297 + " via createWindowContext(Display, int, Bundle) or "
2298 + " createConfigurationContext(Configuration) with a proper configuration.";
2299 final Exception exception = new IllegalAccessException(errorMessage);
2300 StrictMode.onIncorrectContextUsed(message, exception);
2301 Log.e(TAG, errorMessage + " " + message, exception);
2302 }
2303 }
2304
2305 /**
2306 * A helper method to verify if the {@code context} is a UI context and throw
2307 * {@link IncorrectContextUseViolation} if the {@code context} is not a UI context.
2308 *
2309 * @param context The context to verify if it is a UI context
2310 * @param methodName The asserted method name
2311 *
2312 * @see Context#isUiContext()
2313 * @see IncorrectContextUseViolation
2314 *
2315 * @hide
2316 */
2317 public static void assertUiContext(@NonNull Context context, @NonNull String methodName) {
2318 if (vmIncorrectContextUseEnabled() && !context.isUiContext()) {
2319 final String errorMessage = "Tried to access UI related API:" + methodName
2320 + " from a non-UI Context:" + context;
2321 final String message = methodName + " should be accessed from Activity or other UI "
2322 + "Contexts. Use an Activity or a Context created with "
2323 + "Context#createWindowContext(int, Bundle), which are adjusted to "
2324 + "the configuration and visual bounds of an area on screen.";
2325 final Exception exception = new IllegalAccessException(errorMessage);
2326 StrictMode.onIncorrectContextUsed(message, exception);
2327 Log.e(TAG, errorMessage + " " + message, exception);
2328 }
2329 }
2330
2331 /** @hide */
2332 public static void onUnsafeIntentLaunch(Intent intent) {
2333 onVmPolicyViolation(new UnsafeIntentLaunchViolation(intent));
2334 }
2335
2336 /** Assume locked until we hear otherwise */
2337 private static volatile boolean sUserKeyUnlocked = false;
2338
2339 private static boolean isUserKeyUnlocked(int userId) {
2340 final IStorageManager storage = IStorageManager.Stub
2341 .asInterface(ServiceManager.getService("mount"));
2342 if (storage != null) {
2343 try {
2344 return storage.isUserKeyUnlocked(userId);
2345 } catch (RemoteException ignored) {
2346 }
2347 }
2348 return false;
2349 }
2350
2351 /** @hide */
2352 private static void onCredentialProtectedPathAccess(String path, int userId) {
2353 // We can cache the unlocked state for the userId we're running as,
2354 // since any relocking of that user will always result in our
2355 // process being killed to release any CE FDs we're holding onto.
2356 if (userId == UserHandle.myUserId()) {
2357 if (sUserKeyUnlocked) {
2358 return;
2359 } else if (isUserKeyUnlocked(userId)) {
2360 sUserKeyUnlocked = true;
2361 return;
2362 }
2363 } else if (isUserKeyUnlocked(userId)) {
2364 return;
2365 }
2366
2367 onVmPolicyViolation(new CredentialProtectedWhileLockedViolation(
2368 "Accessed credential protected path " + path + " while user " + userId
2369 + " was locked"));
2370 }
2371
2372 // Map from VM violation fingerprint to uptime millis.
2373 @UnsupportedAppUsage
2374 private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<>();
2375 private static final SparseLongArray sRealLastVmViolationTime = new SparseLongArray();
2376
2377 /**
2378 * Clamp the given map by removing elements with timestamp older than the given retainSince.
2379 */
2380 private static void clampViolationTimeMap(final @NonNull SparseLongArray violationTime,
2381 final long retainSince) {
2382 for (int i = 0; i < violationTime.size(); ) {
2383 if (violationTime.valueAt(i) < retainSince) {
2384 // Remove stale entries
2385 violationTime.removeAt(i);
2386 } else {
2387 i++;
2388 }
2389 }
2390 // Ideally we'd cap the total size of the map, though it'll involve quickselect of topK,
2391 // seems not worth it (saving some space immediately but they will be obsoleted soon anyway)
2392 }
2393
2394 /** @hide */
2395 public static void onVmPolicyViolation(Violation originStack) {
2396 onVmPolicyViolation(originStack, false);
2397 }
2398
2399 /** @hide */
2400 public static void onVmPolicyViolation(Violation violation, boolean forceDeath) {
2401 final boolean penaltyDropbox = (sVmPolicy.mask & PENALTY_DROPBOX) != 0;
2402 final boolean penaltyDeath = ((sVmPolicy.mask & PENALTY_DEATH) != 0) || forceDeath;
2403 final boolean penaltyLog = (sVmPolicy.mask & PENALTY_LOG) != 0;
2404
2405 final int penaltyMask = (sVmPolicy.mask & PENALTY_ALL);
2406 final ViolationInfo info = new ViolationInfo(violation, penaltyMask);
2407
2408 // Erase stuff not relevant for process-wide violations
2409 info.numAnimationsRunning = 0;
2410 info.tags = null;
2411 info.broadcastIntentAction = null;
2412
2413 final Integer fingerprint = info.hashCode();
2414 final long now = SystemClock.uptimeMillis();
2415 long lastViolationTime;
2416 long timeSinceLastViolationMillis = Long.MAX_VALUE;
2417 if (sLogger == LOGCAT_LOGGER) { // Don't throttle it if there is a non-default logger
2418 synchronized (sRealLastVmViolationTime) {
2419 if (sRealLastVmViolationTime.indexOfKey(fingerprint) >= 0) {
2420 lastViolationTime = sRealLastVmViolationTime.get(fingerprint);
2421 timeSinceLastViolationMillis = now - lastViolationTime;
2422 }
2423 if (timeSinceLastViolationMillis > MIN_VM_INTERVAL_MS) {
2424 sRealLastVmViolationTime.put(fingerprint, now);
2425 }
2426 clampViolationTimeMap(sRealLastVmViolationTime,
2427 now - Math.max(MIN_VM_INTERVAL_MS, MIN_LOG_INTERVAL_MS));
2428 }
2429 }
2430 if (timeSinceLastViolationMillis <= MIN_VM_INTERVAL_MS) {
2431 // Rate limit all penalties.
2432 return;
2433 }
2434
2435 if (penaltyLog && sLogger != null && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
2436 sLogger.log(info);
2437 }
2438
2439 if (penaltyDropbox) {
2440 if (penaltyDeath) {
2441 handleApplicationStrictModeViolation(PENALTY_DROPBOX, info);
2442 } else {
2443 // Common case for userdebug/eng builds. If no death and
2444 // just dropboxing, we can do the ActivityManager call
2445 // asynchronously.
2446 dropboxViolationAsync(PENALTY_DROPBOX, info);
2447 }
2448 }
2449
2450 if (penaltyDeath) {
2451 System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
2452 Process.killProcess(Process.myPid());
2453 System.exit(10);
2454 }
2455
2456 // If penaltyDeath, we can't guarantee this callback finishes before the process dies for
2457 // all executors. penaltyDeath supersedes penaltyCallback.
2458 if (sVmPolicy.mListener != null && sVmPolicy.mCallbackExecutor != null) {
2459 final OnVmViolationListener listener = sVmPolicy.mListener;
2460 try {
2461 sVmPolicy.mCallbackExecutor.execute(
2462 () -> {
2463 // Lift violated policy to prevent infinite recursion.
2464 VmPolicy oldPolicy = allowVmViolations();
2465 try {
2466 listener.onVmViolation(violation);
2467 } finally {
2468 setVmPolicy(oldPolicy);
2469 }
2470 });
2471 } catch (RejectedExecutionException e) {
2472 Log.e(TAG, "VmPolicy penaltyCallback failed", e);
2473 }
2474 }
2475 }
2476
2477 /** Called from Parcel.writeNoException() */
2478 /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
2479 ArrayList<ViolationInfo> violations = gatheredViolations.get();
2480 if (violations == null) {
2481 p.writeInt(0);
2482 } else {
2483 // To avoid taking up too much transaction space, only include
2484 // details for the first 3 violations. Deep inside, CrashInfo
2485 // will truncate each stack trace to ~20kB.
2486 final int size = Math.min(violations.size(), 3);
2487 p.writeInt(size);
2488 for (int i = 0; i < size; i++) {
2489 violations.get(i).writeToParcel(p, 0);
2490 }
2491 }
2492 gatheredViolations.set(null);
2493 }
2494
2495 /**
2496 * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS, we here
2497 * read back all the encoded violations.
2498 */
2499 /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
2500 Throwable localCallSite = new Throwable();
2501 final int policyMask = getThreadPolicyMask();
2502 final boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
2503
2504 final int size = p.readInt();
2505 for (int i = 0; i < size; i++) {
2506 final ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
2507 info.addLocalStack(localCallSite);
2508 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2509 if (policy instanceof AndroidBlockGuardPolicy) {
2510 ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
2511 }
2512 }
2513 }
2514
2515 /**
2516 * Called from android_util_Binder.cpp's android_os_Parcel_enforceInterface when an incoming
2517 * Binder call requires changing the StrictMode policy mask. The role of this function is to ask
2518 * Binder for its current (native) thread-local policy value and synchronize it to libcore's
2519 * (Java) thread-local policy value.
2520 */
2521 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2522 private static void onBinderStrictModePolicyChange(@ThreadPolicyMask int newPolicy) {
2523 setBlockGuardPolicy(newPolicy);
2524 }
2525
2526 /**
2527 * A tracked, critical time span. (e.g. during an animation.)
2528 *
2529 * <p>The object itself is a linked list node, to avoid any allocations during rapid span
2530 * entries and exits.
2531 *
2532 * @hide
2533 */
2534 public static class Span {
2535 private String mName;
2536 private long mCreateMillis;
2537 private Span mNext;
2538 private Span mPrev; // not used when in freeList, only active
2539 private final ThreadSpanState mContainerState;
2540
2541 Span(ThreadSpanState threadState) {
2542 mContainerState = threadState;
2543 }
2544
2545 // Empty constructor for the NO_OP_SPAN
2546 protected Span() {
2547 mContainerState = null;
2548 }
2549
2550 /**
2551 * To be called when the critical span is complete (i.e. the animation is done animating).
2552 * This can be called on any thread (even a different one from where the animation was
2553 * taking place), but that's only a defensive implementation measure. It really makes no
2554 * sense for you to call this on thread other than that where you created it.
2555 *
2556 * @hide
2557 */
2558 @UnsupportedAppUsage
2559 public void finish() {
2560 ThreadSpanState state = mContainerState;
2561 synchronized (state) {
2562 if (mName == null) {
2563 // Duplicate finish call. Ignore.
2564 return;
2565 }
2566
2567 // Remove ourselves from the active list.
2568 if (mPrev != null) {
2569 mPrev.mNext = mNext;
2570 }
2571 if (mNext != null) {
2572 mNext.mPrev = mPrev;
2573 }
2574 if (state.mActiveHead == this) {
2575 state.mActiveHead = mNext;
2576 }
2577
2578 state.mActiveSize--;
2579
2580 if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
2581
2582 this.mCreateMillis = -1;
2583 this.mName = null;
2584 this.mPrev = null;
2585 this.mNext = null;
2586
2587 // Add ourselves to the freeList, if it's not already
2588 // too big.
2589 if (state.mFreeListSize < 5) {
2590 this.mNext = state.mFreeListHead;
2591 state.mFreeListHead = this;
2592 state.mFreeListSize++;
2593 }
2594 }
2595 }
2596 }
2597
2598 // The no-op span that's used in user builds.
2599 private static final Span NO_OP_SPAN =
2600 new Span() {
2601 public void finish() {
2602 // Do nothing.
2603 }
2604 };
2605
2606 /**
2607 * Linked lists of active spans and a freelist.
2608 *
2609 * <p>Locking notes: there's one of these structures per thread and all members of this
2610 * structure (as well as the Span nodes under it) are guarded by the ThreadSpanState object
2611 * instance. While in theory there'd be no locking required because it's all local per-thread,
2612 * the finish() method above is defensive against people calling it on a different thread from
2613 * where they created the Span, hence the locking.
2614 */
2615 private static class ThreadSpanState {
2616 public Span mActiveHead; // doubly-linked list.
2617 public int mActiveSize;
2618 public Span mFreeListHead; // singly-linked list. only changes at head.
2619 public int mFreeListSize;
2620 }
2621
2622 private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
2623 new ThreadLocal<ThreadSpanState>() {
2624 @Override
2625 protected ThreadSpanState initialValue() {
2626 return new ThreadSpanState();
2627 }
2628 };
2629
2630 @UnsupportedAppUsage
2631 private static Singleton<IWindowManager> sWindowManager =
2632 new Singleton<IWindowManager>() {
2633 protected IWindowManager create() {
2634 return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
2635 }
2636 };
2637
2638 /**
2639 * Enter a named critical span (e.g. an animation)
2640 *
2641 * <p>The name is an arbitary label (or tag) that will be applied to any strictmode violation
2642 * that happens while this span is active. You must call finish() on the span when done.
2643 *
2644 * <p>This will never return null, but on devices without debugging enabled, this may return a
2645 * placeholder object on which the finish() method is a no-op.
2646 *
2647 * <p>TODO: add CloseGuard to this, verifying callers call finish.
2648 *
2649 * @hide
2650 */
2651 @UnsupportedAppUsage
2652 public static Span enterCriticalSpan(String name) {
2653 if (Build.IS_USER) {
2654 return NO_OP_SPAN;
2655 }
2656 if (name == null || name.isEmpty()) {
2657 throw new IllegalArgumentException("name must be non-null and non-empty");
2658 }
2659 ThreadSpanState state = sThisThreadSpanState.get();
2660 Span span = null;
2661 synchronized (state) {
2662 if (state.mFreeListHead != null) {
2663 span = state.mFreeListHead;
2664 state.mFreeListHead = span.mNext;
2665 state.mFreeListSize--;
2666 } else {
2667 // Shouldn't have to do this often.
2668 span = new Span(state);
2669 }
2670 span.mName = name;
2671 span.mCreateMillis = SystemClock.uptimeMillis();
2672 span.mNext = state.mActiveHead;
2673 span.mPrev = null;
2674 state.mActiveHead = span;
2675 state.mActiveSize++;
2676 if (span.mNext != null) {
2677 span.mNext.mPrev = span;
2678 }
2679 if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
2680 }
2681 return span;
2682 }
2683
2684 /**
2685 * For code to note that it's slow. This is a no-op unless the current thread's {@link
2686 * android.os.StrictMode.ThreadPolicy} has {@link
2687 * android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls} enabled.
2688 *
2689 * @param name a short string for the exception stack trace that's built if when this fires.
2690 */
2691 public static void noteSlowCall(String name) {
2692 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2693 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2694 // StrictMode not enabled.
2695 return;
2696 }
2697 ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
2698 }
2699
2700 /** @hide */
2701 @SystemApi(client = MODULE_LIBRARIES)
2702 public static void noteUntaggedSocket() {
2703 if (vmUntaggedSocketEnabled()) onUntaggedSocket();
2704 }
2705
2706 /**
2707 * For code to note that a resource was obtained using a type other than its defined type. This
2708 * is a no-op unless the current thread's {@link android.os.StrictMode.ThreadPolicy} has {@link
2709 * android.os.StrictMode.ThreadPolicy.Builder#detectResourceMismatches()} enabled.
2710 *
2711 * @param tag an object for the exception stack trace that's built if when this fires.
2712 * @hide
2713 */
2714 public static void noteResourceMismatch(Object tag) {
2715 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2716 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2717 // StrictMode not enabled.
2718 return;
2719 }
2720 ((AndroidBlockGuardPolicy) policy).onResourceMismatch(tag);
2721 }
2722
2723 /** @hide */
2724 public static void noteUnbufferedIO() {
2725 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2726 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2727 // StrictMode not enabled.
2728 return;
2729 }
2730 policy.onUnbufferedIO();
2731 }
2732
2733 /** @hide */
2734 public static void noteDiskRead() {
2735 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2736 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2737 // StrictMode not enabled.
2738 return;
2739 }
2740 policy.onReadFromDisk();
2741 }
2742
2743 /** @hide */
2744 public static void noteDiskWrite() {
2745 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2746 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2747 // StrictMode not enabled.
2748 return;
2749 }
2750 policy.onWriteToDisk();
2751 }
2752
2753 @GuardedBy("StrictMode.class")
2754 private static final HashMap<Class, Integer> sExpectedActivityInstanceCount = new HashMap<>();
2755
2756 /**
2757 * Returns an object that is used to track instances of activites. The activity should store a
2758 * reference to the tracker object in one of its fields.
2759 *
2760 * @hide
2761 */
2762 public static Object trackActivity(Object instance) {
2763 return new InstanceTracker(instance);
2764 }
2765
2766 /** @hide */
2767 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2768 public static void incrementExpectedActivityCount(Class klass) {
2769 if (klass == null) {
2770 return;
2771 }
2772
2773 synchronized (StrictMode.class) {
2774 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2775 return;
2776 }
2777
2778 // Use the instance count from InstanceTracker as initial value.
2779 Integer expected = sExpectedActivityInstanceCount.get(klass);
2780 Integer newExpected =
2781 expected == null ? InstanceTracker.getInstanceCount(klass) + 1 : expected + 1;
2782 sExpectedActivityInstanceCount.put(klass, newExpected);
2783 }
2784 }
2785
2786 /** @hide */
2787 public static void decrementExpectedActivityCount(Class klass) {
2788 if (klass == null) {
2789 return;
2790 }
2791
2792 final int limit;
2793 synchronized (StrictMode.class) {
2794 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2795 return;
2796 }
2797
2798 Integer expected = sExpectedActivityInstanceCount.get(klass);
2799 int newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
2800 if (newExpected == 0) {
2801 sExpectedActivityInstanceCount.remove(klass);
2802 } else {
2803 sExpectedActivityInstanceCount.put(klass, newExpected);
2804 }
2805
2806 // Note: adding 1 here to give some breathing room during
2807 // orientation changes. (shouldn't be necessary, though?)
2808 limit = newExpected + 1;
2809 }
2810
2811 // Quick check.
2812 int actual = InstanceTracker.getInstanceCount(klass);
2813 if (actual <= limit) {
2814 return;
2815 }
2816
2817 // Do a GC and explicit count to double-check.
2818 // This is the work that we are trying to avoid by tracking the object instances
2819 // explicity. Running an explicit GC can be expensive (80ms) and so can walking
2820 // the heap to count instance (30ms). This extra work can make the system feel
2821 // noticeably less responsive during orientation changes when activities are
2822 // being restarted. Granted, it is only a problem when StrictMode is enabled
2823 // but it is annoying.
2824
2825 System.gc();
2826 System.runFinalization();
2827 System.gc();
2828
2829 long instances = VMDebug.countInstancesOfClass(klass, false);
2830 if (instances > limit) {
2831 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
2832 }
2833 }
2834
2835 /**
2836 * Parcelable that gets sent in Binder call headers back to callers to report violations that
2837 * happened during a cross-process call.
2838 *
2839 * @hide
2840 */
2841 @TestApi
2842 public static final class ViolationInfo implements Parcelable {
2843 /** Stack and violation details. */
2844 private final Violation mViolation;
2845
2846 /** Path leading to a violation that occurred across binder. */
2847 private final Deque<StackTraceElement[]> mBinderStack = new ArrayDeque<>();
2848
2849 /** Memoized stack trace of full violation. */
2850 @Nullable private String mStackTrace;
2851
2852 /** The strict mode penalty mask at the time of violation. */
2853 private final int mPenaltyMask;
2854
2855 /** The wall time duration of the violation, when known. -1 when not known. */
2856 public int durationMillis = -1;
2857
2858 /** The number of animations currently running. */
2859 public int numAnimationsRunning = 0;
2860
2861 /** List of tags from active Span instances during this violation, or null for none. */
2862 public String[] tags;
2863
2864 /**
2865 * Which violation number this was (1-based) since the last Looper loop, from the
2866 * perspective of the root caller (if it crossed any processes via Binder calls). The value
2867 * is 0 if the root caller wasn't on a Looper thread.
2868 */
2869 public int violationNumThisLoop;
2870
2871 /** The time (in terms of SystemClock.uptimeMillis()) that the violation occurred. */
2872 public long violationUptimeMillis;
2873
2874 /**
2875 * The action of the Intent being broadcast to somebody's onReceive on this thread right
2876 * now, or null.
2877 */
2878 public String broadcastIntentAction;
2879
2880 /** If this is a instance count violation, the number of instances in memory, else -1. */
2881 public long numInstances = -1;
2882
2883 /** Create an instance of ViolationInfo initialized from an exception. */
2884 ViolationInfo(Violation tr, int penaltyMask) {
2885 this.mViolation = tr;
2886 this.mPenaltyMask = penaltyMask;
2887 violationUptimeMillis = SystemClock.uptimeMillis();
2888 this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
2889 Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
2890 if (broadcastIntent != null) {
2891 broadcastIntentAction = broadcastIntent.getAction();
2892 }
2893 ThreadSpanState state = sThisThreadSpanState.get();
2894 if (tr instanceof InstanceCountViolation) {
2895 this.numInstances = ((InstanceCountViolation) tr).getNumberOfInstances();
2896 }
2897 synchronized (state) {
2898 int spanActiveCount = state.mActiveSize;
2899 if (spanActiveCount > MAX_SPAN_TAGS) {
2900 spanActiveCount = MAX_SPAN_TAGS;
2901 }
2902 if (spanActiveCount != 0) {
2903 this.tags = new String[spanActiveCount];
2904 Span iter = state.mActiveHead;
2905 int index = 0;
2906 while (iter != null && index < spanActiveCount) {
2907 this.tags[index] = iter.mName;
2908 index++;
2909 iter = iter.mNext;
2910 }
2911 }
2912 }
2913 }
2914
2915 /**
2916 * Equivalent output to
2917 * {@link android.app.ApplicationErrorReport.CrashInfo#stackTrace}.
2918 */
2919 public String getStackTrace() {
2920 if (mStackTrace == null) {
2921 StringWriter sw = new StringWriter();
2922 PrintWriter pw = new FastPrintWriter(sw, false, 256);
2923 mViolation.printStackTrace(pw);
2924 for (StackTraceElement[] traces : mBinderStack) {
2925 pw.append("# via Binder call with stack:\n");
2926 for (StackTraceElement traceElement : traces) {
2927 pw.append("\tat ");
2928 pw.append(traceElement.toString());
2929 pw.append('\n');
2930 }
2931 }
2932 pw.flush();
2933 pw.close();
2934 mStackTrace = sw.toString();
2935 }
2936 return mStackTrace;
2937 }
2938
2939 public Class<? extends Violation> getViolationClass() {
2940 return mViolation.getClass();
2941 }
2942
2943 /**
2944 * Optional message describing this violation.
2945 *
2946 * @hide
2947 */
2948 @TestApi
2949 public String getViolationDetails() {
2950 return mViolation.getMessage();
2951 }
2952
2953 boolean penaltyEnabled(int p) {
2954 return (mPenaltyMask & p) != 0;
2955 }
2956
2957 /**
2958 * Add a {@link Throwable} from the current process that caused the underlying violation. We
2959 * only preserve the stack trace elements.
2960 *
2961 * @hide
2962 */
2963 void addLocalStack(Throwable t) {
2964 mBinderStack.addFirst(t.getStackTrace());
2965 }
2966
2967 @Override
2968 public int hashCode() {
2969 int result = 17;
2970 if (mViolation != null) {
2971 result = 37 * result + mViolation.hashCode();
2972 }
2973 if (numAnimationsRunning != 0) {
2974 result *= 37;
2975 }
2976 if (broadcastIntentAction != null) {
2977 result = 37 * result + broadcastIntentAction.hashCode();
2978 }
2979 if (tags != null) {
2980 for (String tag : tags) {
2981 result = 37 * result + tag.hashCode();
2982 }
2983 }
2984 return result;
2985 }
2986
2987 /** Create an instance of ViolationInfo initialized from a Parcel. */
2988 @UnsupportedAppUsage
2989 public ViolationInfo(Parcel in) {
2990 this(in, false);
2991 }
2992
2993 /**
2994 * Create an instance of ViolationInfo initialized from a Parcel.
2995 *
2996 * @param unsetGatheringBit if true, the caller is the root caller and the gathering penalty
2997 * should be removed.
2998 */
2999 public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
3000 mViolation = (Violation) in.readSerializable(android.os.strictmode.Violation.class.getClassLoader(), android.os.strictmode.Violation.class);
3001 int binderStackSize = in.readInt();
3002 for (int i = 0; i < binderStackSize; i++) {
3003 StackTraceElement[] traceElements = new StackTraceElement[in.readInt()];
3004 for (int j = 0; j < traceElements.length; j++) {
3005 StackTraceElement element =
3006 new StackTraceElement(
3007 in.readString(),
3008 in.readString(),
3009 in.readString(),
3010 in.readInt());
3011 traceElements[j] = element;
3012 }
3013 mBinderStack.add(traceElements);
3014 }
3015 int rawPenaltyMask = in.readInt();
3016 if (unsetGatheringBit) {
3017 mPenaltyMask = rawPenaltyMask & ~PENALTY_GATHER;
3018 } else {
3019 mPenaltyMask = rawPenaltyMask;
3020 }
3021 durationMillis = in.readInt();
3022 violationNumThisLoop = in.readInt();
3023 numAnimationsRunning = in.readInt();
3024 violationUptimeMillis = in.readLong();
3025 numInstances = in.readLong();
3026 broadcastIntentAction = in.readString();
3027 tags = in.readStringArray();
3028 }
3029
3030 /** Save a ViolationInfo instance to a parcel. */
3031 @Override
3032 public void writeToParcel(Parcel dest, int flags) {
3033 dest.writeSerializable(mViolation);
3034 dest.writeInt(mBinderStack.size());
3035 for (StackTraceElement[] traceElements : mBinderStack) {
3036 dest.writeInt(traceElements.length);
3037 for (StackTraceElement element : traceElements) {
3038 dest.writeString(element.getClassName());
3039 dest.writeString(element.getMethodName());
3040 dest.writeString(element.getFileName());
3041 dest.writeInt(element.getLineNumber());
3042 }
3043 }
3044 int start = dest.dataPosition();
3045 dest.writeInt(mPenaltyMask);
3046 dest.writeInt(durationMillis);
3047 dest.writeInt(violationNumThisLoop);
3048 dest.writeInt(numAnimationsRunning);
3049 dest.writeLong(violationUptimeMillis);
3050 dest.writeLong(numInstances);
3051 dest.writeString(broadcastIntentAction);
3052 dest.writeStringArray(tags);
3053 int total = dest.dataPosition() - start;
3054 if (Binder.CHECK_PARCEL_SIZE && total > 10 * 1024) {
3055 Slog.d(
3056 TAG,
3057 "VIO: penalty="
3058 + mPenaltyMask
3059 + " dur="
3060 + durationMillis
3061 + " numLoop="
3062 + violationNumThisLoop
3063 + " anim="
3064 + numAnimationsRunning
3065 + " uptime="
3066 + violationUptimeMillis
3067 + " numInst="
3068 + numInstances);
3069 Slog.d(TAG, "VIO: action=" + broadcastIntentAction);
3070 Slog.d(TAG, "VIO: tags=" + Arrays.toString(tags));
3071 Slog.d(TAG, "VIO: TOTAL BYTES WRITTEN: " + (dest.dataPosition() - start));
3072 }
3073 }
3074
3075 /** Dump a ViolationInfo instance to a Printer. */
3076 public void dump(Printer pw, String prefix) {
3077 pw.println(prefix + "stackTrace: " + getStackTrace());
3078 pw.println(prefix + "penalty: " + mPenaltyMask);
3079 if (durationMillis != -1) {
3080 pw.println(prefix + "durationMillis: " + durationMillis);
3081 }
3082 if (numInstances != -1) {
3083 pw.println(prefix + "numInstances: " + numInstances);
3084 }
3085 if (violationNumThisLoop != 0) {
3086 pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
3087 }
3088 if (numAnimationsRunning != 0) {
3089 pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
3090 }
3091 pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
3092 if (broadcastIntentAction != null) {
3093 pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
3094 }
3095 if (tags != null) {
3096 int index = 0;
3097 for (String tag : tags) {
3098 pw.println(prefix + "tag[" + (index++) + "]: " + tag);
3099 }
3100 }
3101 }
3102
3103 @Override
3104 public int describeContents() {
3105 return 0;
3106 }
3107
3108 public static final @android.annotation.NonNull Parcelable.Creator<ViolationInfo> CREATOR =
3109 new Parcelable.Creator<ViolationInfo>() {
3110 @Override
3111 public ViolationInfo createFromParcel(Parcel in) {
3112 return new ViolationInfo(in);
3113 }
3114
3115 @Override
3116 public ViolationInfo[] newArray(int size) {
3117 return new ViolationInfo[size];
3118 }
3119 };
3120 }
3121
3122 private static final class InstanceTracker {
3123 private static final HashMap<Class<?>, Integer> sInstanceCounts =
3124 new HashMap<Class<?>, Integer>();
3125
3126 private final Class<?> mKlass;
3127
3128 public InstanceTracker(Object instance) {
3129 mKlass = instance.getClass();
3130
3131 synchronized (sInstanceCounts) {
3132 final Integer value = sInstanceCounts.get(mKlass);
3133 final int newValue = value != null ? value + 1 : 1;
3134 sInstanceCounts.put(mKlass, newValue);
3135 }
3136 }
3137
3138 @Override
3139 protected void finalize() throws Throwable {
3140 try {
3141 synchronized (sInstanceCounts) {
3142 final Integer value = sInstanceCounts.get(mKlass);
3143 if (value != null) {
3144 final int newValue = value - 1;
3145 if (newValue > 0) {
3146 sInstanceCounts.put(mKlass, newValue);
3147 } else {
3148 sInstanceCounts.remove(mKlass);
3149 }
3150 }
3151 }
3152 } finally {
3153 super.finalize();
3154 }
3155 }
3156
3157 public static int getInstanceCount(Class<?> klass) {
3158 synchronized (sInstanceCounts) {
3159 final Integer value = sInstanceCounts.get(klass);
3160 return value != null ? value : 0;
3161 }
3162 }
3163 }
3164 }