blob: 287092320921b9e5bce1c49db66cb5c9f9cdac01 [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;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070019import android.app.ActivityManagerNative;
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -070020import android.app.ActivityThread;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070021import android.app.ApplicationErrorReport;
Brad Fitzpatrick10656852010-11-23 19:01:13 -080022import android.app.IActivityManager;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080023import android.content.BroadcastReceiver;
24import android.content.Context;
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -070025import android.content.Intent;
Jeff Sharkeyd7026f12012-03-01 20:50:32 -080026import android.content.ServiceConnection;
Jeff Sharkey344744b2016-01-28 19:03:30 -070027import android.net.Uri;
Dianne Hackborn390517b2013-05-30 15:03:32 -070028import android.util.ArrayMap;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070029import android.util.Log;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -070030import android.util.Printer;
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -080031import android.util.Singleton;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070032import android.util.Slog;
Brad Fitzpatrick68044332010-11-22 18:19:48 -080033import android.view.IWindowManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070034
35import com.android.internal.os.RuntimeInit;
Dianne Hackborn8c841092013-06-24 13:46:13 -070036import com.android.internal.util.FastPrintWriter;
Jeff Sharkey605eb792014-11-04 13:34:06 -080037import com.android.internal.util.HexDump;
38
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070039import dalvik.system.BlockGuard;
Brian Carlstromfd9ddd12010-11-04 11:24:58 -070040import dalvik.system.CloseGuard;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -080041import dalvik.system.VMDebug;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070042
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070043import java.io.PrintWriter;
44import java.io.StringWriter;
Jeff Sharkey605eb792014-11-04 13:34:06 -080045import java.net.InetAddress;
46import java.net.UnknownHostException;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -070047import java.util.ArrayList;
Dianne Hackborn73d6a822014-09-29 10:52:47 -070048import java.util.Arrays;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070049import java.util.HashMap;
Brad Fitzpatrickbee24872010-11-20 12:09:10 -080050import java.util.concurrent.atomic.AtomicInteger;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -070051
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070052/**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -070053 * <p>StrictMode is a developer tool which detects things you might be
54 * doing by accident and brings them to your attention so you can fix
55 * them.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -070056 *
57 * <p>StrictMode is most commonly used to catch accidental disk or
58 * network access on the application's main thread, where UI
59 * operations are received and animations take place. Keeping disk
60 * and network operations off the main thread makes for much smoother,
Brad Fitzpatrick9fc2fc52010-10-11 12:52:35 -070061 * more responsive applications. By keeping your application's main thread
62 * responsive, you also prevent
63 * <a href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a>
64 * from being shown to users.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -070065 *
66 * <p class="note">Note that even though an Android device's disk is
67 * often on flash memory, many devices run a filesystem on top of that
68 * memory with very limited concurrency. It's often the case that
69 * almost all disk accesses are fast, but may in individual cases be
70 * dramatically slower when certain I/O is happening in the background
71 * from other processes. If possible, it's best to assume that such
72 * things are not fast.</p>
73 *
74 * <p>Example code to enable from early in your
75 * {@link android.app.Application}, {@link android.app.Activity}, or
76 * other application component's
77 * {@link android.app.Application#onCreate} method:
78 *
79 * <pre>
80 * public void onCreate() {
81 * if (DEVELOPER_MODE) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -070082 * StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
83 * .detectDiskReads()
84 * .detectDiskWrites()
85 * .detectNetwork() // or .detectAll() for all detectable problems
86 * .penaltyLog()
87 * .build());
88 * StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -070089 * .detectLeakedSqlLiteObjects()
Brian Carlstromfd9ddd12010-11-04 11:24:58 -070090 * .detectLeakedClosableObjects()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -070091 * .penaltyLog()
92 * .penaltyDeath()
93 * .build());
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -070094 * }
95 * super.onCreate();
96 * }
97 * </pre>
98 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -070099 * <p>You can decide what should happen when a violation is detected.
100 * For example, using {@link ThreadPolicy.Builder#penaltyLog} you can
101 * watch the output of <code>adb logcat</code> while you use your
102 * application to see the violations as they happen.
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700103 *
104 * <p>If you find violations that you feel are problematic, there are
105 * a variety of tools to help solve them: threads, {@link android.os.Handler},
106 * {@link android.os.AsyncTask}, {@link android.app.IntentService}, etc.
107 * But don't feel compelled to fix everything that StrictMode finds. In particular,
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700108 * many cases of disk access are often necessary during the normal activity lifecycle. Use
109 * StrictMode to find things you did by accident. Network requests on the UI thread
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700110 * are almost always a problem, though.
111 *
112 * <p class="note">StrictMode is not a security mechanism and is not
113 * guaranteed to find all disk or network accesses. While it does
114 * propagate its state across process boundaries when doing
115 * {@link android.os.Binder} calls, it's still ultimately a best
116 * effort mechanism. Notably, disk or network access from JNI calls
117 * won't necessarily trigger it. Future versions of Android may catch
118 * more (or fewer) operations, so you should never leave StrictMode
Dirk Dougherty4d7bc6552012-01-27 17:56:49 -0800119 * enabled in applications distributed on Google Play.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700120 */
121public final class StrictMode {
122 private static final String TAG = "StrictMode";
Brad Fitzpatrick82829ef2010-11-18 18:25:08 -0800123 private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700124
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -0800125 private static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
Brad Fitzpatrick68044332010-11-22 18:19:48 -0800126 private static final boolean IS_ENG_BUILD = "eng".equals(Build.TYPE);
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -0800127
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800128 /**
Christopher Tatebc6f0ce2011-11-03 12:18:43 -0700129 * Boolean system property to disable strict mode checks outright.
130 * Set this to 'true' to force disable; 'false' has no effect on other
131 * enable/disable policy.
132 * @hide
133 */
134 public static final String DISABLE_PROPERTY = "persist.sys.strictmode.disable";
135
136 /**
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -0800137 * The boolean system property to control screen flashes on violations.
138 *
139 * @hide
140 */
141 public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
142
Jeff Sharkey605eb792014-11-04 13:34:06 -0800143 /**
144 * Temporary property used to include {@link #DETECT_VM_CLEARTEXT_NETWORK}
145 * in {@link VmPolicy.Builder#detectAll()}. Apps can still always opt-into
146 * detection using {@link VmPolicy.Builder#detectCleartextNetwork()}.
147 */
Jeff Sharkey2e571642015-01-22 11:51:43 -0700148 private static final String CLEARTEXT_PROPERTY = "persist.sys.strictmode.clear";
Jeff Sharkey605eb792014-11-04 13:34:06 -0800149
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700150 // Only log a duplicate stack trace to the logs every second.
151 private static final long MIN_LOG_INTERVAL_MS = 1000;
152
153 // Only show an annoying dialog at most every 30 seconds
154 private static final long MIN_DIALOG_INTERVAL_MS = 30000;
155
Brad Fitzpatricke7520d82010-11-10 18:08:36 -0800156 // How many Span tags (e.g. animations) to report.
157 private static final int MAX_SPAN_TAGS = 20;
158
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -0700159 // How many offending stacks to keep track of (and time) per loop
160 // of the Looper.
161 private static final int MAX_OFFENSES_PER_LOOP = 10;
162
Jeff Sharkey605eb792014-11-04 13:34:06 -0800163 // Byte 1: Thread-policy
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700164
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700165 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700166 * @hide
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700167 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700168 public static final int DETECT_DISK_WRITE = 0x01; // for ThreadPolicy
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700169
170 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700171 * @hide
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700172 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700173 public static final int DETECT_DISK_READ = 0x02; // for ThreadPolicy
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700174
175 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700176 * @hide
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700177 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700178 public static final int DETECT_NETWORK = 0x04; // for ThreadPolicy
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700179
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800180 /**
181 * For StrictMode.noteSlowCall()
182 *
183 * @hide
184 */
185 public static final int DETECT_CUSTOM = 0x08; // for ThreadPolicy
186
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800187 /**
188 * For StrictMode.noteResourceMismatch()
189 *
190 * @hide
191 */
192 public static final int DETECT_RESOURCE_MISMATCH = 0x10; // for ThreadPolicy
193
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800194 private static final int ALL_THREAD_DETECT_BITS =
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800195 DETECT_DISK_WRITE | DETECT_DISK_READ | DETECT_NETWORK | DETECT_CUSTOM |
196 DETECT_RESOURCE_MISMATCH;
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800197
Jeff Sharkey605eb792014-11-04 13:34:06 -0800198 // Byte 2: Process-policy
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700199
200 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700201 * Note, a "VM_" bit, not thread.
202 * @hide
203 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800204 public static final int DETECT_VM_CURSOR_LEAKS = 0x01 << 8; // for VmPolicy
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700205
206 /**
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700207 * Note, a "VM_" bit, not thread.
208 * @hide
209 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800210 public static final int DETECT_VM_CLOSABLE_LEAKS = 0x02 << 8; // for VmPolicy
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800211
212 /**
213 * Note, a "VM_" bit, not thread.
214 * @hide
215 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800216 public static final int DETECT_VM_ACTIVITY_LEAKS = 0x04 << 8; // for VmPolicy
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700217
218 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700219 * @hide
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700220 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800221 private static final int DETECT_VM_INSTANCE_LEAKS = 0x08 << 8; // for VmPolicy
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800222
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800223 /**
224 * @hide
225 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800226 public static final int DETECT_VM_REGISTRATION_LEAKS = 0x10 << 8; // for VmPolicy
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800227
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700228 /**
229 * @hide
230 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800231 private static final int DETECT_VM_FILE_URI_EXPOSURE = 0x20 << 8; // for VmPolicy
232
233 /**
234 * @hide
235 */
236 private static final int DETECT_VM_CLEARTEXT_NETWORK = 0x40 << 8; // for VmPolicy
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700237
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800238 private static final int ALL_VM_DETECT_BITS =
239 DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS |
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800240 DETECT_VM_ACTIVITY_LEAKS | DETECT_VM_INSTANCE_LEAKS |
Jeff Sharkey605eb792014-11-04 13:34:06 -0800241 DETECT_VM_REGISTRATION_LEAKS | DETECT_VM_FILE_URI_EXPOSURE |
242 DETECT_VM_CLEARTEXT_NETWORK;
243
244 // Byte 3: Penalty
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800245
Jeff Sharkey344744b2016-01-28 19:03:30 -0700246 /** {@hide} */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800247 public static final int PENALTY_LOG = 0x01 << 16; // normal android.util.Log
Jeff Sharkey344744b2016-01-28 19:03:30 -0700248 /** {@hide} */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800249 public static final int PENALTY_DIALOG = 0x02 << 16;
Jeff Sharkey344744b2016-01-28 19:03:30 -0700250 /** {@hide} */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800251 public static final int PENALTY_DEATH = 0x04 << 16;
Jeff Sharkey344744b2016-01-28 19:03:30 -0700252 /** {@hide} */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800253 public static final int PENALTY_FLASH = 0x10 << 16;
Jeff Sharkey344744b2016-01-28 19:03:30 -0700254 /** {@hide} */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800255 public static final int PENALTY_DROPBOX = 0x20 << 16;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700256
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700257 /**
258 * Non-public penalty mode which overrides all the other penalty
259 * bits and signals that we're in a Binder call and we should
260 * ignore the other penalty bits and instead serialize back all
261 * our offending stack traces to the caller to ultimately handle
262 * in the originating process.
263 *
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -0700264 * This must be kept in sync with the constant in libs/binder/Parcel.cpp
265 *
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700266 * @hide
267 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800268 public static final int PENALTY_GATHER = 0x40 << 16;
269
Jeff Sharkey344744b2016-01-28 19:03:30 -0700270 // Byte 4: Special cases
271
272 /**
273 * Death when network traffic is detected on main thread.
274 *
275 * @hide
276 */
277 public static final int PENALTY_DEATH_ON_NETWORK = 0x01 << 24;
278
Jeff Sharkey605eb792014-11-04 13:34:06 -0800279 /**
280 * Death when cleartext network traffic is detected.
281 *
282 * @hide
283 */
Jeff Sharkey344744b2016-01-28 19:03:30 -0700284 public static final int PENALTY_DEATH_ON_CLEARTEXT_NETWORK = 0x02 << 24;
285
286 /**
287 * Death when file exposure is detected.
288 *
289 * @hide
290 */
291 public static final int PENALTY_DEATH_ON_FILE_URI_EXPOSURE = 0x04 << 24;
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700292
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700293 /**
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800294 * Mask of all the penalty bits valid for thread policies.
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -0700295 */
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800296 private static final int THREAD_PENALTY_MASK =
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700297 PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER |
Brad Fitzpatrick68044332010-11-22 18:19:48 -0800298 PENALTY_DEATH_ON_NETWORK | PENALTY_FLASH;
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -0700299
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800300 /**
301 * Mask of all the penalty bits valid for VM policies.
302 */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800303 private static final int VM_PENALTY_MASK = PENALTY_LOG | PENALTY_DEATH | PENALTY_DROPBOX
Jeff Sharkey344744b2016-01-28 19:03:30 -0700304 | PENALTY_DEATH_ON_CLEARTEXT_NETWORK | PENALTY_DEATH_ON_FILE_URI_EXPOSURE;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800305
Jeff Sharkey605eb792014-11-04 13:34:06 -0800306 /** {@hide} */
307 public static final int NETWORK_POLICY_ACCEPT = 0;
308 /** {@hide} */
309 public static final int NETWORK_POLICY_LOG = 1;
310 /** {@hide} */
311 public static final int NETWORK_POLICY_REJECT = 2;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -0800312
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800313 // TODO: wrap in some ImmutableHashMap thing.
314 // Note: must be before static initialization of sVmPolicy.
315 private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP = new HashMap<Class, Integer>();
316
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -0700317 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700318 * The current VmPolicy in effect.
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800319 *
320 * TODO: these are redundant (mask is in VmPolicy). Should remove sVmPolicyMask.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700321 */
322 private static volatile int sVmPolicyMask = 0;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800323 private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700324
Brad Fitzpatrickbee24872010-11-20 12:09:10 -0800325 /**
326 * The number of threads trying to do an async dropbox write.
327 * Just to limit ourselves out of paranoia.
328 */
329 private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
330
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700331 private StrictMode() {}
332
333 /**
334 * {@link StrictMode} policy applied to a certain thread.
335 *
336 * <p>The policy is enabled by {@link #setThreadPolicy}. The current policy
337 * can be retrieved with {@link #getThreadPolicy}.
338 *
339 * <p>Note that multiple penalties may be provided and they're run
340 * in order from least to most severe (logging before process
341 * death, for example). There's currently no mechanism to choose
342 * different penalties for different detected actions.
343 */
344 public static final class ThreadPolicy {
345 /**
346 * The default, lax policy which doesn't catch anything.
347 */
348 public static final ThreadPolicy LAX = new ThreadPolicy(0);
349
350 final int mask;
351
352 private ThreadPolicy(int mask) {
353 this.mask = mask;
354 }
355
356 @Override
357 public String toString() {
358 return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
359 }
360
361 /**
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800362 * Creates {@link ThreadPolicy} instances. Methods whose names start
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700363 * with {@code detect} specify what problems we should look
364 * for. Methods whose names start with {@code penalty} specify what
365 * we should do when we detect a problem.
366 *
367 * <p>You can call as many {@code detect} and {@code penalty}
368 * methods as you like. Currently order is insignificant: all
369 * penalties apply to all detected problems.
370 *
371 * <p>For example, detect everything and log anything that's found:
372 * <pre>
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800373 * StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700374 * .detectAll()
375 * .penaltyLog()
376 * .build();
Brad Fitzpatrick320274c2010-12-13 14:07:39 -0800377 * StrictMode.setThreadPolicy(policy);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700378 * </pre>
379 */
380 public static final class Builder {
381 private int mMask = 0;
382
383 /**
384 * Create a Builder that detects nothing and has no
385 * violations. (but note that {@link #build} will default
386 * to enabling {@link #penaltyLog} if no other penalties
387 * are specified)
388 */
389 public Builder() {
390 mMask = 0;
391 }
392
393 /**
394 * Initialize a Builder from an existing ThreadPolicy.
395 */
396 public Builder(ThreadPolicy policy) {
397 mMask = policy.mask;
398 }
399
400 /**
401 * Detect everything that's potentially suspect.
402 *
403 * <p>As of the Gingerbread release this includes network and
404 * disk operations but will likely expand in future releases.
405 */
406 public Builder detectAll() {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800407 return enable(ALL_THREAD_DETECT_BITS);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700408 }
409
410 /**
411 * Disable the detection of everything.
412 */
413 public Builder permitAll() {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800414 return disable(ALL_THREAD_DETECT_BITS);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700415 }
416
417 /**
418 * Enable detection of network operations.
419 */
420 public Builder detectNetwork() {
421 return enable(DETECT_NETWORK);
422 }
423
424 /**
425 * Disable detection of network operations.
426 */
427 public Builder permitNetwork() {
428 return disable(DETECT_NETWORK);
429 }
430
431 /**
432 * Enable detection of disk reads.
433 */
434 public Builder detectDiskReads() {
435 return enable(DETECT_DISK_READ);
436 }
437
438 /**
439 * Disable detection of disk reads.
440 */
441 public Builder permitDiskReads() {
442 return disable(DETECT_DISK_READ);
443 }
444
445 /**
Qi Wang097fbf22012-07-13 09:26:03 +0800446 * Enable detection of slow calls.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800447 */
448 public Builder detectCustomSlowCalls() {
449 return enable(DETECT_CUSTOM);
450 }
451
452 /**
Qi Wang097fbf22012-07-13 09:26:03 +0800453 * Disable detection of slow calls.
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800454 */
455 public Builder permitCustomSlowCalls() {
Qi Wang097fbf22012-07-13 09:26:03 +0800456 return disable(DETECT_CUSTOM);
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800457 }
458
459 /**
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800460 * Disable detection of mismatches between defined resource types
461 * and getter calls.
462 */
463 public Builder permitResourceMismatches() {
464 return disable(DETECT_RESOURCE_MISMATCH);
465 }
466
467 /**
Alan Viverette39bf9a12015-05-13 17:22:34 -0700468 * Enables detection of mismatches between defined resource types
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800469 * and getter calls.
Alan Viverette39bf9a12015-05-13 17:22:34 -0700470 * <p>
471 * This helps detect accidental type mismatches and potentially
472 * expensive type conversions when obtaining typed resources.
473 * <p>
474 * For example, a strict mode violation would be thrown when
475 * calling {@link android.content.res.TypedArray#getInt(int, int)}
476 * on an index that contains a String-type resource. If the string
477 * value can be parsed as an integer, this method call will return
478 * a value without crashing; however, the developer should format
479 * the resource as an integer to avoid unnecessary type conversion.
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800480 */
481 public Builder detectResourceMismatches() {
482 return enable(DETECT_RESOURCE_MISMATCH);
483 }
484
485 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700486 * Enable detection of disk writes.
487 */
488 public Builder detectDiskWrites() {
489 return enable(DETECT_DISK_WRITE);
490 }
491
492 /**
493 * Disable detection of disk writes.
494 */
495 public Builder permitDiskWrites() {
496 return disable(DETECT_DISK_WRITE);
497 }
498
499 /**
500 * Show an annoying dialog to the developer on detected
501 * violations, rate-limited to be only a little annoying.
502 */
503 public Builder penaltyDialog() {
504 return enable(PENALTY_DIALOG);
505 }
506
507 /**
508 * Crash the whole process on violation. This penalty runs at
509 * the end of all enabled penalties so you'll still get
510 * see logging or other violations before the process dies.
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700511 *
512 * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies
513 * to disk reads, disk writes, and network usage if their
514 * corresponding detect flags are set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700515 */
516 public Builder penaltyDeath() {
517 return enable(PENALTY_DEATH);
518 }
519
520 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -0700521 * Crash the whole process on any network usage. Unlike
522 * {@link #penaltyDeath}, this penalty runs
523 * <em>before</em> anything else. You must still have
524 * called {@link #detectNetwork} to enable this.
525 *
526 * <p>In the Honeycomb or later SDKs, this is on by default.
527 */
528 public Builder penaltyDeathOnNetwork() {
529 return enable(PENALTY_DEATH_ON_NETWORK);
530 }
531
532 /**
Brad Fitzpatrick68044332010-11-22 18:19:48 -0800533 * Flash the screen during a violation.
534 */
535 public Builder penaltyFlashScreen() {
536 return enable(PENALTY_FLASH);
537 }
538
539 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700540 * Log detected violations to the system log.
541 */
542 public Builder penaltyLog() {
543 return enable(PENALTY_LOG);
544 }
545
546 /**
547 * Enable detected violations log a stacktrace and timing data
548 * to the {@link android.os.DropBoxManager DropBox} on policy
549 * violation. Intended mostly for platform integrators doing
550 * beta user field data collection.
551 */
552 public Builder penaltyDropBox() {
553 return enable(PENALTY_DROPBOX);
554 }
555
556 private Builder enable(int bit) {
557 mMask |= bit;
558 return this;
559 }
560
561 private Builder disable(int bit) {
562 mMask &= ~bit;
563 return this;
564 }
565
566 /**
567 * Construct the ThreadPolicy instance.
568 *
569 * <p>Note: if no penalties are enabled before calling
570 * <code>build</code>, {@link #penaltyLog} is implicitly
571 * set.
572 */
573 public ThreadPolicy build() {
574 // If there are detection bits set but no violation bits
575 // set, enable simple logging.
576 if (mMask != 0 &&
577 (mMask & (PENALTY_DEATH | PENALTY_LOG |
578 PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
579 penaltyLog();
580 }
581 return new ThreadPolicy(mMask);
582 }
583 }
584 }
585
586 /**
587 * {@link StrictMode} policy applied to all threads in the virtual machine's process.
588 *
589 * <p>The policy is enabled by {@link #setVmPolicy}.
590 */
591 public static final class VmPolicy {
592 /**
593 * The default, lax policy which doesn't catch anything.
594 */
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800595 public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700596
597 final int mask;
598
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800599 // Map from class to max number of allowed instances in memory.
600 final HashMap<Class, Integer> classInstanceLimit;
601
602 private VmPolicy(int mask, HashMap<Class, Integer> classInstanceLimit) {
603 if (classInstanceLimit == null) {
604 throw new NullPointerException("classInstanceLimit == null");
605 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700606 this.mask = mask;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800607 this.classInstanceLimit = classInstanceLimit;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700608 }
609
610 @Override
611 public String toString() {
612 return "[StrictMode.VmPolicy; mask=" + mask + "]";
613 }
614
615 /**
616 * Creates {@link VmPolicy} instances. Methods whose names start
617 * with {@code detect} specify what problems we should look
618 * for. Methods whose names start with {@code penalty} specify what
619 * we should do when we detect a problem.
620 *
621 * <p>You can call as many {@code detect} and {@code penalty}
622 * methods as you like. Currently order is insignificant: all
623 * penalties apply to all detected problems.
624 *
625 * <p>For example, detect everything and log anything that's found:
626 * <pre>
627 * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
628 * .detectAll()
629 * .penaltyLog()
630 * .build();
631 * StrictMode.setVmPolicy(policy);
632 * </pre>
633 */
634 public static final class Builder {
635 private int mMask;
636
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800637 private HashMap<Class, Integer> mClassInstanceLimit; // null until needed
638 private boolean mClassInstanceLimitNeedCow = false; // need copy-on-write
639
640 public Builder() {
641 mMask = 0;
642 }
643
644 /**
645 * Build upon an existing VmPolicy.
646 */
647 public Builder(VmPolicy base) {
648 mMask = base.mask;
649 mClassInstanceLimitNeedCow = true;
650 mClassInstanceLimit = base.classInstanceLimit;
651 }
652
653 /**
654 * Set an upper bound on how many instances of a class can be in memory
655 * at once. Helps to prevent object leaks.
656 */
657 public Builder setClassInstanceLimit(Class klass, int instanceLimit) {
658 if (klass == null) {
659 throw new NullPointerException("klass == null");
660 }
661 if (mClassInstanceLimitNeedCow) {
662 if (mClassInstanceLimit.containsKey(klass) &&
663 mClassInstanceLimit.get(klass) == instanceLimit) {
664 // no-op; don't break COW
665 return this;
666 }
667 mClassInstanceLimitNeedCow = false;
668 mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
669 } else if (mClassInstanceLimit == null) {
670 mClassInstanceLimit = new HashMap<Class, Integer>();
671 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800672 mMask |= DETECT_VM_INSTANCE_LEAKS;
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800673 mClassInstanceLimit.put(klass, instanceLimit);
674 return this;
675 }
676
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800677 /**
678 * Detect leaks of {@link android.app.Activity} subclasses.
679 */
680 public Builder detectActivityLeaks() {
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800681 return enable(DETECT_VM_ACTIVITY_LEAKS);
682 }
683
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700684 /**
685 * Detect everything that's potentially suspect.
686 *
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700687 * <p>In the Honeycomb release this includes leaks of
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -0800688 * SQLite cursors, Activities, and other closable objects
689 * but will likely expand in future releases.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700690 */
691 public Builder detectAll() {
Jeff Sharkey605eb792014-11-04 13:34:06 -0800692 int flags = DETECT_VM_ACTIVITY_LEAKS | DETECT_VM_CURSOR_LEAKS
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700693 | DETECT_VM_CLOSABLE_LEAKS | DETECT_VM_REGISTRATION_LEAKS
Jeff Sharkey605eb792014-11-04 13:34:06 -0800694 | DETECT_VM_FILE_URI_EXPOSURE;
695
696 // TODO: always add DETECT_VM_CLEARTEXT_NETWORK once we have facility
697 // for apps to mark sockets that should be ignored
698 if (SystemProperties.getBoolean(CLEARTEXT_PROPERTY, false)) {
699 flags |= DETECT_VM_CLEARTEXT_NETWORK;
700 }
701
702 return enable(flags);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700703 }
704
705 /**
706 * Detect when an
707 * {@link android.database.sqlite.SQLiteCursor} or other
708 * SQLite object is finalized without having been closed.
709 *
710 * <p>You always want to explicitly close your SQLite
711 * cursors to avoid unnecessary database contention and
712 * temporary memory leaks.
713 */
714 public Builder detectLeakedSqlLiteObjects() {
715 return enable(DETECT_VM_CURSOR_LEAKS);
716 }
717
718 /**
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700719 * Detect when an {@link java.io.Closeable} or other
720 * object with a explict termination method is finalized
721 * without having been closed.
722 *
723 * <p>You always want to explicitly close such objects to
724 * avoid unnecessary resources leaks.
725 */
726 public Builder detectLeakedClosableObjects() {
727 return enable(DETECT_VM_CLOSABLE_LEAKS);
728 }
729
730 /**
Jeff Sharkeyd7026f12012-03-01 20:50:32 -0800731 * Detect when a {@link BroadcastReceiver} or
732 * {@link ServiceConnection} is leaked during {@link Context}
733 * teardown.
734 */
735 public Builder detectLeakedRegistrationObjects() {
736 return enable(DETECT_VM_REGISTRATION_LEAKS);
737 }
738
739 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -0700740 * Detect when this application exposes a {@code file://}
741 * {@link android.net.Uri} to another app.
742 * <p>
743 * This exposure is discouraged since the receiving app may not have
744 * access to the shared path. For example, the receiving app may not
745 * have requested the
746 * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} runtime
747 * permission, or the platform may be sharing the
748 * {@link android.net.Uri} across user profile boundaries.
749 * <p>
750 * Instead, apps should use {@code content://} Uris so the platform
751 * can extend temporary permission for the receiving app to access
752 * the resource.
753 *
754 * @see android.support.v4.content.FileProvider
755 * @see Intent#FLAG_GRANT_READ_URI_PERMISSION
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700756 */
757 public Builder detectFileUriExposure() {
758 return enable(DETECT_VM_FILE_URI_EXPOSURE);
759 }
760
761 /**
Jeff Sharkey605eb792014-11-04 13:34:06 -0800762 * Detect any network traffic from the calling app which is not
763 * wrapped in SSL/TLS. This can help you detect places that your app
764 * is inadvertently sending cleartext data across the network.
765 * <p>
766 * Using {@link #penaltyDeath()} or
767 * {@link #penaltyDeathOnCleartextNetwork()} will block further
768 * traffic on that socket to prevent accidental data leakage, in
769 * addition to crashing your process.
770 * <p>
771 * Using {@link #penaltyDropBox()} will log the raw contents of the
772 * packet that triggered the violation.
773 * <p>
774 * This inspects both IPv4/IPv6 and TCP/UDP network traffic, but it
775 * may be subject to false positives, such as when STARTTLS
776 * protocols or HTTP proxies are used.
Jeff Sharkey605eb792014-11-04 13:34:06 -0800777 */
778 public Builder detectCleartextNetwork() {
779 return enable(DETECT_VM_CLEARTEXT_NETWORK);
780 }
781
782 /**
783 * Crashes the whole process on violation. This penalty runs at the
784 * end of all enabled penalties so you'll still get your logging or
785 * other violations before the process dies.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700786 */
787 public Builder penaltyDeath() {
788 return enable(PENALTY_DEATH);
789 }
790
791 /**
Jeff Sharkey605eb792014-11-04 13:34:06 -0800792 * Crashes the whole process when cleartext network traffic is
793 * detected.
794 *
795 * @see #detectCleartextNetwork()
Jeff Sharkey605eb792014-11-04 13:34:06 -0800796 */
797 public Builder penaltyDeathOnCleartextNetwork() {
798 return enable(PENALTY_DEATH_ON_CLEARTEXT_NETWORK);
799 }
800
801 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -0700802 * Crashes the whole process when a {@code file://}
803 * {@link android.net.Uri} is exposed beyond this app.
804 *
805 * @see #detectFileUriExposure()
806 */
807 public Builder penaltyDeathOnFileUriExposure() {
808 return enable(PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
809 }
810
811 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700812 * Log detected violations to the system log.
813 */
814 public Builder penaltyLog() {
815 return enable(PENALTY_LOG);
816 }
817
818 /**
819 * Enable detected violations log a stacktrace and timing data
820 * to the {@link android.os.DropBoxManager DropBox} on policy
821 * violation. Intended mostly for platform integrators doing
822 * beta user field data collection.
823 */
824 public Builder penaltyDropBox() {
825 return enable(PENALTY_DROPBOX);
826 }
827
828 private Builder enable(int bit) {
829 mMask |= bit;
830 return this;
831 }
832
833 /**
834 * Construct the VmPolicy instance.
835 *
836 * <p>Note: if no penalties are enabled before calling
837 * <code>build</code>, {@link #penaltyLog} is implicitly
838 * set.
839 */
840 public VmPolicy build() {
841 // If there are detection bits set but no violation bits
842 // set, enable simple logging.
843 if (mMask != 0 &&
844 (mMask & (PENALTY_DEATH | PENALTY_LOG |
845 PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
846 penaltyLog();
847 }
Brad Fitzpatrick75803572011-01-13 14:21:03 -0800848 return new VmPolicy(mMask,
849 mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP);
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700850 }
851 }
852 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700853
854 /**
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700855 * Log of strict mode violation stack traces that have occurred
856 * during a Binder call, to be serialized back later to the caller
857 * via Parcel.writeNoException() (amusingly) where the caller can
858 * choose how to react.
859 */
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -0700860 private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
861 new ThreadLocal<ArrayList<ViolationInfo>>() {
862 @Override protected ArrayList<ViolationInfo> initialValue() {
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -0700863 // Starts null to avoid unnecessary allocations when
864 // checking whether there are any violations or not in
865 // hasGatheredViolations() below.
866 return null;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700867 }
868 };
869
870 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700871 * Sets the policy for what actions on the current thread should
872 * be detected, as well as the penalty if such actions occur.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700873 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700874 * <p>Internally this sets a thread-local variable which is
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700875 * propagated across cross-process IPC calls, meaning you can
876 * catch violations when a system service or another process
877 * accesses the disk or network on your behalf.
878 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700879 * @param policy the policy to put into place
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700880 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700881 public static void setThreadPolicy(final ThreadPolicy policy) {
882 setThreadPolicyMask(policy.mask);
883 }
884
885 private static void setThreadPolicyMask(final int policyMask) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700886 // In addition to the Java-level thread-local in Dalvik's
887 // BlockGuard, we also need to keep a native thread-local in
888 // Binder in order to propagate the value across Binder calls,
889 // even across native-only processes. The two are kept in
890 // sync via the callback to onStrictModePolicyChange, below.
891 setBlockGuardPolicy(policyMask);
892
893 // And set the Android native version...
894 Binder.setThreadStrictModePolicy(policyMask);
895 }
896
897 // Sets the policy in Dalvik/libcore (BlockGuard)
898 private static void setBlockGuardPolicy(final int policyMask) {
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700899 if (policyMask == 0) {
900 BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
901 return;
902 }
Jeff Sharkeya2934d52013-06-14 14:43:18 -0700903 final BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
904 final AndroidBlockGuardPolicy androidPolicy;
905 if (policy instanceof AndroidBlockGuardPolicy) {
906 androidPolicy = (AndroidBlockGuardPolicy) policy;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700907 } else {
Jeff Sharkeya2934d52013-06-14 14:43:18 -0700908 androidPolicy = threadAndroidPolicy.get();
909 BlockGuard.setThreadPolicy(androidPolicy);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700910 }
Jeff Sharkeya2934d52013-06-14 14:43:18 -0700911 androidPolicy.setPolicyMask(policyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700912 }
913
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -0800914 // Sets up CloseGuard in Dalvik/libcore
915 private static void setCloseGuardEnabled(boolean enabled) {
Brad Fitzpatrick7c2ae652010-11-14 11:00:05 -0800916 if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -0800917 CloseGuard.setReporter(new AndroidCloseGuardReporter());
918 }
919 CloseGuard.setEnabled(enabled);
920 }
921
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800922 /**
923 * @hide
924 */
925 public static class StrictModeViolation extends BlockGuard.BlockGuardPolicyException {
926 public StrictModeViolation(int policyState, int policyViolated, String message) {
927 super(policyState, policyViolated, message);
928 }
929 }
930
931 /**
932 * @hide
933 */
934 public static class StrictModeNetworkViolation extends StrictModeViolation {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700935 public StrictModeNetworkViolation(int policyMask) {
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800936 super(policyMask, DETECT_NETWORK, null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700937 }
938 }
939
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800940 /**
941 * @hide
942 */
943 private static class StrictModeDiskReadViolation extends StrictModeViolation {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700944 public StrictModeDiskReadViolation(int policyMask) {
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800945 super(policyMask, DETECT_DISK_READ, null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700946 }
947 }
948
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800949 /**
950 * @hide
951 */
952 private static class StrictModeDiskWriteViolation extends StrictModeViolation {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700953 public StrictModeDiskWriteViolation(int policyMask) {
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800954 super(policyMask, DETECT_DISK_WRITE, null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700955 }
956 }
957
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800958 /**
959 * @hide
960 */
961 private static class StrictModeCustomViolation extends StrictModeViolation {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800962 public StrictModeCustomViolation(int policyMask, String name) {
963 super(policyMask, DETECT_CUSTOM, name);
964 }
965 }
966
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700967 /**
Alan Viverette6bbb47b2015-01-05 18:12:44 -0800968 * @hide
969 */
970 private static class StrictModeResourceMismatchViolation extends StrictModeViolation {
971 public StrictModeResourceMismatchViolation(int policyMask, Object tag) {
972 super(policyMask, DETECT_RESOURCE_MISMATCH, tag != null ? tag.toString() : null);
973 }
974 }
975
976 /**
Brad Fitzpatrick15ba4062010-09-22 13:53:57 -0700977 * Returns the bitmask of the current thread's policy.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700978 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700979 * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
980 *
981 * @hide
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700982 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700983 public static int getThreadPolicyMask() {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700984 return BlockGuard.getThreadPolicy().getPolicyMask();
985 }
986
Brad Fitzpatrick5b747192010-07-12 11:05:38 -0700987 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700988 * Returns the current thread's policy.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -0700989 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700990 public static ThreadPolicy getThreadPolicy() {
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -0800991 // TODO: this was a last minute Gingerbread API change (to
992 // introduce VmPolicy cleanly) but this isn't particularly
993 // optimal for users who might call this method often. This
994 // should be in a thread-local and not allocate on each call.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700995 return new ThreadPolicy(getThreadPolicyMask());
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -0700996 }
997
998 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -0700999 * A convenience wrapper that takes the current
1000 * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
1001 * to permit both disk reads &amp; writes, and sets the new policy
1002 * with {@link #setThreadPolicy}, returning the old policy so you
1003 * can restore it at the end of a block.
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001004 *
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001005 * @return the old policy, to be passed to {@link #setThreadPolicy} to
1006 * restore the policy at the end of a block
1007 */
1008 public static ThreadPolicy allowThreadDiskWrites() {
1009 int oldPolicyMask = getThreadPolicyMask();
1010 int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_WRITE | DETECT_DISK_READ);
1011 if (newPolicyMask != oldPolicyMask) {
1012 setThreadPolicyMask(newPolicyMask);
1013 }
1014 return new ThreadPolicy(oldPolicyMask);
1015 }
1016
1017 /**
1018 * A convenience wrapper that takes the current
1019 * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
1020 * to permit disk reads, and sets the new policy
1021 * with {@link #setThreadPolicy}, returning the old policy so you
1022 * can restore it at the end of a block.
1023 *
1024 * @return the old policy, to be passed to setThreadPolicy to
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001025 * restore the policy.
1026 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001027 public static ThreadPolicy allowThreadDiskReads() {
1028 int oldPolicyMask = getThreadPolicyMask();
1029 int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_READ);
1030 if (newPolicyMask != oldPolicyMask) {
1031 setThreadPolicyMask(newPolicyMask);
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001032 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001033 return new ThreadPolicy(oldPolicyMask);
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001034 }
1035
Brad Fitzpatrickf5454592010-11-24 15:27:51 -08001036 // We don't want to flash the screen red in the system server
1037 // process, nor do we want to modify all the call sites of
1038 // conditionallyEnableDebugLogging() in the system server,
1039 // so instead we use this to determine if we are the system server.
1040 private static boolean amTheSystemServerProcess() {
1041 // Fast path. Most apps don't have the system server's UID.
1042 if (Process.myUid() != Process.SYSTEM_UID) {
1043 return false;
1044 }
1045
1046 // The settings app, though, has the system server's UID so
1047 // look up our stack to see if we came from the system server.
1048 Throwable stack = new Throwable();
1049 stack.fillInStackTrace();
1050 for (StackTraceElement ste : stack.getStackTrace()) {
1051 String clsName = ste.getClassName();
1052 if (clsName != null && clsName.startsWith("com.android.server.")) {
1053 return true;
1054 }
1055 }
1056 return false;
1057 }
1058
Brad Fitzpatrick97461bd2010-08-24 11:46:47 -07001059 /**
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001060 * Enable DropBox logging for debug phone builds.
1061 *
1062 * @hide
1063 */
1064 public static boolean conditionallyEnableDebugLogging() {
Christopher Tatebc6f0ce2011-11-03 12:18:43 -07001065 boolean doFlashes = SystemProperties.getBoolean(VISUAL_PROPERTY, false)
1066 && !amTheSystemServerProcess();
1067 final boolean suppress = SystemProperties.getBoolean(DISABLE_PROPERTY, false);
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001068
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001069 // For debug builds, log event loop stalls to dropbox for analysis.
1070 // Similar logic also appears in ActivityThread.java for system apps.
Christopher Tatebc6f0ce2011-11-03 12:18:43 -07001071 if (!doFlashes && (IS_USER_BUILD || suppress)) {
Brad Fitzpatrick7c2ae652010-11-14 11:00:05 -08001072 setCloseGuardEnabled(false);
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001073 return false;
1074 }
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001075
Christopher Tatebc6f0ce2011-11-03 12:18:43 -07001076 // Eng builds have flashes on all the time. The suppression property
1077 // overrides this, so we force the behavior only after the short-circuit
1078 // check above.
1079 if (IS_ENG_BUILD) {
1080 doFlashes = true;
1081 }
1082
Jeff Brownbe7c29c2011-10-11 11:35:23 -07001083 // Thread policy controls BlockGuard.
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001084 int threadPolicyMask = StrictMode.DETECT_DISK_WRITE |
1085 StrictMode.DETECT_DISK_READ |
1086 StrictMode.DETECT_NETWORK;
1087
1088 if (!IS_USER_BUILD) {
1089 threadPolicyMask |= StrictMode.PENALTY_DROPBOX;
1090 }
1091 if (doFlashes) {
1092 threadPolicyMask |= StrictMode.PENALTY_FLASH;
1093 }
1094
1095 StrictMode.setThreadPolicyMask(threadPolicyMask);
1096
Jeff Brownbe7c29c2011-10-11 11:35:23 -07001097 // VM Policy controls CloseGuard, detection of Activity leaks,
1098 // and instance counting.
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001099 if (IS_USER_BUILD) {
1100 setCloseGuardEnabled(false);
1101 } else {
Jeff Brownd5875d92011-10-09 14:59:37 -07001102 VmPolicy.Builder policyBuilder = new VmPolicy.Builder().detectAll().penaltyDropBox();
1103 if (IS_ENG_BUILD) {
1104 policyBuilder.penaltyLog();
1105 }
1106 setVmPolicy(policyBuilder.build());
Brad Fitzpatrickc1a968a2010-11-24 08:56:40 -08001107 setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
1108 }
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07001109 return true;
1110 }
1111
1112 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001113 * Used by the framework to make network usage on the main
1114 * thread a fatal error.
1115 *
1116 * @hide
1117 */
1118 public static void enableDeathOnNetwork() {
1119 int oldPolicy = getThreadPolicyMask();
1120 int newPolicy = oldPolicy | DETECT_NETWORK | PENALTY_DEATH_ON_NETWORK;
1121 setThreadPolicyMask(newPolicy);
1122 }
1123
1124 /**
Jeff Sharkey344744b2016-01-28 19:03:30 -07001125 * Used by the framework to make file usage a fatal error.
1126 *
1127 * @hide
1128 */
1129 public static void enableDeathOnFileUriExposure() {
1130 sVmPolicyMask |= DETECT_VM_FILE_URI_EXPOSURE | PENALTY_DEATH_ON_FILE_URI_EXPOSURE;
1131 }
1132
1133 /**
1134 * Used by lame internal apps that haven't done the hard work to get
1135 * themselves off file:// Uris yet.
1136 *
1137 * @hide
1138 */
1139 public static void disableDeathOnFileUriExposure() {
1140 sVmPolicyMask &= ~(DETECT_VM_FILE_URI_EXPOSURE | PENALTY_DEATH_ON_FILE_URI_EXPOSURE);
1141 }
1142
1143 /**
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001144 * Parses the BlockGuard policy mask out from the Exception's
1145 * getMessage() String value. Kinda gross, but least
1146 * invasive. :/
1147 *
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001148 * Input is of the following forms:
1149 * "policy=137 violation=64"
1150 * "policy=137 violation=64 msg=Arbitrary text"
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001151 *
1152 * Returns 0 on failure, which is a valid policy, but not a
1153 * valid policy during a violation (else there must've been
1154 * some policy in effect to violate).
1155 */
1156 private static int parsePolicyFromMessage(String message) {
1157 if (message == null || !message.startsWith("policy=")) {
1158 return 0;
1159 }
1160 int spaceIndex = message.indexOf(' ');
1161 if (spaceIndex == -1) {
1162 return 0;
1163 }
1164 String policyString = message.substring(7, spaceIndex);
1165 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001166 return Integer.parseInt(policyString);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001167 } catch (NumberFormatException e) {
1168 return 0;
1169 }
1170 }
1171
1172 /**
1173 * Like parsePolicyFromMessage(), but returns the violation.
1174 */
1175 private static int parseViolationFromMessage(String message) {
1176 if (message == null) {
1177 return 0;
1178 }
1179 int violationIndex = message.indexOf("violation=");
1180 if (violationIndex == -1) {
1181 return 0;
1182 }
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001183 int numberStartIndex = violationIndex + "violation=".length();
1184 int numberEndIndex = message.indexOf(' ', numberStartIndex);
1185 if (numberEndIndex == -1) {
1186 numberEndIndex = message.length();
1187 }
1188 String violationString = message.substring(numberStartIndex, numberEndIndex);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001189 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001190 return Integer.parseInt(violationString);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001191 } catch (NumberFormatException e) {
1192 return 0;
1193 }
1194 }
1195
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001196 private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
1197 new ThreadLocal<ArrayList<ViolationInfo>>() {
1198 @Override protected ArrayList<ViolationInfo> initialValue() {
1199 return new ArrayList<ViolationInfo>();
1200 }
1201 };
1202
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001203 // Note: only access this once verifying the thread has a Looper.
1204 private static final ThreadLocal<Handler> threadHandler = new ThreadLocal<Handler>() {
1205 @Override protected Handler initialValue() {
1206 return new Handler();
1207 }
1208 };
1209
Jeff Sharkeya2934d52013-06-14 14:43:18 -07001210 private static final ThreadLocal<AndroidBlockGuardPolicy>
1211 threadAndroidPolicy = new ThreadLocal<AndroidBlockGuardPolicy>() {
1212 @Override
1213 protected AndroidBlockGuardPolicy initialValue() {
1214 return new AndroidBlockGuardPolicy(0);
1215 }
1216 };
1217
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001218 private static boolean tooManyViolationsThisLoop() {
1219 return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
1220 }
1221
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001222 private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
1223 private int mPolicyMask;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001224
1225 // Map from violation stacktrace hashcode -> uptimeMillis of
1226 // last violation. No locking needed, as this is only
1227 // accessed by the same thread.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001228 private ArrayMap<Integer, Long> mLastViolationTime;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001229
1230 public AndroidBlockGuardPolicy(final int policyMask) {
1231 mPolicyMask = policyMask;
1232 }
1233
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001234 @Override
1235 public String toString() {
1236 return "AndroidBlockGuardPolicy; mPolicyMask=" + mPolicyMask;
1237 }
1238
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001239 // Part of BlockGuard.Policy interface:
1240 public int getPolicyMask() {
1241 return mPolicyMask;
1242 }
1243
1244 // Part of BlockGuard.Policy interface:
1245 public void onWriteToDisk() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001246 if ((mPolicyMask & DETECT_DISK_WRITE) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001247 return;
1248 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001249 if (tooManyViolationsThisLoop()) {
1250 return;
1251 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001252 BlockGuard.BlockGuardPolicyException e = new StrictModeDiskWriteViolation(mPolicyMask);
1253 e.fillInStackTrace();
1254 startHandlingViolationException(e);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001255 }
1256
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001257 // Not part of BlockGuard.Policy; just part of StrictMode:
1258 void onCustomSlowCall(String name) {
1259 if ((mPolicyMask & DETECT_CUSTOM) == 0) {
1260 return;
1261 }
1262 if (tooManyViolationsThisLoop()) {
1263 return;
1264 }
1265 BlockGuard.BlockGuardPolicyException e = new StrictModeCustomViolation(mPolicyMask, name);
1266 e.fillInStackTrace();
1267 startHandlingViolationException(e);
1268 }
1269
Alan Viverette6bbb47b2015-01-05 18:12:44 -08001270 // Not part of BlockGuard.Policy; just part of StrictMode:
1271 void onResourceMismatch(Object tag) {
1272 if ((mPolicyMask & DETECT_RESOURCE_MISMATCH) == 0) {
1273 return;
1274 }
1275 if (tooManyViolationsThisLoop()) {
1276 return;
1277 }
1278 BlockGuard.BlockGuardPolicyException e =
1279 new StrictModeResourceMismatchViolation(mPolicyMask, tag);
1280 e.fillInStackTrace();
1281 startHandlingViolationException(e);
1282 }
1283
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001284 // Part of BlockGuard.Policy interface:
1285 public void onReadFromDisk() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001286 if ((mPolicyMask & DETECT_DISK_READ) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001287 return;
1288 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001289 if (tooManyViolationsThisLoop()) {
1290 return;
1291 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001292 BlockGuard.BlockGuardPolicyException e = new StrictModeDiskReadViolation(mPolicyMask);
1293 e.fillInStackTrace();
1294 startHandlingViolationException(e);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001295 }
1296
1297 // Part of BlockGuard.Policy interface:
1298 public void onNetwork() {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001299 if ((mPolicyMask & DETECT_NETWORK) == 0) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001300 return;
1301 }
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07001302 if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
1303 throw new NetworkOnMainThreadException();
1304 }
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001305 if (tooManyViolationsThisLoop()) {
1306 return;
1307 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001308 BlockGuard.BlockGuardPolicyException e = new StrictModeNetworkViolation(mPolicyMask);
1309 e.fillInStackTrace();
1310 startHandlingViolationException(e);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001311 }
1312
1313 public void setPolicyMask(int policyMask) {
1314 mPolicyMask = policyMask;
1315 }
1316
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001317 // Start handling a violation that just started and hasn't
1318 // actually run yet (e.g. no disk write or network operation
1319 // has yet occurred). This sees if we're in an event loop
1320 // thread and, if so, uses it to roughly measure how long the
1321 // violation took.
1322 void startHandlingViolationException(BlockGuard.BlockGuardPolicyException e) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001323 final ViolationInfo info = new ViolationInfo(e, e.getPolicy());
1324 info.violationUptimeMillis = SystemClock.uptimeMillis();
1325 handleViolationWithTimingAttempt(info);
1326 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001327
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001328 // Attempts to fill in the provided ViolationInfo's
1329 // durationMillis field if this thread has a Looper we can use
1330 // to measure with. We measure from the time of violation
1331 // until the time the looper is idle again (right before
1332 // the next epoll_wait)
1333 void handleViolationWithTimingAttempt(final ViolationInfo info) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001334 Looper looper = Looper.myLooper();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001335
1336 // Without a Looper, we're unable to time how long the
1337 // violation takes place. This case should be rare, as
1338 // most users will care about timing violations that
1339 // happen on their main UI thread. Note that this case is
1340 // also hit when a violation takes place in a Binder
1341 // thread, in "gather" mode. In this case, the duration
1342 // of the violation is computed by the ultimate caller and
1343 // its Looper, if any.
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001344 //
1345 // Also, as a special short-cut case when the only penalty
1346 // bit is death, we die immediately, rather than timing
1347 // the violation's duration. This makes it convenient to
1348 // use in unit tests too, rather than waiting on a Looper.
1349 //
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001350 // TODO: if in gather mode, ignore Looper.myLooper() and always
1351 // go into this immediate mode?
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001352 if (looper == null ||
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001353 (info.policy & THREAD_PENALTY_MASK) == PENALTY_DEATH) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001354 info.durationMillis = -1; // unknown (redundant, already set)
1355 handleViolation(info);
1356 return;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001357 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001358
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001359 final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
Brad Fitzpatrick191cdf02010-10-11 11:31:15 -07001360 if (records.size() >= MAX_OFFENSES_PER_LOOP) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001361 // Not worth measuring. Too many offenses in one loop.
1362 return;
1363 }
1364 records.add(info);
1365 if (records.size() > 1) {
1366 // There's already been a violation this loop, so we've already
1367 // registered an idle handler to process the list of violations
1368 // at the end of this Looper's loop.
1369 return;
1370 }
1371
Brad Fitzpatrick68044332010-11-22 18:19:48 -08001372 final IWindowManager windowManager = (info.policy & PENALTY_FLASH) != 0 ?
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -08001373 sWindowManager.get() : null;
Brad Fitzpatrick68044332010-11-22 18:19:48 -08001374 if (windowManager != null) {
1375 try {
1376 windowManager.showStrictModeViolation(true);
1377 } catch (RemoteException unused) {
1378 }
1379 }
1380
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001381 // We post a runnable to a Handler (== delay 0 ms) for
1382 // measuring the end time of a violation instead of using
1383 // an IdleHandler (as was previously used) because an
1384 // IdleHandler may not run for quite a long period of time
1385 // if an ongoing animation is happening and continually
1386 // posting ASAP (0 ms) animation steps. Animations are
1387 // throttled back to 60fps via SurfaceFlinger/View
1388 // invalidates, _not_ by posting frame updates every 16
1389 // milliseconds.
Jeff Sharkey3761f332012-03-16 15:46:46 -07001390 threadHandler.get().postAtFrontOfQueue(new Runnable() {
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001391 public void run() {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001392 long loopFinishTime = SystemClock.uptimeMillis();
Brad Fitzpatrickbea168c2010-11-30 10:56:48 -08001393
1394 // Note: we do this early, before handling the
1395 // violation below, as handling the violation
1396 // may include PENALTY_DEATH and we don't want
1397 // to keep the red border on.
1398 if (windowManager != null) {
1399 try {
1400 windowManager.showStrictModeViolation(false);
1401 } catch (RemoteException unused) {
1402 }
1403 }
1404
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001405 for (int n = 0; n < records.size(); ++n) {
1406 ViolationInfo v = records.get(n);
1407 v.violationNumThisLoop = n + 1;
1408 v.durationMillis =
1409 (int) (loopFinishTime - v.violationUptimeMillis);
1410 handleViolation(v);
1411 }
1412 records.clear();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001413 }
1414 });
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001415 }
1416
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001417 // Note: It's possible (even quite likely) that the
1418 // thread-local policy mask has changed from the time the
1419 // violation fired and now (after the violating code ran) due
1420 // to people who push/pop temporary policy in regions of code,
1421 // hence the policy being passed around.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001422 void handleViolation(final ViolationInfo info) {
1423 if (info == null || info.crashInfo == null || info.crashInfo.stackTrace == null) {
1424 Log.wtf(TAG, "unexpected null stacktrace");
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001425 return;
1426 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001427
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001428 if (LOG_V) Log.d(TAG, "handleViolation; policy=" + info.policy);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001429
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001430 if ((info.policy & PENALTY_GATHER) != 0) {
1431 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001432 if (violations == null) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001433 violations = new ArrayList<ViolationInfo>(1);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001434 gatheredViolations.set(violations);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001435 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001436 for (ViolationInfo previous : violations) {
1437 if (info.crashInfo.stackTrace.equals(previous.crashInfo.stackTrace)) {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001438 // Duplicate. Don't log.
1439 return;
1440 }
1441 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001442 violations.add(info);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001443 return;
1444 }
1445
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001446 // Not perfect, but fast and good enough for dup suppression.
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08001447 Integer crashFingerprint = info.hashCode();
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001448 long lastViolationTime = 0;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001449 if (mLastViolationTime != null) {
1450 Long vtime = mLastViolationTime.get(crashFingerprint);
1451 if (vtime != null) {
1452 lastViolationTime = vtime;
1453 }
1454 } else {
1455 mLastViolationTime = new ArrayMap<Integer, Long>(1);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001456 }
1457 long now = SystemClock.uptimeMillis();
1458 mLastViolationTime.put(crashFingerprint, now);
1459 long timeSinceLastViolationMillis = lastViolationTime == 0 ?
1460 Long.MAX_VALUE : (now - lastViolationTime);
1461
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001462 if ((info.policy & PENALTY_LOG) != 0 &&
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001463 timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001464 if (info.durationMillis != -1) {
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001465 Log.d(TAG, "StrictMode policy violation; ~duration=" +
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001466 info.durationMillis + " ms: " + info.crashInfo.stackTrace);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001467 } else {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001468 Log.d(TAG, "StrictMode policy violation: " + info.crashInfo.stackTrace);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001469 }
1470 }
1471
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001472 // The violationMaskSubset, passed to ActivityManager, is a
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001473 // subset of the original StrictMode policy bitmask, with
1474 // only the bit violated and penalty bits to be executed
1475 // by the ActivityManagerService remaining set.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001476 int violationMaskSubset = 0;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001477
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001478 if ((info.policy & PENALTY_DIALOG) != 0 &&
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001479 timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001480 violationMaskSubset |= PENALTY_DIALOG;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001481 }
1482
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001483 if ((info.policy & PENALTY_DROPBOX) != 0 && lastViolationTime == 0) {
1484 violationMaskSubset |= PENALTY_DROPBOX;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07001485 }
1486
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001487 if (violationMaskSubset != 0) {
1488 int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
1489 violationMaskSubset |= violationBit;
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001490 final int savedPolicyMask = getThreadPolicyMask();
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001491
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001492 final boolean justDropBox = (info.policy & THREAD_PENALTY_MASK) == PENALTY_DROPBOX;
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001493 if (justDropBox) {
1494 // If all we're going to ask the activity manager
1495 // to do is dropbox it (the common case during
1496 // platform development), we can avoid doing this
1497 // call synchronously which Binder data suggests
1498 // isn't always super fast, despite the implementation
1499 // in the ActivityManager trying to be mostly async.
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001500 dropboxViolationAsync(violationMaskSubset, info);
Brad Fitzpatrick71678dd2010-10-28 13:51:58 -07001501 return;
1502 }
1503
1504 // Normal synchronous call to the ActivityManager.
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001505 try {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001506 // First, remove any policy before we call into the Activity Manager,
1507 // otherwise we'll infinite recurse as we try to log policy violations
1508 // to disk, thus violating policy, thus requiring logging, etc...
1509 // We restore the current policy below, in the finally block.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001510 setThreadPolicyMask(0);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001511
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001512 ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1513 RuntimeInit.getApplicationObject(),
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001514 violationMaskSubset,
1515 info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001516 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001517 if (e instanceof DeadObjectException) {
1518 // System process is dead; ignore
1519 } else {
1520 Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1521 }
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001522 } finally {
1523 // Restore the policy.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001524 setThreadPolicyMask(savedPolicyMask);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001525 }
1526 }
1527
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001528 if ((info.policy & PENALTY_DEATH) != 0) {
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001529 executeDeathPenalty(info);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001530 }
1531 }
1532 }
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001533
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08001534 private static void executeDeathPenalty(ViolationInfo info) {
1535 int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
1536 throw new StrictModeViolation(info.policy, violationBit, null);
1537 }
1538
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001539 /**
1540 * In the common case, as set by conditionallyEnableDebugLogging,
1541 * we're just dropboxing any violations but not showing a dialog,
1542 * not loggging, and not killing the process. In these cases we
1543 * don't need to do a synchronous call to the ActivityManager.
1544 * This is used by both per-thread and vm-wide violations when
1545 * applicable.
1546 */
1547 private static void dropboxViolationAsync(
1548 final int violationMaskSubset, final ViolationInfo info) {
1549 int outstanding = sDropboxCallsInFlight.incrementAndGet();
1550 if (outstanding > 20) {
1551 // What's going on? Let's not make make the situation
1552 // worse and just not log.
1553 sDropboxCallsInFlight.decrementAndGet();
1554 return;
1555 }
1556
1557 if (LOG_V) Log.d(TAG, "Dropboxing async; in-flight=" + outstanding);
1558
1559 new Thread("callActivityManagerForStrictModeDropbox") {
1560 public void run() {
1561 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562 try {
Brad Fitzpatrick10656852010-11-23 19:01:13 -08001563 IActivityManager am = ActivityManagerNative.getDefault();
1564 if (am == null) {
1565 Log.d(TAG, "No activity manager; failed to Dropbox violation.");
1566 } else {
1567 am.handleApplicationStrictModeViolation(
1568 RuntimeInit.getApplicationObject(),
1569 violationMaskSubset,
1570 info);
1571 }
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001572 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001573 if (e instanceof DeadObjectException) {
1574 // System process is dead; ignore
1575 } else {
1576 Log.e(TAG, "RemoteException handling StrictMode violation", e);
1577 }
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001578 }
1579 int outstanding = sDropboxCallsInFlight.decrementAndGet();
1580 if (LOG_V) Log.d(TAG, "Dropbox complete; in-flight=" + outstanding);
1581 }
1582 }.start();
1583 }
1584
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001585 private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001586 public void report(String message, Throwable allocationSite) {
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001587 onVmPolicyViolation(message, allocationSite);
1588 }
1589 }
1590
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001591 /**
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001592 * Called from Parcel.writeNoException()
1593 */
1594 /* package */ static boolean hasGatheredViolations() {
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001595 return gatheredViolations.get() != null;
1596 }
1597
1598 /**
1599 * Called from Parcel.writeException(), so we drop this memory and
1600 * don't incorrectly attribute it to the wrong caller on the next
1601 * Binder call on this thread.
1602 */
1603 /* package */ static void clearGatheredViolations() {
1604 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001605 }
1606
1607 /**
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001608 * @hide
1609 */
1610 public static void conditionallyCheckInstanceCounts() {
1611 VmPolicy policy = getVmPolicy();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001612 int policySize = policy.classInstanceLimit.size();
1613 if (policySize == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001614 return;
1615 }
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08001616
1617 System.gc();
1618 System.runFinalization();
1619 System.gc();
1620
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001621 // Note: classInstanceLimit is immutable, so this is lock-free
Mathieu Chartierd288a262015-07-10 13:44:42 -07001622 // Create the classes array.
1623 Class[] classes = policy.classInstanceLimit.keySet().toArray(new Class[policySize]);
1624 long[] instanceCounts = VMDebug.countInstancesOfClasses(classes, false);
1625 for (int i = 0; i < classes.length; ++i) {
1626 Class klass = classes[i];
1627 int limit = policy.classInstanceLimit.get(klass);
1628 long instances = instanceCounts[i];
1629 if (instances > limit) {
1630 Throwable tr = new InstanceCountViolation(klass, instances, limit);
1631 onVmPolicyViolation(tr.getMessage(), tr);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001632 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001633 }
1634 }
1635
1636 private static long sLastInstanceCountCheckMillis = 0;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001637 private static boolean sIsIdlerRegistered = false; // guarded by StrictMode.class
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001638 private static final MessageQueue.IdleHandler sProcessIdleHandler =
1639 new MessageQueue.IdleHandler() {
1640 public boolean queueIdle() {
1641 long now = SystemClock.uptimeMillis();
1642 if (now - sLastInstanceCountCheckMillis > 30 * 1000) {
1643 sLastInstanceCountCheckMillis = now;
1644 conditionallyCheckInstanceCounts();
1645 }
1646 return true;
1647 }
1648 };
1649
1650 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001651 * Sets the policy for what actions in the VM process (on any
1652 * thread) should be detected, as well as the penalty if such
1653 * actions occur.
1654 *
1655 * @param policy the policy to put into place
1656 */
1657 public static void setVmPolicy(final VmPolicy policy) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001658 synchronized (StrictMode.class) {
1659 sVmPolicy = policy;
1660 sVmPolicyMask = policy.mask;
1661 setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001662
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001663 Looper looper = Looper.getMainLooper();
1664 if (looper != null) {
1665 MessageQueue mq = looper.mQueue;
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001666 if (policy.classInstanceLimit.size() == 0 ||
1667 (sVmPolicyMask & VM_PENALTY_MASK) == 0) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001668 mq.removeIdleHandler(sProcessIdleHandler);
Brad Fitzpatrickc0bb0bb2011-01-20 16:29:52 -08001669 sIsIdlerRegistered = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001670 } else if (!sIsIdlerRegistered) {
1671 mq.addIdleHandler(sProcessIdleHandler);
1672 sIsIdlerRegistered = true;
1673 }
1674 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001675
1676 int networkPolicy = NETWORK_POLICY_ACCEPT;
1677 if ((sVmPolicyMask & DETECT_VM_CLEARTEXT_NETWORK) != 0) {
1678 if ((sVmPolicyMask & PENALTY_DEATH) != 0
1679 || (sVmPolicyMask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0) {
1680 networkPolicy = NETWORK_POLICY_REJECT;
1681 } else {
1682 networkPolicy = NETWORK_POLICY_LOG;
1683 }
1684 }
1685
1686 final INetworkManagementService netd = INetworkManagementService.Stub.asInterface(
1687 ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1688 if (netd != null) {
1689 try {
1690 netd.setUidCleartextNetworkPolicy(android.os.Process.myUid(), networkPolicy);
1691 } catch (RemoteException ignored) {
1692 }
1693 } else if (networkPolicy != NETWORK_POLICY_ACCEPT) {
1694 Log.w(TAG, "Dropping requested network policy due to missing service!");
1695 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001696 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001697 }
1698
1699 /**
1700 * Gets the current VM policy.
1701 */
1702 public static VmPolicy getVmPolicy() {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001703 synchronized (StrictMode.class) {
1704 return sVmPolicy;
1705 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001706 }
1707
1708 /**
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07001709 * Enable the recommended StrictMode defaults, with violations just being logged.
1710 *
1711 * <p>This catches disk and network access on the main thread, as
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001712 * well as leaked SQLite cursors and unclosed resources. This is
1713 * simply a wrapper around {@link #setVmPolicy} and {@link
1714 * #setThreadPolicy}.
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07001715 */
1716 public static void enableDefaults() {
1717 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
1718 .detectAll()
1719 .penaltyLog()
1720 .build());
1721 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08001722 .detectAll()
Brad Fitzpatrick62a1eb52010-10-18 14:32:59 -07001723 .penaltyLog()
1724 .build());
1725 }
1726
1727 /**
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001728 * @hide
1729 */
1730 public static boolean vmSqliteObjectLeaksEnabled() {
1731 return (sVmPolicyMask & DETECT_VM_CURSOR_LEAKS) != 0;
1732 }
1733
1734 /**
1735 * @hide
1736 */
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001737 public static boolean vmClosableObjectLeaksEnabled() {
1738 return (sVmPolicyMask & DETECT_VM_CLOSABLE_LEAKS) != 0;
1739 }
1740
1741 /**
1742 * @hide
1743 */
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08001744 public static boolean vmRegistrationLeaksEnabled() {
1745 return (sVmPolicyMask & DETECT_VM_REGISTRATION_LEAKS) != 0;
1746 }
1747
1748 /**
1749 * @hide
1750 */
Jeff Sharkeya14acd22013-04-02 18:27:45 -07001751 public static boolean vmFileUriExposureEnabled() {
1752 return (sVmPolicyMask & DETECT_VM_FILE_URI_EXPOSURE) != 0;
1753 }
1754
1755 /**
1756 * @hide
1757 */
Jeff Sharkey605eb792014-11-04 13:34:06 -08001758 public static boolean vmCleartextNetworkEnabled() {
1759 return (sVmPolicyMask & DETECT_VM_CLEARTEXT_NETWORK) != 0;
1760 }
1761
1762 /**
1763 * @hide
1764 */
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001765 public static void onSqliteObjectLeaked(String message, Throwable originStack) {
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001766 onVmPolicyViolation(message, originStack);
1767 }
1768
Steve Block08d584c2011-05-17 19:05:03 +01001769 /**
1770 * @hide
1771 */
1772 public static void onWebViewMethodCalledOnWrongThread(Throwable originStack) {
1773 onVmPolicyViolation(null, originStack);
1774 }
1775
Jeff Sharkeyd7026f12012-03-01 20:50:32 -08001776 /**
1777 * @hide
1778 */
1779 public static void onIntentReceiverLeaked(Throwable originStack) {
1780 onVmPolicyViolation(null, originStack);
1781 }
1782
1783 /**
1784 * @hide
1785 */
1786 public static void onServiceConnectionLeaked(Throwable originStack) {
1787 onVmPolicyViolation(null, originStack);
1788 }
1789
Jeff Sharkeya14acd22013-04-02 18:27:45 -07001790 /**
1791 * @hide
1792 */
Jeff Sharkey344744b2016-01-28 19:03:30 -07001793 public static void onFileUriExposed(Uri uri, String location) {
1794 final String message = uri + " exposed beyond app through " + location;
1795 if ((sVmPolicyMask & PENALTY_DEATH_ON_FILE_URI_EXPOSURE) != 0) {
1796 throw new FileUriExposedException(message);
1797 } else {
1798 onVmPolicyViolation(null, new Throwable(message));
1799 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001800 }
1801
1802 /**
1803 * @hide
1804 */
1805 public static void onCleartextNetworkDetected(byte[] firstPacket) {
1806 byte[] rawAddr = null;
1807 if (firstPacket != null) {
1808 if (firstPacket.length >= 20 && (firstPacket[0] & 0xf0) == 0x40) {
1809 // IPv4
1810 rawAddr = new byte[4];
1811 System.arraycopy(firstPacket, 16, rawAddr, 0, 4);
1812 } else if (firstPacket.length >= 40 && (firstPacket[0] & 0xf0) == 0x60) {
1813 // IPv6
1814 rawAddr = new byte[16];
1815 System.arraycopy(firstPacket, 24, rawAddr, 0, 16);
1816 }
1817 }
1818
1819 final int uid = android.os.Process.myUid();
1820 String msg = "Detected cleartext network traffic from UID " + uid;
1821 if (rawAddr != null) {
1822 try {
1823 msg = "Detected cleartext network traffic from UID " + uid + " to "
1824 + InetAddress.getByAddress(rawAddr);
1825 } catch (UnknownHostException ignored) {
1826 }
1827 }
1828
1829 final boolean forceDeath = (sVmPolicyMask & PENALTY_DEATH_ON_CLEARTEXT_NETWORK) != 0;
1830 onVmPolicyViolation(HexDump.dumpHexString(firstPacket).trim(), new Throwable(msg),
1831 forceDeath);
Jeff Sharkeya14acd22013-04-02 18:27:45 -07001832 }
1833
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001834 // Map from VM violation fingerprint to uptime millis.
1835 private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<Integer, Long>();
1836
Brian Carlstrom4b9b7c32010-11-08 10:30:40 -08001837 /**
1838 * @hide
1839 */
1840 public static void onVmPolicyViolation(String message, Throwable originStack) {
Jeff Sharkey605eb792014-11-04 13:34:06 -08001841 onVmPolicyViolation(message, originStack, false);
1842 }
1843
1844 /**
1845 * @hide
1846 */
1847 public static void onVmPolicyViolation(String message, Throwable originStack,
1848 boolean forceDeath) {
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001849 final boolean penaltyDropbox = (sVmPolicyMask & PENALTY_DROPBOX) != 0;
Jeff Sharkey605eb792014-11-04 13:34:06 -08001850 final boolean penaltyDeath = ((sVmPolicyMask & PENALTY_DEATH) != 0) || forceDeath;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001851 final boolean penaltyLog = (sVmPolicyMask & PENALTY_LOG) != 0;
Jeff Sharkey605eb792014-11-04 13:34:06 -08001852 final ViolationInfo info = new ViolationInfo(message, originStack, sVmPolicyMask);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001853
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001854 // Erase stuff not relevant for process-wide violations
1855 info.numAnimationsRunning = 0;
1856 info.tags = null;
1857 info.broadcastIntentAction = null;
1858
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001859 final Integer fingerprint = info.hashCode();
1860 final long now = SystemClock.uptimeMillis();
1861 long lastViolationTime = 0;
1862 long timeSinceLastViolationMillis = Long.MAX_VALUE;
1863 synchronized (sLastVmViolationTime) {
1864 if (sLastVmViolationTime.containsKey(fingerprint)) {
1865 lastViolationTime = sLastVmViolationTime.get(fingerprint);
1866 timeSinceLastViolationMillis = now - lastViolationTime;
1867 }
1868 if (timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1869 sLastVmViolationTime.put(fingerprint, now);
1870 }
1871 }
1872
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001873 if (penaltyLog && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001874 Log.e(TAG, message, originStack);
1875 }
1876
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001877 int violationMaskSubset = PENALTY_DROPBOX | (ALL_VM_DETECT_BITS & sVmPolicyMask);
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001878
1879 if (penaltyDropbox && !penaltyDeath) {
1880 // Common case for userdebug/eng builds. If no death and
1881 // just dropboxing, we can do the ActivityManager call
1882 // asynchronously.
1883 dropboxViolationAsync(violationMaskSubset, info);
1884 return;
1885 }
1886
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08001887 if (penaltyDropbox && lastViolationTime == 0) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001888 // The violationMask, passed to ActivityManager, is a
1889 // subset of the original StrictMode policy bitmask, with
1890 // only the bit violated and penalty bits to be executed
1891 // by the ActivityManagerService remaining set.
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001892 final int savedPolicyMask = getThreadPolicyMask();
1893 try {
1894 // First, remove any policy before we call into the Activity Manager,
1895 // otherwise we'll infinite recurse as we try to log policy violations
1896 // to disk, thus violating policy, thus requiring logging, etc...
1897 // We restore the current policy below, in the finally block.
1898 setThreadPolicyMask(0);
1899
1900 ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1901 RuntimeInit.getApplicationObject(),
1902 violationMaskSubset,
1903 info);
1904 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001905 if (e instanceof DeadObjectException) {
1906 // System process is dead; ignore
1907 } else {
1908 Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1909 }
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001910 } finally {
1911 // Restore the policy.
1912 setThreadPolicyMask(savedPolicyMask);
1913 }
1914 }
1915
Brad Fitzpatrickbee24872010-11-20 12:09:10 -08001916 if (penaltyDeath) {
Brad Fitzpatrick32e60c72010-09-30 16:22:36 -07001917 System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
1918 Process.killProcess(Process.myPid());
1919 System.exit(10);
1920 }
1921 }
1922
1923 /**
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001924 * Called from Parcel.writeNoException()
1925 */
1926 /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001927 ArrayList<ViolationInfo> violations = gatheredViolations.get();
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001928 if (violations == null) {
1929 p.writeInt(0);
1930 } else {
Jeff Sharkey20db11c2016-12-06 16:47:00 -07001931 // To avoid taking up too much transaction space, only include
1932 // details for the first 3 violations. Deep inside, CrashInfo
1933 // will truncate each stack trace to ~20kB.
1934 final int size = Math.min(violations.size(), 3);
1935 p.writeInt(size);
1936 for (int i = 0; i < size; i++) {
1937 violations.get(i).writeToParcel(p, 0);
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001938 }
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001939 }
Brad Fitzpatrick703e5d32010-07-15 13:16:41 -07001940 gatheredViolations.set(null);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001941 }
1942
1943 private static class LogStackTrace extends Exception {}
1944
1945 /**
1946 * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS,
1947 * we here read back all the encoded violations.
1948 */
1949 /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
1950 // Our own stack trace to append
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001951 StringWriter sw = new StringWriter();
Jeff Sharkey20db11c2016-12-06 16:47:00 -07001952 sw.append("# via Binder call with stack:\n");
Dianne Hackborn8c841092013-06-24 13:46:13 -07001953 PrintWriter pw = new FastPrintWriter(sw, false, 256);
1954 new LogStackTrace().printStackTrace(pw);
1955 pw.flush();
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001956 String ourStack = sw.toString();
1957
Jeff Sharkey20db11c2016-12-06 16:47:00 -07001958 final int policyMask = getThreadPolicyMask();
1959 final boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001960
Jeff Sharkey20db11c2016-12-06 16:47:00 -07001961 final int size = p.readInt();
1962 for (int i = 0; i < size; i++) {
1963 final ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
1964 info.crashInfo.appendStackTrace(ourStack);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001965 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1966 if (policy instanceof AndroidBlockGuardPolicy) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001967 ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
Brad Fitzpatrick5b747192010-07-12 11:05:38 -07001968 }
1969 }
1970 }
1971
1972 /**
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001973 * Called from android_util_Binder.cpp's
1974 * android_os_Parcel_enforceInterface when an incoming Binder call
1975 * requires changing the StrictMode policy mask. The role of this
1976 * function is to ask Binder for its current (native) thread-local
1977 * policy value and synchronize it to libcore's (Java)
1978 * thread-local policy value.
1979 */
1980 private static void onBinderStrictModePolicyChange(int newPolicy) {
1981 setBlockGuardPolicy(newPolicy);
1982 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07001983
1984 /**
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08001985 * A tracked, critical time span. (e.g. during an animation.)
1986 *
1987 * The object itself is a linked list node, to avoid any allocations
1988 * during rapid span entries and exits.
1989 *
1990 * @hide
1991 */
1992 public static class Span {
1993 private String mName;
1994 private long mCreateMillis;
1995 private Span mNext;
1996 private Span mPrev; // not used when in freeList, only active
1997 private final ThreadSpanState mContainerState;
1998
1999 Span(ThreadSpanState threadState) {
2000 mContainerState = threadState;
2001 }
2002
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002003 // Empty constructor for the NO_OP_SPAN
2004 protected Span() {
2005 mContainerState = null;
2006 }
2007
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002008 /**
2009 * To be called when the critical span is complete (i.e. the
2010 * animation is done animating). This can be called on any
2011 * thread (even a different one from where the animation was
2012 * taking place), but that's only a defensive implementation
2013 * measure. It really makes no sense for you to call this on
2014 * thread other than that where you created it.
2015 *
2016 * @hide
2017 */
2018 public void finish() {
2019 ThreadSpanState state = mContainerState;
2020 synchronized (state) {
2021 if (mName == null) {
2022 // Duplicate finish call. Ignore.
2023 return;
2024 }
2025
2026 // Remove ourselves from the active list.
2027 if (mPrev != null) {
2028 mPrev.mNext = mNext;
2029 }
2030 if (mNext != null) {
2031 mNext.mPrev = mPrev;
2032 }
2033 if (state.mActiveHead == this) {
2034 state.mActiveHead = mNext;
2035 }
2036
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002037 state.mActiveSize--;
2038
2039 if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
2040
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002041 this.mCreateMillis = -1;
2042 this.mName = null;
2043 this.mPrev = null;
2044 this.mNext = null;
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002045
2046 // Add ourselves to the freeList, if it's not already
2047 // too big.
2048 if (state.mFreeListSize < 5) {
2049 this.mNext = state.mFreeListHead;
2050 state.mFreeListHead = this;
2051 state.mFreeListSize++;
2052 }
2053 }
2054 }
2055 }
2056
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002057 // The no-op span that's used in user builds.
2058 private static final Span NO_OP_SPAN = new Span() {
2059 public void finish() {
2060 // Do nothing.
2061 }
2062 };
2063
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002064 /**
2065 * Linked lists of active spans and a freelist.
2066 *
2067 * Locking notes: there's one of these structures per thread and
2068 * all members of this structure (as well as the Span nodes under
2069 * it) are guarded by the ThreadSpanState object instance. While
2070 * in theory there'd be no locking required because it's all local
2071 * per-thread, the finish() method above is defensive against
2072 * people calling it on a different thread from where they created
2073 * the Span, hence the locking.
2074 */
2075 private static class ThreadSpanState {
2076 public Span mActiveHead; // doubly-linked list.
2077 public int mActiveSize;
2078 public Span mFreeListHead; // singly-linked list. only changes at head.
2079 public int mFreeListSize;
2080 }
2081
2082 private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
2083 new ThreadLocal<ThreadSpanState>() {
2084 @Override protected ThreadSpanState initialValue() {
2085 return new ThreadSpanState();
2086 }
2087 };
2088
Brad Fitzpatrickcdcb73e2010-11-22 22:56:23 -08002089 private static Singleton<IWindowManager> sWindowManager = new Singleton<IWindowManager>() {
2090 protected IWindowManager create() {
2091 return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
2092 }
2093 };
2094
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002095 /**
2096 * Enter a named critical span (e.g. an animation)
2097 *
2098 * <p>The name is an arbitary label (or tag) that will be applied
2099 * to any strictmode violation that happens while this span is
2100 * active. You must call finish() on the span when done.
2101 *
2102 * <p>This will never return null, but on devices without debugging
2103 * enabled, this may return a dummy object on which the finish()
2104 * method is a no-op.
2105 *
2106 * <p>TODO: add CloseGuard to this, verifying callers call finish.
2107 *
2108 * @hide
2109 */
2110 public static Span enterCriticalSpan(String name) {
Brad Fitzpatrick1181cbb2010-11-16 12:46:16 -08002111 if (IS_USER_BUILD) {
2112 return NO_OP_SPAN;
2113 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002114 if (name == null || name.isEmpty()) {
2115 throw new IllegalArgumentException("name must be non-null and non-empty");
2116 }
2117 ThreadSpanState state = sThisThreadSpanState.get();
2118 Span span = null;
2119 synchronized (state) {
2120 if (state.mFreeListHead != null) {
2121 span = state.mFreeListHead;
2122 state.mFreeListHead = span.mNext;
2123 state.mFreeListSize--;
2124 } else {
2125 // Shouldn't have to do this often.
2126 span = new Span(state);
2127 }
2128 span.mName = name;
2129 span.mCreateMillis = SystemClock.uptimeMillis();
2130 span.mNext = state.mActiveHead;
2131 span.mPrev = null;
2132 state.mActiveHead = span;
2133 state.mActiveSize++;
2134 if (span.mNext != null) {
2135 span.mNext.mPrev = span;
2136 }
Brad Fitzpatrick1cc13b62010-11-16 15:35:58 -08002137 if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002138 }
2139 return span;
2140 }
2141
Brad Fitzpatricke36f9bf2010-12-10 13:29:17 -08002142 /**
2143 * For code to note that it's slow. This is a no-op unless the
2144 * current thread's {@link android.os.StrictMode.ThreadPolicy} has
2145 * {@link android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls}
2146 * enabled.
2147 *
2148 * @param name a short string for the exception stack trace that's
2149 * built if when this fires.
2150 */
2151 public static void noteSlowCall(String name) {
2152 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2153 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2154 // StrictMode not enabled.
2155 return;
2156 }
2157 ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
2158 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002159
2160 /**
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002161 * For code to note that a resource was obtained using a type other than
2162 * its defined type. This is a no-op unless the current thread's
2163 * {@link android.os.StrictMode.ThreadPolicy} has
2164 * {@link android.os.StrictMode.ThreadPolicy.Builder#detectResourceMismatches()}
2165 * enabled.
2166 *
2167 * @param tag an object for the exception stack trace that's
2168 * built if when this fires.
2169 * @hide
2170 */
2171 public static void noteResourceMismatch(Object tag) {
2172 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2173 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2174 // StrictMode not enabled.
2175 return;
2176 }
2177 ((AndroidBlockGuardPolicy) policy).onResourceMismatch(tag);
2178 }
2179
2180 /**
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002181 * @hide
2182 */
2183 public static void noteDiskRead() {
2184 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002185 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2186 // StrictMode not enabled.
2187 return;
2188 }
2189 ((AndroidBlockGuardPolicy) policy).onReadFromDisk();
2190 }
2191
2192 /**
2193 * @hide
2194 */
2195 public static void noteDiskWrite() {
2196 BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
2197 if (!(policy instanceof AndroidBlockGuardPolicy)) {
2198 // StrictMode not enabled.
2199 return;
2200 }
2201 ((AndroidBlockGuardPolicy) policy).onWriteToDisk();
2202 }
2203
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002204 // Guarded by StrictMode.class
2205 private static final HashMap<Class, Integer> sExpectedActivityInstanceCount =
2206 new HashMap<Class, Integer>();
2207
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -08002208 /**
Jeff Brown7e442832011-06-10 18:00:16 -07002209 * Returns an object that is used to track instances of activites.
2210 * The activity should store a reference to the tracker object in one of its fields.
2211 * @hide
2212 */
2213 public static Object trackActivity(Object instance) {
2214 return new InstanceTracker(instance);
2215 }
2216
2217 /**
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002218 * @hide
2219 */
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002220 public static void incrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002221 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002222 return;
2223 }
Jeff Brown7e442832011-06-10 18:00:16 -07002224
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002225 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002226 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2227 return;
2228 }
2229
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002230 Integer expected = sExpectedActivityInstanceCount.get(klass);
2231 Integer newExpected = expected == null ? 1 : expected + 1;
2232 sExpectedActivityInstanceCount.put(klass, newExpected);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002233 }
2234 }
2235
2236 /**
2237 * @hide
2238 */
2239 public static void decrementExpectedActivityCount(Class klass) {
Jeff Brown7e442832011-06-10 18:00:16 -07002240 if (klass == null) {
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002241 return;
2242 }
Jeff Brown7e442832011-06-10 18:00:16 -07002243
2244 final int limit;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002245 synchronized (StrictMode.class) {
Jeff Brown7e442832011-06-10 18:00:16 -07002246 if ((sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
2247 return;
2248 }
2249
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002250 Integer expected = sExpectedActivityInstanceCount.get(klass);
Jeff Brown7e442832011-06-10 18:00:16 -07002251 int newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002252 if (newExpected == 0) {
2253 sExpectedActivityInstanceCount.remove(klass);
2254 } else {
2255 sExpectedActivityInstanceCount.put(klass, newExpected);
2256 }
Jeff Brown7e442832011-06-10 18:00:16 -07002257
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002258 // Note: adding 1 here to give some breathing room during
2259 // orientation changes. (shouldn't be necessary, though?)
Jeff Brown7e442832011-06-10 18:00:16 -07002260 limit = newExpected + 1;
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002261 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002262
Jeff Brown7e442832011-06-10 18:00:16 -07002263 // Quick check.
2264 int actual = InstanceTracker.getInstanceCount(klass);
2265 if (actual <= limit) {
2266 return;
2267 }
2268
2269 // Do a GC and explicit count to double-check.
2270 // This is the work that we are trying to avoid by tracking the object instances
2271 // explicity. Running an explicit GC can be expensive (80ms) and so can walking
2272 // the heap to count instance (30ms). This extra work can make the system feel
2273 // noticeably less responsive during orientation changes when activities are
2274 // being restarted. Granted, it is only a problem when StrictMode is enabled
2275 // but it is annoying.
Jeff Sharkey6f3a38f2014-01-16 12:46:37 -08002276
2277 System.gc();
2278 System.runFinalization();
2279 System.gc();
Jeff Brown7e442832011-06-10 18:00:16 -07002280
2281 long instances = VMDebug.countInstancesOfClass(klass, false);
2282 if (instances > limit) {
2283 Throwable tr = new InstanceCountViolation(klass, instances, limit);
2284 onVmPolicyViolation(tr.getMessage(), tr);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002285 }
Brad Fitzpatrick75803572011-01-13 14:21:03 -08002286 }
2287
2288 /**
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002289 * Parcelable that gets sent in Binder call headers back to callers
2290 * to report violations that happened during a cross-process call.
2291 *
2292 * @hide
2293 */
2294 public static class ViolationInfo {
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002295 public final String message;
Jeff Sharkey605eb792014-11-04 13:34:06 -08002296
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002297 /**
2298 * Stack and other stuff info.
2299 */
2300 public final ApplicationErrorReport.CrashInfo crashInfo;
2301
2302 /**
2303 * The strict mode policy mask at the time of violation.
2304 */
2305 public final int policy;
2306
2307 /**
2308 * The wall time duration of the violation, when known. -1 when
2309 * not known.
2310 */
2311 public int durationMillis = -1;
2312
2313 /**
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002314 * The number of animations currently running.
2315 */
2316 public int numAnimationsRunning = 0;
2317
2318 /**
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002319 * List of tags from active Span instances during this
2320 * violation, or null for none.
2321 */
2322 public String[] tags;
2323
2324 /**
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002325 * Which violation number this was (1-based) since the last Looper loop,
2326 * from the perspective of the root caller (if it crossed any processes
2327 * via Binder calls). The value is 0 if the root caller wasn't on a Looper
2328 * thread.
2329 */
2330 public int violationNumThisLoop;
2331
2332 /**
2333 * The time (in terms of SystemClock.uptimeMillis()) that the
2334 * violation occurred.
2335 */
2336 public long violationUptimeMillis;
2337
2338 /**
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002339 * The action of the Intent being broadcast to somebody's onReceive
2340 * on this thread right now, or null.
2341 */
2342 public String broadcastIntentAction;
2343
2344 /**
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002345 * If this is a instance count violation, the number of instances in memory,
2346 * else -1.
2347 */
2348 public long numInstances = -1;
2349
2350 /**
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002351 * Create an uninitialized instance of ViolationInfo
2352 */
2353 public ViolationInfo() {
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002354 message = null;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002355 crashInfo = null;
2356 policy = 0;
2357 }
2358
Jeff Sharkey605eb792014-11-04 13:34:06 -08002359 public ViolationInfo(Throwable tr, int policy) {
2360 this(null, tr, policy);
2361 }
2362
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002363 /**
2364 * Create an instance of ViolationInfo initialized from an exception.
2365 */
Jeff Sharkey605eb792014-11-04 13:34:06 -08002366 public ViolationInfo(String message, Throwable tr, int policy) {
2367 this.message = message;
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002368 crashInfo = new ApplicationErrorReport.CrashInfo(tr);
2369 violationUptimeMillis = SystemClock.uptimeMillis();
2370 this.policy = policy;
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002371 this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002372 Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
2373 if (broadcastIntent != null) {
2374 broadcastIntentAction = broadcastIntent.getAction();
2375 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002376 ThreadSpanState state = sThisThreadSpanState.get();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002377 if (tr instanceof InstanceCountViolation) {
2378 this.numInstances = ((InstanceCountViolation) tr).mInstances;
2379 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002380 synchronized (state) {
2381 int spanActiveCount = state.mActiveSize;
2382 if (spanActiveCount > MAX_SPAN_TAGS) {
2383 spanActiveCount = MAX_SPAN_TAGS;
2384 }
2385 if (spanActiveCount != 0) {
2386 this.tags = new String[spanActiveCount];
2387 Span iter = state.mActiveHead;
2388 int index = 0;
2389 while (iter != null && index < spanActiveCount) {
2390 this.tags[index] = iter.mName;
2391 index++;
2392 iter = iter.mNext;
2393 }
2394 }
2395 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002396 }
2397
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002398 @Override
2399 public int hashCode() {
2400 int result = 17;
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002401 if (crashInfo != null) {
2402 result = 37 * result + crashInfo.stackTrace.hashCode();
2403 }
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08002404 if (numAnimationsRunning != 0) {
2405 result *= 37;
2406 }
2407 if (broadcastIntentAction != null) {
2408 result = 37 * result + broadcastIntentAction.hashCode();
2409 }
2410 if (tags != null) {
2411 for (String tag : tags) {
2412 result = 37 * result + tag.hashCode();
2413 }
2414 }
2415 return result;
2416 }
2417
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002418 /**
2419 * Create an instance of ViolationInfo initialized from a Parcel.
2420 */
2421 public ViolationInfo(Parcel in) {
2422 this(in, false);
2423 }
2424
2425 /**
2426 * Create an instance of ViolationInfo initialized from a Parcel.
2427 *
2428 * @param unsetGatheringBit if true, the caller is the root caller
2429 * and the gathering penalty should be removed.
2430 */
2431 public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
Jeff Sharkey605eb792014-11-04 13:34:06 -08002432 message = in.readString();
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002433 if (in.readInt() != 0) {
2434 crashInfo = new ApplicationErrorReport.CrashInfo(in);
2435 } else {
2436 crashInfo = null;
2437 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002438 int rawPolicy = in.readInt();
2439 if (unsetGatheringBit) {
2440 policy = rawPolicy & ~PENALTY_GATHER;
2441 } else {
2442 policy = rawPolicy;
2443 }
2444 durationMillis = in.readInt();
2445 violationNumThisLoop = in.readInt();
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002446 numAnimationsRunning = in.readInt();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002447 violationUptimeMillis = in.readLong();
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002448 numInstances = in.readLong();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002449 broadcastIntentAction = in.readString();
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002450 tags = in.readStringArray();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002451 }
2452
2453 /**
2454 * Save a ViolationInfo instance to a parcel.
2455 */
2456 public void writeToParcel(Parcel dest, int flags) {
Jeff Sharkey605eb792014-11-04 13:34:06 -08002457 dest.writeString(message);
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002458 if (crashInfo != null) {
2459 dest.writeInt(1);
2460 crashInfo.writeToParcel(dest, flags);
2461 } else {
2462 dest.writeInt(0);
2463 }
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002464 int start = dest.dataPosition();
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002465 dest.writeInt(policy);
2466 dest.writeInt(durationMillis);
2467 dest.writeInt(violationNumThisLoop);
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002468 dest.writeInt(numAnimationsRunning);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002469 dest.writeLong(violationUptimeMillis);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002470 dest.writeLong(numInstances);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002471 dest.writeString(broadcastIntentAction);
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002472 dest.writeStringArray(tags);
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002473 int total = dest.dataPosition()-start;
Dianne Hackbornce92b0d2014-09-30 11:28:18 -07002474 if (total > 10*1024) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -07002475 Slog.d(TAG, "VIO: policy=" + policy + " dur=" + durationMillis
2476 + " numLoop=" + violationNumThisLoop
2477 + " anim=" + numAnimationsRunning
2478 + " uptime=" + violationUptimeMillis
2479 + " numInst=" + numInstances);
2480 Slog.d(TAG, "VIO: action=" + broadcastIntentAction);
2481 Slog.d(TAG, "VIO: tags=" + Arrays.toString(tags));
2482 Slog.d(TAG, "VIO: TOTAL BYTES WRITTEN: " + (dest.dataPosition()-start));
2483 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002484 }
2485
2486
2487 /**
2488 * Dump a ViolationInfo instance to a Printer.
2489 */
2490 public void dump(Printer pw, String prefix) {
Jeff Sharkey20db11c2016-12-06 16:47:00 -07002491 if (crashInfo != null) {
2492 crashInfo.dump(pw, prefix);
2493 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002494 pw.println(prefix + "policy: " + policy);
2495 if (durationMillis != -1) {
2496 pw.println(prefix + "durationMillis: " + durationMillis);
2497 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002498 if (numInstances != -1) {
2499 pw.println(prefix + "numInstances: " + numInstances);
2500 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002501 if (violationNumThisLoop != 0) {
2502 pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
2503 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07002504 if (numAnimationsRunning != 0) {
2505 pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
2506 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002507 pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002508 if (broadcastIntentAction != null) {
2509 pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
2510 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08002511 if (tags != null) {
2512 int index = 0;
2513 for (String tag : tags) {
2514 pw.println(prefix + "tag[" + (index++) + "]: " + tag);
2515 }
2516 }
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07002517 }
2518
2519 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002520
2521 // Dummy throwable, for now, since we don't know when or where the
2522 // leaked instances came from. We might in the future, but for
2523 // now we suppress the stack trace because it's useless and/or
2524 // misleading.
2525 private static class InstanceCountViolation extends Throwable {
2526 final Class mClass;
2527 final long mInstances;
2528 final int mLimit;
2529
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002530 private static final StackTraceElement[] FAKE_STACK = {
2531 new StackTraceElement("android.os.StrictMode", "setClassInstanceLimit",
2532 "StrictMode.java", 1)
2533 };
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002534
2535 public InstanceCountViolation(Class klass, long instances, int limit) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002536 super(klass.toString() + "; instances=" + instances + "; limit=" + limit);
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08002537 setStackTrace(FAKE_STACK);
2538 mClass = klass;
2539 mInstances = instances;
2540 mLimit = limit;
2541 }
2542 }
Jeff Brown7e442832011-06-10 18:00:16 -07002543
2544 private static final class InstanceTracker {
2545 private static final HashMap<Class<?>, Integer> sInstanceCounts =
2546 new HashMap<Class<?>, Integer>();
2547
2548 private final Class<?> mKlass;
2549
2550 public InstanceTracker(Object instance) {
2551 mKlass = instance.getClass();
2552
2553 synchronized (sInstanceCounts) {
2554 final Integer value = sInstanceCounts.get(mKlass);
2555 final int newValue = value != null ? value + 1 : 1;
2556 sInstanceCounts.put(mKlass, newValue);
2557 }
2558 }
2559
2560 @Override
2561 protected void finalize() throws Throwable {
2562 try {
2563 synchronized (sInstanceCounts) {
2564 final Integer value = sInstanceCounts.get(mKlass);
2565 if (value != null) {
2566 final int newValue = value - 1;
2567 if (newValue > 0) {
2568 sInstanceCounts.put(mKlass, newValue);
2569 } else {
2570 sInstanceCounts.remove(mKlass);
2571 }
2572 }
2573 }
2574 } finally {
2575 super.finalize();
2576 }
2577 }
2578
2579 public static int getInstanceCount(Class<?> klass) {
2580 synchronized (sInstanceCounts) {
2581 final Integer value = sInstanceCounts.get(klass);
2582 return value != null ? value : 0;
2583 }
2584 }
2585 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07002586}