blob: 5ff6e558736ea6c10a374ab6868d2c1762a41e6c [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;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080026import android.content.BroadcastReceiver;
27import android.content.Context;
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -070028import android.content.Intent;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080029import android.content.ServiceConnection;
Jeff Sharkey89182982017-11-01 19:02:56 -060030import android.content.pm.ApplicationInfo;
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -060031import android.content.pm.PackageManager;
Jeff Sharkey619a5112017-01-19 11:55:54 -070032import android.net.TrafficStats;
Jeff Sharkey344744b2016-01-28 19:03:30 -070033import android.net.Uri;
Jeff Sharkeydd02e332018-06-27 14:41:57 -060034import android.os.storage.IStorageManager;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070035import android.os.strictmode.CleartextNetworkViolation;
36import android.os.strictmode.ContentUriWithoutPermissionViolation;
Jeff Sharkeydd02e332018-06-27 14:41:57 -060037import android.os.strictmode.CredentialProtectedWhileLockedViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070038import android.os.strictmode.CustomViolation;
39import android.os.strictmode.DiskReadViolation;
40import android.os.strictmode.DiskWriteViolation;
Pete Gillin22316b42018-02-15 17:17:27 +000041import android.os.strictmode.ExplicitGcViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070042import android.os.strictmode.FileUriExposedViolation;
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -060043import android.os.strictmode.ImplicitDirectBootViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070044import android.os.strictmode.InstanceCountViolation;
45import android.os.strictmode.IntentReceiverLeakedViolation;
46import android.os.strictmode.LeakedClosableViolation;
47import android.os.strictmode.NetworkViolation;
Narayan Kamathad1b2a92018-03-28 11:29:40 +010048import android.os.strictmode.NonSdkApiUsedViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070049import android.os.strictmode.ResourceMismatchViolation;
50import android.os.strictmode.ServiceConnectionLeakedViolation;
51import android.os.strictmode.SqliteObjectLeakedViolation;
Kurt Nelson0e612802017-11-09 17:25:40 -080052import android.os.strictmode.UnbufferedIoViolation;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -070053import android.os.strictmode.UntaggedSocketViolation;
54import android.os.strictmode.Violation;
55import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation;
Dianne Hackborn390517b2013-05-30 15:03:32 -070056import android.util.ArrayMap;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070057import android.util.Log;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -070058import android.util.Printer;
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -080059import android.util.Singleton;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070060import android.util.Slog;
Brad Fitzpatrick68044332010-11-22 18:19:48 -080061import android.view.IWindowManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070062
Kurt Nelson1981f422017-10-25 13:49:26 -070063import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -070064import com.android.internal.os.BackgroundThread;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070065import com.android.internal.os.RuntimeInit;
Dianne Hackborn8c841092013-06-24 13:46:13 -070066import com.android.internal.util.FastPrintWriter;
Jeff Sharkey605eb792014-11-04 13:34:06 -080067import com.android.internal.util.HexDump;
68
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070069import dalvik.system.BlockGuard;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -070070import dalvik.system.CloseGuard;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -080071import dalvik.system.VMDebug;
Jeff Sharkey0b558702017-01-26 16:48:01 -070072import dalvik.system.VMRuntime;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070073
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070074import java.io.PrintWriter;
75import java.io.StringWriter;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -060076import java.lang.annotation.Retention;
77import java.lang.annotation.RetentionPolicy;
Jeff Sharkey605eb792014-11-04 13:34:06 -080078import java.net.InetAddress;
79import java.net.UnknownHostException;
Kurt Nelson0918c932017-09-07 10:56:56 -070080import java.util.ArrayDeque;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070081import java.util.ArrayList;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070082import java.util.Arrays;
Kurt Nelson0918c932017-09-07 10:56:56 -070083import java.util.Deque;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070084import java.util.HashMap;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -070085import java.util.concurrent.Executor;
86import java.util.concurrent.RejectedExecutionException;
Brad Fitzpatrickbee24872010-11-20 12:09:10 -080087import java.util.concurrent.atomic.AtomicInteger;
Narayan Kamathad1b2a92018-03-28 11:29:40 +010088import java.util.function.Consumer;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070089
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070090/**
Kurt Nelson46974a22017-08-30 13:30:26 -070091 * StrictMode is a developer tool which detects things you might be doing by accident and brings
92 * them to your attention so you can fix them.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -070093 *
Kurt Nelson46974a22017-08-30 13:30:26 -070094 * <p>StrictMode is most commonly used to catch accidental disk or network access on the
95 * application's main thread, where UI operations are received and animations take place. Keeping
96 * disk and network operations off the main thread makes for much smoother, more responsive
97 * applications. By keeping your application's main thread responsive, you also prevent <a
98 * href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a> from being shown to
99 * users.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700100 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700101 * <p class="note">Note that even though an Android device's disk is often on flash memory, many
102 * devices run a filesystem on top of that memory with very limited concurrency. It's often the case
103 * that almost all disk accesses are fast, but may in individual cases be dramatically slower when
104 * certain I/O is happening in the background from other processes. If possible, it's best to assume
105 * that such things are not fast.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700106 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700107 * <p>Example code to enable from early in your {@link android.app.Application}, {@link
108 * android.app.Activity}, or other application component's {@link android.app.Application#onCreate}
109 * method:
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700110 *
111 * <pre>
112 * public void onCreate() {
113 * if (DEVELOPER_MODE) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700114 * StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
115 * .detectDiskReads()
116 * .detectDiskWrites()
117 * .detectNetwork() // or .detectAll() for all detectable problems
118 * .penaltyLog()
119 * .build());
120 * StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -0700121 * .detectLeakedSqlLiteObjects()
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700122 * .detectLeakedClosableObjects()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700123 * .penaltyLog()
124 * .penaltyDeath()
125 * .build());
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700126 * }
127 * super.onCreate();
128 * }
129 * </pre>
130 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700131 * <p>You can decide what should happen when a violation is detected. For example, using {@link
132 * ThreadPolicy.Builder#penaltyLog} you can watch the output of <code>adb logcat</code> while you
133 * use your application to see the violations as they happen.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700134 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700135 * <p>If you find violations that you feel are problematic, there are a variety of tools to help
136 * solve them: threads, {@link android.os.Handler}, {@link android.os.AsyncTask}, {@link
137 * android.app.IntentService}, etc. But don't feel compelled to fix everything that StrictMode
138 * finds. In particular, many cases of disk access are often necessary during the normal activity
139 * lifecycle. Use StrictMode to find things you did by accident. Network requests on the UI thread
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700140 * are almost always a problem, though.
141 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700142 * <p class="note">StrictMode is not a security mechanism and is not guaranteed to find all disk or
143 * network accesses. While it does propagate its state across process boundaries when doing {@link
144 * android.os.Binder} calls, it's still ultimately a best effort mechanism. Notably, disk or network
145 * access from JNI calls won't necessarily trigger it. Future versions of Android may catch more (or
146 * fewer) operations, so you should never leave StrictMode enabled in applications distributed on
147 * Google Play.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700148 */
149public final class StrictMode {
150 private static final String TAG = "StrictMode";
Brad Fitzpatrick82829ef2010-11-18 18:25:08 -0800151 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700152
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800153 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700154 * Boolean system property to disable strict mode checks outright. Set this to 'true' to force
155 * disable; 'false' has no effect on other enable/disable policy.
156 *
Christopher Tatebc6f0ce2011-11-03 12:18:43 -0700157 * @hide
158 */
159 public static final String DISABLE_PROPERTY = "persist.sys.strictmode.disable";
160
161 /**
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800162 * The boolean system property to control screen flashes on violations.
163 *
164 * @hide
165 */
166 public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
167
Jeff Sharkey605eb792014-11-04 13:34:06 -0800168 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700169 * Temporary property used to include {@link #DETECT_VM_CLEARTEXT_NETWORK} in {@link
170 * VmPolicy.Builder#detectAll()}. Apps can still always opt-into detection using {@link
171 * VmPolicy.Builder#detectCleartextNetwork()}.
Jeff Sharkey605eb792014-11-04 13:34:06 -0800172 */
Jeff Sharkey2e571642015-01-22 11:51:43 -0700173 private static final String CLEARTEXT_PROPERTY = "persist.sys.strictmode.clear";
Jeff Sharkey605eb792014-11-04 13:34:06 -0800174
Jeff Sharkey89182982017-11-01 19:02:56 -0600175 /**
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700176 * Quick feature-flag that can be used to disable the defaults provided by {@link
177 * #initThreadDefaults(ApplicationInfo)} and {@link #initVmDefaults(ApplicationInfo)}.
Jeff Sharkey89182982017-11-01 19:02:56 -0600178 */
Jeff Sharkey617e1132017-11-03 17:28:45 -0600179 private static final boolean DISABLE = false;
Jeff Sharkey89182982017-11-01 19:02:56 -0600180
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700181 // Only apply VM penalties for the same violation at this interval.
182 private static final long MIN_VM_INTERVAL_MS = 1000;
183
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700184 // Only log a duplicate stack trace to the logs every second.
185 private static final long MIN_LOG_INTERVAL_MS = 1000;
186
187 // Only show an annoying dialog at most every 30 seconds
188 private static final long MIN_DIALOG_INTERVAL_MS = 30000;
189
Brad Fitzpatricke7520d82010-11-10 18:08:36 -0800190 // How many Span tags (e.g. animations) to report.
191 private static final int MAX_SPAN_TAGS = 20;
192
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -0700193 // How many offending stacks to keep track of (and time) per loop
194 // of the Looper.
195 private static final int MAX_OFFENSES_PER_LOOP = 10;
196
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600197 /** @hide */
198 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
199 DETECT_THREAD_DISK_WRITE,
200 DETECT_THREAD_DISK_READ,
201 DETECT_THREAD_NETWORK,
202 DETECT_THREAD_CUSTOM,
203 DETECT_THREAD_RESOURCE_MISMATCH,
204 DETECT_THREAD_UNBUFFERED_IO,
205 DETECT_THREAD_EXPLICIT_GC,
206 PENALTY_GATHER,
207 PENALTY_LOG,
208 PENALTY_DIALOG,
209 PENALTY_DEATH,
210 PENALTY_FLASH,
211 PENALTY_DROPBOX,
212 PENALTY_DEATH_ON_NETWORK,
213 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
214 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
215 })
216 @Retention(RetentionPolicy.SOURCE)
217 public @interface ThreadPolicyMask {}
218
219 // Thread policy: bits 0-15
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700220
Kurt Nelson46974a22017-08-30 13:30:26 -0700221 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600222 private static final int DETECT_THREAD_DISK_WRITE = 1 << 0;
Kurt Nelson46974a22017-08-30 13:30:26 -0700223 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600224 private static final int DETECT_THREAD_DISK_READ = 1 << 1;
Kurt Nelson46974a22017-08-30 13:30:26 -0700225 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600226 private static final int DETECT_THREAD_NETWORK = 1 << 2;
Kurt Nelson46974a22017-08-30 13:30:26 -0700227 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600228 private static final int DETECT_THREAD_CUSTOM = 1 << 3;
229 /** @hide */
230 private static final int DETECT_THREAD_RESOURCE_MISMATCH = 1 << 4;
231 /** @hide */
232 private static final int DETECT_THREAD_UNBUFFERED_IO = 1 << 5;
Pete Gillin22316b42018-02-15 17:17:27 +0000233 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600234 private static final int DETECT_THREAD_EXPLICIT_GC = 1 << 6;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700235
Kurt Nelson46974a22017-08-30 13:30:26 -0700236 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600237 private static final int DETECT_THREAD_ALL = 0x0000ffff;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800238
Kurt Nelson46974a22017-08-30 13:30:26 -0700239 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600240 @IntDef(flag = true, prefix = { "DETECT_THREAD_", "PENALTY_" }, value = {
241 DETECT_VM_CURSOR_LEAKS,
242 DETECT_VM_CLOSABLE_LEAKS,
243 DETECT_VM_ACTIVITY_LEAKS,
244 DETECT_VM_INSTANCE_LEAKS,
245 DETECT_VM_REGISTRATION_LEAKS,
246 DETECT_VM_FILE_URI_EXPOSURE,
247 DETECT_VM_CLEARTEXT_NETWORK,
248 DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION,
249 DETECT_VM_UNTAGGED_SOCKET,
250 DETECT_VM_NON_SDK_API_USAGE,
251 DETECT_VM_IMPLICIT_DIRECT_BOOT,
252 PENALTY_GATHER,
253 PENALTY_LOG,
254 PENALTY_DIALOG,
255 PENALTY_DEATH,
256 PENALTY_FLASH,
257 PENALTY_DROPBOX,
258 PENALTY_DEATH_ON_NETWORK,
259 PENALTY_DEATH_ON_CLEARTEXT_NETWORK,
260 PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
261 })
262 @Retention(RetentionPolicy.SOURCE)
263 public @interface VmPolicyMask {}
264
265 // VM policy: bits 0-15
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800266
Kurt Nelson46974a22017-08-30 13:30:26 -0700267 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600268 private static final int DETECT_VM_CURSOR_LEAKS = 1 << 0;
269 /** @hide */
270 private static final int DETECT_VM_CLOSABLE_LEAKS = 1 << 1;
271 /** @hide */
272 private static final int DETECT_VM_ACTIVITY_LEAKS = 1 << 2;
273 /** @hide */
274 private static final int DETECT_VM_INSTANCE_LEAKS = 1 << 3;
275 /** @hide */
276 private static final int DETECT_VM_REGISTRATION_LEAKS = 1 << 4;
277 /** @hide */
278 private static final int DETECT_VM_FILE_URI_EXPOSURE = 1 << 5;
279 /** @hide */
280 private static final int DETECT_VM_CLEARTEXT_NETWORK = 1 << 6;
281 /** @hide */
282 private static final int DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION = 1 << 7;
283 /** @hide */
284 private static final int DETECT_VM_UNTAGGED_SOCKET = 1 << 8;
285 /** @hide */
286 private static final int DETECT_VM_NON_SDK_API_USAGE = 1 << 9;
287 /** @hide */
288 private static final int DETECT_VM_IMPLICIT_DIRECT_BOOT = 1 << 10;
Jeff Sharkeydd02e332018-06-27 14:41:57 -0600289 /** @hide */
290 private static final int DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED = 1 << 11;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800291
Kurt Nelson46974a22017-08-30 13:30:26 -0700292 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600293 private static final int DETECT_VM_ALL = 0x0000ffff;
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700294
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600295 // Penalty policy: bits 16-31
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700296
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700297 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700298 * Non-public penalty mode which overrides all the other penalty bits and signals that we're in
299 * a Binder call and we should ignore the other penalty bits and instead serialize back all our
300 * offending stack traces to the caller to ultimately handle in the originating process.
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700301 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700302 * <p>This must be kept in sync with the constant in libs/binder/Parcel.cpp
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -0700303 *
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700304 * @hide
305 */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600306 public static final int PENALTY_GATHER = 1 << 31;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800307
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600308 /** {@hide} */
309 public static final int PENALTY_LOG = 1 << 30;
310 /** {@hide} */
311 public static final int PENALTY_DIALOG = 1 << 29;
312 /** {@hide} */
313 public static final int PENALTY_DEATH = 1 << 28;
314 /** {@hide} */
315 public static final int PENALTY_FLASH = 1 << 27;
316 /** {@hide} */
317 public static final int PENALTY_DROPBOX = 1 << 26;
318 /** {@hide} */
319 public static final int PENALTY_DEATH_ON_NETWORK = 1 << 25;
320 /** {@hide} */
321 public static final int PENALTY_DEATH_ON_CLEARTEXT_NETWORK = 1 << 24;
322 /** {@hide} */
323 public static final int PENALTY_DEATH_ON_FILE_URI_EXPOSURE = 1 << 23;
Jeff Sharkey344744b2016-01-28 19:03:30 -0700324
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600325 /** @hide */
326 public static final int PENALTY_ALL = 0xffff0000;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800327
Jeff Sharkey605eb792014-11-04 13:34:06 -0800328 /** {@hide} */
329 public static final int NETWORK_POLICY_ACCEPT = 0;
330 /** {@hide} */
331 public static final int NETWORK_POLICY_LOG = 1;
332 /** {@hide} */
333 public static final int NETWORK_POLICY_REJECT = 2;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800334
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800335 // TODO: wrap in some ImmutableHashMap thing.
336 // Note: must be before static initialization of sVmPolicy.
Kurt Nelson46974a22017-08-30 13:30:26 -0700337 private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP =
338 new HashMap<Class, Integer>();
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800339
Kurt Nelson2c883f32017-09-01 10:52:45 -0700340 /** The current VmPolicy in effect. */
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800341 private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700342
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600343 /** {@hide} */
Jeff Sharkeyddc3bfd2017-06-26 19:38:56 -0600344 @TestApi
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700345 public interface ViolationLogger {
346
347 /** Called when penaltyLog is enabled and a violation needs logging. */
348 void log(ViolationInfo info);
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600349 }
350
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700351 private static final ViolationLogger LOGCAT_LOGGER =
352 info -> {
353 String msg;
354 if (info.durationMillis != -1) {
355 msg = "StrictMode policy violation; ~duration=" + info.durationMillis + " ms:";
356 } else {
357 msg = "StrictMode policy violation:";
358 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -0700359 Log.d(TAG, msg + " " + info.getStackTrace());
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700360 };
361
362 private static volatile ViolationLogger sLogger = LOGCAT_LOGGER;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600363
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700364 private static final ThreadLocal<OnThreadViolationListener> sThreadViolationListener =
365 new ThreadLocal<>();
366 private static final ThreadLocal<Executor> sThreadViolationExecutor = new ThreadLocal<>();
367
368 /**
369 * When #{@link ThreadPolicy.Builder#penaltyListener} is enabled, the listener is called on the
370 * provided executor when a Thread violation occurs.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700371 */
372 public interface OnThreadViolationListener {
373 /** Called on a thread policy violation. */
374 void onThreadViolation(Violation v);
375 }
376
377 /**
378 * When #{@link VmPolicy.Builder#penaltyListener} is enabled, the listener is called on the
379 * provided executor when a VM violation occurs.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700380 */
381 public interface OnVmViolationListener {
382 /** Called on a VM policy violation. */
383 void onVmViolation(Violation v);
384 }
385
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600386 /** {@hide} */
Jeff Sharkeyddc3bfd2017-06-26 19:38:56 -0600387 @TestApi
Kurt Nelson7d5c07a2017-09-07 16:43:45 -0700388 public static void setViolationLogger(ViolationLogger listener) {
389 if (listener == null) {
390 listener = LOGCAT_LOGGER;
391 }
392 sLogger = listener;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -0600393 }
394
Brad Fitzpatrickbee24872010-11-20 12:09:10 -0800395 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700396 * The number of threads trying to do an async dropbox write. Just to limit ourselves out of
397 * paranoia.
Brad Fitzpatrickbee24872010-11-20 12:09:10 -0800398 */
399 private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
400
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100401 /**
402 * Callback supplied to dalvik / libcore to get informed of usages of java API that are not
403 * a part of the public SDK.
404 */
405 private static final Consumer<String> sNonSdkApiUsageConsumer =
406 message -> onVmPolicyViolation(new NonSdkApiUsedViolation(message));
407
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700408 private StrictMode() {}
409
410 /**
411 * {@link StrictMode} policy applied to a certain thread.
412 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700413 * <p>The policy is enabled by {@link #setThreadPolicy}. The current policy can be retrieved
414 * with {@link #getThreadPolicy}.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700415 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700416 * <p>Note that multiple penalties may be provided and they're run in order from least to most
417 * severe (logging before process death, for example). There's currently no mechanism to choose
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700418 * different penalties for different detected actions.
419 */
420 public static final class ThreadPolicy {
Kurt Nelson46974a22017-08-30 13:30:26 -0700421 /** The default, lax policy which doesn't catch anything. */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700422 public static final ThreadPolicy LAX = new ThreadPolicy(0, null, null);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700423
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600424 final @ThreadPolicyMask int mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700425 final OnThreadViolationListener mListener;
426 final Executor mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700427
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600428 private ThreadPolicy(@ThreadPolicyMask int mask, OnThreadViolationListener listener,
429 Executor executor) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700430 this.mask = mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700431 mListener = listener;
432 mCallbackExecutor = executor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700433 }
434
435 @Override
436 public String toString() {
437 return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
438 }
439
440 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700441 * Creates {@link ThreadPolicy} instances. Methods whose names start with {@code detect}
442 * specify what problems we should look for. Methods whose names start with {@code penalty}
443 * specify what we should do when we detect a problem.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700444 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700445 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
446 * order is insignificant: all penalties apply to all detected problems.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700447 *
448 * <p>For example, detect everything and log anything that's found:
Kurt Nelson46974a22017-08-30 13:30:26 -0700449 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700450 * <pre>
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800451 * StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700452 * .detectAll()
453 * .penaltyLog()
454 * .build();
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800455 * StrictMode.setThreadPolicy(policy);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700456 * </pre>
457 */
458 public static final class Builder {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600459 private @ThreadPolicyMask int mMask = 0;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700460 private OnThreadViolationListener mListener;
461 private Executor mExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700462
463 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700464 * Create a Builder that detects nothing and has no violations. (but note that {@link
465 * #build} will default to enabling {@link #penaltyLog} if no other penalties are
466 * specified)
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700467 */
468 public Builder() {
469 mMask = 0;
470 }
471
Kurt Nelson46974a22017-08-30 13:30:26 -0700472 /** Initialize a Builder from an existing ThreadPolicy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700473 public Builder(ThreadPolicy policy) {
474 mMask = policy.mask;
Kurt Nelson7a8804a2018-02-27 16:45:27 -0800475 mListener = policy.mListener;
476 mExecutor = policy.mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700477 }
478
479 /**
480 * Detect everything that's potentially suspect.
481 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700482 * <p>As of the Gingerbread release this includes network and disk operations but will
483 * likely expand in future releases.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700484 */
485 public Builder detectAll() {
Jeff Sharkey0b558702017-01-26 16:48:01 -0700486 detectDiskReads();
487 detectDiskWrites();
488 detectNetwork();
489
490 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
491 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
492 detectCustomSlowCalls();
493 }
494 if (targetSdk >= Build.VERSION_CODES.M) {
495 detectResourceMismatches();
496 }
497 if (targetSdk >= Build.VERSION_CODES.O) {
498 detectUnbufferedIo();
499 }
500 return this;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700501 }
502
Kurt Nelson46974a22017-08-30 13:30:26 -0700503 /** Disable the detection of everything. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700504 public Builder permitAll() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600505 return disable(DETECT_THREAD_ALL);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700506 }
507
Kurt Nelson46974a22017-08-30 13:30:26 -0700508 /** Enable detection of network operations. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700509 public Builder detectNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600510 return enable(DETECT_THREAD_NETWORK);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700511 }
512
Kurt Nelson46974a22017-08-30 13:30:26 -0700513 /** Disable detection of network operations. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700514 public Builder permitNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600515 return disable(DETECT_THREAD_NETWORK);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700516 }
517
Kurt Nelson46974a22017-08-30 13:30:26 -0700518 /** Enable detection of disk reads. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700519 public Builder detectDiskReads() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600520 return enable(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700521 }
522
Kurt Nelson46974a22017-08-30 13:30:26 -0700523 /** Disable detection of disk reads. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700524 public Builder permitDiskReads() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600525 return disable(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700526 }
527
Kurt Nelson46974a22017-08-30 13:30:26 -0700528 /** Enable detection of slow calls. */
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800529 public Builder detectCustomSlowCalls() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600530 return enable(DETECT_THREAD_CUSTOM);
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800531 }
532
Kurt Nelson46974a22017-08-30 13:30:26 -0700533 /** Disable detection of slow calls. */
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800534 public Builder permitCustomSlowCalls() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600535 return disable(DETECT_THREAD_CUSTOM);
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800536 }
537
Kurt Nelson46974a22017-08-30 13:30:26 -0700538 /** Disable detection of mismatches between defined resource types and getter calls. */
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800539 public Builder permitResourceMismatches() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600540 return disable(DETECT_THREAD_RESOURCE_MISMATCH);
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800541 }
542
Kurt Nelson46974a22017-08-30 13:30:26 -0700543 /** Detect unbuffered input/output operations. */
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100544 public Builder detectUnbufferedIo() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600545 return enable(DETECT_THREAD_UNBUFFERED_IO);
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100546 }
547
Kurt Nelson46974a22017-08-30 13:30:26 -0700548 /** Disable detection of unbuffered input/output operations. */
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100549 public Builder permitUnbufferedIo() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600550 return disable(DETECT_THREAD_UNBUFFERED_IO);
Shubham Ajmera9b7184a2016-06-28 16:32:02 +0100551 }
552
553 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700554 * Enables detection of mismatches between defined resource types and getter calls.
555 *
556 * <p>This helps detect accidental type mismatches and potentially expensive type
557 * conversions when obtaining typed resources.
558 *
559 * <p>For example, a strict mode violation would be thrown when calling {@link
560 * android.content.res.TypedArray#getInt(int, int)} on an index that contains a
561 * String-type resource. If the string value can be parsed as an integer, this method
562 * call will return a value without crashing; however, the developer should format the
563 * resource as an integer to avoid unnecessary type conversion.
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800564 */
565 public Builder detectResourceMismatches() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600566 return enable(DETECT_THREAD_RESOURCE_MISMATCH);
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800567 }
568
Kurt Nelson46974a22017-08-30 13:30:26 -0700569 /** Enable detection of disk writes. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700570 public Builder detectDiskWrites() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600571 return enable(DETECT_THREAD_DISK_WRITE);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700572 }
573
Kurt Nelson46974a22017-08-30 13:30:26 -0700574 /** Disable detection of disk writes. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700575 public Builder permitDiskWrites() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600576 return disable(DETECT_THREAD_DISK_WRITE);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700577 }
578
579 /**
Pete Gillin22316b42018-02-15 17:17:27 +0000580 * Detect explicit GC requests, i.e. calls to Runtime.gc().
581 *
582 * @hide
583 */
Jeff Sharkeyc6091162018-06-29 17:15:40 -0600584 @TestApi
Pete Gillin22316b42018-02-15 17:17:27 +0000585 public Builder detectExplicitGc() {
586 // TODO(b/3400644): Un-hide this for next API update
587 // TODO(b/3400644): Un-hide ExplicitGcViolation for next API update
588 // TODO(b/3400644): Make DETECT_EXPLICIT_GC a @TestApi for next API update
589 // TODO(b/3400644): Call this from detectAll in next API update
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600590 return enable(DETECT_THREAD_EXPLICIT_GC);
Pete Gillin22316b42018-02-15 17:17:27 +0000591 }
592
593 /**
594 * Disable detection of explicit GC requests, i.e. calls to Runtime.gc().
595 *
596 * @hide
597 */
598 public Builder permitExplicitGc() {
599 // TODO(b/3400644): Un-hide this for next API update
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600600 return disable(DETECT_THREAD_EXPLICIT_GC);
Pete Gillin22316b42018-02-15 17:17:27 +0000601 }
602
603 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700604 * Show an annoying dialog to the developer on detected violations, rate-limited to be
605 * only a little annoying.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700606 */
607 public Builder penaltyDialog() {
608 return enable(PENALTY_DIALOG);
609 }
610
611 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700612 * Crash the whole process on violation. This penalty runs at the end of all enabled
613 * penalties so you'll still get see logging or other violations before the process
614 * dies.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700615 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700616 * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies to disk reads, disk writes,
617 * and network usage if their corresponding detect flags are set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700618 */
619 public Builder penaltyDeath() {
620 return enable(PENALTY_DEATH);
621 }
622
623 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700624 * Crash the whole process on any network usage. Unlike {@link #penaltyDeath}, this
625 * penalty runs <em>before</em> anything else. You must still have called {@link
626 * #detectNetwork} to enable this.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700627 *
628 * <p>In the Honeycomb or later SDKs, this is on by default.
629 */
630 public Builder penaltyDeathOnNetwork() {
631 return enable(PENALTY_DEATH_ON_NETWORK);
632 }
633
Kurt Nelson46974a22017-08-30 13:30:26 -0700634 /** Flash the screen during a violation. */
Brad Fitzpatrick68044332010-11-22 18:19:48 -0800635 public Builder penaltyFlashScreen() {
636 return enable(PENALTY_FLASH);
637 }
638
Kurt Nelson46974a22017-08-30 13:30:26 -0700639 /** Log detected violations to the system log. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700640 public Builder penaltyLog() {
641 return enable(PENALTY_LOG);
642 }
643
644 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700645 * Enable detected violations log a stacktrace and timing data to the {@link
646 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
647 * integrators doing beta user field data collection.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700648 */
649 public Builder penaltyDropBox() {
650 return enable(PENALTY_DROPBOX);
651 }
652
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700653 /**
654 * Call #{@link OnThreadViolationListener#onThreadViolation(Violation)} on specified
655 * executor every violation.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700656 */
657 public Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -0800658 @NonNull Executor executor, @NonNull OnThreadViolationListener listener) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700659 if (executor == null) {
660 throw new NullPointerException("executor must not be null");
661 }
662 mListener = listener;
663 mExecutor = executor;
664 return this;
665 }
666
Kurt Nelson72534b72018-02-22 11:21:15 -0800667 /** @removed */
668 public Builder penaltyListener(
669 @NonNull OnThreadViolationListener listener, @NonNull Executor executor) {
670 return penaltyListener(executor, listener);
671 }
672
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600673 private Builder enable(@ThreadPolicyMask int mask) {
674 mMask |= mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700675 return this;
676 }
677
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600678 private Builder disable(@ThreadPolicyMask int mask) {
679 mMask &= ~mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700680 return this;
681 }
682
683 /**
684 * Construct the ThreadPolicy instance.
685 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700686 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
687 * #penaltyLog} is implicitly set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700688 */
689 public ThreadPolicy build() {
690 // If there are detection bits set but no violation bits
691 // set, enable simple logging.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700692 if (mListener == null
693 && mMask != 0
Kurt Nelson46974a22017-08-30 13:30:26 -0700694 && (mMask
695 & (PENALTY_DEATH
696 | PENALTY_LOG
697 | PENALTY_DROPBOX
698 | PENALTY_DIALOG))
699 == 0) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700700 penaltyLog();
701 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700702 return new ThreadPolicy(mMask, mListener, mExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700703 }
704 }
705 }
706
707 /**
708 * {@link StrictMode} policy applied to all threads in the virtual machine's process.
709 *
710 * <p>The policy is enabled by {@link #setVmPolicy}.
711 */
712 public static final class VmPolicy {
Kurt Nelson46974a22017-08-30 13:30:26 -0700713 /** The default, lax policy which doesn't catch anything. */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700714 public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP, null, null);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700715
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600716 final @VmPolicyMask int mask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700717 final OnVmViolationListener mListener;
718 final Executor mCallbackExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700719
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800720 // Map from class to max number of allowed instances in memory.
721 final HashMap<Class, Integer> classInstanceLimit;
722
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700723 private VmPolicy(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600724 @VmPolicyMask int mask,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700725 HashMap<Class, Integer> classInstanceLimit,
726 OnVmViolationListener listener,
727 Executor executor) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800728 if (classInstanceLimit == null) {
729 throw new NullPointerException("classInstanceLimit == null");
730 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700731 this.mask = mask;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800732 this.classInstanceLimit = classInstanceLimit;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700733 mListener = listener;
734 mCallbackExecutor = executor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700735 }
736
737 @Override
738 public String toString() {
739 return "[StrictMode.VmPolicy; mask=" + mask + "]";
740 }
741
742 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700743 * Creates {@link VmPolicy} instances. Methods whose names start with {@code detect} specify
744 * what problems we should look for. Methods whose names start with {@code penalty} specify
745 * what we should do when we detect a problem.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700746 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700747 * <p>You can call as many {@code detect} and {@code penalty} methods as you like. Currently
748 * order is insignificant: all penalties apply to all detected problems.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700749 *
750 * <p>For example, detect everything and log anything that's found:
Kurt Nelson46974a22017-08-30 13:30:26 -0700751 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700752 * <pre>
753 * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
754 * .detectAll()
755 * .penaltyLog()
756 * .build();
757 * StrictMode.setVmPolicy(policy);
758 * </pre>
759 */
760 public static final class Builder {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -0600761 private @VmPolicyMask int mMask;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700762 private OnVmViolationListener mListener;
763 private Executor mExecutor;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700764
Kurt Nelson46974a22017-08-30 13:30:26 -0700765 private HashMap<Class, Integer> mClassInstanceLimit; // null until needed
766 private boolean mClassInstanceLimitNeedCow = false; // need copy-on-write
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800767
768 public Builder() {
769 mMask = 0;
770 }
771
Kurt Nelson46974a22017-08-30 13:30:26 -0700772 /** Build upon an existing VmPolicy. */
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800773 public Builder(VmPolicy base) {
774 mMask = base.mask;
775 mClassInstanceLimitNeedCow = true;
776 mClassInstanceLimit = base.classInstanceLimit;
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -0700777 mListener = base.mListener;
778 mExecutor = base.mCallbackExecutor;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800779 }
780
781 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700782 * Set an upper bound on how many instances of a class can be in memory at once. Helps
783 * to prevent object leaks.
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800784 */
785 public Builder setClassInstanceLimit(Class klass, int instanceLimit) {
786 if (klass == null) {
787 throw new NullPointerException("klass == null");
788 }
789 if (mClassInstanceLimitNeedCow) {
Kurt Nelson46974a22017-08-30 13:30:26 -0700790 if (mClassInstanceLimit.containsKey(klass)
791 && mClassInstanceLimit.get(klass) == instanceLimit) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800792 // no-op; don't break COW
793 return this;
794 }
795 mClassInstanceLimitNeedCow = false;
796 mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
797 } else if (mClassInstanceLimit == null) {
798 mClassInstanceLimit = new HashMap<Class, Integer>();
799 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800800 mMask |= DETECT_VM_INSTANCE_LEAKS;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800801 mClassInstanceLimit.put(klass, instanceLimit);
802 return this;
803 }
804
Kurt Nelson46974a22017-08-30 13:30:26 -0700805 /** Detect leaks of {@link android.app.Activity} subclasses. */
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800806 public Builder detectActivityLeaks() {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800807 return enable(DETECT_VM_ACTIVITY_LEAKS);
808 }
809
Jeff Sharkey89182982017-11-01 19:02:56 -0600810 /** @hide */
811 public Builder permitActivityLeaks() {
812 return disable(DETECT_VM_ACTIVITY_LEAKS);
813 }
814
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700815 /**
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100816 * Detect reflective usage of APIs that are not part of the public Android SDK.
Mathew Inwoodd82a7432018-04-19 14:42:58 +0100817 *
818 * <p>Note that any non-SDK APIs that this processes accesses before this detection is
819 * enabled may not be detected. To ensure that all such API accesses are detected,
820 * you should apply this policy as early as possible after process creation.
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100821 */
822 public Builder detectNonSdkApiUsage() {
823 return enable(DETECT_VM_NON_SDK_API_USAGE);
824 }
825
826 /**
827 * Permit reflective usage of APIs that are not part of the public Android SDK. Note
828 * that this <b>only</b> affects {@code StrictMode}, the underlying runtime may
829 * continue to restrict or warn on access to methods that are not part of the
830 * public SDK.
831 */
832 public Builder permitNonSdkApiUsage() {
833 return disable(DETECT_VM_NON_SDK_API_USAGE);
834 }
835
836 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700837 * Detect everything that's potentially suspect.
838 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700839 * <p>In the Honeycomb release this includes leaks of SQLite cursors, Activities, and
840 * other closable objects but will likely expand in future releases.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700841 */
842 public Builder detectAll() {
Jeff Sharkey0b558702017-01-26 16:48:01 -0700843 detectLeakedSqlLiteObjects();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800844
Jeff Sharkey0b558702017-01-26 16:48:01 -0700845 final int targetSdk = VMRuntime.getRuntime().getTargetSdkVersion();
846 if (targetSdk >= Build.VERSION_CODES.HONEYCOMB) {
847 detectActivityLeaks();
848 detectLeakedClosableObjects();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800849 }
Jeff Sharkey0b558702017-01-26 16:48:01 -0700850 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN) {
851 detectLeakedRegistrationObjects();
852 }
853 if (targetSdk >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
854 detectFileUriExposure();
855 }
856 if (targetSdk >= Build.VERSION_CODES.M) {
857 // TODO: always add DETECT_VM_CLEARTEXT_NETWORK once we have
858 // facility for apps to mark sockets that should be ignored
859 if (SystemProperties.getBoolean(CLEARTEXT_PROPERTY, false)) {
860 detectCleartextNetwork();
861 }
862 }
863 if (targetSdk >= Build.VERSION_CODES.O) {
864 detectContentUriWithoutPermission();
865 detectUntaggedSockets();
866 }
Jeff Sharkeydd02e332018-06-27 14:41:57 -0600867 if (targetSdk >= Build.VERSION_CODES.Q) {
868 detectCredentialProtectedWhileLocked();
869 }
Narayan Kamathad1b2a92018-03-28 11:29:40 +0100870
871 // TODO: Decide whether to detect non SDK API usage beyond a certain API level.
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -0600872 // TODO: enable detectImplicitDirectBoot() once system is less noisy
873
Jeff Sharkey0b558702017-01-26 16:48:01 -0700874 return this;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700875 }
876
877 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700878 * Detect when an {@link android.database.sqlite.SQLiteCursor} or other SQLite object is
879 * finalized without having been closed.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700880 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700881 * <p>You always want to explicitly close your SQLite cursors to avoid unnecessary
882 * database contention and temporary memory leaks.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700883 */
884 public Builder detectLeakedSqlLiteObjects() {
885 return enable(DETECT_VM_CURSOR_LEAKS);
886 }
887
888 /**
Kurt Nelsond25bd9f2017-09-14 11:36:34 -0700889 * Detect when an {@link java.io.Closeable} or other object with an explicit termination
Kurt Nelson46974a22017-08-30 13:30:26 -0700890 * method is finalized without having been closed.
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700891 *
Kurt Nelson46974a22017-08-30 13:30:26 -0700892 * <p>You always want to explicitly close such objects to avoid unnecessary resources
893 * leaks.
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700894 */
895 public Builder detectLeakedClosableObjects() {
896 return enable(DETECT_VM_CLOSABLE_LEAKS);
897 }
898
899 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700900 * Detect when a {@link BroadcastReceiver} or {@link ServiceConnection} is leaked during
901 * {@link Context} teardown.
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800902 */
903 public Builder detectLeakedRegistrationObjects() {
904 return enable(DETECT_VM_REGISTRATION_LEAKS);
905 }
906
907 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700908 * Detect when the calling application exposes a {@code file://} {@link android.net.Uri}
909 * to another app.
910 *
911 * <p>This exposure is discouraged since the receiving app may not have access to the
912 * shared path. For example, the receiving app may not have requested the {@link
913 * android.Manifest.permission#READ_EXTERNAL_STORAGE} runtime permission, or the
914 * platform may be sharing the {@link android.net.Uri} across user profile boundaries.
915 *
916 * <p>Instead, apps should use {@code content://} Uris so the platform can extend
917 * temporary permission for the receiving app to access the resource.
Jeff Sharkey344744b2016-01-28 19:03:30 -0700918 *
919 * @see android.support.v4.content.FileProvider
920 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700921 */
922 public Builder detectFileUriExposure() {
923 return enable(DETECT_VM_FILE_URI_EXPOSURE);
924 }
925
926 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700927 * Detect any network traffic from the calling app which is not wrapped in SSL/TLS. This
928 * can help you detect places that your app is inadvertently sending cleartext data
929 * across the network.
930 *
931 * <p>Using {@link #penaltyDeath()} or {@link #penaltyDeathOnCleartextNetwork()} will
932 * block further traffic on that socket to prevent accidental data leakage, in addition
933 * to crashing your process.
934 *
935 * <p>Using {@link #penaltyDropBox()} will log the raw contents of the packet that
936 * triggered the violation.
937 *
938 * <p>This inspects both IPv4/IPv6 and TCP/UDP network traffic, but it may be subject to
939 * false positives, such as when STARTTLS protocols or HTTP proxies are used.
Jeff Sharkey605eb792014-11-04 13:34:06 -0800940 */
941 public Builder detectCleartextNetwork() {
942 return enable(DETECT_VM_CLEARTEXT_NETWORK);
943 }
944
945 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700946 * Detect when the calling application sends a {@code content://} {@link
947 * android.net.Uri} to another app without setting {@link
948 * Intent#FLAG_GRANT_READ_URI_PERMISSION} or {@link
949 * Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
950 *
951 * <p>Forgetting to include one or more of these flags when sending an intent is
952 * typically an app bug.
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -0700953 *
954 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
955 * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
956 */
957 public Builder detectContentUriWithoutPermission() {
958 return enable(DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION);
959 }
960
961 /**
Kurt Nelson46974a22017-08-30 13:30:26 -0700962 * Detect any sockets in the calling app which have not been tagged using {@link
963 * TrafficStats}. Tagging sockets can help you investigate network usage inside your
964 * app, such as a narrowing down heavy usage to a specific library or component.
965 *
966 * <p>This currently does not detect sockets created in native code.
Jeff Sharkey619a5112017-01-19 11:55:54 -0700967 *
968 * @see TrafficStats#setThreadStatsTag(int)
969 * @see TrafficStats#tagSocket(java.net.Socket)
970 * @see TrafficStats#tagDatagramSocket(java.net.DatagramSocket)
971 */
972 public Builder detectUntaggedSockets() {
973 return enable(DETECT_VM_UNTAGGED_SOCKET);
974 }
975
Jeff Sharkey89182982017-11-01 19:02:56 -0600976 /** @hide */
977 public Builder permitUntaggedSockets() {
978 return disable(DETECT_VM_UNTAGGED_SOCKET);
979 }
980
Jeff Sharkey619a5112017-01-19 11:55:54 -0700981 /**
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -0600982 * Detect any implicit reliance on Direct Boot automatic filtering
983 * of {@link PackageManager} values. Violations are only triggered
984 * when implicit calls are made while the user is locked.
985 * <p>
986 * Apps becoming Direct Boot aware need to carefully inspect each
987 * query site and explicitly decide which combination of flags they
988 * want to use:
989 * <ul>
990 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AWARE}
991 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_UNAWARE}
992 * <li>{@link PackageManager#MATCH_DIRECT_BOOT_AUTO}
993 * </ul>
994 */
995 public Builder detectImplicitDirectBoot() {
996 return enable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
997 }
998
999 /** @hide */
1000 public Builder permitImplicitDirectBoot() {
1001 return disable(DETECT_VM_IMPLICIT_DIRECT_BOOT);
1002 }
1003
1004 /**
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001005 * Detect access to filesystem paths stored in credential protected
1006 * storage areas while the user is locked.
1007 * <p>
1008 * When a user is locked, credential protected storage is
1009 * unavailable, and files stored in these locations appear to not
1010 * exist, which can result in subtle app bugs if they assume default
1011 * behaviors or empty states. Instead, apps should store data needed
1012 * while a user is locked under device protected storage areas.
1013 *
1014 * @see Context#createCredentialProtectedStorageContext()
1015 * @see Context#createDeviceProtectedStorageContext()
1016 */
1017 public Builder detectCredentialProtectedWhileLocked() {
1018 return enable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1019 }
1020
1021 /** @hide */
1022 public Builder permitCredentialProtectedWhileLocked() {
1023 return disable(DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED);
1024 }
1025
1026 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001027 * Crashes the whole process on violation. This penalty runs at the end of all enabled
1028 * penalties so you'll still get your logging or other violations before the process
1029 * dies.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001030 */
1031 public Builder penaltyDeath() {
1032 return enable(PENALTY_DEATH);
1033 }
1034
1035 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001036 * Crashes the whole process when cleartext network traffic is detected.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001037 *
1038 * @see #detectCleartextNetwork()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001039 */
1040 public Builder penaltyDeathOnCleartextNetwork() {
1041 return enable(PENALTY_DEATH_ON_CLEARTEXT_NETWORK);
1042 }
1043
1044 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001045 * Crashes the whole process when a {@code file://} {@link android.net.Uri} is exposed
1046 * beyond this app.
Jeff Sharkey344744b2016-01-28 19:03:30 -07001047 *
1048 * @see #detectFileUriExposure()
1049 */
1050 public Builder penaltyDeathOnFileUriExposure() {
1051 return enable(PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
1052 }
1053
Kurt Nelson46974a22017-08-30 13:30:26 -07001054 /** Log detected violations to the system log. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001055 public Builder penaltyLog() {
1056 return enable(PENALTY_LOG);
1057 }
1058
1059 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001060 * Enable detected violations log a stacktrace and timing data to the {@link
1061 * android.os.DropBoxManager DropBox} on policy violation. Intended mostly for platform
1062 * integrators doing beta user field data collection.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001063 */
1064 public Builder penaltyDropBox() {
1065 return enable(PENALTY_DROPBOX);
1066 }
1067
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001068 /**
1069 * Call #{@link OnVmViolationListener#onVmViolation(Violation)} on every violation.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001070 */
1071 public Builder penaltyListener(
Kurt Nelson72534b72018-02-22 11:21:15 -08001072 @NonNull Executor executor, @NonNull OnVmViolationListener listener) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001073 if (executor == null) {
1074 throw new NullPointerException("executor must not be null");
1075 }
1076 mListener = listener;
1077 mExecutor = executor;
1078 return this;
1079 }
1080
Kurt Nelson72534b72018-02-22 11:21:15 -08001081 /** @removed */
1082 public Builder penaltyListener(
1083 @NonNull OnVmViolationListener listener, @NonNull Executor executor) {
1084 return penaltyListener(executor, listener);
1085 }
1086
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001087 private Builder enable(@VmPolicyMask int mask) {
1088 mMask |= mask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001089 return this;
1090 }
1091
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001092 Builder disable(@VmPolicyMask int mask) {
1093 mMask &= ~mask;
Mathieu Chartierca8c1052017-06-19 18:42:57 -07001094 return this;
1095 }
1096
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001097 /**
1098 * Construct the VmPolicy instance.
1099 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001100 * <p>Note: if no penalties are enabled before calling <code>build</code>, {@link
1101 * #penaltyLog} is implicitly set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001102 */
1103 public VmPolicy build() {
1104 // If there are detection bits set but no violation bits
1105 // set, enable simple logging.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001106 if (mListener == null
1107 && mMask != 0
Kurt Nelson46974a22017-08-30 13:30:26 -07001108 && (mMask
1109 & (PENALTY_DEATH
1110 | PENALTY_LOG
1111 | PENALTY_DROPBOX
1112 | PENALTY_DIALOG))
1113 == 0) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001114 penaltyLog();
1115 }
Kurt Nelson46974a22017-08-30 13:30:26 -07001116 return new VmPolicy(
1117 mMask,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001118 mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP,
1119 mListener,
1120 mExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001121 }
1122 }
1123 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001124
1125 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001126 * Log of strict mode violation stack traces that have occurred during a Binder call, to be
1127 * serialized back later to the caller via Parcel.writeNoException() (amusingly) where the
1128 * caller can choose how to react.
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001129 */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001130 private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
1131 new ThreadLocal<ArrayList<ViolationInfo>>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07001132 @Override
1133 protected ArrayList<ViolationInfo> initialValue() {
1134 // Starts null to avoid unnecessary allocations when
1135 // checking whether there are any violations or not in
1136 // hasGatheredViolations() below.
1137 return null;
1138 }
1139 };
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001140
1141 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001142 * Sets the policy for what actions on the current thread should be detected, as well as the
1143 * penalty if such actions occur.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001144 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001145 * <p>Internally this sets a thread-local variable which is propagated across cross-process IPC
1146 * calls, meaning you can catch violations when a system service or another process accesses the
1147 * disk or network on your behalf.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -07001148 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001149 * @param policy the policy to put into place
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001150 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001151 public static void setThreadPolicy(final ThreadPolicy policy) {
1152 setThreadPolicyMask(policy.mask);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001153 sThreadViolationListener.set(policy.mListener);
1154 sThreadViolationExecutor.set(policy.mCallbackExecutor);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001155 }
1156
Jeff Sharkey89182982017-11-01 19:02:56 -06001157 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001158 public static void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001159 // In addition to the Java-level thread-local in Dalvik's
1160 // BlockGuard, we also need to keep a native thread-local in
1161 // Binder in order to propagate the value across Binder calls,
1162 // even across native-only processes. The two are kept in
1163 // sync via the callback to onStrictModePolicyChange, below.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001164 setBlockGuardPolicy(threadPolicyMask);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001165
1166 // And set the Android native version...
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001167 Binder.setThreadStrictModePolicy(threadPolicyMask);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001168 }
1169
1170 // Sets the policy in Dalvik/libcore (BlockGuard)
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001171 private static void setBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1172 if (threadPolicyMask == 0) {
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001173 BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
1174 return;
1175 }
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001176 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1177 final AndroidBlockGuardPolicy androidPolicy;
1178 if (policy instanceof AndroidBlockGuardPolicy) {
1179 androidPolicy = (AndroidBlockGuardPolicy) policy;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001180 } else {
Kurt Nelson46974a22017-08-30 13:30:26 -07001181 androidPolicy = THREAD_ANDROID_POLICY.get();
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001182 BlockGuard.setThreadPolicy(androidPolicy);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001183 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001184 androidPolicy.setThreadPolicyMask(threadPolicyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001185 }
1186
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001187 private static void setBlockGuardVmPolicy(@VmPolicyMask int vmPolicyMask) {
1188 // We only need to install BlockGuard for a small subset of VM policies
1189 vmPolicyMask &= DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED;
1190 if (vmPolicyMask != 0) {
1191 BlockGuard.setVmPolicy(VM_ANDROID_POLICY);
1192 } else {
1193 BlockGuard.setVmPolicy(BlockGuard.LAX_VM_POLICY);
1194 }
1195 }
1196
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001197 // Sets up CloseGuard in Dalvik/libcore
1198 private static void setCloseGuardEnabled(boolean enabled) {
Brad Fitzpatrick7c2ae652010-11-14 11:00:05 -08001199 if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001200 CloseGuard.setReporter(new AndroidCloseGuardReporter());
1201 }
1202 CloseGuard.setEnabled(enabled);
1203 }
1204
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001205 /**
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -07001206 * Returns the bitmask of the current thread's policy.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001207 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001208 * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001209 * @hide
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001210 */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001211 public static @ThreadPolicyMask int getThreadPolicyMask() {
1212 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1213 if (policy instanceof AndroidBlockGuardPolicy) {
1214 return ((AndroidBlockGuardPolicy) policy).getThreadPolicyMask();
1215 } else {
1216 return 0;
1217 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001218 }
1219
Kurt Nelson46974a22017-08-30 13:30:26 -07001220 /** Returns the current thread's policy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001221 public static ThreadPolicy getThreadPolicy() {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001222 // TODO: this was a last minute Gingerbread API change (to
1223 // introduce VmPolicy cleanly) but this isn't particularly
1224 // optimal for users who might call this method often. This
1225 // should be in a thread-local and not allocate on each call.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001226 return new ThreadPolicy(
1227 getThreadPolicyMask(),
1228 sThreadViolationListener.get(),
1229 sThreadViolationExecutor.get());
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001230 }
1231
1232 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001233 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1234 * #getThreadPolicy}, modifies it to permit both disk reads &amp; writes, and sets the new
1235 * policy with {@link #setThreadPolicy}, returning the old policy so you can restore it at the
1236 * end of a block.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001237 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001238 * @return the old policy, to be passed to {@link #setThreadPolicy} to restore the policy at the
1239 * end of a block
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001240 */
1241 public static ThreadPolicy allowThreadDiskWrites() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001242 return new ThreadPolicy(
1243 allowThreadDiskWritesMask(),
1244 sThreadViolationListener.get(),
1245 sThreadViolationExecutor.get());
Jeff Sharkey89182982017-11-01 19:02:56 -06001246 }
1247
1248 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001249 public static @ThreadPolicyMask int allowThreadDiskWritesMask() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001250 int oldPolicyMask = getThreadPolicyMask();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001251 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_WRITE | DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001252 if (newPolicyMask != oldPolicyMask) {
1253 setThreadPolicyMask(newPolicyMask);
1254 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001255 return oldPolicyMask;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001256 }
1257
1258 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001259 * A convenience wrapper that takes the current {@link ThreadPolicy} from {@link
1260 * #getThreadPolicy}, modifies it to permit disk reads, and sets the new policy with {@link
1261 * #setThreadPolicy}, returning the old policy so you can restore it at the end of a block.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001262 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001263 * @return the old policy, to be passed to setThreadPolicy to restore the policy.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001264 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001265 public static ThreadPolicy allowThreadDiskReads() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001266 return new ThreadPolicy(
1267 allowThreadDiskReadsMask(),
1268 sThreadViolationListener.get(),
1269 sThreadViolationExecutor.get());
Jeff Sharkey89182982017-11-01 19:02:56 -06001270 }
1271
1272 /** @hide */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001273 public static @ThreadPolicyMask int allowThreadDiskReadsMask() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001274 int oldPolicyMask = getThreadPolicyMask();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001275 int newPolicyMask = oldPolicyMask & ~(DETECT_THREAD_DISK_READ);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001276 if (newPolicyMask != oldPolicyMask) {
1277 setThreadPolicyMask(newPolicyMask);
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001278 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001279 return oldPolicyMask;
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001280 }
1281
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001282 private static ThreadPolicy allowThreadViolations() {
1283 ThreadPolicy oldPolicy = getThreadPolicy();
1284 setThreadPolicyMask(0);
1285 return oldPolicy;
1286 }
1287
1288 private static VmPolicy allowVmViolations() {
1289 VmPolicy oldPolicy = getVmPolicy();
1290 sVmPolicy = VmPolicy.LAX;
1291 return oldPolicy;
1292 }
1293
Jeff Sharkey89182982017-11-01 19:02:56 -06001294 /**
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001295 * Determine if the given app is "bundled" as part of the system image. These bundled apps are
1296 * developed in lock-step with the OS, and they aren't updated outside of an OTA, so we want to
1297 * chase any {@link StrictMode} regressions by enabling detection when running on {@link
1298 * Build#IS_USERDEBUG} or {@link Build#IS_ENG} builds.
1299 *
1300 * <p>Unbundled apps included in the system image are expected to detect and triage their own
1301 * {@link StrictMode} issues separate from the OS release process, which is why we don't enable
1302 * them here.
Jeff Sharkey89182982017-11-01 19:02:56 -06001303 *
1304 * @hide
1305 */
1306 public static boolean isBundledSystemApp(ApplicationInfo ai) {
1307 if (ai == null || ai.packageName == null) {
1308 // Probably system server
1309 return true;
1310 } else if (ai.isSystemApp()) {
1311 // Ignore unbundled apps living in the wrong namespace
1312 if (ai.packageName.equals("com.android.vending")
1313 || ai.packageName.equals("com.android.chrome")) {
1314 return false;
1315 }
Brad Fitzpatrickf5454592010-11-24 15:27:51 -08001316
Jeff Sharkey89182982017-11-01 19:02:56 -06001317 // Ignore bundled apps that are way too spammy
1318 // STOPSHIP: burn this list down to zero
1319 if (ai.packageName.equals("com.android.phone")) {
1320 return false;
1321 }
1322
1323 if (ai.packageName.equals("android")
1324 || ai.packageName.startsWith("android.")
1325 || ai.packageName.startsWith("com.android.")) {
Brad Fitzpatrickf5454592010-11-24 15:27:51 -08001326 return true;
1327 }
1328 }
1329 return false;
1330 }
1331
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001332 /**
Jeff Sharkey89182982017-11-01 19:02:56 -06001333 * Initialize default {@link ThreadPolicy} for the current thread.
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001334 *
1335 * @hide
1336 */
Jeff Sharkey89182982017-11-01 19:02:56 -06001337 public static void initThreadDefaults(ApplicationInfo ai) {
1338 final ThreadPolicy.Builder builder = new ThreadPolicy.Builder();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001339 final int targetSdkVersion =
1340 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001341
Jeff Sharkey89182982017-11-01 19:02:56 -06001342 // Starting in HC, we don't allow network usage on the main thread
1343 if (targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
1344 builder.detectNetwork();
1345 builder.penaltyDeathOnNetwork();
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001346 }
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001347
Jeff Sharkey89182982017-11-01 19:02:56 -06001348 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1349 // Detect nothing extra
1350 } else if (Build.IS_USERDEBUG) {
1351 // Detect everything in bundled apps
1352 if (isBundledSystemApp(ai)) {
1353 builder.detectAll();
1354 builder.penaltyDropBox();
1355 if (SystemProperties.getBoolean(VISUAL_PROPERTY, false)) {
1356 builder.penaltyFlashScreen();
1357 }
Mathieu Chartierca8c1052017-06-19 18:42:57 -07001358 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001359 } else if (Build.IS_ENG) {
1360 // Detect everything in bundled apps
1361 if (isBundledSystemApp(ai)) {
1362 builder.detectAll();
1363 builder.penaltyDropBox();
1364 builder.penaltyLog();
1365 builder.penaltyFlashScreen();
Jeff Brownd5875d92011-10-09 14:59:37 -07001366 }
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001367 }
Jeff Sharkey89182982017-11-01 19:02:56 -06001368
1369 setThreadPolicy(builder.build());
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001370 }
1371
1372 /**
Jeff Sharkey89182982017-11-01 19:02:56 -06001373 * Initialize default {@link VmPolicy} for the current VM.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001374 *
1375 * @hide
1376 */
Jeff Sharkey89182982017-11-01 19:02:56 -06001377 public static void initVmDefaults(ApplicationInfo ai) {
1378 final VmPolicy.Builder builder = new VmPolicy.Builder();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001379 final int targetSdkVersion =
1380 (ai != null) ? ai.targetSdkVersion : Build.VERSION_CODES.CUR_DEVELOPMENT;
Jeff Sharkey89182982017-11-01 19:02:56 -06001381
1382 // Starting in N, we don't allow file:// Uri exposure
1383 if (targetSdkVersion >= Build.VERSION_CODES.N) {
1384 builder.detectFileUriExposure();
1385 builder.penaltyDeathOnFileUriExposure();
1386 }
1387
1388 if (Build.IS_USER || DISABLE || SystemProperties.getBoolean(DISABLE_PROPERTY, false)) {
1389 // Detect nothing extra
1390 } else if (Build.IS_USERDEBUG) {
1391 // Detect everything in bundled apps (except activity leaks, which
1392 // are expensive to track)
1393 if (isBundledSystemApp(ai)) {
1394 builder.detectAll();
1395 builder.permitActivityLeaks();
1396 builder.penaltyDropBox();
1397 }
1398 } else if (Build.IS_ENG) {
1399 // Detect everything in bundled apps
1400 if (isBundledSystemApp(ai)) {
1401 builder.detectAll();
1402 builder.penaltyDropBox();
1403 builder.penaltyLog();
1404 }
1405 }
1406
1407 setVmPolicy(builder.build());
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001408 }
1409
1410 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -07001411 * Used by the framework to make file usage a fatal error.
1412 *
1413 * @hide
1414 */
1415 public static void enableDeathOnFileUriExposure() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07001416 sVmPolicy =
1417 new VmPolicy(
1418 sVmPolicy.mask
1419 | DETECT_VM_FILE_URI_EXPOSURE
1420 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE,
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001421 sVmPolicy.classInstanceLimit,
1422 sVmPolicy.mListener,
1423 sVmPolicy.mCallbackExecutor);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001424 }
1425
1426 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001427 * Used by lame internal apps that haven't done the hard work to get themselves off file:// Uris
1428 * yet.
Jeff Sharkey344744b2016-01-28 19:03:30 -07001429 *
1430 * @hide
1431 */
1432 public static void disableDeathOnFileUriExposure() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07001433 sVmPolicy =
1434 new VmPolicy(
1435 sVmPolicy.mask
1436 & ~(DETECT_VM_FILE_URI_EXPOSURE
1437 | PENALTY_DEATH_ON_FILE_URI_EXPOSURE),
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001438 sVmPolicy.classInstanceLimit,
1439 sVmPolicy.mListener,
1440 sVmPolicy.mCallbackExecutor);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001441 }
1442
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001443 private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
1444 new ThreadLocal<ArrayList<ViolationInfo>>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07001445 @Override
1446 protected ArrayList<ViolationInfo> initialValue() {
1447 return new ArrayList<ViolationInfo>();
1448 }
1449 };
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001450
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001451 // Note: only access this once verifying the thread has a Looper.
Kurt Nelson46974a22017-08-30 13:30:26 -07001452 private static final ThreadLocal<Handler> THREAD_HANDLER =
1453 new ThreadLocal<Handler>() {
1454 @Override
1455 protected Handler initialValue() {
1456 return new Handler();
1457 }
1458 };
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001459
Kurt Nelson46974a22017-08-30 13:30:26 -07001460 private static final ThreadLocal<AndroidBlockGuardPolicy> THREAD_ANDROID_POLICY =
1461 new ThreadLocal<AndroidBlockGuardPolicy>() {
1462 @Override
1463 protected AndroidBlockGuardPolicy initialValue() {
1464 return new AndroidBlockGuardPolicy(0);
1465 }
1466 };
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001467
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001468 private static boolean tooManyViolationsThisLoop() {
1469 return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
1470 }
1471
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001472 private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001473 private @ThreadPolicyMask int mThreadPolicyMask;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001474
1475 // Map from violation stacktrace hashcode -> uptimeMillis of
1476 // last violation. No locking needed, as this is only
1477 // accessed by the same thread.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001478 private ArrayMap<Integer, Long> mLastViolationTime;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001479
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001480 public AndroidBlockGuardPolicy(@ThreadPolicyMask int threadPolicyMask) {
1481 mThreadPolicyMask = threadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001482 }
1483
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001484 @Override
1485 public String toString() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001486 return "AndroidBlockGuardPolicy; mPolicyMask=" + mThreadPolicyMask;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001487 }
1488
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001489 // Part of BlockGuard.Policy interface:
1490 public int getPolicyMask() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001491 return mThreadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001492 }
1493
1494 // Part of BlockGuard.Policy interface:
1495 public void onWriteToDisk() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001496 if ((mThreadPolicyMask & DETECT_THREAD_DISK_WRITE) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001497 return;
1498 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001499 if (tooManyViolationsThisLoop()) {
1500 return;
1501 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001502 startHandlingViolationException(new DiskWriteViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001503 }
1504
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001505 // Not part of BlockGuard.Policy; just part of StrictMode:
1506 void onCustomSlowCall(String name) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001507 if ((mThreadPolicyMask & DETECT_THREAD_CUSTOM) == 0) {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001508 return;
1509 }
1510 if (tooManyViolationsThisLoop()) {
1511 return;
1512 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001513 startHandlingViolationException(new CustomViolation(name));
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001514 }
1515
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001516 // Not part of BlockGuard.Policy; just part of StrictMode:
1517 void onResourceMismatch(Object tag) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001518 if ((mThreadPolicyMask & DETECT_THREAD_RESOURCE_MISMATCH) == 0) {
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001519 return;
1520 }
1521 if (tooManyViolationsThisLoop()) {
1522 return;
1523 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001524 startHandlingViolationException(new ResourceMismatchViolation(tag));
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001525 }
1526
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001527 // Not part of BlockGuard.Policy; just part of StrictMode:
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001528 public void onUnbufferedIO() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001529 if ((mThreadPolicyMask & DETECT_THREAD_UNBUFFERED_IO) == 0) {
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001530 return;
1531 }
1532 if (tooManyViolationsThisLoop()) {
1533 return;
1534 }
Kurt Nelson0e612802017-11-09 17:25:40 -08001535 startHandlingViolationException(new UnbufferedIoViolation());
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01001536 }
1537
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001538 // Part of BlockGuard.Policy interface:
1539 public void onReadFromDisk() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001540 if ((mThreadPolicyMask & DETECT_THREAD_DISK_READ) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001541 return;
1542 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001543 if (tooManyViolationsThisLoop()) {
1544 return;
1545 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001546 startHandlingViolationException(new DiskReadViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001547 }
1548
1549 // Part of BlockGuard.Policy interface:
1550 public void onNetwork() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001551 if ((mThreadPolicyMask & DETECT_THREAD_NETWORK) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001552 return;
1553 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001554 if ((mThreadPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001555 throw new NetworkOnMainThreadException();
1556 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001557 if (tooManyViolationsThisLoop()) {
1558 return;
1559 }
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001560 startHandlingViolationException(new NetworkViolation());
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001561 }
1562
Pete Gillin22316b42018-02-15 17:17:27 +00001563 // Part of BlockGuard.Policy interface:
1564 public void onExplicitGc() {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001565 if ((mThreadPolicyMask & DETECT_THREAD_EXPLICIT_GC) == 0) {
Pete Gillin22316b42018-02-15 17:17:27 +00001566 return;
1567 }
1568 if (tooManyViolationsThisLoop()) {
1569 return;
1570 }
1571 startHandlingViolationException(new ExplicitGcViolation());
1572 }
1573
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001574 public @ThreadPolicyMask int getThreadPolicyMask() {
1575 return mThreadPolicyMask;
1576 }
1577
1578 public void setThreadPolicyMask(@ThreadPolicyMask int threadPolicyMask) {
1579 mThreadPolicyMask = threadPolicyMask;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001580 }
1581
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001582 // Start handling a violation that just started and hasn't
1583 // actually run yet (e.g. no disk write or network operation
1584 // has yet occurred). This sees if we're in an event loop
1585 // thread and, if so, uses it to roughly measure how long the
1586 // violation took.
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001587 void startHandlingViolationException(Violation e) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001588 final int penaltyMask = (mThreadPolicyMask & PENALTY_ALL);
1589 final ViolationInfo info = new ViolationInfo(e, penaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001590 info.violationUptimeMillis = SystemClock.uptimeMillis();
1591 handleViolationWithTimingAttempt(info);
1592 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001593
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001594 // Attempts to fill in the provided ViolationInfo's
1595 // durationMillis field if this thread has a Looper we can use
1596 // to measure with. We measure from the time of violation
1597 // until the time the looper is idle again (right before
1598 // the next epoll_wait)
1599 void handleViolationWithTimingAttempt(final ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001600 Looper looper = Looper.myLooper();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001601
1602 // Without a Looper, we're unable to time how long the
1603 // violation takes place. This case should be rare, as
1604 // most users will care about timing violations that
1605 // happen on their main UI thread. Note that this case is
1606 // also hit when a violation takes place in a Binder
1607 // thread, in "gather" mode. In this case, the duration
1608 // of the violation is computed by the ultimate caller and
1609 // its Looper, if any.
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001610 //
1611 // Also, as a special short-cut case when the only penalty
1612 // bit is death, we die immediately, rather than timing
1613 // the violation's duration. This makes it convenient to
1614 // use in unit tests too, rather than waiting on a Looper.
1615 //
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001616 // TODO: if in gather mode, ignore Looper.myLooper() and always
1617 // go into this immediate mode?
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001618 if (looper == null || (info.mPenaltyMask == PENALTY_DEATH)) {
Kurt Nelson46974a22017-08-30 13:30:26 -07001619 info.durationMillis = -1; // unknown (redundant, already set)
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001620 onThreadPolicyViolation(info);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001621 return;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001622 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001623
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001624 final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001625 if (records.size() >= MAX_OFFENSES_PER_LOOP) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001626 // Not worth measuring. Too many offenses in one loop.
1627 return;
1628 }
1629 records.add(info);
1630 if (records.size() > 1) {
1631 // There's already been a violation this loop, so we've already
1632 // registered an idle handler to process the list of violations
1633 // at the end of this Looper's loop.
1634 return;
1635 }
1636
Kurt Nelson46974a22017-08-30 13:30:26 -07001637 final IWindowManager windowManager =
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001638 info.penaltyEnabled(PENALTY_FLASH) ? sWindowManager.get() : null;
Brad Fitzpatrick68044332010-11-22 18:19:48 -08001639 if (windowManager != null) {
1640 try {
1641 windowManager.showStrictModeViolation(true);
1642 } catch (RemoteException unused) {
1643 }
1644 }
1645
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001646 // We post a runnable to a Handler (== delay 0 ms) for
1647 // measuring the end time of a violation instead of using
1648 // an IdleHandler (as was previously used) because an
1649 // IdleHandler may not run for quite a long period of time
1650 // if an ongoing animation is happening and continually
1651 // posting ASAP (0 ms) animation steps. Animations are
1652 // throttled back to 60fps via SurfaceFlinger/View
1653 // invalidates, _not_ by posting frame updates every 16
1654 // milliseconds.
Kurt Nelson46974a22017-08-30 13:30:26 -07001655 THREAD_HANDLER
1656 .get()
1657 .postAtFrontOfQueue(
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001658 () -> {
1659 long loopFinishTime = SystemClock.uptimeMillis();
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001660
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001661 // Note: we do this early, before handling the
1662 // violation below, as handling the violation
1663 // may include PENALTY_DEATH and we don't want
1664 // to keep the red border on.
1665 if (windowManager != null) {
1666 try {
1667 windowManager.showStrictModeViolation(false);
1668 } catch (RemoteException unused) {
Kurt Nelson46974a22017-08-30 13:30:26 -07001669 }
Kurt Nelson46974a22017-08-30 13:30:26 -07001670 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001671
1672 for (int n = 0; n < records.size(); ++n) {
1673 ViolationInfo v = records.get(n);
1674 v.violationNumThisLoop = n + 1;
1675 v.durationMillis =
1676 (int) (loopFinishTime - v.violationUptimeMillis);
1677 onThreadPolicyViolation(v);
1678 }
1679 records.clear();
Kurt Nelson46974a22017-08-30 13:30:26 -07001680 });
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001681 }
1682
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001683 // Note: It's possible (even quite likely) that the
1684 // thread-local policy mask has changed from the time the
1685 // violation fired and now (after the violating code ran) due
1686 // to people who push/pop temporary policy in regions of code,
1687 // hence the policy being passed around.
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001688 void onThreadPolicyViolation(final ViolationInfo info) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001689 if (LOG_V) Log.d(TAG, "onThreadPolicyViolation; penalty=" + info.mPenaltyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001690
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001691 if (info.penaltyEnabled(PENALTY_GATHER)) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001692 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001693 if (violations == null) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001694 violations = new ArrayList<>(1);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001695 gatheredViolations.set(violations);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001696 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001697 for (ViolationInfo previous : violations) {
Kurt Nelson0918c932017-09-07 10:56:56 -07001698 if (info.getStackTrace().equals(previous.getStackTrace())) {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001699 // Duplicate. Don't log.
1700 return;
1701 }
1702 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001703 violations.add(info);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001704 return;
1705 }
1706
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001707 // Not perfect, but fast and good enough for dup suppression.
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001708 Integer crashFingerprint = info.hashCode();
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001709 long lastViolationTime = 0;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001710 if (mLastViolationTime != null) {
1711 Long vtime = mLastViolationTime.get(crashFingerprint);
1712 if (vtime != null) {
1713 lastViolationTime = vtime;
1714 }
1715 } else {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07001716 mLastViolationTime = new ArrayMap<>(1);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001717 }
1718 long now = SystemClock.uptimeMillis();
1719 mLastViolationTime.put(crashFingerprint, now);
Kurt Nelson46974a22017-08-30 13:30:26 -07001720 long timeSinceLastViolationMillis =
1721 lastViolationTime == 0 ? Long.MAX_VALUE : (now - lastViolationTime);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001722
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001723 if (info.penaltyEnabled(PENALTY_LOG)
Kurt Nelson46974a22017-08-30 13:30:26 -07001724 && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07001725 sLogger.log(info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001726 }
1727
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001728 final Violation violation = info.mViolation;
1729
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001730 // Penalties that ActivityManager should execute on our behalf.
1731 int penaltyMask = 0;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001732
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001733 if (info.penaltyEnabled(PENALTY_DIALOG)
Kurt Nelson46974a22017-08-30 13:30:26 -07001734 && timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001735 penaltyMask |= PENALTY_DIALOG;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001736 }
1737
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001738 if (info.penaltyEnabled(PENALTY_DROPBOX) && lastViolationTime == 0) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001739 penaltyMask |= PENALTY_DROPBOX;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001740 }
1741
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001742 if (penaltyMask != 0) {
1743 final boolean justDropBox = (info.mPenaltyMask == PENALTY_DROPBOX);
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001744 if (justDropBox) {
1745 // If all we're going to ask the activity manager
1746 // to do is dropbox it (the common case during
1747 // platform development), we can avoid doing this
1748 // call synchronously which Binder data suggests
1749 // isn't always super fast, despite the implementation
1750 // in the ActivityManager trying to be mostly async.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001751 dropboxViolationAsync(penaltyMask, info);
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001752 } else {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001753 handleApplicationStrictModeViolation(penaltyMask, info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001754 }
1755 }
1756
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001757 if (info.penaltyEnabled(PENALTY_DEATH)) {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001758 throw new RuntimeException("StrictMode ThreadPolicy violation", violation);
1759 }
1760
1761 // penaltyDeath will cause penaltyCallback to no-op since we cannot guarantee the
1762 // executor finishes before crashing.
1763 final OnThreadViolationListener listener = sThreadViolationListener.get();
1764 final Executor executor = sThreadViolationExecutor.get();
1765 if (listener != null && executor != null) {
1766 try {
1767 executor.execute(
1768 () -> {
1769 // Lift violated policy to prevent infinite recursion.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001770 ThreadPolicy oldPolicy = StrictMode.allowThreadViolations();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001771 try {
1772 listener.onThreadViolation(violation);
1773 } finally {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001774 StrictMode.setThreadPolicy(oldPolicy);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001775 }
1776 });
1777 } catch (RejectedExecutionException e) {
1778 Log.e(TAG, "ThreadPolicy penaltyCallback failed", e);
1779 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001780 }
1781 }
1782 }
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001783
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001784 private static final BlockGuard.VmPolicy VM_ANDROID_POLICY = new BlockGuard.VmPolicy() {
1785 @Override
1786 public void onPathAccess(String path) {
1787 if (path == null) return;
1788
1789 // NOTE: keep credential-protected paths in sync with Environment.java
1790 if (path.startsWith("/data/user/")
1791 || path.startsWith("/data/media/")
1792 || path.startsWith("/data/system_ce/")
1793 || path.startsWith("/data/misc_ce/")
1794 || path.startsWith("/data/vendor_ce/")
1795 || path.startsWith("/storage/emulated/")) {
1796 final int second = path.indexOf('/', 1);
1797 final int third = path.indexOf('/', second + 1);
1798 final int fourth = path.indexOf('/', third + 1);
1799 if (fourth == -1) return;
1800
1801 try {
1802 final int userId = Integer.parseInt(path.substring(third + 1, fourth));
1803 onCredentialProtectedPathAccess(path, userId);
1804 } catch (NumberFormatException ignored) {
1805 }
1806 } else if (path.startsWith("/data/data/")) {
1807 onCredentialProtectedPathAccess(path, UserHandle.USER_SYSTEM);
1808 }
1809 }
1810 };
1811
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001812 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001813 * In the common case, as set by conditionallyEnableDebugLogging, we're just dropboxing any
1814 * violations but not showing a dialog, not loggging, and not killing the process. In these
1815 * cases we don't need to do a synchronous call to the ActivityManager. This is used by both
1816 * per-thread and vm-wide violations when applicable.
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001817 */
1818 private static void dropboxViolationAsync(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001819 final int penaltyMask, final ViolationInfo info) {
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001820 int outstanding = sDropboxCallsInFlight.incrementAndGet();
1821 if (outstanding > 20) {
1822 // What's going on? Let's not make make the situation
1823 // worse and just not log.
1824 sDropboxCallsInFlight.decrementAndGet();
1825 return;
1826 }
1827
1828 if (LOG_V) Log.d(TAG, "Dropboxing async; in-flight=" + outstanding);
1829
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001830 BackgroundThread.getHandler().post(() -> {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001831 handleApplicationStrictModeViolation(penaltyMask, info);
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001832 int outstandingInner = sDropboxCallsInFlight.decrementAndGet();
1833 if (LOG_V) Log.d(TAG, "Dropbox complete; in-flight=" + outstandingInner);
1834 });
1835 }
1836
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001837 private static void handleApplicationStrictModeViolation(int penaltyMask,
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001838 ViolationInfo info) {
1839 final int oldMask = getThreadPolicyMask();
1840 try {
1841 // First, remove any policy before we call into the Activity Manager,
1842 // otherwise we'll infinite recurse as we try to log policy violations
1843 // to disk, thus violating policy, thus requiring logging, etc...
1844 // We restore the current policy below, in the finally block.
1845 setThreadPolicyMask(0);
1846
1847 IActivityManager am = ActivityManager.getService();
1848 if (am == null) {
1849 Log.w(TAG, "No activity manager; failed to Dropbox violation.");
1850 } else {
1851 am.handleApplicationStrictModeViolation(
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001852 RuntimeInit.getApplicationObject(), penaltyMask, info);
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001853 }
Jeff Sharkeyda4e50f2017-11-06 15:23:03 -07001854 } catch (RemoteException e) {
1855 if (e instanceof DeadObjectException) {
1856 // System process is dead; ignore
1857 } else {
1858 Log.e(TAG, "RemoteException handling StrictMode violation", e);
1859 }
1860 } finally {
1861 setThreadPolicyMask(oldMask);
1862 }
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001863 }
1864
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001865 private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001866 public void report(String message, Throwable allocationSite) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001867 onVmPolicyViolation(new LeakedClosableViolation(message, allocationSite));
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001868 }
1869 }
1870
Kurt Nelson46974a22017-08-30 13:30:26 -07001871 /** Called from Parcel.writeNoException() */
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001872 /* package */ static boolean hasGatheredViolations() {
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001873 return gatheredViolations.get() != null;
1874 }
1875
1876 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001877 * Called from Parcel.writeException(), so we drop this memory and don't incorrectly attribute
1878 * it to the wrong caller on the next Binder call on this thread.
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001879 */
1880 /* package */ static void clearGatheredViolations() {
1881 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001882 }
1883
Kurt Nelson46974a22017-08-30 13:30:26 -07001884 /** @hide */
Jeff Sharkeyc6091162018-06-29 17:15:40 -06001885 @TestApi
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001886 public static void conditionallyCheckInstanceCounts() {
1887 VmPolicy policy = getVmPolicy();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001888 int policySize = policy.classInstanceLimit.size();
1889 if (policySize == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001890 return;
1891 }
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08001892
1893 System.gc();
1894 System.runFinalization();
1895 System.gc();
1896
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001897 // Note: classInstanceLimit is immutable, so this is lock-free
Mathieu Chartierd288a262015-07-10 13:44:42 -07001898 // Create the classes array.
1899 Class[] classes = policy.classInstanceLimit.keySet().toArray(new Class[policySize]);
1900 long[] instanceCounts = VMDebug.countInstancesOfClasses(classes, false);
1901 for (int i = 0; i < classes.length; ++i) {
1902 Class klass = classes[i];
1903 int limit = policy.classInstanceLimit.get(klass);
1904 long instances = instanceCounts[i];
1905 if (instances > limit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07001906 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001907 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001908 }
1909 }
1910
1911 private static long sLastInstanceCountCheckMillis = 0;
Kurt Nelson46974a22017-08-30 13:30:26 -07001912 private static boolean sIsIdlerRegistered = false; // guarded by StrictMode.class
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001913 private static final MessageQueue.IdleHandler sProcessIdleHandler =
1914 new MessageQueue.IdleHandler() {
1915 public boolean queueIdle() {
1916 long now = SystemClock.uptimeMillis();
1917 if (now - sLastInstanceCountCheckMillis > 30 * 1000) {
1918 sLastInstanceCountCheckMillis = now;
1919 conditionallyCheckInstanceCounts();
1920 }
1921 return true;
1922 }
1923 };
1924
1925 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07001926 * Sets the policy for what actions in the VM process (on any thread) should be detected, as
1927 * well as the penalty if such actions occur.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001928 *
1929 * @param policy the policy to put into place
1930 */
1931 public static void setVmPolicy(final VmPolicy policy) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001932 synchronized (StrictMode.class) {
1933 sVmPolicy = policy;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001934 setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001935
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001936 Looper looper = Looper.getMainLooper();
1937 if (looper != null) {
1938 MessageQueue mq = looper.mQueue;
Kurt Nelson46974a22017-08-30 13:30:26 -07001939 if (policy.classInstanceLimit.size() == 0
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06001940 || (sVmPolicy.mask & PENALTY_ALL) == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001941 mq.removeIdleHandler(sProcessIdleHandler);
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001942 sIsIdlerRegistered = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001943 } else if (!sIsIdlerRegistered) {
1944 mq.addIdleHandler(sProcessIdleHandler);
1945 sIsIdlerRegistered = true;
1946 }
1947 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001948
1949 int networkPolicy = NETWORK_POLICY_ACCEPT;
Kurt Nelson2c883f32017-09-01 10:52:45 -07001950 if ((sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0) {
1951 if ((sVmPolicy.mask & PENALTY_DEATH) != 0
1952 || (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0) {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001953 networkPolicy = NETWORK_POLICY_REJECT;
1954 } else {
1955 networkPolicy = NETWORK_POLICY_LOG;
1956 }
1957 }
1958
Kurt Nelson46974a22017-08-30 13:30:26 -07001959 final INetworkManagementService netd =
1960 INetworkManagementService.Stub.asInterface(
1961 ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
Jeff Sharkey605eb792014-11-04 13:34:06 -08001962 if (netd != null) {
1963 try {
1964 netd.setUidCleartextNetworkPolicy(android.os.Process.myUid(), networkPolicy);
1965 } catch (RemoteException ignored) {
1966 }
1967 } else if (networkPolicy != NETWORK_POLICY_ACCEPT) {
1968 Log.w(TAG, "Dropping requested network policy due to missing service!");
1969 }
Narayan Kamathad1b2a92018-03-28 11:29:40 +01001970
1971
1972 if ((sVmPolicy.mask & DETECT_VM_NON_SDK_API_USAGE) != 0) {
1973 VMRuntime.setNonSdkApiUsageConsumer(sNonSdkApiUsageConsumer);
Mathew Inwoodd82a7432018-04-19 14:42:58 +01001974 VMRuntime.setDedupeHiddenApiWarnings(false);
Narayan Kamathad1b2a92018-03-28 11:29:40 +01001975 } else {
1976 VMRuntime.setNonSdkApiUsageConsumer(null);
Mathew Inwoodd82a7432018-04-19 14:42:58 +01001977 VMRuntime.setDedupeHiddenApiWarnings(true);
Narayan Kamathad1b2a92018-03-28 11:29:40 +01001978 }
Jeff Sharkeydd02e332018-06-27 14:41:57 -06001979
1980 setBlockGuardVmPolicy(sVmPolicy.mask);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001981 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001982 }
1983
Kurt Nelson46974a22017-08-30 13:30:26 -07001984 /** Gets the current VM policy. */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001985 public static VmPolicy getVmPolicy() {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001986 synchronized (StrictMode.class) {
1987 return sVmPolicy;
1988 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001989 }
1990
1991 /**
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07001992 * Enable the recommended StrictMode defaults, with violations just being logged.
1993 *
Kurt Nelson46974a22017-08-30 13:30:26 -07001994 * <p>This catches disk and network access on the main thread, as well as leaked SQLite cursors
1995 * and unclosed resources. This is simply a wrapper around {@link #setVmPolicy} and {@link
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001996 * #setThreadPolicy}.
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07001997 */
1998 public static void enableDefaults() {
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07001999 setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
2000 setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07002001 }
2002
Kurt Nelson46974a22017-08-30 13:30:26 -07002003 /** @hide */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002004 public static boolean vmSqliteObjectLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002005 return (sVmPolicy.mask & DETECT_VM_CURSOR_LEAKS) != 0;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002006 }
2007
Kurt Nelson46974a22017-08-30 13:30:26 -07002008 /** @hide */
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07002009 public static boolean vmClosableObjectLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002010 return (sVmPolicy.mask & DETECT_VM_CLOSABLE_LEAKS) != 0;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07002011 }
2012
Kurt Nelson46974a22017-08-30 13:30:26 -07002013 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002014 public static boolean vmRegistrationLeaksEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002015 return (sVmPolicy.mask & DETECT_VM_REGISTRATION_LEAKS) != 0;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002016 }
2017
Kurt Nelson46974a22017-08-30 13:30:26 -07002018 /** @hide */
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002019 public static boolean vmFileUriExposureEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002020 return (sVmPolicy.mask & DETECT_VM_FILE_URI_EXPOSURE) != 0;
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002021 }
2022
Kurt Nelson46974a22017-08-30 13:30:26 -07002023 /** @hide */
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -07002024 public static boolean vmCleartextNetworkEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002025 return (sVmPolicy.mask & DETECT_VM_CLEARTEXT_NETWORK) != 0;
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002026 }
2027
Kurt Nelson46974a22017-08-30 13:30:26 -07002028 /** @hide */
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -07002029 public static boolean vmContentUriWithoutPermissionEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002030 return (sVmPolicy.mask & DETECT_VM_CONTENT_URI_WITHOUT_PERMISSION) != 0;
Jeff Sharkey605eb792014-11-04 13:34:06 -08002031 }
2032
Kurt Nelson46974a22017-08-30 13:30:26 -07002033 /** @hide */
Jeff Sharkey619a5112017-01-19 11:55:54 -07002034 public static boolean vmUntaggedSocketEnabled() {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002035 return (sVmPolicy.mask & DETECT_VM_UNTAGGED_SOCKET) != 0;
Jeff Sharkey619a5112017-01-19 11:55:54 -07002036 }
2037
Kurt Nelson46974a22017-08-30 13:30:26 -07002038 /** @hide */
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06002039 public static boolean vmImplicitDirectBootEnabled() {
2040 return (sVmPolicy.mask & DETECT_VM_IMPLICIT_DIRECT_BOOT) != 0;
2041 }
2042
2043 /** @hide */
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002044 public static boolean vmCredentialProtectedWhileLockedEnabled() {
2045 return (sVmPolicy.mask & DETECT_VM_CREDENTIAL_PROTECTED_WHILE_LOCKED) != 0;
2046 }
2047
2048 /** @hide */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002049 public static void onSqliteObjectLeaked(String message, Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002050 onVmPolicyViolation(new SqliteObjectLeakedViolation(message, originStack));
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08002051 }
2052
Kurt Nelson46974a22017-08-30 13:30:26 -07002053 /** @hide */
Steve Block08d584c2011-05-17 19:05:03 +01002054 public static void onWebViewMethodCalledOnWrongThread(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002055 onVmPolicyViolation(new WebViewMethodCalledOnWrongThreadViolation(originStack));
Steve Block08d584c2011-05-17 19:05:03 +01002056 }
2057
Kurt Nelson46974a22017-08-30 13:30:26 -07002058 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002059 public static void onIntentReceiverLeaked(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002060 onVmPolicyViolation(new IntentReceiverLeakedViolation(originStack));
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002061 }
2062
Kurt Nelson46974a22017-08-30 13:30:26 -07002063 /** @hide */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002064 public static void onServiceConnectionLeaked(Throwable originStack) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002065 onVmPolicyViolation(new ServiceConnectionLeakedViolation(originStack));
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08002066 }
2067
Kurt Nelson46974a22017-08-30 13:30:26 -07002068 /** @hide */
Jeff Sharkey344744b2016-01-28 19:03:30 -07002069 public static void onFileUriExposed(Uri uri, String location) {
2070 final String message = uri + " exposed beyond app through " + location;
Kurt Nelson2c883f32017-09-01 10:52:45 -07002071 if ((sVmPolicy.mask & PENALTY_DEATH_ON_FILE_URI_EXPOSURE) != 0) {
Jeff Sharkey344744b2016-01-28 19:03:30 -07002072 throw new FileUriExposedException(message);
2073 } else {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002074 onVmPolicyViolation(new FileUriExposedViolation(message));
Jeff Sharkey344744b2016-01-28 19:03:30 -07002075 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08002076 }
2077
Kurt Nelson46974a22017-08-30 13:30:26 -07002078 /** @hide */
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002079 public static void onContentUriWithoutPermission(Uri uri, String location) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002080 onVmPolicyViolation(new ContentUriWithoutPermissionViolation(uri, location));
Jeff Sharkeyfb833f32016-12-01 14:59:59 -07002081 }
2082
Kurt Nelson46974a22017-08-30 13:30:26 -07002083 /** @hide */
Jeff Sharkey605eb792014-11-04 13:34:06 -08002084 public static void onCleartextNetworkDetected(byte[] firstPacket) {
2085 byte[] rawAddr = null;
2086 if (firstPacket != null) {
2087 if (firstPacket.length >= 20 && (firstPacket[0] & 0xf0) == 0x40) {
2088 // IPv4
2089 rawAddr = new byte[4];
2090 System.arraycopy(firstPacket, 16, rawAddr, 0, 4);
2091 } else if (firstPacket.length >= 40 && (firstPacket[0] & 0xf0) == 0x60) {
2092 // IPv6
2093 rawAddr = new byte[16];
2094 System.arraycopy(firstPacket, 24, rawAddr, 0, 16);
2095 }
2096 }
2097
2098 final int uid = android.os.Process.myUid();
Jeff Sharkeyc6091162018-06-29 17:15:40 -06002099 String msg = "Detected cleartext network traffic from UID " + uid;
Jeff Sharkey605eb792014-11-04 13:34:06 -08002100 if (rawAddr != null) {
2101 try {
Kurt Nelsoncf8c4fa2017-09-19 12:26:02 -07002102 msg += " to " + InetAddress.getByAddress(rawAddr);
Jeff Sharkey605eb792014-11-04 13:34:06 -08002103 } catch (UnknownHostException ignored) {
2104 }
2105 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002106 msg += HexDump.dumpHexString(firstPacket).trim() + " ";
Kurt Nelson2c883f32017-09-01 10:52:45 -07002107 final boolean forceDeath = (sVmPolicy.mask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002108 onVmPolicyViolation(new CleartextNetworkViolation(msg), forceDeath);
Jeff Sharkeya14acd22013-04-02 18:27:45 -07002109 }
2110
Kurt Nelson46974a22017-08-30 13:30:26 -07002111 /** @hide */
Jeff Sharkey619a5112017-01-19 11:55:54 -07002112 public static void onUntaggedSocket() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002113 onVmPolicyViolation(new UntaggedSocketViolation());
Jeff Sharkey619a5112017-01-19 11:55:54 -07002114 }
2115
Jeff Sharkeyc59a5e72018-06-21 19:14:58 -06002116 /** @hide */
2117 public static void onImplicitDirectBoot() {
2118 onVmPolicyViolation(new ImplicitDirectBootViolation());
2119 }
2120
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002121 /** Assume locked until we hear otherwise */
2122 private static volatile boolean sUserKeyUnlocked = false;
2123
2124 private static boolean isUserKeyUnlocked(int userId) {
2125 final IStorageManager storage = IStorageManager.Stub
2126 .asInterface(ServiceManager.getService("mount"));
2127 if (storage != null) {
2128 try {
2129 return storage.isUserKeyUnlocked(userId);
2130 } catch (RemoteException ignored) {
2131 }
2132 }
2133 return false;
2134 }
2135
2136 /** @hide */
2137 private static void onCredentialProtectedPathAccess(String path, int userId) {
2138 // We can cache the unlocked state for the userId we're running as,
2139 // since any relocking of that user will always result in our
2140 // process being killed to release any CE FDs we're holding onto.
2141 if (userId == UserHandle.myUserId()) {
2142 if (sUserKeyUnlocked) {
2143 return;
2144 } else if (isUserKeyUnlocked(userId)) {
2145 sUserKeyUnlocked = true;
2146 return;
2147 }
2148 } else if (isUserKeyUnlocked(userId)) {
2149 return;
2150 }
2151
2152 onVmPolicyViolation(new CredentialProtectedWhileLockedViolation(
2153 "Accessed credential protected path " + path + " while user " + userId
2154 + " was locked"));
2155 }
2156
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002157 // Map from VM violation fingerprint to uptime millis.
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002158 private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<>();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002159
Kurt Nelson46974a22017-08-30 13:30:26 -07002160 /** @hide */
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002161 public static void onVmPolicyViolation(Violation originStack) {
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002162 onVmPolicyViolation(originStack, false);
Jeff Sharkey605eb792014-11-04 13:34:06 -08002163 }
2164
Kurt Nelson46974a22017-08-30 13:30:26 -07002165 /** @hide */
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002166 public static void onVmPolicyViolation(Violation violation, boolean forceDeath) {
Kurt Nelson2c883f32017-09-01 10:52:45 -07002167 final boolean penaltyDropbox = (sVmPolicy.mask & PENALTY_DROPBOX) != 0;
2168 final boolean penaltyDeath = ((sVmPolicy.mask & PENALTY_DEATH) != 0) || forceDeath;
2169 final boolean penaltyLog = (sVmPolicy.mask & PENALTY_LOG) != 0;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002170
2171 final int penaltyMask = (sVmPolicy.mask & PENALTY_ALL);
2172 final ViolationInfo info = new ViolationInfo(violation, penaltyMask);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002173
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002174 // Erase stuff not relevant for process-wide violations
2175 info.numAnimationsRunning = 0;
2176 info.tags = null;
2177 info.broadcastIntentAction = null;
2178
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002179 final Integer fingerprint = info.hashCode();
2180 final long now = SystemClock.uptimeMillis();
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002181 long lastViolationTime;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002182 long timeSinceLastViolationMillis = Long.MAX_VALUE;
2183 synchronized (sLastVmViolationTime) {
2184 if (sLastVmViolationTime.containsKey(fingerprint)) {
2185 lastViolationTime = sLastVmViolationTime.get(fingerprint);
2186 timeSinceLastViolationMillis = now - lastViolationTime;
2187 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002188 if (timeSinceLastViolationMillis > MIN_VM_INTERVAL_MS) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002189 sLastVmViolationTime.put(fingerprint, now);
2190 }
2191 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002192 if (timeSinceLastViolationMillis <= MIN_VM_INTERVAL_MS) {
2193 // Rate limit all penalties.
2194 return;
Jeff Sharkeyc985ffd2017-05-24 12:45:40 -06002195 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002196
2197 if (penaltyLog && sLogger != null && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07002198 sLogger.log(info);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002199 }
2200
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002201 if (penaltyDropbox) {
2202 if (penaltyDeath) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002203 handleApplicationStrictModeViolation(PENALTY_DROPBOX, info);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002204 } else {
2205 // Common case for userdebug/eng builds. If no death and
2206 // just dropboxing, we can do the ActivityManager call
2207 // asynchronously.
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002208 dropboxViolationAsync(PENALTY_DROPBOX, info);
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002209 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002210 }
2211
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08002212 if (penaltyDeath) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002213 System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
2214 Process.killProcess(Process.myPid());
2215 System.exit(10);
2216 }
Kurt Nelsone6e0ebf2017-08-29 18:04:21 -07002217
2218 // If penaltyDeath, we can't guarantee this callback finishes before the process dies for
2219 // all executors. penaltyDeath supersedes penaltyCallback.
2220 if (sVmPolicy.mListener != null && sVmPolicy.mCallbackExecutor != null) {
2221 final OnVmViolationListener listener = sVmPolicy.mListener;
2222 try {
2223 sVmPolicy.mCallbackExecutor.execute(
2224 () -> {
2225 // Lift violated policy to prevent infinite recursion.
2226 VmPolicy oldPolicy = allowVmViolations();
2227 try {
2228 listener.onVmViolation(violation);
2229 } finally {
2230 setVmPolicy(oldPolicy);
2231 }
2232 });
2233 } catch (RejectedExecutionException e) {
2234 Log.e(TAG, "VmPolicy penaltyCallback failed", e);
2235 }
2236 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07002237 }
2238
Kurt Nelson46974a22017-08-30 13:30:26 -07002239 /** Called from Parcel.writeNoException() */
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002240 /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002241 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002242 if (violations == null) {
2243 p.writeInt(0);
2244 } else {
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002245 // To avoid taking up too much transaction space, only include
2246 // details for the first 3 violations. Deep inside, CrashInfo
2247 // will truncate each stack trace to ~20kB.
2248 final int size = Math.min(violations.size(), 3);
2249 p.writeInt(size);
2250 for (int i = 0; i < size; i++) {
2251 violations.get(i).writeToParcel(p, 0);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002252 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002253 }
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07002254 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002255 }
2256
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002257 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002258 * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS, we here
2259 * read back all the encoded violations.
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002260 */
2261 /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002262 Throwable localCallSite = new Throwable();
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002263 final int policyMask = getThreadPolicyMask();
2264 final boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002265
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002266 final int size = p.readInt();
2267 for (int i = 0; i < size; i++) {
2268 final ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
Kurt Nelson0918c932017-09-07 10:56:56 -07002269 info.addLocalStack(localCallSite);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002270 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2271 if (policy instanceof AndroidBlockGuardPolicy) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002272 ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07002273 }
2274 }
2275 }
2276
2277 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002278 * Called from android_util_Binder.cpp's android_os_Parcel_enforceInterface when an incoming
2279 * Binder call requires changing the StrictMode policy mask. The role of this function is to ask
2280 * Binder for its current (native) thread-local policy value and synchronize it to libcore's
2281 * (Java) thread-local policy value.
Brad Fitzpatrick727de402010-07-07 16:06:39 -07002282 */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002283 private static void onBinderStrictModePolicyChange(@ThreadPolicyMask int newPolicy) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07002284 setBlockGuardPolicy(newPolicy);
2285 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002286
2287 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002288 * A tracked, critical time span. (e.g. during an animation.)
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002289 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002290 * <p>The object itself is a linked list node, to avoid any allocations during rapid span
2291 * entries and exits.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002292 *
2293 * @hide
2294 */
2295 public static class Span {
2296 private String mName;
2297 private long mCreateMillis;
2298 private Span mNext;
Kurt Nelson46974a22017-08-30 13:30:26 -07002299 private Span mPrev; // not used when in freeList, only active
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002300 private final ThreadSpanState mContainerState;
2301
2302 Span(ThreadSpanState threadState) {
2303 mContainerState = threadState;
2304 }
2305
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002306 // Empty constructor for the NO_OP_SPAN
2307 protected Span() {
2308 mContainerState = null;
2309 }
2310
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002311 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002312 * To be called when the critical span is complete (i.e. the animation is done animating).
2313 * This can be called on any thread (even a different one from where the animation was
2314 * taking place), but that's only a defensive implementation measure. It really makes no
2315 * sense for you to call this on thread other than that where you created it.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002316 *
2317 * @hide
2318 */
2319 public void finish() {
2320 ThreadSpanState state = mContainerState;
2321 synchronized (state) {
2322 if (mName == null) {
2323 // Duplicate finish call. Ignore.
2324 return;
2325 }
2326
2327 // Remove ourselves from the active list.
2328 if (mPrev != null) {
2329 mPrev.mNext = mNext;
2330 }
2331 if (mNext != null) {
2332 mNext.mPrev = mPrev;
2333 }
2334 if (state.mActiveHead == this) {
2335 state.mActiveHead = mNext;
2336 }
2337
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002338 state.mActiveSize--;
2339
2340 if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
2341
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002342 this.mCreateMillis = -1;
2343 this.mName = null;
2344 this.mPrev = null;
2345 this.mNext = null;
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002346
2347 // Add ourselves to the freeList, if it's not already
2348 // too big.
2349 if (state.mFreeListSize < 5) {
2350 this.mNext = state.mFreeListHead;
2351 state.mFreeListHead = this;
2352 state.mFreeListSize++;
2353 }
2354 }
2355 }
2356 }
2357
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002358 // The no-op span that's used in user builds.
Kurt Nelson46974a22017-08-30 13:30:26 -07002359 private static final Span NO_OP_SPAN =
2360 new Span() {
2361 public void finish() {
2362 // Do nothing.
2363 }
2364 };
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002365
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002366 /**
2367 * Linked lists of active spans and a freelist.
2368 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002369 * <p>Locking notes: there's one of these structures per thread and all members of this
2370 * structure (as well as the Span nodes under it) are guarded by the ThreadSpanState object
2371 * instance. While in theory there'd be no locking required because it's all local per-thread,
2372 * the finish() method above is defensive against people calling it on a different thread from
2373 * where they created the Span, hence the locking.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002374 */
2375 private static class ThreadSpanState {
Kurt Nelson46974a22017-08-30 13:30:26 -07002376 public Span mActiveHead; // doubly-linked list.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002377 public int mActiveSize;
Kurt Nelson46974a22017-08-30 13:30:26 -07002378 public Span mFreeListHead; // singly-linked list. only changes at head.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002379 public int mFreeListSize;
2380 }
2381
2382 private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
2383 new ThreadLocal<ThreadSpanState>() {
Kurt Nelson46974a22017-08-30 13:30:26 -07002384 @Override
2385 protected ThreadSpanState initialValue() {
2386 return new ThreadSpanState();
2387 }
2388 };
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002389
Kurt Nelson46974a22017-08-30 13:30:26 -07002390 private static Singleton<IWindowManager> sWindowManager =
2391 new Singleton<IWindowManager>() {
2392 protected IWindowManager create() {
2393 return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
2394 }
2395 };
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -08002396
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002397 /**
2398 * Enter a named critical span (e.g. an animation)
2399 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002400 * <p>The name is an arbitary label (or tag) that will be applied to any strictmode violation
2401 * that happens while this span is active. You must call finish() on the span when done.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002402 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002403 * <p>This will never return null, but on devices without debugging enabled, this may return a
2404 * dummy object on which the finish() method is a no-op.
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002405 *
2406 * <p>TODO: add CloseGuard to this, verifying callers call finish.
2407 *
2408 * @hide
2409 */
2410 public static Span enterCriticalSpan(String name) {
Jeff Sharkey5ab02432017-06-27 11:01:36 -06002411 if (Build.IS_USER) {
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002412 return NO_OP_SPAN;
2413 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002414 if (name == null || name.isEmpty()) {
2415 throw new IllegalArgumentException("name must be non-null and non-empty");
2416 }
2417 ThreadSpanState state = sThisThreadSpanState.get();
2418 Span span = null;
2419 synchronized (state) {
2420 if (state.mFreeListHead != null) {
2421 span = state.mFreeListHead;
2422 state.mFreeListHead = span.mNext;
2423 state.mFreeListSize--;
2424 } else {
2425 // Shouldn't have to do this often.
2426 span = new Span(state);
2427 }
2428 span.mName = name;
2429 span.mCreateMillis = SystemClock.uptimeMillis();
2430 span.mNext = state.mActiveHead;
2431 span.mPrev = null;
2432 state.mActiveHead = span;
2433 state.mActiveSize++;
2434 if (span.mNext != null) {
2435 span.mNext.mPrev = span;
2436 }
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002437 if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002438 }
2439 return span;
2440 }
2441
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002442 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002443 * For code to note that it's slow. This is a no-op unless the current thread's {@link
2444 * android.os.StrictMode.ThreadPolicy} has {@link
2445 * android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls} enabled.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002446 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002447 * @param name a short string for the exception stack trace that's built if when this fires.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002448 */
2449 public static void noteSlowCall(String name) {
2450 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2451 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2452 // StrictMode not enabled.
2453 return;
2454 }
2455 ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
2456 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002457
2458 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002459 * For code to note that a resource was obtained using a type other than its defined type. This
2460 * is a no-op unless the current thread's {@link android.os.StrictMode.ThreadPolicy} has {@link
2461 * android.os.StrictMode.ThreadPolicy.Builder#detectResourceMismatches()} enabled.
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002462 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002463 * @param tag an object for the exception stack trace that's built if when this fires.
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002464 * @hide
2465 */
2466 public static void noteResourceMismatch(Object tag) {
2467 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2468 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2469 // StrictMode not enabled.
2470 return;
2471 }
2472 ((AndroidBlockGuardPolicy) policy).onResourceMismatch(tag);
2473 }
2474
Kurt Nelson46974a22017-08-30 13:30:26 -07002475 /** @hide */
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01002476 public static void noteUnbufferedIO() {
2477 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2478 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2479 // StrictMode not enabled.
2480 return;
2481 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002482 policy.onUnbufferedIO();
Shubham Ajmera9b7184a2016-06-28 16:32:02 +01002483 }
2484
Kurt Nelson46974a22017-08-30 13:30:26 -07002485 /** @hide */
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002486 public static void noteDiskRead() {
2487 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002488 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2489 // StrictMode not enabled.
2490 return;
2491 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002492 policy.onReadFromDisk();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002493 }
2494
Kurt Nelson46974a22017-08-30 13:30:26 -07002495 /** @hide */
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002496 public static void noteDiskWrite() {
2497 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2498 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2499 // StrictMode not enabled.
2500 return;
2501 }
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002502 policy.onWriteToDisk();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002503 }
2504
Kurt Nelson1981f422017-10-25 13:49:26 -07002505 @GuardedBy("StrictMode.class")
2506 private static final HashMap<Class, Integer> sExpectedActivityInstanceCount = new HashMap<>();
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002507
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002508 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002509 * Returns an object that is used to track instances of activites. The activity should store a
2510 * reference to the tracker object in one of its fields.
2511 *
Jeff Brown7e442832011-06-10 18:00:16 -07002512 * @hide
2513 */
2514 public static Object trackActivity(Object instance) {
2515 return new InstanceTracker(instance);
2516 }
2517
Kurt Nelson46974a22017-08-30 13:30:26 -07002518 /** @hide */
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002519 public static void incrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002520 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002521 return;
2522 }
Jeff Brown7e442832011-06-10 18:00:16 -07002523
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002524 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002525 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2526 return;
2527 }
2528
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002529 Integer expected = sExpectedActivityInstanceCount.get(klass);
2530 Integer newExpected = expected == null ? 1 : expected + 1;
2531 sExpectedActivityInstanceCount.put(klass, newExpected);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002532 }
2533 }
2534
Kurt Nelson46974a22017-08-30 13:30:26 -07002535 /** @hide */
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002536 public static void decrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002537 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002538 return;
2539 }
Jeff Brown7e442832011-06-10 18:00:16 -07002540
2541 final int limit;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002542 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002543 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2544 return;
2545 }
2546
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002547 Integer expected = sExpectedActivityInstanceCount.get(klass);
Jeff Brown7e442832011-06-10 18:00:16 -07002548 int newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002549 if (newExpected == 0) {
2550 sExpectedActivityInstanceCount.remove(klass);
2551 } else {
2552 sExpectedActivityInstanceCount.put(klass, newExpected);
2553 }
Jeff Brown7e442832011-06-10 18:00:16 -07002554
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002555 // Note: adding 1 here to give some breathing room during
2556 // orientation changes. (shouldn't be necessary, though?)
Jeff Brown7e442832011-06-10 18:00:16 -07002557 limit = newExpected + 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002558 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002559
Jeff Brown7e442832011-06-10 18:00:16 -07002560 // Quick check.
2561 int actual = InstanceTracker.getInstanceCount(klass);
2562 if (actual <= limit) {
2563 return;
2564 }
2565
2566 // Do a GC and explicit count to double-check.
2567 // This is the work that we are trying to avoid by tracking the object instances
2568 // explicity. Running an explicit GC can be expensive (80ms) and so can walking
2569 // the heap to count instance (30ms). This extra work can make the system feel
2570 // noticeably less responsive during orientation changes when activities are
2571 // being restarted. Granted, it is only a problem when StrictMode is enabled
2572 // but it is annoying.
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08002573
2574 System.gc();
2575 System.runFinalization();
2576 System.gc();
Jeff Brown7e442832011-06-10 18:00:16 -07002577
2578 long instances = VMDebug.countInstancesOfClass(klass, false);
2579 if (instances > limit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002580 onVmPolicyViolation(new InstanceCountViolation(klass, instances, limit));
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002581 }
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002582 }
2583
2584 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002585 * Parcelable that gets sent in Binder call headers back to callers to report violations that
2586 * happened during a cross-process call.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002587 *
2588 * @hide
2589 */
Kurt Nelson7d5c07a2017-09-07 16:43:45 -07002590 @TestApi
2591 public static final class ViolationInfo implements Parcelable {
Kurt Nelson0918c932017-09-07 10:56:56 -07002592 /** Stack and violation details. */
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002593 private final Violation mViolation;
Kurt Nelson0918c932017-09-07 10:56:56 -07002594
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002595 /** Path leading to a violation that occurred across binder. */
2596 private final Deque<StackTraceElement[]> mBinderStack = new ArrayDeque<>();
Kurt Nelson0918c932017-09-07 10:56:56 -07002597
2598 /** Memoized stack trace of full violation. */
2599 @Nullable private String mStackTrace;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002600
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002601 /** The strict mode penalty mask at the time of violation. */
2602 private final int mPenaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002603
Kurt Nelson46974a22017-08-30 13:30:26 -07002604 /** The wall time duration of the violation, when known. -1 when not known. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002605 public int durationMillis = -1;
2606
Kurt Nelson46974a22017-08-30 13:30:26 -07002607 /** The number of animations currently running. */
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002608 public int numAnimationsRunning = 0;
2609
Kurt Nelson46974a22017-08-30 13:30:26 -07002610 /** List of tags from active Span instances during this violation, or null for none. */
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002611 public String[] tags;
2612
2613 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002614 * Which violation number this was (1-based) since the last Looper loop, from the
2615 * perspective of the root caller (if it crossed any processes via Binder calls). The value
2616 * is 0 if the root caller wasn't on a Looper thread.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002617 */
2618 public int violationNumThisLoop;
2619
Kurt Nelson46974a22017-08-30 13:30:26 -07002620 /** The time (in terms of SystemClock.uptimeMillis()) that the violation occurred. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002621 public long violationUptimeMillis;
2622
2623 /**
Kurt Nelson46974a22017-08-30 13:30:26 -07002624 * The action of the Intent being broadcast to somebody's onReceive on this thread right
2625 * now, or null.
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002626 */
2627 public String broadcastIntentAction;
2628
Kurt Nelson46974a22017-08-30 13:30:26 -07002629 /** If this is a instance count violation, the number of instances in memory, else -1. */
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002630 public long numInstances = -1;
2631
Kurt Nelson9bcd7e92017-10-25 13:38:06 -07002632 /** Create an instance of ViolationInfo initialized from an exception. */
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002633 ViolationInfo(Violation tr, int penaltyMask) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002634 this.mViolation = tr;
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002635 this.mPenaltyMask = penaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002636 violationUptimeMillis = SystemClock.uptimeMillis();
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002637 this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002638 Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
2639 if (broadcastIntent != null) {
2640 broadcastIntentAction = broadcastIntent.getAction();
2641 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002642 ThreadSpanState state = sThisThreadSpanState.get();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002643 if (tr instanceof InstanceCountViolation) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002644 this.numInstances = ((InstanceCountViolation) tr).getNumberOfInstances();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002645 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002646 synchronized (state) {
2647 int spanActiveCount = state.mActiveSize;
2648 if (spanActiveCount > MAX_SPAN_TAGS) {
2649 spanActiveCount = MAX_SPAN_TAGS;
2650 }
2651 if (spanActiveCount != 0) {
2652 this.tags = new String[spanActiveCount];
2653 Span iter = state.mActiveHead;
2654 int index = 0;
2655 while (iter != null && index < spanActiveCount) {
2656 this.tags[index] = iter.mName;
2657 index++;
2658 iter = iter.mNext;
2659 }
2660 }
2661 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002662 }
2663
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002664 /**
2665 * Equivalent output to
2666 * {@link android.app.ApplicationErrorReport.CrashInfo#stackTrace}.
2667 */
Kurt Nelson0918c932017-09-07 10:56:56 -07002668 public String getStackTrace() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002669 if (mStackTrace == null) {
Kurt Nelson0918c932017-09-07 10:56:56 -07002670 StringWriter sw = new StringWriter();
2671 PrintWriter pw = new FastPrintWriter(sw, false, 256);
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002672 mViolation.printStackTrace(pw);
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002673 for (StackTraceElement[] traces : mBinderStack) {
Kurt Nelson0918c932017-09-07 10:56:56 -07002674 pw.append("# via Binder call with stack:\n");
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002675 for (StackTraceElement traceElement : traces) {
2676 pw.append("\tat ");
2677 pw.append(traceElement.toString());
2678 pw.append('\n');
2679 }
Kurt Nelson0918c932017-09-07 10:56:56 -07002680 }
2681 pw.flush();
2682 pw.close();
2683 mStackTrace = sw.toString();
2684 }
2685 return mStackTrace;
2686 }
2687
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002688 public Class<? extends Violation> getViolationClass() {
2689 return mViolation.getClass();
2690 }
2691
Kurt Nelson0918c932017-09-07 10:56:56 -07002692 /**
2693 * Optional message describing this violation.
2694 *
2695 * @hide
2696 */
2697 @TestApi
2698 public String getViolationDetails() {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002699 return mViolation.getMessage();
Kurt Nelson0918c932017-09-07 10:56:56 -07002700 }
2701
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002702 boolean penaltyEnabled(int p) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002703 return (mPenaltyMask & p) != 0;
Kurt Nelson0918c932017-09-07 10:56:56 -07002704 }
2705
2706 /**
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002707 * Add a {@link Throwable} from the current process that caused the underlying violation. We
2708 * only preserve the stack trace elements.
Kurt Nelson0918c932017-09-07 10:56:56 -07002709 *
2710 * @hide
2711 */
2712 void addLocalStack(Throwable t) {
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002713 mBinderStack.addFirst(t.getStackTrace());
Kurt Nelson0918c932017-09-07 10:56:56 -07002714 }
2715
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002716 @Override
2717 public int hashCode() {
2718 int result = 17;
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002719 if (mViolation != null) {
2720 result = 37 * result + mViolation.hashCode();
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002721 }
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002722 if (numAnimationsRunning != 0) {
2723 result *= 37;
2724 }
2725 if (broadcastIntentAction != null) {
2726 result = 37 * result + broadcastIntentAction.hashCode();
2727 }
2728 if (tags != null) {
2729 for (String tag : tags) {
2730 result = 37 * result + tag.hashCode();
2731 }
2732 }
2733 return result;
2734 }
2735
Kurt Nelson46974a22017-08-30 13:30:26 -07002736 /** Create an instance of ViolationInfo initialized from a Parcel. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002737 public ViolationInfo(Parcel in) {
2738 this(in, false);
2739 }
2740
2741 /**
2742 * Create an instance of ViolationInfo initialized from a Parcel.
2743 *
Kurt Nelson46974a22017-08-30 13:30:26 -07002744 * @param unsetGatheringBit if true, the caller is the root caller and the gathering penalty
2745 * should be removed.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002746 */
2747 public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002748 mViolation = (Violation) in.readSerializable();
Kurt Nelson0918c932017-09-07 10:56:56 -07002749 int binderStackSize = in.readInt();
2750 for (int i = 0; i < binderStackSize; i++) {
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002751 StackTraceElement[] traceElements = new StackTraceElement[in.readInt()];
2752 for (int j = 0; j < traceElements.length; j++) {
2753 StackTraceElement element =
2754 new StackTraceElement(
2755 in.readString(),
2756 in.readString(),
2757 in.readString(),
2758 in.readInt());
2759 traceElements[j] = element;
2760 }
2761 mBinderStack.add(traceElements);
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002762 }
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002763 int rawPenaltyMask = in.readInt();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002764 if (unsetGatheringBit) {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002765 mPenaltyMask = rawPenaltyMask & ~PENALTY_GATHER;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002766 } else {
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002767 mPenaltyMask = rawPenaltyMask;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002768 }
2769 durationMillis = in.readInt();
2770 violationNumThisLoop = in.readInt();
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002771 numAnimationsRunning = in.readInt();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002772 violationUptimeMillis = in.readLong();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002773 numInstances = in.readLong();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002774 broadcastIntentAction = in.readString();
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002775 tags = in.readStringArray();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002776 }
2777
Kurt Nelson46974a22017-08-30 13:30:26 -07002778 /** Save a ViolationInfo instance to a parcel. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002779 @Override
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002780 public void writeToParcel(Parcel dest, int flags) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002781 dest.writeSerializable(mViolation);
Kurt Nelson0918c932017-09-07 10:56:56 -07002782 dest.writeInt(mBinderStack.size());
Kurt Nelson87dd8bc2017-10-25 15:24:15 -07002783 for (StackTraceElement[] traceElements : mBinderStack) {
2784 dest.writeInt(traceElements.length);
2785 for (StackTraceElement element : traceElements) {
2786 dest.writeString(element.getClassName());
2787 dest.writeString(element.getMethodName());
2788 dest.writeString(element.getFileName());
2789 dest.writeInt(element.getLineNumber());
2790 }
Jeff Sharkey58f27b52016-12-06 16:47:00 -07002791 }
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002792 int start = dest.dataPosition();
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002793 dest.writeInt(mPenaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002794 dest.writeInt(durationMillis);
2795 dest.writeInt(violationNumThisLoop);
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002796 dest.writeInt(numAnimationsRunning);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002797 dest.writeLong(violationUptimeMillis);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002798 dest.writeLong(numInstances);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002799 dest.writeString(broadcastIntentAction);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002800 dest.writeStringArray(tags);
Kurt Nelson46974a22017-08-30 13:30:26 -07002801 int total = dest.dataPosition() - start;
2802 if (Binder.CHECK_PARCEL_SIZE && total > 10 * 1024) {
2803 Slog.d(
2804 TAG,
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002805 "VIO: penalty="
2806 + mPenaltyMask
Kurt Nelson46974a22017-08-30 13:30:26 -07002807 + " dur="
2808 + durationMillis
2809 + " numLoop="
2810 + violationNumThisLoop
2811 + " anim="
2812 + numAnimationsRunning
2813 + " uptime="
2814 + violationUptimeMillis
2815 + " numInst="
2816 + numInstances);
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002817 Slog.d(TAG, "VIO: action=" + broadcastIntentAction);
2818 Slog.d(TAG, "VIO: tags=" + Arrays.toString(tags));
Kurt Nelson46974a22017-08-30 13:30:26 -07002819 Slog.d(TAG, "VIO: TOTAL BYTES WRITTEN: " + (dest.dataPosition() - start));
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002820 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002821 }
2822
Kurt Nelson46974a22017-08-30 13:30:26 -07002823 /** Dump a ViolationInfo instance to a Printer. */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002824 public void dump(Printer pw, String prefix) {
Kurt Nelson1bb93bf2017-10-26 18:06:12 -07002825 pw.println(prefix + "stackTrace: " + getStackTrace());
Jeff Sharkey3ac2a432018-06-26 10:52:48 -06002826 pw.println(prefix + "penalty: " + mPenaltyMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002827 if (durationMillis != -1) {
2828 pw.println(prefix + "durationMillis: " + durationMillis);
2829 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002830 if (numInstances != -1) {
2831 pw.println(prefix + "numInstances: " + numInstances);
2832 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002833 if (violationNumThisLoop != 0) {
2834 pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
2835 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002836 if (numAnimationsRunning != 0) {
2837 pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
2838 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002839 pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002840 if (broadcastIntentAction != null) {
2841 pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
2842 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002843 if (tags != null) {
2844 int index = 0;
2845 for (String tag : tags) {
2846 pw.println(prefix + "tag[" + (index++) + "]: " + tag);
2847 }
2848 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002849 }
2850
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002851 @Override
2852 public int describeContents() {
2853 return 0;
2854 }
2855
2856 public static final Parcelable.Creator<ViolationInfo> CREATOR =
2857 new Parcelable.Creator<ViolationInfo>() {
2858 @Override
2859 public ViolationInfo createFromParcel(Parcel in) {
2860 return new ViolationInfo(in);
2861 }
2862
2863 @Override
2864 public ViolationInfo[] newArray(int size) {
2865 return new ViolationInfo[size];
2866 }
2867 };
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002868 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002869
Jeff Brown7e442832011-06-10 18:00:16 -07002870 private static final class InstanceTracker {
2871 private static final HashMap<Class<?>, Integer> sInstanceCounts =
2872 new HashMap<Class<?>, Integer>();
2873
2874 private final Class<?> mKlass;
2875
2876 public InstanceTracker(Object instance) {
2877 mKlass = instance.getClass();
2878
2879 synchronized (sInstanceCounts) {
2880 final Integer value = sInstanceCounts.get(mKlass);
2881 final int newValue = value != null ? value + 1 : 1;
2882 sInstanceCounts.put(mKlass, newValue);
2883 }
2884 }
2885
2886 @Override
2887 protected void finalize() throws Throwable {
2888 try {
2889 synchronized (sInstanceCounts) {
2890 final Integer value = sInstanceCounts.get(mKlass);
2891 if (value != null) {
2892 final int newValue = value - 1;
2893 if (newValue > 0) {
2894 sInstanceCounts.put(mKlass, newValue);
2895 } else {
2896 sInstanceCounts.remove(mKlass);
2897 }
2898 }
2899 }
2900 } finally {
2901 super.finalize();
2902 }
2903 }
2904
2905 public static int getInstanceCount(Class<?> klass) {
2906 synchronized (sInstanceCounts) {
2907 final Integer value = sInstanceCounts.get(klass);
2908 return value != null ? value : 0;
2909 }
2910 }
2911 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07002912}