blob: 772845d4e68370ff434e0407c2e0530c2a31e7cd [file] [log] [blame]
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001/*
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 */
16package android.os;
17
Brad Fitzpatrick599ca292010-10-22 14:47:03 -070018import android.animation.ValueAnimator;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -060019import android.annotation.IntDef;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -070020import android.annotation.NonNull;
Kurt Nelson7d5c07a2017-09-07 16:43:45 -070021import android.annotation.Nullable;
Jeff Sharkeyddc3bfd2017-06-26 19:38:56 -060022import android.annotation.TestApi;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -070023import android.app.ActivityManager;
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -070024import android.app.ActivityThread;
Brad Fitzpatrick10656852010-11-23 19:01:13 -080025import android.app.IActivityManager;
Artur Satayevafdb23a2019-12-10 17:47:53 +000026import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080027import android.content.BroadcastReceiver;
28import android.content.Context;
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -070029import android.content.Intent;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080030import android.content.ServiceConnection;
Jeff Sharkey89182982017-11-01 19:02:56 -060031import android.content.pm.ApplicationInfo;
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -060032import android.content.pm.PackageManager;
Jeff Sharkey619a5112017-01-19 11:55:54 -070033import android.net.TrafficStats;
Jeff Sharkey344744b2016-01-28 19:03:30 -070034import android.net.Uri;
Jeff Sharkeydd02e332018-06-27 14:41:57 -060035import android.os.storage.IStorageManager;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070036import android.os.strictmode.CleartextNetworkViolation;
37import android.os.strictmode.ContentUriWithoutPermissionViolation;
Jeff Sharkeydd02e332018-06-27 14:41:57 -060038import android.os.strictmode.CredentialProtectedWhileLockedViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070039import android.os.strictmode.CustomViolation;
40import android.os.strictmode.DiskReadViolation;
41import android.os.strictmode.DiskWriteViolation;
Pete Gillin22316b42018-02-15 17:17:27 +000042import android.os.strictmode.ExplicitGcViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070043import android.os.strictmode.FileUriExposedViolation;
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -060044import android.os.strictmode.ImplicitDirectBootViolation;
Andrii Kulian5877c7d2020-01-29 16:57:32 -080045import android.os.strictmode.IncorrectContextUseViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070046import android.os.strictmode.InstanceCountViolation;
47import android.os.strictmode.IntentReceiverLeakedViolation;
48import android.os.strictmode.LeakedClosableViolation;
49import android.os.strictmode.NetworkViolation;
Narayan Kamathad1b2a92018-03-28 11:29:40 +010050import android.os.strictmode.NonSdkApiUsedViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070051import android.os.strictmode.ResourceMismatchViolation;
52import android.os.strictmode.ServiceConnectionLeakedViolation;
53import android.os.strictmode.SqliteObjectLeakedViolation;
Kurt Nelson0e612802017-11-09 17:25:40 -080054import android.os.strictmode.UnbufferedIoViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070055import android.os.strictmode.UntaggedSocketViolation;
56import android.os.strictmode.Violation;
57import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation;
Dianne Hackborn390517b2013-05-30 15:03:32 -070058import android.util.ArrayMap;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070059import android.util.Log;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -070060import android.util.Printer;
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -080061import android.util.Singleton;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070062import android.util.Slog;
Brad Fitzpatrick68044332010-11-22 18:19:48 -080063import android.view.IWindowManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070064
Kurt Nelson1981f422017-10-25 13:49:26 -070065import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -070066import com.android.internal.os.BackgroundThread;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070067import com.android.internal.os.RuntimeInit;
Dianne Hackborn8c841092013-06-24 13:46:13 -070068import com.android.internal.util.FastPrintWriter;
Jeff Sharkey605eb792014-11-04 13:34:06 -080069import com.android.internal.util.HexDump;
70
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070071import dalvik.system.BlockGuard;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -070072import dalvik.system.CloseGuard;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -080073import dalvik.system.VMDebug;
Jeff Sharkey0b558702017-01-26 16:48:01 -070074import dalvik.system.VMRuntime;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070075
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070076import java.io.PrintWriter;
77import java.io.StringWriter;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -060078import java.lang.annotation.Retention;
79import java.lang.annotation.RetentionPolicy;
Jeff Sharkey605eb792014-11-04 13:34:06 -080080import java.net.InetAddress;
81import java.net.UnknownHostException;
Kurt Nelson0918c932017-09-07 10:56:56 -070082import java.util.ArrayDeque;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070083import java.util.ArrayList;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070084import java.util.Arrays;
Kurt Nelson0918c932017-09-07 10:56:56 -070085import java.util.Deque;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070086import java.util.HashMap;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -070087import java.util.concurrent.Executor;
88import java.util.concurrent.RejectedExecutionException;
Brad Fitzpatrickbee24872010-11-20 12:09:10 -080089import java.util.concurrent.atomic.AtomicInteger;
Narayan Kamathad1b2a92018-03-28 11:29:40 +010090import java.util.function.Consumer;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070091
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070092/**
Kurt Nelson46974a22017-08-30 13:30:26 -070093 * StrictMode is a developer tool which detects things you might be doing by accident and brings
94 * them to your attention so you can fix them.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -070095 *
Kurt Nelson46974a22017-08-30 13:30:26 -070096 * <p>StrictMode is most commonly used to catch accidental disk or network access on the
97 * application's main thread, where UI operations are received and animations take place. Keeping
98 * disk and network operations off the main thread makes for much smoother, more responsive
99 * applications. By keeping your application's main thread responsive, you also prevent <a
100 * href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a> from being shown to
101 * users.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700102 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700103 * <p class="note">Note that even though an Android device's disk is often on flash memory, many
104 * devices run a filesystem on top of that memory with very limited concurrency. It's often the case
105 * that almost all disk accesses are fast, but may in individual cases be dramatically slower when
106 * certain I/O is happening in the background from other processes. If possible, it's best to assume
107 * that such things are not fast.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700108 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700109 * <p>Example code to enable from early in your {@link android.app.Application}, {@link
110 * android.app.Activity}, or other application component's {@link android.app.Application#onCreate}
111 * method:
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700112 *
113 * <pre>
114 * public void onCreate() {
115 * if (DEVELOPER_MODE) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700116 * StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
117 * .detectDiskReads()
118 * .detectDiskWrites()
119 * .detectNetwork() // or .detectAll() for all detectable problems
120 * .penaltyLog()
121 * .build());
122 * StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -0700123 * .detectLeakedSqlLiteObjects()
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700124 * .detectLeakedClosableObjects()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700125 * .penaltyLog()
126 * .penaltyDeath()
127 * .build());
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700128 * }
129 * super.onCreate();
130 * }
131 * </pre>
132 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700133 * <p>You can decide what should happen when a violation is detected. For example, using {@link
134 * ThreadPolicy.Builder#penaltyLog} you can watch the output of <code>adb logcat</code> while you
135 * use your application to see the violations as they happen.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700136 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700137 * <p>If you find violations that you feel are problematic, there are a variety of tools to help
138 * solve them: threads, {@link android.os.Handler}, {@link android.os.AsyncTask}, {@link
139 * android.app.IntentService}, etc. But don't feel compelled to fix everything that StrictMode
140 * finds. In particular, many cases of disk access are often necessary during the normal activity
141 * lifecycle. Use StrictMode to find things you did by accident. Network requests on the UI thread
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700142 * are almost always a problem, though.
143 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700144 * <p class="note">StrictMode is not a security mechanism and is not guaranteed to find all disk or
145 * network accesses. While it does propagate its state across process boundaries when doing {@link
146 * android.os.Binder} calls, it's still ultimately a best effort mechanism. Notably, disk or network
147 * access from JNI calls won't necessarily trigger it. Future versions of Android may catch more (or
148 * fewer) operations, so you should never leave StrictMode enabled in applications distributed on
149 * Google Play.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700150 */
151public final class StrictMode {
152 private static final String TAG = "StrictMode";
Brad Fitzpatrick82829ef2010-11-18 18:25:08 -0800153 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700154
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800155 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700156 * Boolean system property to disable strict mode checks outright. Set this to 'true' to force
157 * disable; 'false' has no effect on other enable/disable policy.
158 *
Christopher Tatebc6f0ce2011-11-03 12:18:43 -0700159 * @hide
160 */
161 public static final String DISABLE_PROPERTY = "persist.sys.strictmode.disable";
162
163 /**
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800164 * The boolean system property to control screen flashes on violations.
165 *
166 * @hide
167 */
168 public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
169
Jeff Sharkey605eb792014-11-04 13:34:06 -0800170 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700171 * Temporary property used to include {@link #DETECT_VM_CLEARTEXT_NETWORK} in {@link
172 * VmPolicy.Builder#detectAll()}. Apps can still always opt-into detection using {@link
173 * VmPolicy.Builder#detectCleartextNetwork()}.
Jeff Sharkey605eb792014-11-04 13:34:06 -0800174 */
Jeff Sharkey2e571642015-01-22 11:51:43 -0700175 private static final String CLEARTEXT_PROPERTY = "persist.sys.strictmode.clear";
Jeff Sharkey605eb792014-11-04 13:34:06 -0800176
Jeff Sharkey89182982017-11-01 19:02:56 -0600177 /**
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700178 * Quick feature-flag that can be used to disable the defaults provided by {@link
179 * #initThreadDefaults(ApplicationInfo)} and {@link #initVmDefaults(ApplicationInfo)}.
Jeff Sharkey89182982017-11-01 19:02:56 -0600180 */
Jeff Sharkey617e1132017-11-03 17:28:45 -0600181 private static final boolean DISABLE = false;
Jeff Sharkey89182982017-11-01 19:02:56 -0600182
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700183 // Only apply VM penalties for the same violation at this interval.
184 private static final long MIN_VM_INTERVAL_MS = 1000;
185
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700186 // Only log a duplicate stack trace to the logs every second.
187 private static final long MIN_LOG_INTERVAL_MS = 1000;
188
189 // Only show an annoying dialog at most every 30 seconds
190 private static final long MIN_DIALOG_INTERVAL_MS = 30000;
191
Brad Fitzpatricke7520d82010-11-10 18:08:36 -0800192 // How many Span tags (e.g. animations) to report.
193 private static final int MAX_SPAN_TAGS = 20;
194
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -0700195 // How many offending stacks to keep track of (and time) per loop
196 // of the Looper.
197 private static final int MAX_OFFENSES_PER_LOOP = 10;
198
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600199 /** @hide */
200 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
201 DETECT_THREAD_DISK_WRITE,
202 DETECT_THREAD_DISK_READ,
203 DETECT_THREAD_NETWORK,
204 DETECT_THREAD_CUSTOM,
205 DETECT_THREAD_RESOURCE_MISMATCH,
206 DETECT_THREAD_UNBUFFERED_IO,
207 DETECT_THREAD_EXPLICIT_GC,
208 PENALTY_GATHER,
209 PENALTY_LOG,
210 PENALTY_DIALOG,
211 PENALTY_DEATH,
212 PENALTY_FLASH,
213 PENALTY_DROPBOX,
214 PENALTY_DEATH_ON_NETWORK,
215 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
216 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
217 })
218 @Retention(RetentionPolicy.SOURCE)
219 public @interface ThreadPolicyMask {}
220
221 // Thread policy: bits 0-15
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700222
Kurt Nelson46974a22017-08-30 13:30:26 -0700223 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600224 private static final int DETECT_THREAD_DISK_WRITE = 1 << 0;
Kurt Nelson46974a22017-08-30 13:30:26 -0700225 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600226 private static final int DETECT_THREAD_DISK_READ = 1 << 1;
Kurt Nelson46974a22017-08-30 13:30:26 -0700227 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600228 private static final int DETECT_THREAD_NETWORK = 1 << 2;
Kurt Nelson46974a22017-08-30 13:30:26 -0700229 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600230 private static final int DETECT_THREAD_CUSTOM = 1 << 3;
231 /** @hide */
232 private static final int DETECT_THREAD_RESOURCE_MISMATCH = 1 << 4;
233 /** @hide */
234 private static final int DETECT_THREAD_UNBUFFERED_IO = 1 << 5;
Pete Gillin22316b42018-02-15 17:17:27 +0000235 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600236 private static final int DETECT_THREAD_EXPLICIT_GC = 1 << 6;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700237
Kurt Nelson46974a22017-08-30 13:30:26 -0700238 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600239 private static final int DETECT_THREAD_ALL = 0x0000ffff;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800240
Kurt Nelson46974a22017-08-30 13:30:26 -0700241 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600242 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
243 DETECT_VM_CURSOR_LEAKS,
244 DETECT_VM_CLOSABLE_LEAKS,
245 DETECT_VM_ACTIVITY_LEAKS,
246 DETECT_VM_INSTANCE_LEAKS,
247 DETECT_VM_REGISTRATION_LEAKS,
248 DETECT_VM_FILE_URI_EXPOSURE,
249 DETECT_VM_CLEARTEXT_NETWORK,
250 DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION,
251 DETECT_VM_UNTAGGED_SOCKET,
252 DETECT_VM_NON_SDK_API_USAGE,
253 DETECT_VM_IMPLICIT_DIRECT_BOOT,
Andrii Kulian5877c7d2020-01-29 16:57:32 -0800254 DETECT_VM_INCORRECT_CONTEXT_USE,
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600255 PENALTY_GATHER,
256 PENALTY_LOG,
257 PENALTY_DIALOG,
258 PENALTY_DEATH,
259 PENALTY_FLASH,
260 PENALTY_DROPBOX,
261 PENALTY_DEATH_ON_NETWORK,
262 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
263 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
264 })
265 @Retention(RetentionPolicy.SOURCE)
266 public @interface VmPolicyMask {}
267
268 // VM policy: bits 0-15
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800269
Kurt Nelson46974a22017-08-30 13:30:26 -0700270 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600271 private static final int DETECT_VM_CURSOR_LEAKS = 1 << 0;
272 /** @hide */
273 private static final int DETECT_VM_CLOSABLE_LEAKS = 1 << 1;
274 /** @hide */
275 private static final int DETECT_VM_ACTIVITY_LEAKS = 1 << 2;
276 /** @hide */
277 private static final int DETECT_VM_INSTANCE_LEAKS = 1 << 3;
278 /** @hide */
279 private static final int DETECT_VM_REGISTRATION_LEAKS = 1 << 4;
280 /** @hide */
281 private static final int DETECT_VM_FILE_URI_EXPOSURE = 1 << 5;
282 /** @hide */
283 private static final int DETECT_VM_CLEARTEXT_NETWORK = 1 << 6;
284 /** @hide */
285 private static final int DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION = 1 << 7;
286 /** @hide */
287 private static final int DETECT_VM_UNTAGGED_SOCKET = 1 << 8;
288 /** @hide */
289 private static final int DETECT_VM_NON_SDK_API_USAGE = 1 << 9;
290 /** @hide */
291 private static final int DETECT_VM_IMPLICIT_DIRECT_BOOT = 1 << 10;
Jeff Sharkeydd02e332018-06-27 14:41:57 -0600292 /** @hide */
293 private static final int DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED = 1 << 11;
Andrii Kulian5877c7d2020-01-29 16:57:32 -0800294 /** @hide */
295 private static final int DETECT_VM_INCORRECT_CONTEXT_USE = 1 << 12;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800296
Kurt Nelson46974a22017-08-30 13:30:26 -0700297 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600298 private static final int DETECT_VM_ALL = 0x0000ffff;
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700299
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600300 // Penalty policy: bits 16-31
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700301
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700302 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700303 * Non-public penalty mode which overrides all the other penalty bits and signals that we're in
304 * a Binder call and we should ignore the other penalty bits and instead serialize back all our
305 * offending stack traces to the caller to ultimately handle in the originating process.
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700306 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700307 * <p>This must be kept in sync with the constant in libs/binder/Parcel.cpp
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -0700308 *
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700309 * @hide
310 */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600311 public static final int PENALTY_GATHER = 1 << 31;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800312
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600313 /** {@hide} */
314 public static final int PENALTY_LOG = 1 << 30;
315 /** {@hide} */
316 public static final int PENALTY_DIALOG = 1 << 29;
317 /** {@hide} */
318 public static final int PENALTY_DEATH = 1 << 28;
319 /** {@hide} */
320 public static final int PENALTY_FLASH = 1 << 27;
321 /** {@hide} */
322 public static final int PENALTY_DROPBOX = 1 << 26;
323 /** {@hide} */
324 public static final int PENALTY_DEATH_ON_NETWORK = 1 << 25;
325 /** {@hide} */
326 public static final int PENALTY_DEATH_ON_CLEARTEXT_NETWORK = 1 << 24;
327 /** {@hide} */
328 public static final int PENALTY_DEATH_ON_FILE_URI_EXPOSURE = 1 << 23;
Jeff Sharkey344744b2016-01-28 19:03:30 -0700329
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600330 /** @hide */
331 public static final int PENALTY_ALL = 0xffff0000;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800332
Jeff Sharkey605eb792014-11-04 13:34:06 -0800333 /** {@hide} */
334 public static final int NETWORK_POLICY_ACCEPT = 0;
335 /** {@hide} */
336 public static final int NETWORK_POLICY_LOG = 1;
337 /** {@hide} */
338 public static final int NETWORK_POLICY_REJECT = 2;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800339
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800340 // TODO: wrap in some ImmutableHashMap thing.
341 // Note: must be before static initialization of sVmPolicy.
Kurt Nelson46974a22017-08-30 13:30:26 -0700342 private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP =
343 new HashMap<Class, Integer>();
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800344
Kurt Nelson2c883f32017-09-01 10:52:45 -0700345 /** The current VmPolicy in effect. */
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800346 private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700347
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600348 /** {@hide} */
Jeff Sharkeyddc3bfd2017-06-26 19:38:56 -0600349 @TestApi
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700350 public interface ViolationLogger {
351
352 /** Called when penaltyLog is enabled and a violation needs logging. */
353 void log(ViolationInfo info);
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600354 }
355
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700356 private static final ViolationLogger LOGCAT_LOGGER =
357 info -> {
358 String msg;
359 if (info.durationMillis != -1) {
360 msg = "StrictMode policy violation; ~duration=" + info.durationMillis + " ms:";
361 } else {
362 msg = "StrictMode policy violation:";
363 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -0700364 Log.d(TAG, msg + " " + info.getStackTrace());
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700365 };
366
367 private static volatile ViolationLogger sLogger = LOGCAT_LOGGER;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600368
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700369 private static final ThreadLocal<OnThreadViolationListener> sThreadViolationListener =
370 new ThreadLocal<>();
371 private static final ThreadLocal<Executor> sThreadViolationExecutor = new ThreadLocal<>();
372
373 /**
374 * When #{@link ThreadPolicy.Builder#penaltyListener} is enabled, the listener is called on the
375 * provided executor when a Thread violation occurs.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700376 */
377 public interface OnThreadViolationListener {
378 /** Called on a thread policy violation. */
379 void onThreadViolation(Violation v);
380 }
381
382 /**
383 * When #{@link VmPolicy.Builder#penaltyListener} is enabled, the listener is called on the
384 * provided executor when a VM violation occurs.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700385 */
386 public interface OnVmViolationListener {
387 /** Called on a VM policy violation. */
388 void onVmViolation(Violation v);
389 }
390
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600391 /** {@hide} */
Jeff Sharkeyddc3bfd2017-06-26 19:38:56 -0600392 @TestApi
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700393 public static void setViolationLogger(ViolationLogger listener) {
394 if (listener == null) {
395 listener = LOGCAT_LOGGER;
396 }
397 sLogger = listener;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600398 }
399
Brad Fitzpatrickbee24872010-11-20 12:09:10 -0800400 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700401 * The number of threads trying to do an async dropbox write. Just to limit ourselves out of
402 * paranoia.
Brad Fitzpatrickbee24872010-11-20 12:09:10 -0800403 */
404 private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
405
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100406 /**
407 * Callback supplied to dalvik / libcore to get informed of usages of java API that are not
408 * a part of the public SDK.
409 */
410 private static final Consumer<String> sNonSdkApiUsageConsumer =
411 message -> onVmPolicyViolation(new NonSdkApiUsedViolation(message));
412
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700413 private StrictMode() {}
414
415 /**
416 * {@link StrictMode} policy applied to a certain thread.
417 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700418 * <p>The policy is enabled by {@link #setThreadPolicy}. The current policy can be retrieved
419 * with {@link #getThreadPolicy}.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700420 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700421 * <p>Note that multiple penalties may be provided and they're run in order from least to most
422 * severe (logging before process death, for example). There's currently no mechanism to choose
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700423 * different penalties for different detected actions.
424 */
425 public static final class ThreadPolicy {
Kurt Nelson46974a22017-08-30 13:30:26 -0700426 /** The default, lax policy which doesn't catch anything. */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700427 public static final ThreadPolicy LAX = new ThreadPolicy(0, null, null);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700428
Andrei Onea24ec3212019-03-15 17:35:05 +0000429 @UnsupportedAppUsage
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600430 final @ThreadPolicyMask int mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700431 final OnThreadViolationListener mListener;
432 final Executor mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700433
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600434 private ThreadPolicy(@ThreadPolicyMask int mask, OnThreadViolationListener listener,
435 Executor executor) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700436 this.mask = mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700437 mListener = listener;
438 mCallbackExecutor = executor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700439 }
440
441 @Override
442 public String toString() {
443 return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
444 }
445
446 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700447 * Creates {@link ThreadPolicy} instances. Methods whose names start with {@code detect}
448 * specify what problems we should look for. Methods whose names start with {@code penalty}
449 * specify what we should do when we detect a problem.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700450 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700451 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
452 * order is insignificant: all penalties apply to all detected problems.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700453 *
454 * <p>For example, detect everything and log anything that's found:
Kurt Nelson46974a22017-08-30 13:30:26 -0700455 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700456 * <pre>
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800457 * StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700458 * .detectAll()
459 * .penaltyLog()
460 * .build();
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800461 * StrictMode.setThreadPolicy(policy);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700462 * </pre>
463 */
464 public static final class Builder {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600465 private @ThreadPolicyMask int mMask = 0;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700466 private OnThreadViolationListener mListener;
467 private Executor mExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700468
469 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700470 * Create a Builder that detects nothing and has no violations. (but note that {@link
471 * #build} will default to enabling {@link #penaltyLog} if no other penalties are
472 * specified)
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700473 */
474 public Builder() {
475 mMask = 0;
476 }
477
Kurt Nelson46974a22017-08-30 13:30:26 -0700478 /** Initialize a Builder from an existing ThreadPolicy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700479 public Builder(ThreadPolicy policy) {
480 mMask = policy.mask;
Kurt Nelson7a8804a2018-02-27 16:45:27 -0800481 mListener = policy.mListener;
482 mExecutor = policy.mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700483 }
484
485 /**
486 * Detect everything that's potentially suspect.
487 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700488 * <p>As of the Gingerbread release this includes network and disk operations but will
489 * likely expand in future releases.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700490 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700491 public @NonNull Builder detectAll() {
Jeff Sharkey0b558702017-01-26 16:48:01 -0700492 detectDiskReads();
493 detectDiskWrites();
494 detectNetwork();
495
496 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
497 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
498 detectCustomSlowCalls();
499 }
500 if (targetSdk >= Build.VERSION_CODES.M) {
501 detectResourceMismatches();
502 }
503 if (targetSdk >= Build.VERSION_CODES.O) {
504 detectUnbufferedIo();
505 }
506 return this;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700507 }
508
Kurt Nelson46974a22017-08-30 13:30:26 -0700509 /** Disable the detection of everything. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700510 public @NonNull Builder permitAll() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600511 return disable(DETECT_THREAD_ALL);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700512 }
513
Kurt Nelson46974a22017-08-30 13:30:26 -0700514 /** Enable detection of network operations. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700515 public @NonNull Builder detectNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600516 return enable(DETECT_THREAD_NETWORK);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700517 }
518
Kurt Nelson46974a22017-08-30 13:30:26 -0700519 /** Disable detection of network operations. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700520 public @NonNull Builder permitNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600521 return disable(DETECT_THREAD_NETWORK);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700522 }
523
Kurt Nelson46974a22017-08-30 13:30:26 -0700524 /** Enable detection of disk reads. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700525 public @NonNull Builder detectDiskReads() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600526 return enable(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700527 }
528
Kurt Nelson46974a22017-08-30 13:30:26 -0700529 /** Disable detection of disk reads. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700530 public @NonNull Builder permitDiskReads() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600531 return disable(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700532 }
533
Kurt Nelson46974a22017-08-30 13:30:26 -0700534 /** Enable detection of slow calls. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700535 public @NonNull Builder detectCustomSlowCalls() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600536 return enable(DETECT_THREAD_CUSTOM);
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800537 }
538
Kurt Nelson46974a22017-08-30 13:30:26 -0700539 /** Disable detection of slow calls. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700540 public @NonNull Builder permitCustomSlowCalls() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600541 return disable(DETECT_THREAD_CUSTOM);
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800542 }
543
Kurt Nelson46974a22017-08-30 13:30:26 -0700544 /** Disable detection of mismatches between defined resource types and getter calls. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700545 public @NonNull Builder permitResourceMismatches() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600546 return disable(DETECT_THREAD_RESOURCE_MISMATCH);
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800547 }
548
Kurt Nelson46974a22017-08-30 13:30:26 -0700549 /** Detect unbuffered input/output operations. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700550 public @NonNull Builder detectUnbufferedIo() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600551 return enable(DETECT_THREAD_UNBUFFERED_IO);
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100552 }
553
Kurt Nelson46974a22017-08-30 13:30:26 -0700554 /** Disable detection of unbuffered input/output operations. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700555 public @NonNull Builder permitUnbufferedIo() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600556 return disable(DETECT_THREAD_UNBUFFERED_IO);
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100557 }
558
559 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700560 * Enables detection of mismatches between defined resource types and getter calls.
561 *
562 * <p>This helps detect accidental type mismatches and potentially expensive type
563 * conversions when obtaining typed resources.
564 *
565 * <p>For example, a strict mode violation would be thrown when calling {@link
566 * android.content.res.TypedArray#getInt(int, int)} on an index that contains a
567 * String-type resource. If the string value can be parsed as an integer, this method
568 * call will return a value without crashing; however, the developer should format the
569 * resource as an integer to avoid unnecessary type conversion.
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800570 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700571 public @NonNull Builder detectResourceMismatches() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600572 return enable(DETECT_THREAD_RESOURCE_MISMATCH);
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800573 }
574
Kurt Nelson46974a22017-08-30 13:30:26 -0700575 /** Enable detection of disk writes. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700576 public @NonNull Builder detectDiskWrites() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600577 return enable(DETECT_THREAD_DISK_WRITE);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700578 }
579
Kurt Nelson46974a22017-08-30 13:30:26 -0700580 /** Disable detection of disk writes. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700581 public @NonNull Builder permitDiskWrites() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600582 return disable(DETECT_THREAD_DISK_WRITE);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700583 }
584
585 /**
Pete Gillin22316b42018-02-15 17:17:27 +0000586 * Detect explicit GC requests, i.e. calls to Runtime.gc().
587 *
588 * @hide
589 */
Jeff Sharkeyc6091162018-06-29 17:15:40 -0600590 @TestApi
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700591 public @NonNull Builder detectExplicitGc() {
Pete Gillin22316b42018-02-15 17:17:27 +0000592 // TODO(b/3400644): Un-hide this for next API update
593 // TODO(b/3400644): Un-hide ExplicitGcViolation for next API update
594 // TODO(b/3400644): Make DETECT_EXPLICIT_GC a @TestApi for next API update
595 // TODO(b/3400644): Call this from detectAll in next API update
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600596 return enable(DETECT_THREAD_EXPLICIT_GC);
Pete Gillin22316b42018-02-15 17:17:27 +0000597 }
598
599 /**
600 * Disable detection of explicit GC requests, i.e. calls to Runtime.gc().
601 *
602 * @hide
603 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700604 public @NonNull Builder permitExplicitGc() {
Pete Gillin22316b42018-02-15 17:17:27 +0000605 // TODO(b/3400644): Un-hide this for next API update
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600606 return disable(DETECT_THREAD_EXPLICIT_GC);
Pete Gillin22316b42018-02-15 17:17:27 +0000607 }
608
609 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700610 * Show an annoying dialog to the developer on detected violations, rate-limited to be
611 * only a little annoying.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700612 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700613 public @NonNull Builder penaltyDialog() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700614 return enable(PENALTY_DIALOG);
615 }
616
617 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700618 * Crash the whole process on violation. This penalty runs at the end of all enabled
619 * penalties so you'll still get see logging or other violations before the process
620 * dies.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700621 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700622 * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies to disk reads, disk writes,
623 * and network usage if their corresponding detect flags are set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700624 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700625 public @NonNull Builder penaltyDeath() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700626 return enable(PENALTY_DEATH);
627 }
628
629 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700630 * Crash the whole process on any network usage. Unlike {@link #penaltyDeath}, this
631 * penalty runs <em>before</em> anything else. You must still have called {@link
632 * #detectNetwork} to enable this.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700633 *
634 * <p>In the Honeycomb or later SDKs, this is on by default.
635 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700636 public @NonNull Builder penaltyDeathOnNetwork() {
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700637 return enable(PENALTY_DEATH_ON_NETWORK);
638 }
639
Kurt Nelson46974a22017-08-30 13:30:26 -0700640 /** Flash the screen during a violation. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700641 public @NonNull Builder penaltyFlashScreen() {
Brad Fitzpatrick68044332010-11-22 18:19:48 -0800642 return enable(PENALTY_FLASH);
643 }
644
Kurt Nelson46974a22017-08-30 13:30:26 -0700645 /** Log detected violations to the system log. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700646 public @NonNull Builder penaltyLog() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700647 return enable(PENALTY_LOG);
648 }
649
650 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700651 * Enable detected violations log a stacktrace and timing data to the {@link
652 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
653 * integrators doing beta user field data collection.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700654 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700655 public @NonNull Builder penaltyDropBox() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700656 return enable(PENALTY_DROPBOX);
657 }
658
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700659 /**
660 * Call #{@link OnThreadViolationListener#onThreadViolation(Violation)} on specified
661 * executor every violation.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700662 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700663 public @NonNull Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -0800664 @NonNull Executor executor, @NonNull OnThreadViolationListener listener) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700665 if (executor == null) {
666 throw new NullPointerException("executor must not be null");
667 }
668 mListener = listener;
669 mExecutor = executor;
670 return this;
671 }
672
Kurt Nelson72534b72018-02-22 11:21:15 -0800673 /** @removed */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700674 public @NonNull Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -0800675 @NonNull OnThreadViolationListener listener, @NonNull Executor executor) {
676 return penaltyListener(executor, listener);
677 }
678
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600679 private Builder enable(@ThreadPolicyMask int mask) {
680 mMask |= mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700681 return this;
682 }
683
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600684 private Builder disable(@ThreadPolicyMask int mask) {
685 mMask &= ~mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700686 return this;
687 }
688
689 /**
690 * Construct the ThreadPolicy instance.
691 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700692 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
693 * #penaltyLog} is implicitly set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700694 */
695 public ThreadPolicy build() {
696 // If there are detection bits set but no violation bits
697 // set, enable simple logging.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700698 if (mListener == null
699 && mMask != 0
Kurt Nelson46974a22017-08-30 13:30:26 -0700700 && (mMask
701 & (PENALTY_DEATH
702 | PENALTY_LOG
703 | PENALTY_DROPBOX
704 | PENALTY_DIALOG))
705 == 0) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700706 penaltyLog();
707 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700708 return new ThreadPolicy(mMask, mListener, mExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700709 }
710 }
711 }
712
713 /**
714 * {@link StrictMode} policy applied to all threads in the virtual machine's process.
715 *
716 * <p>The policy is enabled by {@link #setVmPolicy}.
717 */
718 public static final class VmPolicy {
Kurt Nelson46974a22017-08-30 13:30:26 -0700719 /** The default, lax policy which doesn't catch anything. */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700720 public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP, null, null);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700721
Andrei Onea24ec3212019-03-15 17:35:05 +0000722 @UnsupportedAppUsage
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600723 final @VmPolicyMask int mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700724 final OnVmViolationListener mListener;
725 final Executor mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700726
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800727 // Map from class to max number of allowed instances in memory.
728 final HashMap<Class, Integer> classInstanceLimit;
729
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700730 private VmPolicy(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600731 @VmPolicyMask int mask,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700732 HashMap<Class, Integer> classInstanceLimit,
733 OnVmViolationListener listener,
734 Executor executor) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800735 if (classInstanceLimit == null) {
736 throw new NullPointerException("classInstanceLimit == null");
737 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700738 this.mask = mask;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800739 this.classInstanceLimit = classInstanceLimit;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700740 mListener = listener;
741 mCallbackExecutor = executor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700742 }
743
744 @Override
745 public String toString() {
746 return "[StrictMode.VmPolicy; mask=" + mask + "]";
747 }
748
749 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700750 * Creates {@link VmPolicy} instances. Methods whose names start with {@code detect} specify
751 * what problems we should look for. Methods whose names start with {@code penalty} specify
752 * what we should do when we detect a problem.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700753 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700754 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
755 * order is insignificant: all penalties apply to all detected problems.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700756 *
757 * <p>For example, detect everything and log anything that's found:
Kurt Nelson46974a22017-08-30 13:30:26 -0700758 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700759 * <pre>
760 * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
761 * .detectAll()
762 * .penaltyLog()
763 * .build();
764 * StrictMode.setVmPolicy(policy);
765 * </pre>
766 */
767 public static final class Builder {
Andrei Onea24ec3212019-03-15 17:35:05 +0000768 @UnsupportedAppUsage
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600769 private @VmPolicyMask int mMask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700770 private OnVmViolationListener mListener;
771 private Executor mExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700772
Kurt Nelson46974a22017-08-30 13:30:26 -0700773 private HashMap<Class, Integer> mClassInstanceLimit; // null until needed
774 private boolean mClassInstanceLimitNeedCow = false; // need copy-on-write
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800775
776 public Builder() {
777 mMask = 0;
778 }
779
Kurt Nelson46974a22017-08-30 13:30:26 -0700780 /** Build upon an existing VmPolicy. */
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800781 public Builder(VmPolicy base) {
782 mMask = base.mask;
783 mClassInstanceLimitNeedCow = true;
784 mClassInstanceLimit = base.classInstanceLimit;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700785 mListener = base.mListener;
786 mExecutor = base.mCallbackExecutor;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800787 }
788
789 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700790 * Set an upper bound on how many instances of a class can be in memory at once. Helps
791 * to prevent object leaks.
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800792 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700793 public @NonNull Builder setClassInstanceLimit(Class klass, int instanceLimit) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800794 if (klass == null) {
795 throw new NullPointerException("klass == null");
796 }
797 if (mClassInstanceLimitNeedCow) {
Kurt Nelson46974a22017-08-30 13:30:26 -0700798 if (mClassInstanceLimit.containsKey(klass)
799 && mClassInstanceLimit.get(klass) == instanceLimit) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800800 // no-op; don't break COW
801 return this;
802 }
803 mClassInstanceLimitNeedCow = false;
804 mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
805 } else if (mClassInstanceLimit == null) {
806 mClassInstanceLimit = new HashMap<Class, Integer>();
807 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800808 mMask |= DETECT_VM_INSTANCE_LEAKS;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800809 mClassInstanceLimit.put(klass, instanceLimit);
810 return this;
811 }
812
Kurt Nelson46974a22017-08-30 13:30:26 -0700813 /** Detect leaks of {@link android.app.Activity} subclasses. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700814 public @NonNull Builder detectActivityLeaks() {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800815 return enable(DETECT_VM_ACTIVITY_LEAKS);
816 }
817
Jeff Sharkey89182982017-11-01 19:02:56 -0600818 /** @hide */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700819 public @NonNull Builder permitActivityLeaks() {
Chilun762f0492020-05-13 17:20:09 +0800820 synchronized (StrictMode.class) {
821 sExpectedActivityInstanceCount.clear();
822 }
Jeff Sharkey89182982017-11-01 19:02:56 -0600823 return disable(DETECT_VM_ACTIVITY_LEAKS);
824 }
825
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700826 /**
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100827 * Detect reflective usage of APIs that are not part of the public Android SDK.
Mathew Inwoodd82a7432018-04-19 14:42:58 +0100828 *
829 * <p>Note that any non-SDK APIs that this processes accesses before this detection is
830 * enabled may not be detected. To ensure that all such API accesses are detected,
831 * you should apply this policy as early as possible after process creation.
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100832 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700833 public @NonNull Builder detectNonSdkApiUsage() {
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100834 return enable(DETECT_VM_NON_SDK_API_USAGE);
835 }
836
837 /**
838 * Permit reflective usage of APIs that are not part of the public Android SDK. Note
839 * that this <b>only</b> affects {@code StrictMode}, the underlying runtime may
840 * continue to restrict or warn on access to methods that are not part of the
841 * public SDK.
842 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700843 public @NonNull Builder permitNonSdkApiUsage() {
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100844 return disable(DETECT_VM_NON_SDK_API_USAGE);
845 }
846
847 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700848 * Detect everything that's potentially suspect.
849 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700850 * <p>In the Honeycomb release this includes leaks of SQLite cursors, Activities, and
851 * other closable objects but will likely expand in future releases.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700852 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700853 public @NonNull Builder detectAll() {
Jeff Sharkey0b558702017-01-26 16:48:01 -0700854 detectLeakedSqlLiteObjects();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800855
Jeff Sharkey0b558702017-01-26 16:48:01 -0700856 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
857 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
858 detectActivityLeaks();
859 detectLeakedClosableObjects();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800860 }
Jeff Sharkey0b558702017-01-26 16:48:01 -0700861 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN) {
862 detectLeakedRegistrationObjects();
863 }
864 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
865 detectFileUriExposure();
866 }
867 if (targetSdk >= Build.VERSION_CODES.M) {
868 // TODO: always add DETECT_VM_CLEARTEXT_NETWORK once we have
869 // facility for apps to mark sockets that should be ignored
870 if (SystemProperties.getBoolean(CLEARTEXT_PROPERTY, false)) {
871 detectCleartextNetwork();
872 }
873 }
874 if (targetSdk >= Build.VERSION_CODES.O) {
875 detectContentUriWithoutPermission();
876 detectUntaggedSockets();
877 }
Jeff Sharkeydd02e332018-06-27 14:41:57 -0600878 if (targetSdk >= Build.VERSION_CODES.Q) {
879 detectCredentialProtectedWhileLocked();
880 }
Andrii Kulian5877c7d2020-01-29 16:57:32 -0800881 if (targetSdk >= Build.VERSION_CODES.R) {
882 detectIncorrectContextUse();
883 }
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100884
885 // TODO: Decide whether to detect non SDK API usage beyond a certain API level.
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -0600886 // TODO: enable detectImplicitDirectBoot() once system is less noisy
887
Jeff Sharkey0b558702017-01-26 16:48:01 -0700888 return this;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700889 }
890
891 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700892 * Detect when an {@link android.database.sqlite.SQLiteCursor} or other SQLite object is
893 * finalized without having been closed.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700894 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700895 * <p>You always want to explicitly close your SQLite cursors to avoid unnecessary
896 * database contention and temporary memory leaks.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700897 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700898 public @NonNull Builder detectLeakedSqlLiteObjects() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700899 return enable(DETECT_VM_CURSOR_LEAKS);
900 }
901
902 /**
Kurt Nelsond25bd9f2017-09-14 11:36:34 -0700903 * Detect when an {@link java.io.Closeable} or other object with an explicit termination
Kurt Nelson46974a22017-08-30 13:30:26 -0700904 * method is finalized without having been closed.
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700905 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700906 * <p>You always want to explicitly close such objects to avoid unnecessary resources
907 * leaks.
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700908 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700909 public @NonNull Builder detectLeakedClosableObjects() {
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700910 return enable(DETECT_VM_CLOSABLE_LEAKS);
911 }
912
913 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700914 * Detect when a {@link BroadcastReceiver} or {@link ServiceConnection} is leaked during
915 * {@link Context} teardown.
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800916 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700917 public @NonNull Builder detectLeakedRegistrationObjects() {
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800918 return enable(DETECT_VM_REGISTRATION_LEAKS);
919 }
920
921 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700922 * Detect when the calling application exposes a {@code file://} {@link android.net.Uri}
923 * to another app.
924 *
925 * <p>This exposure is discouraged since the receiving app may not have access to the
926 * shared path. For example, the receiving app may not have requested the {@link
927 * android.Manifest.permission#READ_EXTERNAL_STORAGE} runtime permission, or the
928 * platform may be sharing the {@link android.net.Uri} across user profile boundaries.
929 *
930 * <p>Instead, apps should use {@code content://} Uris so the platform can extend
931 * temporary permission for the receiving app to access the resource.
Jeff Sharkey344744b2016-01-28 19:03:30 -0700932 *
933 * @see android.support.v4.content.FileProvider
934 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700935 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700936 public @NonNull Builder detectFileUriExposure() {
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700937 return enable(DETECT_VM_FILE_URI_EXPOSURE);
938 }
939
940 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700941 * Detect any network traffic from the calling app which is not wrapped in SSL/TLS. This
942 * can help you detect places that your app is inadvertently sending cleartext data
943 * across the network.
944 *
945 * <p>Using {@link #penaltyDeath()} or {@link #penaltyDeathOnCleartextNetwork()} will
946 * block further traffic on that socket to prevent accidental data leakage, in addition
947 * to crashing your process.
948 *
949 * <p>Using {@link #penaltyDropBox()} will log the raw contents of the packet that
950 * triggered the violation.
951 *
952 * <p>This inspects both IPv4/IPv6 and TCP/UDP network traffic, but it may be subject to
953 * false positives, such as when STARTTLS protocols or HTTP proxies are used.
Jeff Sharkey605eb792014-11-04 13:34:06 -0800954 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700955 public @NonNull Builder detectCleartextNetwork() {
Jeff Sharkey605eb792014-11-04 13:34:06 -0800956 return enable(DETECT_VM_CLEARTEXT_NETWORK);
957 }
958
959 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700960 * Detect when the calling application sends a {@code content://} {@link
961 * android.net.Uri} to another app without setting {@link
962 * Intent#FLAG_GRANT_READ_URI_PERMISSION} or {@link
963 * Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
964 *
965 * <p>Forgetting to include one or more of these flags when sending an intent is
966 * typically an app bug.
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -0700967 *
968 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
969 * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
970 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700971 public @NonNull Builder detectContentUriWithoutPermission() {
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -0700972 return enable(DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION);
973 }
974
975 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700976 * Detect any sockets in the calling app which have not been tagged using {@link
977 * TrafficStats}. Tagging sockets can help you investigate network usage inside your
978 * app, such as a narrowing down heavy usage to a specific library or component.
979 *
980 * <p>This currently does not detect sockets created in native code.
Jeff Sharkey619a5112017-01-19 11:55:54 -0700981 *
982 * @see TrafficStats#setThreadStatsTag(int)
983 * @see TrafficStats#tagSocket(java.net.Socket)
984 * @see TrafficStats#tagDatagramSocket(java.net.DatagramSocket)
985 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700986 public @NonNull Builder detectUntaggedSockets() {
Jeff Sharkey619a5112017-01-19 11:55:54 -0700987 return enable(DETECT_VM_UNTAGGED_SOCKET);
988 }
989
Jeff Sharkey89182982017-11-01 19:02:56 -0600990 /** @hide */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -0700991 public @NonNull Builder permitUntaggedSockets() {
Jeff Sharkey89182982017-11-01 19:02:56 -0600992 return disable(DETECT_VM_UNTAGGED_SOCKET);
993 }
994
Jeff Sharkey619a5112017-01-19 11:55:54 -0700995 /**
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -0600996 * Detect any implicit reliance on Direct Boot automatic filtering
997 * of {@link PackageManager} values. Violations are only triggered
998 * when implicit calls are made while the user is locked.
999 * <p>
1000 * Apps becoming Direct Boot aware need to carefully inspect each
1001 * query site and explicitly decide which combination of flags they
1002 * want to use:
1003 * <ul>
1004 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AWARE}
1005 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_UNAWARE}
1006 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AUTO}
1007 * </ul>
1008 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001009 public @NonNull Builder detectImplicitDirectBoot() {
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06001010 return enable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
1011 }
1012
1013 /** @hide */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001014 public @NonNull Builder permitImplicitDirectBoot() {
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06001015 return disable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
1016 }
1017
1018 /**
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001019 * Detect access to filesystem paths stored in credential protected
1020 * storage areas while the user is locked.
1021 * <p>
1022 * When a user is locked, credential protected storage is
1023 * unavailable, and files stored in these locations appear to not
1024 * exist, which can result in subtle app bugs if they assume default
1025 * behaviors or empty states. Instead, apps should store data needed
1026 * while a user is locked under device protected storage areas.
1027 *
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001028 * @see Context#createDeviceProtectedStorageContext()
1029 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001030 public @NonNull Builder detectCredentialProtectedWhileLocked() {
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001031 return enable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1032 }
1033
1034 /** @hide */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001035 public @NonNull Builder permitCredentialProtectedWhileLocked() {
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001036 return disable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1037 }
1038
1039 /**
Andrii Kulian5877c7d2020-01-29 16:57:32 -08001040 * Detect attempts to invoke a method on a {@link Context} that is not suited for such
1041 * operation.
1042 * <p>An example of this is trying to obtain an instance of visual service (e.g.
1043 * {@link android.view.WindowManager}) from a non-visual {@link Context}. This is not
1044 * allowed, since a non-visual {@link Context} is not adjusted to any visual area, and
1045 * therefore can report incorrect metrics or resources.
1046 * @see Context#getDisplay()
1047 * @see Context#getSystemService(String)
1048 * @hide
1049 */
1050 @TestApi
1051 public @NonNull Builder detectIncorrectContextUse() {
1052 return enable(DETECT_VM_INCORRECT_CONTEXT_USE);
1053 }
1054
1055 /**
1056 * Disable detection of incorrect context use.
1057 * TODO(b/149790106): Fix usages and remove.
1058 * @hide
1059 */
1060 @TestApi
1061 public @NonNull Builder permitIncorrectContextUse() {
1062 return disable(DETECT_VM_INCORRECT_CONTEXT_USE);
1063 }
1064
1065 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001066 * Crashes the whole process on violation. This penalty runs at the end of all enabled
1067 * penalties so you'll still get your logging or other violations before the process
1068 * dies.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001069 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001070 public @NonNull Builder penaltyDeath() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001071 return enable(PENALTY_DEATH);
1072 }
1073
1074 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001075 * Crashes the whole process when cleartext network traffic is detected.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001076 *
1077 * @see #detectCleartextNetwork()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001078 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001079 public @NonNull Builder penaltyDeathOnCleartextNetwork() {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001080 return enable(PENALTY_DEATH_ON_CLEARTEXT_NETWORK);
1081 }
1082
1083 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001084 * Crashes the whole process when a {@code file://} {@link android.net.Uri} is exposed
1085 * beyond this app.
Jeff Sharkey344744b2016-01-28 19:03:30 -07001086 *
1087 * @see #detectFileUriExposure()
1088 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001089 public @NonNull Builder penaltyDeathOnFileUriExposure() {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001090 return enable(PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
1091 }
1092
Kurt Nelson46974a22017-08-30 13:30:26 -07001093 /** Log detected violations to the system log. */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001094 public @NonNull Builder penaltyLog() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001095 return enable(PENALTY_LOG);
1096 }
1097
1098 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001099 * Enable detected violations log a stacktrace and timing data to the {@link
1100 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
1101 * integrators doing beta user field data collection.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001102 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001103 public @NonNull Builder penaltyDropBox() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001104 return enable(PENALTY_DROPBOX);
1105 }
1106
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001107 /**
1108 * Call #{@link OnVmViolationListener#onVmViolation(Violation)} on every violation.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001109 */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001110 public @NonNull Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -08001111 @NonNull Executor executor, @NonNull OnVmViolationListener listener) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001112 if (executor == null) {
1113 throw new NullPointerException("executor must not be null");
1114 }
1115 mListener = listener;
1116 mExecutor = executor;
1117 return this;
1118 }
1119
Kurt Nelson72534b72018-02-22 11:21:15 -08001120 /** @removed */
Jeff Sharkeya30e5c32019-02-28 12:02:10 -07001121 public @NonNull Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -08001122 @NonNull OnVmViolationListener listener, @NonNull Executor executor) {
1123 return penaltyListener(executor, listener);
1124 }
1125
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001126 private Builder enable(@VmPolicyMask int mask) {
1127 mMask |= mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001128 return this;
1129 }
1130
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001131 Builder disable(@VmPolicyMask int mask) {
1132 mMask &= ~mask;
Mathieu Chartierca8c1052017-06-19 18:42:57 -07001133 return this;
1134 }
1135
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001136 /**
1137 * Construct the VmPolicy instance.
1138 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001139 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
1140 * #penaltyLog} is implicitly set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001141 */
1142 public VmPolicy build() {
1143 // If there are detection bits set but no violation bits
1144 // set, enable simple logging.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001145 if (mListener == null
1146 && mMask != 0
Kurt Nelson46974a22017-08-30 13:30:26 -07001147 && (mMask
1148 & (PENALTY_DEATH
1149 | PENALTY_LOG
1150 | PENALTY_DROPBOX
1151 | PENALTY_DIALOG))
1152 == 0) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001153 penaltyLog();
1154 }
Kurt Nelson46974a22017-08-30 13:30:26 -07001155 return new VmPolicy(
1156 mMask,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001157 mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP,
1158 mListener,
1159 mExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001160 }
1161 }
1162 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001163
1164 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001165 * Log of strict mode violation stack traces that have occurred during a Binder call, to be
1166 * serialized back later to the caller via Parcel.writeNoException() (amusingly) where the
1167 * caller can choose how to react.
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001168 */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001169 private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
1170 new ThreadLocal<ArrayList<ViolationInfo>>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07001171 @Override
1172 protected ArrayList<ViolationInfo> initialValue() {
1173 // Starts null to avoid unnecessary allocations when
1174 // checking whether there are any violations or not in
1175 // hasGatheredViolations() below.
1176 return null;
1177 }
1178 };
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001179
1180 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001181 * Sets the policy for what actions on the current thread should be detected, as well as the
1182 * penalty if such actions occur.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001183 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001184 * <p>Internally this sets a thread-local variable which is propagated across cross-process IPC
1185 * calls, meaning you can catch violations when a system service or another process accesses the
1186 * disk or network on your behalf.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -07001187 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001188 * @param policy the policy to put into place
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001189 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001190 public static void setThreadPolicy(final ThreadPolicy policy) {
1191 setThreadPolicyMask(policy.mask);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001192 sThreadViolationListener.set(policy.mListener);
1193 sThreadViolationExecutor.set(policy.mCallbackExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001194 }
1195
Jeff Sharkey89182982017-11-01 19:02:56 -06001196 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001197 public static void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001198 // In addition to the Java-level thread-local in Dalvik's
1199 // BlockGuard, we also need to keep a native thread-local in
1200 // Binder in order to propagate the value across Binder calls,
1201 // even across native-only processes. The two are kept in
1202 // sync via the callback to onStrictModePolicyChange, below.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001203 setBlockGuardPolicy(threadPolicyMask);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001204
1205 // And set the Android native version...
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001206 Binder.setThreadStrictModePolicy(threadPolicyMask);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001207 }
1208
1209 // Sets the policy in Dalvik/libcore (BlockGuard)
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001210 private static void setBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1211 if (threadPolicyMask == 0) {
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001212 BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
1213 return;
1214 }
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001215 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1216 final AndroidBlockGuardPolicy androidPolicy;
1217 if (policy instanceof AndroidBlockGuardPolicy) {
1218 androidPolicy = (AndroidBlockGuardPolicy) policy;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001219 } else {
Kurt Nelson46974a22017-08-30 13:30:26 -07001220 androidPolicy = THREAD_ANDROID_POLICY.get();
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001221 BlockGuard.setThreadPolicy(androidPolicy);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001222 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001223 androidPolicy.setThreadPolicyMask(threadPolicyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001224 }
1225
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001226 private static void setBlockGuardVmPolicy(@VmPolicyMask int vmPolicyMask) {
1227 // We only need to install BlockGuard for a small subset of VM policies
1228 vmPolicyMask &= DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED;
1229 if (vmPolicyMask != 0) {
1230 BlockGuard.setVmPolicy(VM_ANDROID_POLICY);
1231 } else {
1232 BlockGuard.setVmPolicy(BlockGuard.LAX_VM_POLICY);
1233 }
1234 }
1235
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001236 // Sets up CloseGuard in Dalvik/libcore
1237 private static void setCloseGuardEnabled(boolean enabled) {
Brad Fitzpatrick7c2ae652010-11-14 11:00:05 -08001238 if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001239 CloseGuard.setReporter(new AndroidCloseGuardReporter());
1240 }
1241 CloseGuard.setEnabled(enabled);
1242 }
1243
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001244 /**
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -07001245 * Returns the bitmask of the current thread's policy.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001246 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001247 * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001248 * @hide
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001249 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001250 @UnsupportedAppUsage
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001251 public static @ThreadPolicyMask int getThreadPolicyMask() {
1252 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1253 if (policy instanceof AndroidBlockGuardPolicy) {
1254 return ((AndroidBlockGuardPolicy) policy).getThreadPolicyMask();
1255 } else {
1256 return 0;
1257 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001258 }
1259
Kurt Nelson46974a22017-08-30 13:30:26 -07001260 /** Returns the current thread's policy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001261 public static ThreadPolicy getThreadPolicy() {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001262 // TODO: this was a last minute Gingerbread API change (to
1263 // introduce VmPolicy cleanly) but this isn't particularly
1264 // optimal for users who might call this method often. This
1265 // should be in a thread-local and not allocate on each call.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001266 return new ThreadPolicy(
1267 getThreadPolicyMask(),
1268 sThreadViolationListener.get(),
1269 sThreadViolationExecutor.get());
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001270 }
1271
1272 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001273 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1274 * #getThreadPolicy}, modifies it to permit both disk reads &amp; writes, and sets the new
1275 * policy with {@link #setThreadPolicy}, returning the old policy so you can restore it at the
1276 * end of a block.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001277 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001278 * @return the old policy, to be passed to {@link #setThreadPolicy} to restore the policy at the
1279 * end of a block
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001280 */
1281 public static ThreadPolicy allowThreadDiskWrites() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001282 return new ThreadPolicy(
1283 allowThreadDiskWritesMask(),
1284 sThreadViolationListener.get(),
1285 sThreadViolationExecutor.get());
Jeff Sharkey89182982017-11-01 19:02:56 -06001286 }
1287
1288 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001289 public static @ThreadPolicyMask int allowThreadDiskWritesMask() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001290 int oldPolicyMask = getThreadPolicyMask();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001291 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_WRITE | DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001292 if (newPolicyMask != oldPolicyMask) {
1293 setThreadPolicyMask(newPolicyMask);
1294 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001295 return oldPolicyMask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001296 }
1297
1298 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001299 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1300 * #getThreadPolicy}, modifies it to permit disk reads, and sets the new policy with {@link
1301 * #setThreadPolicy}, returning the old policy so you can restore it at the end of a block.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001302 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001303 * @return the old policy, to be passed to setThreadPolicy to restore the policy.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001304 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001305 public static ThreadPolicy allowThreadDiskReads() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001306 return new ThreadPolicy(
1307 allowThreadDiskReadsMask(),
1308 sThreadViolationListener.get(),
1309 sThreadViolationExecutor.get());
Jeff Sharkey89182982017-11-01 19:02:56 -06001310 }
1311
1312 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001313 public static @ThreadPolicyMask int allowThreadDiskReadsMask() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001314 int oldPolicyMask = getThreadPolicyMask();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001315 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001316 if (newPolicyMask != oldPolicyMask) {
1317 setThreadPolicyMask(newPolicyMask);
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001318 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001319 return oldPolicyMask;
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001320 }
1321
Jeff Sharkeye3644412019-04-27 17:13:57 -06001322 /** @hide */
1323 public static ThreadPolicy allowThreadViolations() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001324 ThreadPolicy oldPolicy = getThreadPolicy();
1325 setThreadPolicyMask(0);
1326 return oldPolicy;
1327 }
1328
Jeff Sharkeye3644412019-04-27 17:13:57 -06001329 /** @hide */
1330 public static VmPolicy allowVmViolations() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001331 VmPolicy oldPolicy = getVmPolicy();
1332 sVmPolicy = VmPolicy.LAX;
1333 return oldPolicy;
1334 }
1335
Jeff Sharkey89182982017-11-01 19:02:56 -06001336 /**
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001337 * Determine if the given app is "bundled" as part of the system image. These bundled apps are
1338 * developed in lock-step with the OS, and they aren't updated outside of an OTA, so we want to
1339 * chase any {@link StrictMode} regressions by enabling detection when running on {@link
1340 * Build#IS_USERDEBUG} or {@link Build#IS_ENG} builds.
1341 *
1342 * <p>Unbundled apps included in the system image are expected to detect and triage their own
1343 * {@link StrictMode} issues separate from the OS release process, which is why we don't enable
1344 * them here.
Jeff Sharkey89182982017-11-01 19:02:56 -06001345 *
1346 * @hide
1347 */
1348 public static boolean isBundledSystemApp(ApplicationInfo ai) {
1349 if (ai == null || ai.packageName == null) {
1350 // Probably system server
1351 return true;
1352 } else if (ai.isSystemApp()) {
1353 // Ignore unbundled apps living in the wrong namespace
1354 if (ai.packageName.equals("com.android.vending")
1355 || ai.packageName.equals("com.android.chrome")) {
1356 return false;
1357 }
Brad Fitzpatrickf5454592010-11-24 15:27:51 -08001358
Jeff Sharkey89182982017-11-01 19:02:56 -06001359 // Ignore bundled apps that are way too spammy
1360 // STOPSHIP: burn this list down to zero
1361 if (ai.packageName.equals("com.android.phone")) {
1362 return false;
1363 }
1364
1365 if (ai.packageName.equals("android")
1366 || ai.packageName.startsWith("android.")
1367 || ai.packageName.startsWith("com.android.")) {
Brad Fitzpatrickf5454592010-11-24 15:27:51 -08001368 return true;
1369 }
1370 }
1371 return false;
1372 }
1373
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001374 /**
Jeff Sharkey89182982017-11-01 19:02:56 -06001375 * Initialize default {@link ThreadPolicy} for the current thread.
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001376 *
1377 * @hide
1378 */
Jeff Sharkey89182982017-11-01 19:02:56 -06001379 public static void initThreadDefaults(ApplicationInfo ai) {
1380 final ThreadPolicy.Builder builder = new ThreadPolicy.Builder();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001381 final int targetSdkVersion =
1382 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001383
Jeff Sharkey89182982017-11-01 19:02:56 -06001384 // Starting in HC, we don't allow network usage on the main thread
1385 if (targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
1386 builder.detectNetwork();
1387 builder.penaltyDeathOnNetwork();
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001388 }
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001389
Jeff Sharkey89182982017-11-01 19:02:56 -06001390 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1391 // Detect nothing extra
1392 } else if (Build.IS_USERDEBUG) {
1393 // Detect everything in bundled apps
1394 if (isBundledSystemApp(ai)) {
1395 builder.detectAll();
1396 builder.penaltyDropBox();
1397 if (SystemProperties.getBoolean(VISUAL_PROPERTY, false)) {
1398 builder.penaltyFlashScreen();
1399 }
Mathieu Chartierca8c1052017-06-19 18:42:57 -07001400 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001401 } else if (Build.IS_ENG) {
1402 // Detect everything in bundled apps
1403 if (isBundledSystemApp(ai)) {
1404 builder.detectAll();
1405 builder.penaltyDropBox();
1406 builder.penaltyLog();
1407 builder.penaltyFlashScreen();
Jeff Brownd5875d92011-10-09 14:59:37 -07001408 }
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001409 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001410
1411 setThreadPolicy(builder.build());
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001412 }
1413
1414 /**
Jeff Sharkey89182982017-11-01 19:02:56 -06001415 * Initialize default {@link VmPolicy} for the current VM.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001416 *
1417 * @hide
1418 */
Jeff Sharkey89182982017-11-01 19:02:56 -06001419 public static void initVmDefaults(ApplicationInfo ai) {
1420 final VmPolicy.Builder builder = new VmPolicy.Builder();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001421 final int targetSdkVersion =
1422 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
Jeff Sharkey89182982017-11-01 19:02:56 -06001423
1424 // Starting in N, we don't allow file:// Uri exposure
1425 if (targetSdkVersion >= Build.VERSION_CODES.N) {
1426 builder.detectFileUriExposure();
1427 builder.penaltyDeathOnFileUriExposure();
1428 }
1429
1430 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1431 // Detect nothing extra
1432 } else if (Build.IS_USERDEBUG) {
1433 // Detect everything in bundled apps (except activity leaks, which
1434 // are expensive to track)
1435 if (isBundledSystemApp(ai)) {
1436 builder.detectAll();
1437 builder.permitActivityLeaks();
1438 builder.penaltyDropBox();
1439 }
1440 } else if (Build.IS_ENG) {
1441 // Detect everything in bundled apps
1442 if (isBundledSystemApp(ai)) {
1443 builder.detectAll();
1444 builder.penaltyDropBox();
1445 builder.penaltyLog();
1446 }
1447 }
1448
1449 setVmPolicy(builder.build());
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001450 }
1451
1452 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -07001453 * Used by the framework to make file usage a fatal error.
1454 *
1455 * @hide
1456 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001457 @UnsupportedAppUsage
Jeff Sharkey344744b2016-01-28 19:03:30 -07001458 public static void enableDeathOnFileUriExposure() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07001459 sVmPolicy =
1460 new VmPolicy(
1461 sVmPolicy.mask
1462 | DETECT_VM_FILE_URI_EXPOSURE
1463 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001464 sVmPolicy.classInstanceLimit,
1465 sVmPolicy.mListener,
1466 sVmPolicy.mCallbackExecutor);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001467 }
1468
1469 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001470 * Used by lame internal apps that haven't done the hard work to get themselves off file:// Uris
1471 * yet.
Jeff Sharkey344744b2016-01-28 19:03:30 -07001472 *
1473 * @hide
1474 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001475 @UnsupportedAppUsage
Jeff Sharkey344744b2016-01-28 19:03:30 -07001476 public static void disableDeathOnFileUriExposure() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07001477 sVmPolicy =
1478 new VmPolicy(
1479 sVmPolicy.mask
1480 & ~(DETECT_VM_FILE_URI_EXPOSURE
1481 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE),
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001482 sVmPolicy.classInstanceLimit,
1483 sVmPolicy.mListener,
1484 sVmPolicy.mCallbackExecutor);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001485 }
1486
Andrei Onea24ec3212019-03-15 17:35:05 +00001487 @UnsupportedAppUsage
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001488 private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
1489 new ThreadLocal<ArrayList<ViolationInfo>>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07001490 @Override
1491 protected ArrayList<ViolationInfo> initialValue() {
1492 return new ArrayList<ViolationInfo>();
1493 }
1494 };
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001495
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001496 // Note: only access this once verifying the thread has a Looper.
Kurt Nelson46974a22017-08-30 13:30:26 -07001497 private static final ThreadLocal<Handler> THREAD_HANDLER =
1498 new ThreadLocal<Handler>() {
1499 @Override
1500 protected Handler initialValue() {
1501 return new Handler();
1502 }
1503 };
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001504
Kurt Nelson46974a22017-08-30 13:30:26 -07001505 private static final ThreadLocal<AndroidBlockGuardPolicy> THREAD_ANDROID_POLICY =
1506 new ThreadLocal<AndroidBlockGuardPolicy>() {
1507 @Override
1508 protected AndroidBlockGuardPolicy initialValue() {
1509 return new AndroidBlockGuardPolicy(0);
1510 }
1511 };
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001512
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001513 private static boolean tooManyViolationsThisLoop() {
1514 return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
1515 }
1516
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001517 private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001518 private @ThreadPolicyMask int mThreadPolicyMask;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001519
1520 // Map from violation stacktrace hashcode -> uptimeMillis of
1521 // last violation. No locking needed, as this is only
1522 // accessed by the same thread.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001523 private ArrayMap<Integer, Long> mLastViolationTime;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001524
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001525 public AndroidBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1526 mThreadPolicyMask = threadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001527 }
1528
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001529 @Override
1530 public String toString() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001531 return "AndroidBlockGuardPolicy; mPolicyMask=" + mThreadPolicyMask;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001532 }
1533
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001534 // Part of BlockGuard.Policy interface:
1535 public int getPolicyMask() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001536 return mThreadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001537 }
1538
1539 // Part of BlockGuard.Policy interface:
1540 public void onWriteToDisk() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001541 if ((mThreadPolicyMask & DETECT_THREAD_DISK_WRITE) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001542 return;
1543 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001544 if (tooManyViolationsThisLoop()) {
1545 return;
1546 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001547 startHandlingViolationException(new DiskWriteViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001548 }
1549
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001550 // Not part of BlockGuard.Policy; just part of StrictMode:
1551 void onCustomSlowCall(String name) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001552 if ((mThreadPolicyMask & DETECT_THREAD_CUSTOM) == 0) {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001553 return;
1554 }
1555 if (tooManyViolationsThisLoop()) {
1556 return;
1557 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001558 startHandlingViolationException(new CustomViolation(name));
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001559 }
1560
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001561 // Not part of BlockGuard.Policy; just part of StrictMode:
1562 void onResourceMismatch(Object tag) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001563 if ((mThreadPolicyMask & DETECT_THREAD_RESOURCE_MISMATCH) == 0) {
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001564 return;
1565 }
1566 if (tooManyViolationsThisLoop()) {
1567 return;
1568 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001569 startHandlingViolationException(new ResourceMismatchViolation(tag));
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001570 }
1571
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001572 // Not part of BlockGuard.Policy; just part of StrictMode:
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001573 public void onUnbufferedIO() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001574 if ((mThreadPolicyMask & DETECT_THREAD_UNBUFFERED_IO) == 0) {
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001575 return;
1576 }
1577 if (tooManyViolationsThisLoop()) {
1578 return;
1579 }
Kurt Nelson0e612802017-11-09 17:25:40 -08001580 startHandlingViolationException(new UnbufferedIoViolation());
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001581 }
1582
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001583 // Part of BlockGuard.Policy interface:
1584 public void onReadFromDisk() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001585 if ((mThreadPolicyMask & DETECT_THREAD_DISK_READ) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001586 return;
1587 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001588 if (tooManyViolationsThisLoop()) {
1589 return;
1590 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001591 startHandlingViolationException(new DiskReadViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001592 }
1593
1594 // Part of BlockGuard.Policy interface:
1595 public void onNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001596 if ((mThreadPolicyMask & DETECT_THREAD_NETWORK) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001597 return;
1598 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001599 if ((mThreadPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001600 throw new NetworkOnMainThreadException();
1601 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001602 if (tooManyViolationsThisLoop()) {
1603 return;
1604 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001605 startHandlingViolationException(new NetworkViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001606 }
1607
Pete Gillin22316b42018-02-15 17:17:27 +00001608 // Part of BlockGuard.Policy interface:
1609 public void onExplicitGc() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001610 if ((mThreadPolicyMask & DETECT_THREAD_EXPLICIT_GC) == 0) {
Pete Gillin22316b42018-02-15 17:17:27 +00001611 return;
1612 }
1613 if (tooManyViolationsThisLoop()) {
1614 return;
1615 }
1616 startHandlingViolationException(new ExplicitGcViolation());
1617 }
1618
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001619 public @ThreadPolicyMask int getThreadPolicyMask() {
1620 return mThreadPolicyMask;
1621 }
1622
1623 public void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
1624 mThreadPolicyMask = threadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001625 }
1626
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001627 // Start handling a violation that just started and hasn't
1628 // actually run yet (e.g. no disk write or network operation
1629 // has yet occurred). This sees if we're in an event loop
1630 // thread and, if so, uses it to roughly measure how long the
1631 // violation took.
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001632 void startHandlingViolationException(Violation e) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001633 final int penaltyMask = (mThreadPolicyMask & PENALTY_ALL);
1634 final ViolationInfo info = new ViolationInfo(e, penaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001635 info.violationUptimeMillis = SystemClock.uptimeMillis();
1636 handleViolationWithTimingAttempt(info);
1637 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001638
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001639 // Attempts to fill in the provided ViolationInfo's
1640 // durationMillis field if this thread has a Looper we can use
1641 // to measure with. We measure from the time of violation
1642 // until the time the looper is idle again (right before
1643 // the next epoll_wait)
1644 void handleViolationWithTimingAttempt(final ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001645 Looper looper = Looper.myLooper();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001646
1647 // Without a Looper, we're unable to time how long the
1648 // violation takes place. This case should be rare, as
1649 // most users will care about timing violations that
1650 // happen on their main UI thread. Note that this case is
1651 // also hit when a violation takes place in a Binder
1652 // thread, in "gather" mode. In this case, the duration
1653 // of the violation is computed by the ultimate caller and
1654 // its Looper, if any.
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001655 //
1656 // Also, as a special short-cut case when the only penalty
1657 // bit is death, we die immediately, rather than timing
1658 // the violation's duration. This makes it convenient to
1659 // use in unit tests too, rather than waiting on a Looper.
1660 //
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001661 // TODO: if in gather mode, ignore Looper.myLooper() and always
1662 // go into this immediate mode?
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001663 if (looper == null || (info.mPenaltyMask == PENALTY_DEATH)) {
Kurt Nelson46974a22017-08-30 13:30:26 -07001664 info.durationMillis = -1; // unknown (redundant, already set)
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001665 onThreadPolicyViolation(info);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001666 return;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001667 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001668
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001669 final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001670 if (records.size() >= MAX_OFFENSES_PER_LOOP) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001671 // Not worth measuring. Too many offenses in one loop.
1672 return;
1673 }
1674 records.add(info);
1675 if (records.size() > 1) {
1676 // There's already been a violation this loop, so we've already
1677 // registered an idle handler to process the list of violations
1678 // at the end of this Looper's loop.
1679 return;
1680 }
1681
Kurt Nelson46974a22017-08-30 13:30:26 -07001682 final IWindowManager windowManager =
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001683 info.penaltyEnabled(PENALTY_FLASH) ? sWindowManager.get() : null;
Brad Fitzpatrick68044332010-11-22 18:19:48 -08001684 if (windowManager != null) {
1685 try {
1686 windowManager.showStrictModeViolation(true);
1687 } catch (RemoteException unused) {
1688 }
1689 }
1690
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001691 // We post a runnable to a Handler (== delay 0 ms) for
1692 // measuring the end time of a violation instead of using
1693 // an IdleHandler (as was previously used) because an
1694 // IdleHandler may not run for quite a long period of time
1695 // if an ongoing animation is happening and continually
1696 // posting ASAP (0 ms) animation steps. Animations are
1697 // throttled back to 60fps via SurfaceFlinger/View
1698 // invalidates, _not_ by posting frame updates every 16
1699 // milliseconds.
Kurt Nelson46974a22017-08-30 13:30:26 -07001700 THREAD_HANDLER
1701 .get()
1702 .postAtFrontOfQueue(
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001703 () -> {
1704 long loopFinishTime = SystemClock.uptimeMillis();
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001705
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001706 // Note: we do this early, before handling the
1707 // violation below, as handling the violation
1708 // may include PENALTY_DEATH and we don't want
1709 // to keep the red border on.
1710 if (windowManager != null) {
1711 try {
1712 windowManager.showStrictModeViolation(false);
1713 } catch (RemoteException unused) {
Kurt Nelson46974a22017-08-30 13:30:26 -07001714 }
Kurt Nelson46974a22017-08-30 13:30:26 -07001715 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001716
1717 for (int n = 0; n < records.size(); ++n) {
1718 ViolationInfo v = records.get(n);
1719 v.violationNumThisLoop = n + 1;
1720 v.durationMillis =
1721 (int) (loopFinishTime - v.violationUptimeMillis);
1722 onThreadPolicyViolation(v);
1723 }
1724 records.clear();
Kurt Nelson46974a22017-08-30 13:30:26 -07001725 });
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001726 }
1727
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001728 // Note: It's possible (even quite likely) that the
1729 // thread-local policy mask has changed from the time the
1730 // violation fired and now (after the violating code ran) due
1731 // to people who push/pop temporary policy in regions of code,
1732 // hence the policy being passed around.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001733 void onThreadPolicyViolation(final ViolationInfo info) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001734 if (LOG_V) Log.d(TAG, "onThreadPolicyViolation; penalty=" + info.mPenaltyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001735
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001736 if (info.penaltyEnabled(PENALTY_GATHER)) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001737 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001738 if (violations == null) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001739 violations = new ArrayList<>(1);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001740 gatheredViolations.set(violations);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001741 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001742 for (ViolationInfo previous : violations) {
Kurt Nelson0918c932017-09-07 10:56:56 -07001743 if (info.getStackTrace().equals(previous.getStackTrace())) {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001744 // Duplicate. Don't log.
1745 return;
1746 }
1747 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001748 violations.add(info);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001749 return;
1750 }
1751
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001752 // Not perfect, but fast and good enough for dup suppression.
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001753 Integer crashFingerprint = info.hashCode();
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001754 long lastViolationTime = 0;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001755 if (mLastViolationTime != null) {
1756 Long vtime = mLastViolationTime.get(crashFingerprint);
1757 if (vtime != null) {
1758 lastViolationTime = vtime;
1759 }
1760 } else {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07001761 mLastViolationTime = new ArrayMap<>(1);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001762 }
1763 long now = SystemClock.uptimeMillis();
1764 mLastViolationTime.put(crashFingerprint, now);
Kurt Nelson46974a22017-08-30 13:30:26 -07001765 long timeSinceLastViolationMillis =
1766 lastViolationTime == 0 ? Long.MAX_VALUE : (now - lastViolationTime);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001767
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001768 if (info.penaltyEnabled(PENALTY_LOG)
Kurt Nelson46974a22017-08-30 13:30:26 -07001769 && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07001770 sLogger.log(info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001771 }
1772
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001773 final Violation violation = info.mViolation;
1774
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001775 // Penalties that ActivityManager should execute on our behalf.
1776 int penaltyMask = 0;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001777
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001778 if (info.penaltyEnabled(PENALTY_DIALOG)
Kurt Nelson46974a22017-08-30 13:30:26 -07001779 && timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001780 penaltyMask |= PENALTY_DIALOG;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001781 }
1782
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001783 if (info.penaltyEnabled(PENALTY_DROPBOX) && lastViolationTime == 0) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001784 penaltyMask |= PENALTY_DROPBOX;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001785 }
1786
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001787 if (penaltyMask != 0) {
1788 final boolean justDropBox = (info.mPenaltyMask == PENALTY_DROPBOX);
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001789 if (justDropBox) {
1790 // If all we're going to ask the activity manager
1791 // to do is dropbox it (the common case during
1792 // platform development), we can avoid doing this
1793 // call synchronously which Binder data suggests
1794 // isn't always super fast, despite the implementation
1795 // in the ActivityManager trying to be mostly async.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001796 dropboxViolationAsync(penaltyMask, info);
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001797 } else {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001798 handleApplicationStrictModeViolation(penaltyMask, info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001799 }
1800 }
1801
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001802 if (info.penaltyEnabled(PENALTY_DEATH)) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001803 throw new RuntimeException("StrictMode ThreadPolicy violation", violation);
1804 }
1805
1806 // penaltyDeath will cause penaltyCallback to no-op since we cannot guarantee the
1807 // executor finishes before crashing.
1808 final OnThreadViolationListener listener = sThreadViolationListener.get();
1809 final Executor executor = sThreadViolationExecutor.get();
1810 if (listener != null && executor != null) {
1811 try {
1812 executor.execute(
1813 () -> {
1814 // Lift violated policy to prevent infinite recursion.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001815 ThreadPolicy oldPolicy = StrictMode.allowThreadViolations();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001816 try {
1817 listener.onThreadViolation(violation);
1818 } finally {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001819 StrictMode.setThreadPolicy(oldPolicy);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001820 }
1821 });
1822 } catch (RejectedExecutionException e) {
1823 Log.e(TAG, "ThreadPolicy penaltyCallback failed", e);
1824 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001825 }
1826 }
1827 }
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001828
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001829 private static final BlockGuard.VmPolicy VM_ANDROID_POLICY = new BlockGuard.VmPolicy() {
1830 @Override
1831 public void onPathAccess(String path) {
1832 if (path == null) return;
1833
1834 // NOTE: keep credential-protected paths in sync with Environment.java
1835 if (path.startsWith("/data/user/")
1836 || path.startsWith("/data/media/")
1837 || path.startsWith("/data/system_ce/")
1838 || path.startsWith("/data/misc_ce/")
1839 || path.startsWith("/data/vendor_ce/")
1840 || path.startsWith("/storage/emulated/")) {
1841 final int second = path.indexOf('/', 1);
1842 final int third = path.indexOf('/', second + 1);
1843 final int fourth = path.indexOf('/', third + 1);
1844 if (fourth == -1) return;
1845
1846 try {
1847 final int userId = Integer.parseInt(path.substring(third + 1, fourth));
1848 onCredentialProtectedPathAccess(path, userId);
1849 } catch (NumberFormatException ignored) {
1850 }
1851 } else if (path.startsWith("/data/data/")) {
1852 onCredentialProtectedPathAccess(path, UserHandle.USER_SYSTEM);
1853 }
1854 }
1855 };
1856
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001857 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001858 * In the common case, as set by conditionallyEnableDebugLogging, we're just dropboxing any
1859 * violations but not showing a dialog, not loggging, and not killing the process. In these
1860 * cases we don't need to do a synchronous call to the ActivityManager. This is used by both
1861 * per-thread and vm-wide violations when applicable.
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001862 */
1863 private static void dropboxViolationAsync(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001864 final int penaltyMask, final ViolationInfo info) {
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001865 int outstanding = sDropboxCallsInFlight.incrementAndGet();
1866 if (outstanding > 20) {
1867 // What's going on? Let's not make make the situation
1868 // worse and just not log.
1869 sDropboxCallsInFlight.decrementAndGet();
1870 return;
1871 }
1872
1873 if (LOG_V) Log.d(TAG, "Dropboxing async; in-flight=" + outstanding);
1874
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001875 BackgroundThread.getHandler().post(() -> {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001876 handleApplicationStrictModeViolation(penaltyMask, info);
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001877 int outstandingInner = sDropboxCallsInFlight.decrementAndGet();
1878 if (LOG_V) Log.d(TAG, "Dropbox complete; in-flight=" + outstandingInner);
1879 });
1880 }
1881
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001882 private static void handleApplicationStrictModeViolation(int penaltyMask,
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001883 ViolationInfo info) {
1884 final int oldMask = getThreadPolicyMask();
1885 try {
1886 // First, remove any policy before we call into the Activity Manager,
1887 // otherwise we'll infinite recurse as we try to log policy violations
1888 // to disk, thus violating policy, thus requiring logging, etc...
1889 // We restore the current policy below, in the finally block.
1890 setThreadPolicyMask(0);
1891
1892 IActivityManager am = ActivityManager.getService();
1893 if (am == null) {
1894 Log.w(TAG, "No activity manager; failed to Dropbox violation.");
1895 } else {
1896 am.handleApplicationStrictModeViolation(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001897 RuntimeInit.getApplicationObject(), penaltyMask, info);
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001898 }
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001899 } catch (RemoteException e) {
1900 if (e instanceof DeadObjectException) {
1901 // System process is dead; ignore
1902 } else {
1903 Log.e(TAG, "RemoteException handling StrictMode violation", e);
1904 }
1905 } finally {
1906 setThreadPolicyMask(oldMask);
1907 }
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001908 }
1909
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001910 private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001911 public void report(String message, Throwable allocationSite) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001912 onVmPolicyViolation(new LeakedClosableViolation(message, allocationSite));
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001913 }
1914 }
1915
Kurt Nelson46974a22017-08-30 13:30:26 -07001916 /** Called from Parcel.writeNoException() */
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001917 /* package */ static boolean hasGatheredViolations() {
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001918 return gatheredViolations.get() != null;
1919 }
1920
1921 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001922 * Called from Parcel.writeException(), so we drop this memory and don't incorrectly attribute
1923 * it to the wrong caller on the next Binder call on this thread.
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001924 */
1925 /* package */ static void clearGatheredViolations() {
1926 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001927 }
1928
Kurt Nelson46974a22017-08-30 13:30:26 -07001929 /** @hide */
Artur Satayevf0b7d0b2019-11-04 11:16:45 +00001930 @UnsupportedAppUsage
Jeff Sharkeyc6091162018-06-29 17:15:40 -06001931 @TestApi
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001932 public static void conditionallyCheckInstanceCounts() {
1933 VmPolicy policy = getVmPolicy();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001934 int policySize = policy.classInstanceLimit.size();
1935 if (policySize == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001936 return;
1937 }
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08001938
1939 System.gc();
1940 System.runFinalization();
1941 System.gc();
1942
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001943 // Note: classInstanceLimit is immutable, so this is lock-free
Mathieu Chartierd288a262015-07-10 13:44:42 -07001944 // Create the classes array.
1945 Class[] classes = policy.classInstanceLimit.keySet().toArray(new Class[policySize]);
1946 long[] instanceCounts = VMDebug.countInstancesOfClasses(classes, false);
1947 for (int i = 0; i < classes.length; ++i) {
1948 Class klass = classes[i];
1949 int limit = policy.classInstanceLimit.get(klass);
1950 long instances = instanceCounts[i];
1951 if (instances > limit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001952 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001953 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001954 }
1955 }
1956
1957 private static long sLastInstanceCountCheckMillis = 0;
Kurt Nelson46974a22017-08-30 13:30:26 -07001958 private static boolean sIsIdlerRegistered = false; // guarded by StrictMode.class
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001959 private static final MessageQueue.IdleHandler sProcessIdleHandler =
1960 new MessageQueue.IdleHandler() {
1961 public boolean queueIdle() {
1962 long now = SystemClock.uptimeMillis();
1963 if (now - sLastInstanceCountCheckMillis > 30 * 1000) {
1964 sLastInstanceCountCheckMillis = now;
1965 conditionallyCheckInstanceCounts();
1966 }
1967 return true;
1968 }
1969 };
1970
1971 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001972 * Sets the policy for what actions in the VM process (on any thread) should be detected, as
1973 * well as the penalty if such actions occur.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001974 *
1975 * @param policy the policy to put into place
1976 */
1977 public static void setVmPolicy(final VmPolicy policy) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001978 synchronized (StrictMode.class) {
1979 sVmPolicy = policy;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001980 setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001981
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001982 Looper looper = Looper.getMainLooper();
1983 if (looper != null) {
1984 MessageQueue mq = looper.mQueue;
Kurt Nelson46974a22017-08-30 13:30:26 -07001985 if (policy.classInstanceLimit.size() == 0
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001986 || (sVmPolicy.mask & PENALTY_ALL) == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001987 mq.removeIdleHandler(sProcessIdleHandler);
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001988 sIsIdlerRegistered = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001989 } else if (!sIsIdlerRegistered) {
1990 mq.addIdleHandler(sProcessIdleHandler);
1991 sIsIdlerRegistered = true;
1992 }
1993 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001994
1995 int networkPolicy = NETWORK_POLICY_ACCEPT;
Kurt Nelson2c883f32017-09-01 10:52:45 -07001996 if ((sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0) {
1997 if ((sVmPolicy.mask & PENALTY_DEATH) != 0
1998 || (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0) {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001999 networkPolicy = NETWORK_POLICY_REJECT;
2000 } else {
2001 networkPolicy = NETWORK_POLICY_LOG;
2002 }
2003 }
2004
Kurt Nelson46974a22017-08-30 13:30:26 -07002005 final INetworkManagementService netd =
2006 INetworkManagementService.Stub.asInterface(
2007 ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
Jeff Sharkey605eb792014-11-04 13:34:06 -08002008 if (netd != null) {
2009 try {
2010 netd.setUidCleartextNetworkPolicy(android.os.Process.myUid(), networkPolicy);
2011 } catch (RemoteException ignored) {
2012 }
2013 } else if (networkPolicy != NETWORK_POLICY_ACCEPT) {
2014 Log.w(TAG, "Dropping requested network policy due to missing service!");
2015 }
Narayan Kamathad1b2a92018-03-28 11:29:40 +01002016
2017
2018 if ((sVmPolicy.mask & DETECT_VM_NON_SDK_API_USAGE) != 0) {
2019 VMRuntime.setNonSdkApiUsageConsumer(sNonSdkApiUsageConsumer);
Mathew Inwoodd82a7432018-04-19 14:42:58 +01002020 VMRuntime.setDedupeHiddenApiWarnings(false);
Narayan Kamathad1b2a92018-03-28 11:29:40 +01002021 } else {
2022 VMRuntime.setNonSdkApiUsageConsumer(null);
Mathew Inwoodd82a7432018-04-19 14:42:58 +01002023 VMRuntime.setDedupeHiddenApiWarnings(true);
Narayan Kamathad1b2a92018-03-28 11:29:40 +01002024 }
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002025
2026 setBlockGuardVmPolicy(sVmPolicy.mask);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002027 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002028 }
2029
Kurt Nelson46974a22017-08-30 13:30:26 -07002030 /** Gets the current VM policy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002031 public static VmPolicy getVmPolicy() {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002032 synchronized (StrictMode.class) {
2033 return sVmPolicy;
2034 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002035 }
2036
2037 /**
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07002038 * Enable the recommended StrictMode defaults, with violations just being logged.
2039 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002040 * <p>This catches disk and network access on the main thread, as well as leaked SQLite cursors
2041 * and unclosed resources. This is simply a wrapper around {@link #setVmPolicy} and {@link
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07002042 * #setThreadPolicy}.
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07002043 */
2044 public static void enableDefaults() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002045 setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
2046 setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07002047 }
2048
Kurt Nelson46974a22017-08-30 13:30:26 -07002049 /** @hide */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002050 public static boolean vmSqliteObjectLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002051 return (sVmPolicy.mask & DETECT_VM_CURSOR_LEAKS) != 0;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002052 }
2053
Kurt Nelson46974a22017-08-30 13:30:26 -07002054 /** @hide */
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07002055 public static boolean vmClosableObjectLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002056 return (sVmPolicy.mask & DETECT_VM_CLOSABLE_LEAKS) != 0;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07002057 }
2058
Kurt Nelson46974a22017-08-30 13:30:26 -07002059 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002060 public static boolean vmRegistrationLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002061 return (sVmPolicy.mask & DETECT_VM_REGISTRATION_LEAKS) != 0;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002062 }
2063
Kurt Nelson46974a22017-08-30 13:30:26 -07002064 /** @hide */
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002065 public static boolean vmFileUriExposureEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002066 return (sVmPolicy.mask & DETECT_VM_FILE_URI_EXPOSURE) != 0;
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002067 }
2068
Kurt Nelson46974a22017-08-30 13:30:26 -07002069 /** @hide */
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -07002070 public static boolean vmCleartextNetworkEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002071 return (sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0;
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002072 }
2073
Kurt Nelson46974a22017-08-30 13:30:26 -07002074 /** @hide */
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -07002075 public static boolean vmContentUriWithoutPermissionEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002076 return (sVmPolicy.mask & DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION) != 0;
Jeff Sharkey605eb792014-11-04 13:34:06 -08002077 }
2078
Kurt Nelson46974a22017-08-30 13:30:26 -07002079 /** @hide */
Jeff Sharkey619a5112017-01-19 11:55:54 -07002080 public static boolean vmUntaggedSocketEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002081 return (sVmPolicy.mask & DETECT_VM_UNTAGGED_SOCKET) != 0;
Jeff Sharkey619a5112017-01-19 11:55:54 -07002082 }
2083
Kurt Nelson46974a22017-08-30 13:30:26 -07002084 /** @hide */
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06002085 public static boolean vmImplicitDirectBootEnabled() {
2086 return (sVmPolicy.mask & DETECT_VM_IMPLICIT_DIRECT_BOOT) != 0;
2087 }
2088
2089 /** @hide */
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002090 public static boolean vmCredentialProtectedWhileLockedEnabled() {
2091 return (sVmPolicy.mask & DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED) != 0;
2092 }
2093
2094 /** @hide */
Andrii Kulian5877c7d2020-01-29 16:57:32 -08002095 public static boolean vmIncorrectContextUseEnabled() {
2096 return (sVmPolicy.mask & DETECT_VM_INCORRECT_CONTEXT_USE) != 0;
2097 }
2098
2099 /** @hide */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002100 public static void onSqliteObjectLeaked(String message, Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002101 onVmPolicyViolation(new SqliteObjectLeakedViolation(message, originStack));
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08002102 }
2103
Kurt Nelson46974a22017-08-30 13:30:26 -07002104 /** @hide */
Andrei Onea24ec3212019-03-15 17:35:05 +00002105 @UnsupportedAppUsage
Steve Block08d584c2011-05-17 19:05:03 +01002106 public static void onWebViewMethodCalledOnWrongThread(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002107 onVmPolicyViolation(new WebViewMethodCalledOnWrongThreadViolation(originStack));
Steve Block08d584c2011-05-17 19:05:03 +01002108 }
2109
Kurt Nelson46974a22017-08-30 13:30:26 -07002110 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002111 public static void onIntentReceiverLeaked(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002112 onVmPolicyViolation(new IntentReceiverLeakedViolation(originStack));
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002113 }
2114
Kurt Nelson46974a22017-08-30 13:30:26 -07002115 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002116 public static void onServiceConnectionLeaked(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002117 onVmPolicyViolation(new ServiceConnectionLeakedViolation(originStack));
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002118 }
2119
Kurt Nelson46974a22017-08-30 13:30:26 -07002120 /** @hide */
Jeff Sharkey344744b2016-01-28 19:03:30 -07002121 public static void onFileUriExposed(Uri uri, String location) {
2122 final String message = uri + " exposed beyond app through " + location;
Kurt Nelson2c883f32017-09-01 10:52:45 -07002123 if ((sVmPolicy.mask & PENALTY_DEATH_ON_FILE_URI_EXPOSURE) != 0) {
Jeff Sharkey344744b2016-01-28 19:03:30 -07002124 throw new FileUriExposedException(message);
2125 } else {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002126 onVmPolicyViolation(new FileUriExposedViolation(message));
Jeff Sharkey344744b2016-01-28 19:03:30 -07002127 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08002128 }
2129
Kurt Nelson46974a22017-08-30 13:30:26 -07002130 /** @hide */
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002131 public static void onContentUriWithoutPermission(Uri uri, String location) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002132 onVmPolicyViolation(new ContentUriWithoutPermissionViolation(uri, location));
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002133 }
2134
Kurt Nelson46974a22017-08-30 13:30:26 -07002135 /** @hide */
Jeff Sharkey605eb792014-11-04 13:34:06 -08002136 public static void onCleartextNetworkDetected(byte[] firstPacket) {
2137 byte[] rawAddr = null;
2138 if (firstPacket != null) {
2139 if (firstPacket.length >= 20 && (firstPacket[0] & 0xf0) == 0x40) {
2140 // IPv4
2141 rawAddr = new byte[4];
2142 System.arraycopy(firstPacket, 16, rawAddr, 0, 4);
2143 } else if (firstPacket.length >= 40 && (firstPacket[0] & 0xf0) == 0x60) {
2144 // IPv6
2145 rawAddr = new byte[16];
2146 System.arraycopy(firstPacket, 24, rawAddr, 0, 16);
2147 }
2148 }
2149
2150 final int uid = android.os.Process.myUid();
Jeff Sharkeyc6091162018-06-29 17:15:40 -06002151 String msg = "Detected cleartext network traffic from UID " + uid;
Jeff Sharkey605eb792014-11-04 13:34:06 -08002152 if (rawAddr != null) {
2153 try {
Kurt Nelsoncf8c4fa2017-09-19 12:26:02 -07002154 msg += " to " + InetAddress.getByAddress(rawAddr);
Jeff Sharkey605eb792014-11-04 13:34:06 -08002155 } catch (UnknownHostException ignored) {
2156 }
2157 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002158 msg += HexDump.dumpHexString(firstPacket).trim() + " ";
Kurt Nelson2c883f32017-09-01 10:52:45 -07002159 final boolean forceDeath = (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002160 onVmPolicyViolation(new CleartextNetworkViolation(msg), forceDeath);
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002161 }
2162
Kurt Nelson46974a22017-08-30 13:30:26 -07002163 /** @hide */
Jeff Sharkey619a5112017-01-19 11:55:54 -07002164 public static void onUntaggedSocket() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002165 onVmPolicyViolation(new UntaggedSocketViolation());
Jeff Sharkey619a5112017-01-19 11:55:54 -07002166 }
2167
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06002168 /** @hide */
2169 public static void onImplicitDirectBoot() {
2170 onVmPolicyViolation(new ImplicitDirectBootViolation());
2171 }
2172
Andrii Kulian5877c7d2020-01-29 16:57:32 -08002173 /** @hide */
2174 public static void onIncorrectContextUsed(String message, Throwable originStack) {
2175 onVmPolicyViolation(new IncorrectContextUseViolation(message, originStack));
2176 }
2177
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002178 /** Assume locked until we hear otherwise */
2179 private static volatile boolean sUserKeyUnlocked = false;
2180
2181 private static boolean isUserKeyUnlocked(int userId) {
2182 final IStorageManager storage = IStorageManager.Stub
2183 .asInterface(ServiceManager.getService("mount"));
2184 if (storage != null) {
2185 try {
2186 return storage.isUserKeyUnlocked(userId);
2187 } catch (RemoteException ignored) {
2188 }
2189 }
2190 return false;
2191 }
2192
2193 /** @hide */
2194 private static void onCredentialProtectedPathAccess(String path, int userId) {
2195 // We can cache the unlocked state for the userId we're running as,
2196 // since any relocking of that user will always result in our
2197 // process being killed to release any CE FDs we're holding onto.
2198 if (userId == UserHandle.myUserId()) {
2199 if (sUserKeyUnlocked) {
2200 return;
2201 } else if (isUserKeyUnlocked(userId)) {
2202 sUserKeyUnlocked = true;
2203 return;
2204 }
2205 } else if (isUserKeyUnlocked(userId)) {
2206 return;
2207 }
2208
2209 onVmPolicyViolation(new CredentialProtectedWhileLockedViolation(
2210 "Accessed credential protected path " + path + " while user " + userId
2211 + " was locked"));
2212 }
2213
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002214 // Map from VM violation fingerprint to uptime millis.
Andrei Onea24ec3212019-03-15 17:35:05 +00002215 @UnsupportedAppUsage
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002216 private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<>();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002217
Kurt Nelson46974a22017-08-30 13:30:26 -07002218 /** @hide */
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002219 public static void onVmPolicyViolation(Violation originStack) {
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002220 onVmPolicyViolation(originStack, false);
Jeff Sharkey605eb792014-11-04 13:34:06 -08002221 }
2222
Kurt Nelson46974a22017-08-30 13:30:26 -07002223 /** @hide */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002224 public static void onVmPolicyViolation(Violation violation, boolean forceDeath) {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002225 final boolean penaltyDropbox = (sVmPolicy.mask & PENALTY_DROPBOX) != 0;
2226 final boolean penaltyDeath = ((sVmPolicy.mask & PENALTY_DEATH) != 0) || forceDeath;
2227 final boolean penaltyLog = (sVmPolicy.mask & PENALTY_LOG) != 0;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002228
2229 final int penaltyMask = (sVmPolicy.mask & PENALTY_ALL);
2230 final ViolationInfo info = new ViolationInfo(violation, penaltyMask);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002231
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002232 // Erase stuff not relevant for process-wide violations
2233 info.numAnimationsRunning = 0;
2234 info.tags = null;
2235 info.broadcastIntentAction = null;
2236
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002237 final Integer fingerprint = info.hashCode();
2238 final long now = SystemClock.uptimeMillis();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002239 long lastViolationTime;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002240 long timeSinceLastViolationMillis = Long.MAX_VALUE;
2241 synchronized (sLastVmViolationTime) {
2242 if (sLastVmViolationTime.containsKey(fingerprint)) {
2243 lastViolationTime = sLastVmViolationTime.get(fingerprint);
2244 timeSinceLastViolationMillis = now - lastViolationTime;
2245 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002246 if (timeSinceLastViolationMillis > MIN_VM_INTERVAL_MS) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002247 sLastVmViolationTime.put(fingerprint, now);
2248 }
2249 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002250 if (timeSinceLastViolationMillis <= MIN_VM_INTERVAL_MS) {
2251 // Rate limit all penalties.
2252 return;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -06002253 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002254
2255 if (penaltyLog && sLogger != null && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07002256 sLogger.log(info);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002257 }
2258
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002259 if (penaltyDropbox) {
2260 if (penaltyDeath) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002261 handleApplicationStrictModeViolation(PENALTY_DROPBOX, info);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002262 } else {
2263 // Common case for userdebug/eng builds. If no death and
2264 // just dropboxing, we can do the ActivityManager call
2265 // asynchronously.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002266 dropboxViolationAsync(PENALTY_DROPBOX, info);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002267 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002268 }
2269
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08002270 if (penaltyDeath) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002271 System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
2272 Process.killProcess(Process.myPid());
2273 System.exit(10);
2274 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002275
2276 // If penaltyDeath, we can't guarantee this callback finishes before the process dies for
2277 // all executors. penaltyDeath supersedes penaltyCallback.
2278 if (sVmPolicy.mListener != null && sVmPolicy.mCallbackExecutor != null) {
2279 final OnVmViolationListener listener = sVmPolicy.mListener;
2280 try {
2281 sVmPolicy.mCallbackExecutor.execute(
2282 () -> {
2283 // Lift violated policy to prevent infinite recursion.
2284 VmPolicy oldPolicy = allowVmViolations();
2285 try {
2286 listener.onVmViolation(violation);
2287 } finally {
2288 setVmPolicy(oldPolicy);
2289 }
2290 });
2291 } catch (RejectedExecutionException e) {
2292 Log.e(TAG, "VmPolicy penaltyCallback failed", e);
2293 }
2294 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002295 }
2296
Kurt Nelson46974a22017-08-30 13:30:26 -07002297 /** Called from Parcel.writeNoException() */
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002298 /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002299 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002300 if (violations == null) {
2301 p.writeInt(0);
2302 } else {
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002303 // To avoid taking up too much transaction space, only include
2304 // details for the first 3 violations. Deep inside, CrashInfo
2305 // will truncate each stack trace to ~20kB.
2306 final int size = Math.min(violations.size(), 3);
2307 p.writeInt(size);
2308 for (int i = 0; i < size; i++) {
2309 violations.get(i).writeToParcel(p, 0);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002310 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002311 }
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002312 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002313 }
2314
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002315 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002316 * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS, we here
2317 * read back all the encoded violations.
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002318 */
2319 /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002320 Throwable localCallSite = new Throwable();
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002321 final int policyMask = getThreadPolicyMask();
2322 final boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002323
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002324 final int size = p.readInt();
2325 for (int i = 0; i < size; i++) {
2326 final ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
Kurt Nelson0918c932017-09-07 10:56:56 -07002327 info.addLocalStack(localCallSite);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002328 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2329 if (policy instanceof AndroidBlockGuardPolicy) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002330 ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002331 }
2332 }
2333 }
2334
2335 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002336 * Called from android_util_Binder.cpp's android_os_Parcel_enforceInterface when an incoming
2337 * Binder call requires changing the StrictMode policy mask. The role of this function is to ask
2338 * Binder for its current (native) thread-local policy value and synchronize it to libcore's
2339 * (Java) thread-local policy value.
Brad Fitzpatrick727de402010-07-07 16:06:39 -07002340 */
Andrei Onea24ec3212019-03-15 17:35:05 +00002341 @UnsupportedAppUsage
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002342 private static void onBinderStrictModePolicyChange(@ThreadPolicyMask int newPolicy) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07002343 setBlockGuardPolicy(newPolicy);
2344 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002345
2346 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002347 * A tracked, critical time span. (e.g. during an animation.)
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002348 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002349 * <p>The object itself is a linked list node, to avoid any allocations during rapid span
2350 * entries and exits.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002351 *
2352 * @hide
2353 */
2354 public static class Span {
2355 private String mName;
2356 private long mCreateMillis;
2357 private Span mNext;
Kurt Nelson46974a22017-08-30 13:30:26 -07002358 private Span mPrev; // not used when in freeList, only active
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002359 private final ThreadSpanState mContainerState;
2360
2361 Span(ThreadSpanState threadState) {
2362 mContainerState = threadState;
2363 }
2364
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002365 // Empty constructor for the NO_OP_SPAN
2366 protected Span() {
2367 mContainerState = null;
2368 }
2369
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002370 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002371 * To be called when the critical span is complete (i.e. the animation is done animating).
2372 * This can be called on any thread (even a different one from where the animation was
2373 * taking place), but that's only a defensive implementation measure. It really makes no
2374 * sense for you to call this on thread other than that where you created it.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002375 *
2376 * @hide
2377 */
Andrei Onea24ec3212019-03-15 17:35:05 +00002378 @UnsupportedAppUsage
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002379 public void finish() {
2380 ThreadSpanState state = mContainerState;
2381 synchronized (state) {
2382 if (mName == null) {
2383 // Duplicate finish call. Ignore.
2384 return;
2385 }
2386
2387 // Remove ourselves from the active list.
2388 if (mPrev != null) {
2389 mPrev.mNext = mNext;
2390 }
2391 if (mNext != null) {
2392 mNext.mPrev = mPrev;
2393 }
2394 if (state.mActiveHead == this) {
2395 state.mActiveHead = mNext;
2396 }
2397
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002398 state.mActiveSize--;
2399
2400 if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
2401
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002402 this.mCreateMillis = -1;
2403 this.mName = null;
2404 this.mPrev = null;
2405 this.mNext = null;
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002406
2407 // Add ourselves to the freeList, if it's not already
2408 // too big.
2409 if (state.mFreeListSize < 5) {
2410 this.mNext = state.mFreeListHead;
2411 state.mFreeListHead = this;
2412 state.mFreeListSize++;
2413 }
2414 }
2415 }
2416 }
2417
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002418 // The no-op span that's used in user builds.
Kurt Nelson46974a22017-08-30 13:30:26 -07002419 private static final Span NO_OP_SPAN =
2420 new Span() {
2421 public void finish() {
2422 // Do nothing.
2423 }
2424 };
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002425
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002426 /**
2427 * Linked lists of active spans and a freelist.
2428 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002429 * <p>Locking notes: there's one of these structures per thread and all members of this
2430 * structure (as well as the Span nodes under it) are guarded by the ThreadSpanState object
2431 * instance. While in theory there'd be no locking required because it's all local per-thread,
2432 * the finish() method above is defensive against people calling it on a different thread from
2433 * where they created the Span, hence the locking.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002434 */
2435 private static class ThreadSpanState {
Kurt Nelson46974a22017-08-30 13:30:26 -07002436 public Span mActiveHead; // doubly-linked list.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002437 public int mActiveSize;
Kurt Nelson46974a22017-08-30 13:30:26 -07002438 public Span mFreeListHead; // singly-linked list. only changes at head.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002439 public int mFreeListSize;
2440 }
2441
2442 private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
2443 new ThreadLocal<ThreadSpanState>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07002444 @Override
2445 protected ThreadSpanState initialValue() {
2446 return new ThreadSpanState();
2447 }
2448 };
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002449
Andrei Onea24ec3212019-03-15 17:35:05 +00002450 @UnsupportedAppUsage
Kurt Nelson46974a22017-08-30 13:30:26 -07002451 private static Singleton<IWindowManager> sWindowManager =
2452 new Singleton<IWindowManager>() {
2453 protected IWindowManager create() {
2454 return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
2455 }
2456 };
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -08002457
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002458 /**
2459 * Enter a named critical span (e.g. an animation)
2460 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002461 * <p>The name is an arbitary label (or tag) that will be applied to any strictmode violation
2462 * that happens while this span is active. You must call finish() on the span when done.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002463 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002464 * <p>This will never return null, but on devices without debugging enabled, this may return a
2465 * dummy object on which the finish() method is a no-op.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002466 *
2467 * <p>TODO: add CloseGuard to this, verifying callers call finish.
2468 *
2469 * @hide
2470 */
Andrei Onea24ec3212019-03-15 17:35:05 +00002471 @UnsupportedAppUsage
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002472 public static Span enterCriticalSpan(String name) {
Jeff Sharkey5ab02432017-06-27 11:01:36 -06002473 if (Build.IS_USER) {
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002474 return NO_OP_SPAN;
2475 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002476 if (name == null || name.isEmpty()) {
2477 throw new IllegalArgumentException("name must be non-null and non-empty");
2478 }
2479 ThreadSpanState state = sThisThreadSpanState.get();
2480 Span span = null;
2481 synchronized (state) {
2482 if (state.mFreeListHead != null) {
2483 span = state.mFreeListHead;
2484 state.mFreeListHead = span.mNext;
2485 state.mFreeListSize--;
2486 } else {
2487 // Shouldn't have to do this often.
2488 span = new Span(state);
2489 }
2490 span.mName = name;
2491 span.mCreateMillis = SystemClock.uptimeMillis();
2492 span.mNext = state.mActiveHead;
2493 span.mPrev = null;
2494 state.mActiveHead = span;
2495 state.mActiveSize++;
2496 if (span.mNext != null) {
2497 span.mNext.mPrev = span;
2498 }
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002499 if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002500 }
2501 return span;
2502 }
2503
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002504 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002505 * For code to note that it's slow. This is a no-op unless the current thread's {@link
2506 * android.os.StrictMode.ThreadPolicy} has {@link
2507 * android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls} enabled.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002508 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002509 * @param name a short string for the exception stack trace that's built if when this fires.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002510 */
2511 public static void noteSlowCall(String name) {
2512 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2513 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2514 // StrictMode not enabled.
2515 return;
2516 }
2517 ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
2518 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002519
2520 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002521 * For code to note that a resource was obtained using a type other than its defined type. This
2522 * is a no-op unless the current thread's {@link android.os.StrictMode.ThreadPolicy} has {@link
2523 * android.os.StrictMode.ThreadPolicy.Builder#detectResourceMismatches()} enabled.
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002524 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002525 * @param tag an object for the exception stack trace that's built if when this fires.
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002526 * @hide
2527 */
2528 public static void noteResourceMismatch(Object tag) {
2529 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2530 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2531 // StrictMode not enabled.
2532 return;
2533 }
2534 ((AndroidBlockGuardPolicy) policy).onResourceMismatch(tag);
2535 }
2536
Kurt Nelson46974a22017-08-30 13:30:26 -07002537 /** @hide */
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01002538 public static void noteUnbufferedIO() {
2539 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2540 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2541 // StrictMode not enabled.
2542 return;
2543 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002544 policy.onUnbufferedIO();
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01002545 }
2546
Kurt Nelson46974a22017-08-30 13:30:26 -07002547 /** @hide */
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002548 public static void noteDiskRead() {
2549 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002550 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2551 // StrictMode not enabled.
2552 return;
2553 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002554 policy.onReadFromDisk();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002555 }
2556
Kurt Nelson46974a22017-08-30 13:30:26 -07002557 /** @hide */
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002558 public static void noteDiskWrite() {
2559 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2560 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2561 // StrictMode not enabled.
2562 return;
2563 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002564 policy.onWriteToDisk();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002565 }
2566
Kurt Nelson1981f422017-10-25 13:49:26 -07002567 @GuardedBy("StrictMode.class")
2568 private static final HashMap<Class, Integer> sExpectedActivityInstanceCount = new HashMap<>();
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002569
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002570 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002571 * Returns an object that is used to track instances of activites. The activity should store a
2572 * reference to the tracker object in one of its fields.
2573 *
Jeff Brown7e442832011-06-10 18:00:16 -07002574 * @hide
2575 */
2576 public static Object trackActivity(Object instance) {
2577 return new InstanceTracker(instance);
2578 }
2579
Kurt Nelson46974a22017-08-30 13:30:26 -07002580 /** @hide */
Andrei Onea24ec3212019-03-15 17:35:05 +00002581 @UnsupportedAppUsage
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002582 public static void incrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002583 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002584 return;
2585 }
Jeff Brown7e442832011-06-10 18:00:16 -07002586
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002587 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002588 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2589 return;
2590 }
2591
Chilun762f0492020-05-13 17:20:09 +08002592 // Use the instance count from InstanceTracker as initial value.
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002593 Integer expected = sExpectedActivityInstanceCount.get(klass);
Chilun762f0492020-05-13 17:20:09 +08002594 Integer newExpected =
2595 expected == null ? InstanceTracker.getInstanceCount(klass) + 1 : expected + 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002596 sExpectedActivityInstanceCount.put(klass, newExpected);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002597 }
2598 }
2599
Kurt Nelson46974a22017-08-30 13:30:26 -07002600 /** @hide */
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002601 public static void decrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002602 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002603 return;
2604 }
Jeff Brown7e442832011-06-10 18:00:16 -07002605
2606 final int limit;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002607 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002608 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2609 return;
2610 }
2611
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002612 Integer expected = sExpectedActivityInstanceCount.get(klass);
Jeff Brown7e442832011-06-10 18:00:16 -07002613 int newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002614 if (newExpected == 0) {
2615 sExpectedActivityInstanceCount.remove(klass);
2616 } else {
2617 sExpectedActivityInstanceCount.put(klass, newExpected);
2618 }
Jeff Brown7e442832011-06-10 18:00:16 -07002619
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002620 // Note: adding 1 here to give some breathing room during
2621 // orientation changes. (shouldn't be necessary, though?)
Jeff Brown7e442832011-06-10 18:00:16 -07002622 limit = newExpected + 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002623 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002624
Jeff Brown7e442832011-06-10 18:00:16 -07002625 // Quick check.
2626 int actual = InstanceTracker.getInstanceCount(klass);
2627 if (actual <= limit) {
2628 return;
2629 }
2630
2631 // Do a GC and explicit count to double-check.
2632 // This is the work that we are trying to avoid by tracking the object instances
2633 // explicity. Running an explicit GC can be expensive (80ms) and so can walking
2634 // the heap to count instance (30ms). This extra work can make the system feel
2635 // noticeably less responsive during orientation changes when activities are
2636 // being restarted. Granted, it is only a problem when StrictMode is enabled
2637 // but it is annoying.
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08002638
2639 System.gc();
2640 System.runFinalization();
2641 System.gc();
Jeff Brown7e442832011-06-10 18:00:16 -07002642
2643 long instances = VMDebug.countInstancesOfClass(klass, false);
2644 if (instances > limit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002645 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002646 }
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002647 }
2648
2649 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002650 * Parcelable that gets sent in Binder call headers back to callers to report violations that
2651 * happened during a cross-process call.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002652 *
2653 * @hide
2654 */
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07002655 @TestApi
2656 public static final class ViolationInfo implements Parcelable {
Kurt Nelson0918c932017-09-07 10:56:56 -07002657 /** Stack and violation details. */
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002658 private final Violation mViolation;
Kurt Nelson0918c932017-09-07 10:56:56 -07002659
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002660 /** Path leading to a violation that occurred across binder. */
2661 private final Deque<StackTraceElement[]> mBinderStack = new ArrayDeque<>();
Kurt Nelson0918c932017-09-07 10:56:56 -07002662
2663 /** Memoized stack trace of full violation. */
2664 @Nullable private String mStackTrace;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002665
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002666 /** The strict mode penalty mask at the time of violation. */
2667 private final int mPenaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002668
Kurt Nelson46974a22017-08-30 13:30:26 -07002669 /** The wall time duration of the violation, when known. -1 when not known. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002670 public int durationMillis = -1;
2671
Kurt Nelson46974a22017-08-30 13:30:26 -07002672 /** The number of animations currently running. */
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002673 public int numAnimationsRunning = 0;
2674
Kurt Nelson46974a22017-08-30 13:30:26 -07002675 /** List of tags from active Span instances during this violation, or null for none. */
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002676 public String[] tags;
2677
2678 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002679 * Which violation number this was (1-based) since the last Looper loop, from the
2680 * perspective of the root caller (if it crossed any processes via Binder calls). The value
2681 * is 0 if the root caller wasn't on a Looper thread.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002682 */
2683 public int violationNumThisLoop;
2684
Kurt Nelson46974a22017-08-30 13:30:26 -07002685 /** The time (in terms of SystemClock.uptimeMillis()) that the violation occurred. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002686 public long violationUptimeMillis;
2687
2688 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002689 * The action of the Intent being broadcast to somebody's onReceive on this thread right
2690 * now, or null.
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002691 */
2692 public String broadcastIntentAction;
2693
Kurt Nelson46974a22017-08-30 13:30:26 -07002694 /** If this is a instance count violation, the number of instances in memory, else -1. */
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002695 public long numInstances = -1;
2696
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002697 /** Create an instance of ViolationInfo initialized from an exception. */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002698 ViolationInfo(Violation tr, int penaltyMask) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002699 this.mViolation = tr;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002700 this.mPenaltyMask = penaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002701 violationUptimeMillis = SystemClock.uptimeMillis();
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002702 this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002703 Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
2704 if (broadcastIntent != null) {
2705 broadcastIntentAction = broadcastIntent.getAction();
2706 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002707 ThreadSpanState state = sThisThreadSpanState.get();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002708 if (tr instanceof InstanceCountViolation) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002709 this.numInstances = ((InstanceCountViolation) tr).getNumberOfInstances();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002710 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002711 synchronized (state) {
2712 int spanActiveCount = state.mActiveSize;
2713 if (spanActiveCount > MAX_SPAN_TAGS) {
2714 spanActiveCount = MAX_SPAN_TAGS;
2715 }
2716 if (spanActiveCount != 0) {
2717 this.tags = new String[spanActiveCount];
2718 Span iter = state.mActiveHead;
2719 int index = 0;
2720 while (iter != null && index < spanActiveCount) {
2721 this.tags[index] = iter.mName;
2722 index++;
2723 iter = iter.mNext;
2724 }
2725 }
2726 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002727 }
2728
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002729 /**
2730 * Equivalent output to
2731 * {@link android.app.ApplicationErrorReport.CrashInfo#stackTrace}.
2732 */
Kurt Nelson0918c932017-09-07 10:56:56 -07002733 public String getStackTrace() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002734 if (mStackTrace == null) {
Kurt Nelson0918c932017-09-07 10:56:56 -07002735 StringWriter sw = new StringWriter();
2736 PrintWriter pw = new FastPrintWriter(sw, false, 256);
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002737 mViolation.printStackTrace(pw);
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002738 for (StackTraceElement[] traces : mBinderStack) {
Kurt Nelson0918c932017-09-07 10:56:56 -07002739 pw.append("# via Binder call with stack:\n");
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002740 for (StackTraceElement traceElement : traces) {
2741 pw.append("\tat ");
2742 pw.append(traceElement.toString());
2743 pw.append('\n');
2744 }
Kurt Nelson0918c932017-09-07 10:56:56 -07002745 }
2746 pw.flush();
2747 pw.close();
2748 mStackTrace = sw.toString();
2749 }
2750 return mStackTrace;
2751 }
2752
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002753 public Class<? extends Violation> getViolationClass() {
2754 return mViolation.getClass();
2755 }
2756
Kurt Nelson0918c932017-09-07 10:56:56 -07002757 /**
2758 * Optional message describing this violation.
2759 *
2760 * @hide
2761 */
2762 @TestApi
2763 public String getViolationDetails() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002764 return mViolation.getMessage();
Kurt Nelson0918c932017-09-07 10:56:56 -07002765 }
2766
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002767 boolean penaltyEnabled(int p) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002768 return (mPenaltyMask & p) != 0;
Kurt Nelson0918c932017-09-07 10:56:56 -07002769 }
2770
2771 /**
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002772 * Add a {@link Throwable} from the current process that caused the underlying violation. We
2773 * only preserve the stack trace elements.
Kurt Nelson0918c932017-09-07 10:56:56 -07002774 *
2775 * @hide
2776 */
2777 void addLocalStack(Throwable t) {
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002778 mBinderStack.addFirst(t.getStackTrace());
Kurt Nelson0918c932017-09-07 10:56:56 -07002779 }
2780
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002781 @Override
2782 public int hashCode() {
2783 int result = 17;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002784 if (mViolation != null) {
2785 result = 37 * result + mViolation.hashCode();
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002786 }
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002787 if (numAnimationsRunning != 0) {
2788 result *= 37;
2789 }
2790 if (broadcastIntentAction != null) {
2791 result = 37 * result + broadcastIntentAction.hashCode();
2792 }
2793 if (tags != null) {
2794 for (String tag : tags) {
2795 result = 37 * result + tag.hashCode();
2796 }
2797 }
2798 return result;
2799 }
2800
Kurt Nelson46974a22017-08-30 13:30:26 -07002801 /** Create an instance of ViolationInfo initialized from a Parcel. */
Artur Satayevf0b7d0b2019-11-04 11:16:45 +00002802 @UnsupportedAppUsage
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002803 public ViolationInfo(Parcel in) {
2804 this(in, false);
2805 }
2806
2807 /**
2808 * Create an instance of ViolationInfo initialized from a Parcel.
2809 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002810 * @param unsetGatheringBit if true, the caller is the root caller and the gathering penalty
2811 * should be removed.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002812 */
2813 public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002814 mViolation = (Violation) in.readSerializable();
Kurt Nelson0918c932017-09-07 10:56:56 -07002815 int binderStackSize = in.readInt();
2816 for (int i = 0; i < binderStackSize; i++) {
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002817 StackTraceElement[] traceElements = new StackTraceElement[in.readInt()];
2818 for (int j = 0; j < traceElements.length; j++) {
2819 StackTraceElement element =
2820 new StackTraceElement(
2821 in.readString(),
2822 in.readString(),
2823 in.readString(),
2824 in.readInt());
2825 traceElements[j] = element;
2826 }
2827 mBinderStack.add(traceElements);
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002828 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002829 int rawPenaltyMask = in.readInt();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002830 if (unsetGatheringBit) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002831 mPenaltyMask = rawPenaltyMask & ~PENALTY_GATHER;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002832 } else {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002833 mPenaltyMask = rawPenaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002834 }
2835 durationMillis = in.readInt();
2836 violationNumThisLoop = in.readInt();
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002837 numAnimationsRunning = in.readInt();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002838 violationUptimeMillis = in.readLong();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002839 numInstances = in.readLong();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002840 broadcastIntentAction = in.readString();
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002841 tags = in.readStringArray();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002842 }
2843
Kurt Nelson46974a22017-08-30 13:30:26 -07002844 /** Save a ViolationInfo instance to a parcel. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002845 @Override
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002846 public void writeToParcel(Parcel dest, int flags) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002847 dest.writeSerializable(mViolation);
Kurt Nelson0918c932017-09-07 10:56:56 -07002848 dest.writeInt(mBinderStack.size());
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002849 for (StackTraceElement[] traceElements : mBinderStack) {
2850 dest.writeInt(traceElements.length);
2851 for (StackTraceElement element : traceElements) {
2852 dest.writeString(element.getClassName());
2853 dest.writeString(element.getMethodName());
2854 dest.writeString(element.getFileName());
2855 dest.writeInt(element.getLineNumber());
2856 }
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002857 }
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002858 int start = dest.dataPosition();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002859 dest.writeInt(mPenaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002860 dest.writeInt(durationMillis);
2861 dest.writeInt(violationNumThisLoop);
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002862 dest.writeInt(numAnimationsRunning);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002863 dest.writeLong(violationUptimeMillis);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002864 dest.writeLong(numInstances);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002865 dest.writeString(broadcastIntentAction);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002866 dest.writeStringArray(tags);
Kurt Nelson46974a22017-08-30 13:30:26 -07002867 int total = dest.dataPosition() - start;
2868 if (Binder.CHECK_PARCEL_SIZE && total > 10 * 1024) {
2869 Slog.d(
2870 TAG,
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002871 "VIO: penalty="
2872 + mPenaltyMask
Kurt Nelson46974a22017-08-30 13:30:26 -07002873 + " dur="
2874 + durationMillis
2875 + " numLoop="
2876 + violationNumThisLoop
2877 + " anim="
2878 + numAnimationsRunning
2879 + " uptime="
2880 + violationUptimeMillis
2881 + " numInst="
2882 + numInstances);
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002883 Slog.d(TAG, "VIO: action=" + broadcastIntentAction);
2884 Slog.d(TAG, "VIO: tags=" + Arrays.toString(tags));
Kurt Nelson46974a22017-08-30 13:30:26 -07002885 Slog.d(TAG, "VIO: TOTAL BYTES WRITTEN: " + (dest.dataPosition() - start));
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002886 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002887 }
2888
Kurt Nelson46974a22017-08-30 13:30:26 -07002889 /** Dump a ViolationInfo instance to a Printer. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002890 public void dump(Printer pw, String prefix) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002891 pw.println(prefix + "stackTrace: " + getStackTrace());
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002892 pw.println(prefix + "penalty: " + mPenaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002893 if (durationMillis != -1) {
2894 pw.println(prefix + "durationMillis: " + durationMillis);
2895 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002896 if (numInstances != -1) {
2897 pw.println(prefix + "numInstances: " + numInstances);
2898 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002899 if (violationNumThisLoop != 0) {
2900 pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
2901 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002902 if (numAnimationsRunning != 0) {
2903 pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
2904 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002905 pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002906 if (broadcastIntentAction != null) {
2907 pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
2908 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002909 if (tags != null) {
2910 int index = 0;
2911 for (String tag : tags) {
2912 pw.println(prefix + "tag[" + (index++) + "]: " + tag);
2913 }
2914 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002915 }
2916
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002917 @Override
2918 public int describeContents() {
2919 return 0;
2920 }
2921
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -07002922 public static final @android.annotation.NonNull Parcelable.Creator<ViolationInfo> CREATOR =
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002923 new Parcelable.Creator<ViolationInfo>() {
2924 @Override
2925 public ViolationInfo createFromParcel(Parcel in) {
2926 return new ViolationInfo(in);
2927 }
2928
2929 @Override
2930 public ViolationInfo[] newArray(int size) {
2931 return new ViolationInfo[size];
2932 }
2933 };
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002934 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002935
Jeff Brown7e442832011-06-10 18:00:16 -07002936 private static final class InstanceTracker {
2937 private static final HashMap<Class<?>, Integer> sInstanceCounts =
2938 new HashMap<Class<?>, Integer>();
2939
2940 private final Class<?> mKlass;
2941
2942 public InstanceTracker(Object instance) {
2943 mKlass = instance.getClass();
2944
2945 synchronized (sInstanceCounts) {
2946 final Integer value = sInstanceCounts.get(mKlass);
2947 final int newValue = value != null ? value + 1 : 1;
2948 sInstanceCounts.put(mKlass, newValue);
2949 }
2950 }
2951
2952 @Override
2953 protected void finalize() throws Throwable {
2954 try {
2955 synchronized (sInstanceCounts) {
2956 final Integer value = sInstanceCounts.get(mKlass);
2957 if (value != null) {
2958 final int newValue = value - 1;
2959 if (newValue > 0) {
2960 sInstanceCounts.put(mKlass, newValue);
2961 } else {
2962 sInstanceCounts.remove(mKlass);
2963 }
2964 }
2965 }
2966 } finally {
2967 super.finalize();
2968 }
2969 }
2970
2971 public static int getInstanceCount(Class<?> klass) {
2972 synchronized (sInstanceCounts) {
2973 final Integer value = sInstanceCounts.get(klass);
2974 return value != null ? value : 0;
2975 }
2976 }
2977 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07002978}