StrictMode.java revision 4b9b7c38e8f52259f9d2f960072d35e8a1ab2129
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.os;
17
18import android.animation.ValueAnimator;
19import android.app.ActivityManagerNative;
20import android.app.ActivityThread;
21import android.app.ApplicationErrorReport;
22import android.content.Intent;
23import android.util.Log;
24import android.util.Printer;
25
26import com.android.internal.os.RuntimeInit;
27
28import dalvik.system.BlockGuard;
29import dalvik.system.CloseGuard;
30
31import java.io.PrintWriter;
32import java.io.StringWriter;
33import java.util.ArrayList;
34import java.util.HashMap;
35
36/**
37 * <p>StrictMode is a developer tool which detects things you might be
38 * doing by accident and brings them to your attention so you can fix
39 * them.
40 *
41 * <p>StrictMode is most commonly used to catch accidental disk or
42 * network access on the application's main thread, where UI
43 * operations are received and animations take place.  Keeping disk
44 * and network operations off the main thread makes for much smoother,
45 * more responsive applications.  By keeping your application's main thread
46 * responsive, you also prevent
47 * <a href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a>
48 * from being shown to users.
49 *
50 * <p class="note">Note that even though an Android device's disk is
51 * often on flash memory, many devices run a filesystem on top of that
52 * memory with very limited concurrency.  It's often the case that
53 * almost all disk accesses are fast, but may in individual cases be
54 * dramatically slower when certain I/O is happening in the background
55 * from other processes.  If possible, it's best to assume that such
56 * things are not fast.</p>
57 *
58 * <p>Example code to enable from early in your
59 * {@link android.app.Application}, {@link android.app.Activity}, or
60 * other application component's
61 * {@link android.app.Application#onCreate} method:
62 *
63 * <pre>
64 * public void onCreate() {
65 *     if (DEVELOPER_MODE) {
66 *         StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
67 *                 .detectDiskReads()
68 *                 .detectDiskWrites()
69 *                 .detectNetwork()   // or .detectAll() for all detectable problems
70 *                 .penaltyLog()
71 *                 .build());
72 *         StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
73 *                 .detectLeakedSqlLiteObjects()
74 *                 .detectLeakedClosableObjects()
75 *                 .penaltyLog()
76 *                 .penaltyDeath()
77 *                 .build());
78 *     }
79 *     super.onCreate();
80 * }
81 * </pre>
82 *
83 * <p>You can decide what should happen when a violation is detected.
84 * For example, using {@link ThreadPolicy.Builder#penaltyLog} you can
85 * watch the output of <code>adb logcat</code> while you use your
86 * application to see the violations as they happen.
87 *
88 * <p>If you find violations that you feel are problematic, there are
89 * a variety of tools to help solve them: threads, {@link android.os.Handler},
90 * {@link android.os.AsyncTask}, {@link android.app.IntentService}, etc.
91 * But don't feel compelled to fix everything that StrictMode finds.  In particular,
92 * many cases of disk access are often necessary during the normal activity lifecycle.  Use
93 * StrictMode to find things you did by accident.  Network requests on the UI thread
94 * are almost always a problem, though.
95 *
96 * <p class="note">StrictMode is not a security mechanism and is not
97 * guaranteed to find all disk or network accesses.  While it does
98 * propagate its state across process boundaries when doing
99 * {@link android.os.Binder} calls, it's still ultimately a best
100 * effort mechanism.  Notably, disk or network access from JNI calls
101 * won't necessarily trigger it.  Future versions of Android may catch
102 * more (or fewer) operations, so you should never leave StrictMode
103 * enabled in shipping applications on the Android Market.
104 */
105public final class StrictMode {
106    private static final String TAG = "StrictMode";
107    private static final boolean LOG_V = false;
108
109    // Only log a duplicate stack trace to the logs every second.
110    private static final long MIN_LOG_INTERVAL_MS = 1000;
111
112    // Only show an annoying dialog at most every 30 seconds
113    private static final long MIN_DIALOG_INTERVAL_MS = 30000;
114
115    // How many offending stacks to keep track of (and time) per loop
116    // of the Looper.
117    private static final int MAX_OFFENSES_PER_LOOP = 10;
118
119    // Thread-policy:
120
121    /**
122     * @hide
123     */
124    public static final int DETECT_DISK_WRITE = 0x01;  // for ThreadPolicy
125
126    /**
127      * @hide
128     */
129    public static final int DETECT_DISK_READ = 0x02;  // for ThreadPolicy
130
131    /**
132     * @hide
133     */
134    public static final int DETECT_NETWORK = 0x04;  // for ThreadPolicy
135
136    // Process-policy:
137
138    /**
139     * Note, a "VM_" bit, not thread.
140     * @hide
141     */
142    public static final int DETECT_VM_CURSOR_LEAKS = 0x200;  // for ProcessPolicy
143
144    /**
145     * Note, a "VM_" bit, not thread.
146     * @hide
147     */
148    public static final int DETECT_VM_CLOSABLE_LEAKS = 0x400;  // for ProcessPolicy
149
150    /**
151     * @hide
152     */
153    public static final int PENALTY_LOG = 0x10;  // normal android.util.Log
154
155    // Used for both process and thread policy:
156
157    /**
158     * @hide
159     */
160    public static final int PENALTY_DIALOG = 0x20;
161
162    /**
163     * Death on any detected violation.
164     *
165     * @hide
166     */
167    public static final int PENALTY_DEATH = 0x40;
168
169    /**
170     * Death just for detected network usage.
171     *
172     * @hide
173     */
174    public static final int PENALTY_DEATH_ON_NETWORK = 0x200;
175
176    /**
177     * @hide
178     */
179    public static final int PENALTY_DROPBOX = 0x80;
180
181    /**
182     * Non-public penalty mode which overrides all the other penalty
183     * bits and signals that we're in a Binder call and we should
184     * ignore the other penalty bits and instead serialize back all
185     * our offending stack traces to the caller to ultimately handle
186     * in the originating process.
187     *
188     * This must be kept in sync with the constant in libs/binder/Parcel.cpp
189     *
190     * @hide
191     */
192    public static final int PENALTY_GATHER = 0x100;
193
194    /**
195     * Mask of all the penalty bits.
196     */
197    private static final int PENALTY_MASK =
198            PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER |
199            PENALTY_DEATH_ON_NETWORK;
200
201    /**
202     * The current VmPolicy in effect.
203     */
204    private static volatile int sVmPolicyMask = 0;
205
206    private StrictMode() {}
207
208    /**
209     * {@link StrictMode} policy applied to a certain thread.
210     *
211     * <p>The policy is enabled by {@link #setThreadPolicy}.  The current policy
212     * can be retrieved with {@link #getThreadPolicy}.
213     *
214     * <p>Note that multiple penalties may be provided and they're run
215     * in order from least to most severe (logging before process
216     * death, for example).  There's currently no mechanism to choose
217     * different penalties for different detected actions.
218     */
219    public static final class ThreadPolicy {
220        /**
221         * The default, lax policy which doesn't catch anything.
222         */
223        public static final ThreadPolicy LAX = new ThreadPolicy(0);
224
225        final int mask;
226
227        private ThreadPolicy(int mask) {
228            this.mask = mask;
229        }
230
231        @Override
232        public String toString() {
233            return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
234        }
235
236        /**
237         * Creates ThreadPolicy instances.  Methods whose names start
238         * with {@code detect} specify what problems we should look
239         * for.  Methods whose names start with {@code penalty} specify what
240         * we should do when we detect a problem.
241         *
242         * <p>You can call as many {@code detect} and {@code penalty}
243         * methods as you like. Currently order is insignificant: all
244         * penalties apply to all detected problems.
245         *
246         * <p>For example, detect everything and log anything that's found:
247         * <pre>
248         * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
249         *     .detectAll()
250         *     .penaltyLog()
251         *     .build();
252         * StrictMode.setVmPolicy(policy);
253         * </pre>
254         */
255        public static final class Builder {
256            private int mMask = 0;
257
258            /**
259             * Create a Builder that detects nothing and has no
260             * violations.  (but note that {@link #build} will default
261             * to enabling {@link #penaltyLog} if no other penalties
262             * are specified)
263             */
264            public Builder() {
265                mMask = 0;
266            }
267
268            /**
269             * Initialize a Builder from an existing ThreadPolicy.
270             */
271            public Builder(ThreadPolicy policy) {
272                mMask = policy.mask;
273            }
274
275            /**
276             * Detect everything that's potentially suspect.
277             *
278             * <p>As of the Gingerbread release this includes network and
279             * disk operations but will likely expand in future releases.
280             */
281            public Builder detectAll() {
282                return enable(DETECT_DISK_WRITE | DETECT_DISK_READ | DETECT_NETWORK);
283            }
284
285            /**
286             * Disable the detection of everything.
287             */
288            public Builder permitAll() {
289                return disable(DETECT_DISK_WRITE | DETECT_DISK_READ | DETECT_NETWORK);
290            }
291
292            /**
293             * Enable detection of network operations.
294             */
295            public Builder detectNetwork() {
296                return enable(DETECT_NETWORK);
297            }
298
299            /**
300             * Disable detection of network operations.
301             */
302            public Builder permitNetwork() {
303                return disable(DETECT_NETWORK);
304            }
305
306            /**
307             * Enable detection of disk reads.
308             */
309            public Builder detectDiskReads() {
310                return enable(DETECT_DISK_READ);
311            }
312
313            /**
314             * Disable detection of disk reads.
315             */
316            public Builder permitDiskReads() {
317                return disable(DETECT_DISK_READ);
318            }
319
320            /**
321             * Enable detection of disk writes.
322             */
323            public Builder detectDiskWrites() {
324                return enable(DETECT_DISK_WRITE);
325            }
326
327            /**
328             * Disable detection of disk writes.
329             */
330            public Builder permitDiskWrites() {
331                return disable(DETECT_DISK_WRITE);
332            }
333
334            /**
335             * Show an annoying dialog to the developer on detected
336             * violations, rate-limited to be only a little annoying.
337             */
338            public Builder penaltyDialog() {
339                return enable(PENALTY_DIALOG);
340            }
341
342            /**
343             * Crash the whole process on violation.  This penalty runs at
344             * the end of all enabled penalties so you'll still get
345             * see logging or other violations before the process dies.
346             *
347             * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies
348             * to disk reads, disk writes, and network usage if their
349             * corresponding detect flags are set.
350             */
351            public Builder penaltyDeath() {
352                return enable(PENALTY_DEATH);
353            }
354
355            /**
356             * Crash the whole process on any network usage.  Unlike
357             * {@link #penaltyDeath}, this penalty runs
358             * <em>before</em> anything else.  You must still have
359             * called {@link #detectNetwork} to enable this.
360             *
361             * <p>In the Honeycomb or later SDKs, this is on by default.
362             */
363            public Builder penaltyDeathOnNetwork() {
364                return enable(PENALTY_DEATH_ON_NETWORK);
365            }
366
367            /**
368             * Log detected violations to the system log.
369             */
370            public Builder penaltyLog() {
371                return enable(PENALTY_LOG);
372            }
373
374            /**
375             * Enable detected violations log a stacktrace and timing data
376             * to the {@link android.os.DropBoxManager DropBox} on policy
377             * violation.  Intended mostly for platform integrators doing
378             * beta user field data collection.
379             */
380            public Builder penaltyDropBox() {
381                return enable(PENALTY_DROPBOX);
382            }
383
384            private Builder enable(int bit) {
385                mMask |= bit;
386                return this;
387            }
388
389            private Builder disable(int bit) {
390                mMask &= ~bit;
391                return this;
392            }
393
394            /**
395             * Construct the ThreadPolicy instance.
396             *
397             * <p>Note: if no penalties are enabled before calling
398             * <code>build</code>, {@link #penaltyLog} is implicitly
399             * set.
400             */
401            public ThreadPolicy build() {
402                // If there are detection bits set but no violation bits
403                // set, enable simple logging.
404                if (mMask != 0 &&
405                    (mMask & (PENALTY_DEATH | PENALTY_LOG |
406                              PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
407                    penaltyLog();
408                }
409                return new ThreadPolicy(mMask);
410            }
411        }
412    }
413
414    /**
415     * {@link StrictMode} policy applied to all threads in the virtual machine's process.
416     *
417     * <p>The policy is enabled by {@link #setVmPolicy}.
418     */
419    public static final class VmPolicy {
420        /**
421         * The default, lax policy which doesn't catch anything.
422         */
423        public static final VmPolicy LAX = new VmPolicy(0);
424
425        final int mask;
426
427        private VmPolicy(int mask) {
428            this.mask = mask;
429        }
430
431        @Override
432        public String toString() {
433            return "[StrictMode.VmPolicy; mask=" + mask + "]";
434        }
435
436        /**
437         * Creates {@link VmPolicy} instances.  Methods whose names start
438         * with {@code detect} specify what problems we should look
439         * for.  Methods whose names start with {@code penalty} specify what
440         * we should do when we detect a problem.
441         *
442         * <p>You can call as many {@code detect} and {@code penalty}
443         * methods as you like. Currently order is insignificant: all
444         * penalties apply to all detected problems.
445         *
446         * <p>For example, detect everything and log anything that's found:
447         * <pre>
448         * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
449         *     .detectAll()
450         *     .penaltyLog()
451         *     .build();
452         * StrictMode.setVmPolicy(policy);
453         * </pre>
454         */
455        public static final class Builder {
456            private int mMask;
457
458            /**
459             * Detect everything that's potentially suspect.
460             *
461             * <p>In the Honeycomb release this includes leaks of
462             * SQLite cursors and other closable objects but will
463             * likely expand in future releases.
464             */
465            public Builder detectAll() {
466                return enable(DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS);
467            }
468
469            /**
470             * Detect when an
471             * {@link android.database.sqlite.SQLiteCursor} or other
472             * SQLite object is finalized without having been closed.
473             *
474             * <p>You always want to explicitly close your SQLite
475             * cursors to avoid unnecessary database contention and
476             * temporary memory leaks.
477             */
478            public Builder detectLeakedSqlLiteObjects() {
479                return enable(DETECT_VM_CURSOR_LEAKS);
480            }
481
482            /**
483             * Detect when an {@link java.io.Closeable} or other
484             * object with a explict termination method is finalized
485             * without having been closed.
486             *
487             * <p>You always want to explicitly close such objects to
488             * avoid unnecessary resources leaks.
489             */
490            public Builder detectLeakedClosableObjects() {
491                return enable(DETECT_VM_CLOSABLE_LEAKS);
492            }
493
494            /**
495             * Crashes the whole process on violation.  This penalty runs at
496             * the end of all enabled penalties so yo you'll still get
497             * your logging or other violations before the process dies.
498             */
499            public Builder penaltyDeath() {
500                return enable(PENALTY_DEATH);
501            }
502
503            /**
504             * Log detected violations to the system log.
505             */
506            public Builder penaltyLog() {
507                return enable(PENALTY_LOG);
508            }
509
510            /**
511             * Enable detected violations log a stacktrace and timing data
512             * to the {@link android.os.DropBoxManager DropBox} on policy
513             * violation.  Intended mostly for platform integrators doing
514             * beta user field data collection.
515             */
516            public Builder penaltyDropBox() {
517                return enable(PENALTY_DROPBOX);
518            }
519
520            private Builder enable(int bit) {
521                mMask |= bit;
522                return this;
523            }
524
525            /**
526             * Construct the VmPolicy instance.
527             *
528             * <p>Note: if no penalties are enabled before calling
529             * <code>build</code>, {@link #penaltyLog} is implicitly
530             * set.
531             */
532            public VmPolicy build() {
533                // If there are detection bits set but no violation bits
534                // set, enable simple logging.
535                if (mMask != 0 &&
536                    (mMask & (PENALTY_DEATH | PENALTY_LOG |
537                              PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
538                    penaltyLog();
539                }
540                return new VmPolicy(mMask);
541            }
542        }
543    }
544
545    /**
546     * Log of strict mode violation stack traces that have occurred
547     * during a Binder call, to be serialized back later to the caller
548     * via Parcel.writeNoException() (amusingly) where the caller can
549     * choose how to react.
550     */
551    private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
552            new ThreadLocal<ArrayList<ViolationInfo>>() {
553        @Override protected ArrayList<ViolationInfo> initialValue() {
554            // Starts null to avoid unnecessary allocations when
555            // checking whether there are any violations or not in
556            // hasGatheredViolations() below.
557            return null;
558        }
559    };
560
561    /**
562     * Sets the policy for what actions on the current thread should
563     * be detected, as well as the penalty if such actions occur.
564     *
565     * <p>Internally this sets a thread-local variable which is
566     * propagated across cross-process IPC calls, meaning you can
567     * catch violations when a system service or another process
568     * accesses the disk or network on your behalf.
569     *
570     * @param policy the policy to put into place
571     */
572    public static void setThreadPolicy(final ThreadPolicy policy) {
573        setThreadPolicyMask(policy.mask);
574    }
575
576    private static void setThreadPolicyMask(final int policyMask) {
577        // In addition to the Java-level thread-local in Dalvik's
578        // BlockGuard, we also need to keep a native thread-local in
579        // Binder in order to propagate the value across Binder calls,
580        // even across native-only processes.  The two are kept in
581        // sync via the callback to onStrictModePolicyChange, below.
582        setBlockGuardPolicy(policyMask);
583
584        // And set the Android native version...
585        Binder.setThreadStrictModePolicy(policyMask);
586    }
587
588    // Sets the policy in Dalvik/libcore (BlockGuard)
589    private static void setBlockGuardPolicy(final int policyMask) {
590        if (policyMask == 0) {
591            BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
592            return;
593        }
594        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
595        if (!(policy instanceof AndroidBlockGuardPolicy)) {
596            BlockGuard.setThreadPolicy(new AndroidBlockGuardPolicy(policyMask));
597        } else {
598            AndroidBlockGuardPolicy androidPolicy = (AndroidBlockGuardPolicy) policy;
599            androidPolicy.setPolicyMask(policyMask);
600        }
601    }
602
603    // Sets up CloseGuard in Dalvik/libcore
604    private static void setCloseGuardEnabled(boolean enabled) {
605        if (!(CloseGuard.getReporter() instanceof AndroidBlockGuardPolicy)) {
606            CloseGuard.setReporter(new AndroidCloseGuardReporter());
607        }
608        CloseGuard.setEnabled(enabled);
609    }
610
611    private static class StrictModeNetworkViolation extends BlockGuard.BlockGuardPolicyException {
612        public StrictModeNetworkViolation(int policyMask) {
613            super(policyMask, DETECT_NETWORK);
614        }
615    }
616
617    private static class StrictModeDiskReadViolation extends BlockGuard.BlockGuardPolicyException {
618        public StrictModeDiskReadViolation(int policyMask) {
619            super(policyMask, DETECT_DISK_READ);
620        }
621    }
622
623    private static class StrictModeDiskWriteViolation extends BlockGuard.BlockGuardPolicyException {
624        public StrictModeDiskWriteViolation(int policyMask) {
625            super(policyMask, DETECT_DISK_WRITE);
626        }
627    }
628
629    /**
630     * Returns the bitmask of the current thread's policy.
631     *
632     * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
633     *
634     * @hide
635     */
636    public static int getThreadPolicyMask() {
637        return BlockGuard.getThreadPolicy().getPolicyMask();
638    }
639
640    /**
641     * Returns the current thread's policy.
642     */
643    public static ThreadPolicy getThreadPolicy() {
644        return new ThreadPolicy(getThreadPolicyMask());
645    }
646
647    /**
648     * A convenience wrapper that takes the current
649     * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
650     * to permit both disk reads &amp; writes, and sets the new policy
651     * with {@link #setThreadPolicy}, returning the old policy so you
652     * can restore it at the end of a block.
653     *
654     * @return the old policy, to be passed to {@link #setThreadPolicy} to
655     *         restore the policy at the end of a block
656     */
657    public static ThreadPolicy allowThreadDiskWrites() {
658        int oldPolicyMask = getThreadPolicyMask();
659        int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_WRITE | DETECT_DISK_READ);
660        if (newPolicyMask != oldPolicyMask) {
661            setThreadPolicyMask(newPolicyMask);
662        }
663        return new ThreadPolicy(oldPolicyMask);
664    }
665
666    /**
667     * A convenience wrapper that takes the current
668     * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
669     * to permit disk reads, and sets the new policy
670     * with {@link #setThreadPolicy}, returning the old policy so you
671     * can restore it at the end of a block.
672     *
673     * @return the old policy, to be passed to setThreadPolicy to
674     *         restore the policy.
675     */
676    public static ThreadPolicy allowThreadDiskReads() {
677        int oldPolicyMask = getThreadPolicyMask();
678        int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_READ);
679        if (newPolicyMask != oldPolicyMask) {
680            setThreadPolicyMask(newPolicyMask);
681        }
682        return new ThreadPolicy(oldPolicyMask);
683    }
684
685    /**
686     * Enable DropBox logging for debug phone builds.
687     *
688     * @hide
689     */
690    public static boolean conditionallyEnableDebugLogging() {
691        // For debug builds, log event loop stalls to dropbox for analysis.
692        // Similar logic also appears in ActivityThread.java for system apps.
693        if ("user".equals(Build.TYPE)) {
694            return false;
695        }
696        StrictMode.setThreadPolicyMask(
697            StrictMode.DETECT_DISK_WRITE |
698            StrictMode.DETECT_DISK_READ |
699            StrictMode.DETECT_NETWORK |
700            StrictMode.PENALTY_DROPBOX);
701        sVmPolicyMask = StrictMode.DETECT_VM_CURSOR_LEAKS |
702                StrictMode.DETECT_VM_CLOSABLE_LEAKS |
703                StrictMode.PENALTY_DROPBOX |
704                StrictMode.PENALTY_LOG;
705        return true;
706    }
707
708    /**
709     * Used by the framework to make network usage on the main
710     * thread a fatal error.
711     *
712     * @hide
713     */
714    public static void enableDeathOnNetwork() {
715        int oldPolicy = getThreadPolicyMask();
716        int newPolicy = oldPolicy | DETECT_NETWORK | PENALTY_DEATH_ON_NETWORK;
717        setThreadPolicyMask(newPolicy);
718    }
719
720    /**
721     * Parses the BlockGuard policy mask out from the Exception's
722     * getMessage() String value.  Kinda gross, but least
723     * invasive.  :/
724     *
725     * Input is of form "policy=137 violation=64"
726     *
727     * Returns 0 on failure, which is a valid policy, but not a
728     * valid policy during a violation (else there must've been
729     * some policy in effect to violate).
730     */
731    private static int parsePolicyFromMessage(String message) {
732        if (message == null || !message.startsWith("policy=")) {
733            return 0;
734        }
735        int spaceIndex = message.indexOf(' ');
736        if (spaceIndex == -1) {
737            return 0;
738        }
739        String policyString = message.substring(7, spaceIndex);
740        try {
741            return Integer.valueOf(policyString).intValue();
742        } catch (NumberFormatException e) {
743            return 0;
744        }
745    }
746
747    /**
748     * Like parsePolicyFromMessage(), but returns the violation.
749     */
750    private static int parseViolationFromMessage(String message) {
751        if (message == null) {
752            return 0;
753        }
754        int violationIndex = message.indexOf("violation=");
755        if (violationIndex == -1) {
756            return 0;
757        }
758        String violationString = message.substring(violationIndex + 10);
759        try {
760            return Integer.valueOf(violationString).intValue();
761        } catch (NumberFormatException e) {
762            return 0;
763        }
764    }
765
766    private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
767            new ThreadLocal<ArrayList<ViolationInfo>>() {
768        @Override protected ArrayList<ViolationInfo> initialValue() {
769            return new ArrayList<ViolationInfo>();
770        }
771    };
772
773    private static boolean tooManyViolationsThisLoop() {
774        return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
775    }
776
777    private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
778        private int mPolicyMask;
779
780        // Map from violation stacktrace hashcode -> uptimeMillis of
781        // last violation.  No locking needed, as this is only
782        // accessed by the same thread.
783        private final HashMap<Integer, Long> mLastViolationTime = new HashMap<Integer, Long>();
784
785        public AndroidBlockGuardPolicy(final int policyMask) {
786            mPolicyMask = policyMask;
787        }
788
789        @Override
790        public String toString() {
791            return "AndroidBlockGuardPolicy; mPolicyMask=" + mPolicyMask;
792        }
793
794        // Part of BlockGuard.Policy interface:
795        public int getPolicyMask() {
796            return mPolicyMask;
797        }
798
799        // Part of BlockGuard.Policy interface:
800        public void onWriteToDisk() {
801            if ((mPolicyMask & DETECT_DISK_WRITE) == 0) {
802                return;
803            }
804            if (tooManyViolationsThisLoop()) {
805                return;
806            }
807            BlockGuard.BlockGuardPolicyException e = new StrictModeDiskWriteViolation(mPolicyMask);
808            e.fillInStackTrace();
809            startHandlingViolationException(e);
810        }
811
812        // Part of BlockGuard.Policy interface:
813        public void onReadFromDisk() {
814            if ((mPolicyMask & DETECT_DISK_READ) == 0) {
815                return;
816            }
817            if (tooManyViolationsThisLoop()) {
818                return;
819            }
820            BlockGuard.BlockGuardPolicyException e = new StrictModeDiskReadViolation(mPolicyMask);
821            e.fillInStackTrace();
822            startHandlingViolationException(e);
823        }
824
825        // Part of BlockGuard.Policy interface:
826        public void onNetwork() {
827            if ((mPolicyMask & DETECT_NETWORK) == 0) {
828                return;
829            }
830            if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
831                throw new NetworkOnMainThreadException();
832            }
833            if (tooManyViolationsThisLoop()) {
834                return;
835            }
836            BlockGuard.BlockGuardPolicyException e = new StrictModeNetworkViolation(mPolicyMask);
837            e.fillInStackTrace();
838            startHandlingViolationException(e);
839        }
840
841        public void setPolicyMask(int policyMask) {
842            mPolicyMask = policyMask;
843        }
844
845        // Start handling a violation that just started and hasn't
846        // actually run yet (e.g. no disk write or network operation
847        // has yet occurred).  This sees if we're in an event loop
848        // thread and, if so, uses it to roughly measure how long the
849        // violation took.
850        void startHandlingViolationException(BlockGuard.BlockGuardPolicyException e) {
851            final ViolationInfo info = new ViolationInfo(e, e.getPolicy());
852            info.violationUptimeMillis = SystemClock.uptimeMillis();
853            handleViolationWithTimingAttempt(info);
854        }
855
856        // Attempts to fill in the provided ViolationInfo's
857        // durationMillis field if this thread has a Looper we can use
858        // to measure with.  We measure from the time of violation
859        // until the time the looper is idle again (right before
860        // the next epoll_wait)
861        void handleViolationWithTimingAttempt(final ViolationInfo info) {
862            Looper looper = Looper.myLooper();
863
864            // Without a Looper, we're unable to time how long the
865            // violation takes place.  This case should be rare, as
866            // most users will care about timing violations that
867            // happen on their main UI thread.  Note that this case is
868            // also hit when a violation takes place in a Binder
869            // thread, in "gather" mode.  In this case, the duration
870            // of the violation is computed by the ultimate caller and
871            // its Looper, if any.
872            // TODO: if in gather mode, ignore Looper.myLooper() and always
873            //       go into this immediate mode?
874            if (looper == null) {
875                info.durationMillis = -1;  // unknown (redundant, already set)
876                handleViolation(info);
877                return;
878            }
879
880            MessageQueue queue = Looper.myQueue();
881            final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
882            if (records.size() >= MAX_OFFENSES_PER_LOOP) {
883                // Not worth measuring.  Too many offenses in one loop.
884                return;
885            }
886            records.add(info);
887            if (records.size() > 1) {
888                // There's already been a violation this loop, so we've already
889                // registered an idle handler to process the list of violations
890                // at the end of this Looper's loop.
891                return;
892            }
893
894            queue.addIdleHandler(new MessageQueue.IdleHandler() {
895                    public boolean queueIdle() {
896                        long loopFinishTime = SystemClock.uptimeMillis();
897                        for (int n = 0; n < records.size(); ++n) {
898                            ViolationInfo v = records.get(n);
899                            v.violationNumThisLoop = n + 1;
900                            v.durationMillis =
901                                    (int) (loopFinishTime - v.violationUptimeMillis);
902                            handleViolation(v);
903                        }
904                        records.clear();
905                        return false;  // remove this idle handler from the array
906                    }
907                });
908        }
909
910        // Note: It's possible (even quite likely) that the
911        // thread-local policy mask has changed from the time the
912        // violation fired and now (after the violating code ran) due
913        // to people who push/pop temporary policy in regions of code,
914        // hence the policy being passed around.
915        void handleViolation(final ViolationInfo info) {
916            if (info == null || info.crashInfo == null || info.crashInfo.stackTrace == null) {
917                Log.wtf(TAG, "unexpected null stacktrace");
918                return;
919            }
920
921            if (LOG_V) Log.d(TAG, "handleViolation; policy=" + info.policy);
922
923            if ((info.policy & PENALTY_GATHER) != 0) {
924                ArrayList<ViolationInfo> violations = gatheredViolations.get();
925                if (violations == null) {
926                    violations = new ArrayList<ViolationInfo>(1);
927                    gatheredViolations.set(violations);
928                } else if (violations.size() >= 5) {
929                    // Too many.  In a loop or something?  Don't gather them all.
930                    return;
931                }
932                for (ViolationInfo previous : violations) {
933                    if (info.crashInfo.stackTrace.equals(previous.crashInfo.stackTrace)) {
934                        // Duplicate. Don't log.
935                        return;
936                    }
937                }
938                violations.add(info);
939                return;
940            }
941
942            // Not perfect, but fast and good enough for dup suppression.
943            Integer crashFingerprint = info.crashInfo.stackTrace.hashCode();
944            long lastViolationTime = 0;
945            if (mLastViolationTime.containsKey(crashFingerprint)) {
946                lastViolationTime = mLastViolationTime.get(crashFingerprint);
947            }
948            long now = SystemClock.uptimeMillis();
949            mLastViolationTime.put(crashFingerprint, now);
950            long timeSinceLastViolationMillis = lastViolationTime == 0 ?
951                    Long.MAX_VALUE : (now - lastViolationTime);
952
953            if ((info.policy & PENALTY_LOG) != 0 &&
954                timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
955                if (info.durationMillis != -1) {
956                    Log.d(TAG, "StrictMode policy violation; ~duration=" +
957                          info.durationMillis + " ms: " + info.crashInfo.stackTrace);
958                } else {
959                    Log.d(TAG, "StrictMode policy violation: " + info.crashInfo.stackTrace);
960                }
961            }
962
963            // The violationMaskSubset, passed to ActivityManager, is a
964            // subset of the original StrictMode policy bitmask, with
965            // only the bit violated and penalty bits to be executed
966            // by the ActivityManagerService remaining set.
967            int violationMaskSubset = 0;
968
969            if ((info.policy & PENALTY_DIALOG) != 0 &&
970                timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
971                violationMaskSubset |= PENALTY_DIALOG;
972            }
973
974            if ((info.policy & PENALTY_DROPBOX) != 0 && lastViolationTime == 0) {
975                violationMaskSubset |= PENALTY_DROPBOX;
976            }
977
978            if (violationMaskSubset != 0) {
979                int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
980                violationMaskSubset |= violationBit;
981                final int violationMaskSubsetFinal = violationMaskSubset;
982                final int savedPolicyMask = getThreadPolicyMask();
983
984                final boolean justDropBox = (info.policy & PENALTY_MASK) == PENALTY_DROPBOX;
985                if (justDropBox) {
986                    // If all we're going to ask the activity manager
987                    // to do is dropbox it (the common case during
988                    // platform development), we can avoid doing this
989                    // call synchronously which Binder data suggests
990                    // isn't always super fast, despite the implementation
991                    // in the ActivityManager trying to be mostly async.
992                    new Thread("callActivityManagerForStrictModeDropbox") {
993                        public void run() {
994                            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
995                            try {
996                                ActivityManagerNative.getDefault().
997                                        handleApplicationStrictModeViolation(
998                                            RuntimeInit.getApplicationObject(),
999                                            violationMaskSubsetFinal,
1000                                            info);
1001                            } catch (RemoteException e) {
1002                                Log.e(TAG, "RemoteException handling StrictMode violation", e);
1003                            }
1004                        }
1005                    }.start();
1006                    return;
1007                }
1008
1009                // Normal synchronous call to the ActivityManager.
1010                try {
1011                    // First, remove any policy before we call into the Activity Manager,
1012                    // otherwise we'll infinite recurse as we try to log policy violations
1013                    // to disk, thus violating policy, thus requiring logging, etc...
1014                    // We restore the current policy below, in the finally block.
1015                    setThreadPolicyMask(0);
1016
1017                    ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1018                        RuntimeInit.getApplicationObject(),
1019                        violationMaskSubset,
1020                        info);
1021                } catch (RemoteException e) {
1022                    Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1023                } finally {
1024                    // Restore the policy.
1025                    setThreadPolicyMask(savedPolicyMask);
1026                }
1027            }
1028
1029            if ((info.policy & PENALTY_DEATH) != 0) {
1030                System.err.println("StrictMode policy violation with POLICY_DEATH; shutting down.");
1031                Process.killProcess(Process.myPid());
1032                System.exit(10);
1033            }
1034        }
1035    }
1036
1037    private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
1038        public void report (String message, Throwable allocationSite) {
1039            onVmPolicyViolation(message, allocationSite);
1040        }
1041    }
1042
1043    /**
1044     * Called from Parcel.writeNoException()
1045     */
1046    /* package */ static boolean hasGatheredViolations() {
1047        return gatheredViolations.get() != null;
1048    }
1049
1050    /**
1051     * Called from Parcel.writeException(), so we drop this memory and
1052     * don't incorrectly attribute it to the wrong caller on the next
1053     * Binder call on this thread.
1054     */
1055    /* package */ static void clearGatheredViolations() {
1056        gatheredViolations.set(null);
1057    }
1058
1059    /**
1060     * Sets the policy for what actions in the VM process (on any
1061     * thread) should be detected, as well as the penalty if such
1062     * actions occur.
1063     *
1064     * @param policy the policy to put into place
1065     */
1066    public static void setVmPolicy(final VmPolicy policy) {
1067        sVmPolicyMask = policy.mask;
1068        setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
1069    }
1070
1071    /**
1072     * Gets the current VM policy.
1073     */
1074    public static VmPolicy getVmPolicy() {
1075        return new VmPolicy(sVmPolicyMask);
1076    }
1077
1078    /**
1079     * Enable the recommended StrictMode defaults, with violations just being logged.
1080     *
1081     * <p>This catches disk and network access on the main thread, as
1082     * well as leaked SQLite cursors and unclosed resources.  This is
1083     * simply a wrapper around {@link #setVmPolicy} and {@link
1084     * #setThreadPolicy}.
1085     */
1086    public static void enableDefaults() {
1087        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
1088                                   .detectAll()
1089                                   .penaltyLog()
1090                                   .build());
1091        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
1092                               .detectLeakedSqlLiteObjects()
1093                               .detectLeakedClosableObjects()
1094                               .penaltyLog()
1095                               .build());
1096    }
1097
1098    /**
1099     * @hide
1100     */
1101    public static boolean vmSqliteObjectLeaksEnabled() {
1102        return (sVmPolicyMask & DETECT_VM_CURSOR_LEAKS) != 0;
1103    }
1104
1105    /**
1106     * @hide
1107     */
1108    public static boolean vmClosableObjectLeaksEnabled() {
1109        return (sVmPolicyMask & DETECT_VM_CLOSABLE_LEAKS) != 0;
1110    }
1111
1112    /**
1113     * @hide
1114     */
1115    public static void onSqliteObjectLeaked(String message, Throwable originStack) {
1116        onVmPolicyViolation(message, originStack);
1117    }
1118
1119    /**
1120     * @hide
1121     */
1122    public static void onVmPolicyViolation(String message, Throwable originStack) {
1123        if ((sVmPolicyMask & PENALTY_LOG) != 0) {
1124            Log.e(TAG, message, originStack);
1125        }
1126
1127        if ((sVmPolicyMask & PENALTY_DROPBOX) != 0) {
1128            final ViolationInfo info = new ViolationInfo(originStack, sVmPolicyMask);
1129
1130            // The violationMask, passed to ActivityManager, is a
1131            // subset of the original StrictMode policy bitmask, with
1132            // only the bit violated and penalty bits to be executed
1133            // by the ActivityManagerService remaining set.
1134            int violationMaskSubset = PENALTY_DROPBOX | DETECT_VM_CURSOR_LEAKS;
1135            final int savedPolicyMask = getThreadPolicyMask();
1136            try {
1137                // First, remove any policy before we call into the Activity Manager,
1138                // otherwise we'll infinite recurse as we try to log policy violations
1139                // to disk, thus violating policy, thus requiring logging, etc...
1140                // We restore the current policy below, in the finally block.
1141                setThreadPolicyMask(0);
1142
1143                ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1144                    RuntimeInit.getApplicationObject(),
1145                    violationMaskSubset,
1146                    info);
1147            } catch (RemoteException e) {
1148                Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1149            } finally {
1150                // Restore the policy.
1151                setThreadPolicyMask(savedPolicyMask);
1152            }
1153        }
1154
1155        if ((sVmPolicyMask & PENALTY_DEATH) != 0) {
1156            System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
1157            Process.killProcess(Process.myPid());
1158            System.exit(10);
1159        }
1160    }
1161
1162    /**
1163     * Called from Parcel.writeNoException()
1164     */
1165    /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
1166        ArrayList<ViolationInfo> violations = gatheredViolations.get();
1167        if (violations == null) {
1168            p.writeInt(0);
1169        } else {
1170            p.writeInt(violations.size());
1171            for (int i = 0; i < violations.size(); ++i) {
1172                violations.get(i).writeToParcel(p, 0 /* unused flags? */);
1173            }
1174            if (LOG_V) Log.d(TAG, "wrote violations to response parcel; num=" + violations.size());
1175            violations.clear(); // somewhat redundant, as we're about to null the threadlocal
1176        }
1177        gatheredViolations.set(null);
1178    }
1179
1180    private static class LogStackTrace extends Exception {}
1181
1182    /**
1183     * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS,
1184     * we here read back all the encoded violations.
1185     */
1186    /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
1187        // Our own stack trace to append
1188        StringWriter sw = new StringWriter();
1189        new LogStackTrace().printStackTrace(new PrintWriter(sw));
1190        String ourStack = sw.toString();
1191
1192        int policyMask = getThreadPolicyMask();
1193        boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
1194
1195        int numViolations = p.readInt();
1196        for (int i = 0; i < numViolations; ++i) {
1197            if (LOG_V) Log.d(TAG, "strict mode violation stacks read from binder call.  i=" + i);
1198            ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
1199            info.crashInfo.stackTrace += "# via Binder call with stack:\n" + ourStack;
1200            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1201            if (policy instanceof AndroidBlockGuardPolicy) {
1202                ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
1203            }
1204        }
1205    }
1206
1207    /**
1208     * Called from android_util_Binder.cpp's
1209     * android_os_Parcel_enforceInterface when an incoming Binder call
1210     * requires changing the StrictMode policy mask.  The role of this
1211     * function is to ask Binder for its current (native) thread-local
1212     * policy value and synchronize it to libcore's (Java)
1213     * thread-local policy value.
1214     */
1215    private static void onBinderStrictModePolicyChange(int newPolicy) {
1216        setBlockGuardPolicy(newPolicy);
1217    }
1218
1219    /**
1220     * Parcelable that gets sent in Binder call headers back to callers
1221     * to report violations that happened during a cross-process call.
1222     *
1223     * @hide
1224     */
1225    public static class ViolationInfo {
1226        /**
1227         * Stack and other stuff info.
1228         */
1229        public final ApplicationErrorReport.CrashInfo crashInfo;
1230
1231        /**
1232         * The strict mode policy mask at the time of violation.
1233         */
1234        public final int policy;
1235
1236        /**
1237         * The wall time duration of the violation, when known.  -1 when
1238         * not known.
1239         */
1240        public int durationMillis = -1;
1241
1242        /**
1243         * The number of animations currently running.
1244         */
1245        public int numAnimationsRunning = 0;
1246
1247        /**
1248         * Which violation number this was (1-based) since the last Looper loop,
1249         * from the perspective of the root caller (if it crossed any processes
1250         * via Binder calls).  The value is 0 if the root caller wasn't on a Looper
1251         * thread.
1252         */
1253        public int violationNumThisLoop;
1254
1255        /**
1256         * The time (in terms of SystemClock.uptimeMillis()) that the
1257         * violation occurred.
1258         */
1259        public long violationUptimeMillis;
1260
1261        /**
1262         * The action of the Intent being broadcast to somebody's onReceive
1263         * on this thread right now, or null.
1264         */
1265        public String broadcastIntentAction;
1266
1267        /**
1268         * Create an uninitialized instance of ViolationInfo
1269         */
1270        public ViolationInfo() {
1271            crashInfo = null;
1272            policy = 0;
1273        }
1274
1275        /**
1276         * Create an instance of ViolationInfo initialized from an exception.
1277         */
1278        public ViolationInfo(Throwable tr, int policy) {
1279            crashInfo = new ApplicationErrorReport.CrashInfo(tr);
1280            violationUptimeMillis = SystemClock.uptimeMillis();
1281            this.policy = policy;
1282            this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
1283            Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
1284            if (broadcastIntent != null) {
1285                broadcastIntentAction = broadcastIntent.getAction();
1286            }
1287        }
1288
1289        /**
1290         * Create an instance of ViolationInfo initialized from a Parcel.
1291         */
1292        public ViolationInfo(Parcel in) {
1293            this(in, false);
1294        }
1295
1296        /**
1297         * Create an instance of ViolationInfo initialized from a Parcel.
1298         *
1299         * @param unsetGatheringBit if true, the caller is the root caller
1300         *   and the gathering penalty should be removed.
1301         */
1302        public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
1303            crashInfo = new ApplicationErrorReport.CrashInfo(in);
1304            int rawPolicy = in.readInt();
1305            if (unsetGatheringBit) {
1306                policy = rawPolicy & ~PENALTY_GATHER;
1307            } else {
1308                policy = rawPolicy;
1309            }
1310            durationMillis = in.readInt();
1311            violationNumThisLoop = in.readInt();
1312            numAnimationsRunning = in.readInt();
1313            violationUptimeMillis = in.readLong();
1314            broadcastIntentAction = in.readString();
1315        }
1316
1317        /**
1318         * Save a ViolationInfo instance to a parcel.
1319         */
1320        public void writeToParcel(Parcel dest, int flags) {
1321            crashInfo.writeToParcel(dest, flags);
1322            dest.writeInt(policy);
1323            dest.writeInt(durationMillis);
1324            dest.writeInt(violationNumThisLoop);
1325            dest.writeInt(numAnimationsRunning);
1326            dest.writeLong(violationUptimeMillis);
1327            dest.writeString(broadcastIntentAction);
1328        }
1329
1330
1331        /**
1332         * Dump a ViolationInfo instance to a Printer.
1333         */
1334        public void dump(Printer pw, String prefix) {
1335            crashInfo.dump(pw, prefix);
1336            pw.println(prefix + "policy: " + policy);
1337            if (durationMillis != -1) {
1338                pw.println(prefix + "durationMillis: " + durationMillis);
1339            }
1340            if (violationNumThisLoop != 0) {
1341                pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
1342            }
1343            if (numAnimationsRunning != 0) {
1344                pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
1345            }
1346            pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
1347            if (broadcastIntentAction != null) {
1348                pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
1349            }
1350        }
1351
1352    }
1353}
1354