StrictMode.java revision 08d584cd1cba05284ccd2d0ea128c297624f0c47
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.app.IActivityManager;
23import android.content.Intent;
24import android.util.Log;
25import android.util.Printer;
26import android.util.Singleton;
27import android.view.IWindowManager;
28
29import com.android.internal.os.RuntimeInit;
30
31import dalvik.system.BlockGuard;
32import dalvik.system.CloseGuard;
33import dalvik.system.VMDebug;
34
35import java.io.PrintWriter;
36import java.io.StringWriter;
37import java.util.ArrayList;
38import java.util.Collections;
39import java.util.HashMap;
40import java.util.Map;
41import java.util.concurrent.atomic.AtomicInteger;
42
43/**
44 * <p>StrictMode is a developer tool which detects things you might be
45 * doing by accident and brings them to your attention so you can fix
46 * them.
47 *
48 * <p>StrictMode is most commonly used to catch accidental disk or
49 * network access on the application's main thread, where UI
50 * operations are received and animations take place.  Keeping disk
51 * and network operations off the main thread makes for much smoother,
52 * more responsive applications.  By keeping your application's main thread
53 * responsive, you also prevent
54 * <a href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a>
55 * from being shown to users.
56 *
57 * <p class="note">Note that even though an Android device's disk is
58 * often on flash memory, many devices run a filesystem on top of that
59 * memory with very limited concurrency.  It's often the case that
60 * almost all disk accesses are fast, but may in individual cases be
61 * dramatically slower when certain I/O is happening in the background
62 * from other processes.  If possible, it's best to assume that such
63 * things are not fast.</p>
64 *
65 * <p>Example code to enable from early in your
66 * {@link android.app.Application}, {@link android.app.Activity}, or
67 * other application component's
68 * {@link android.app.Application#onCreate} method:
69 *
70 * <pre>
71 * public void onCreate() {
72 *     if (DEVELOPER_MODE) {
73 *         StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
74 *                 .detectDiskReads()
75 *                 .detectDiskWrites()
76 *                 .detectNetwork()   // or .detectAll() for all detectable problems
77 *                 .penaltyLog()
78 *                 .build());
79 *         StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
80 *                 .detectLeakedSqlLiteObjects()
81 *                 .detectLeakedClosableObjects()
82 *                 .penaltyLog()
83 *                 .penaltyDeath()
84 *                 .build());
85 *     }
86 *     super.onCreate();
87 * }
88 * </pre>
89 *
90 * <p>You can decide what should happen when a violation is detected.
91 * For example, using {@link ThreadPolicy.Builder#penaltyLog} you can
92 * watch the output of <code>adb logcat</code> while you use your
93 * application to see the violations as they happen.
94 *
95 * <p>If you find violations that you feel are problematic, there are
96 * a variety of tools to help solve them: threads, {@link android.os.Handler},
97 * {@link android.os.AsyncTask}, {@link android.app.IntentService}, etc.
98 * But don't feel compelled to fix everything that StrictMode finds.  In particular,
99 * many cases of disk access are often necessary during the normal activity lifecycle.  Use
100 * StrictMode to find things you did by accident.  Network requests on the UI thread
101 * are almost always a problem, though.
102 *
103 * <p class="note">StrictMode is not a security mechanism and is not
104 * guaranteed to find all disk or network accesses.  While it does
105 * propagate its state across process boundaries when doing
106 * {@link android.os.Binder} calls, it's still ultimately a best
107 * effort mechanism.  Notably, disk or network access from JNI calls
108 * won't necessarily trigger it.  Future versions of Android may catch
109 * more (or fewer) operations, so you should never leave StrictMode
110 * enabled in shipping applications on the Android Market.
111 */
112public final class StrictMode {
113    private static final String TAG = "StrictMode";
114    private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
115
116    private static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
117    private static final boolean IS_ENG_BUILD = "eng".equals(Build.TYPE);
118
119    /**
120     * The boolean system property to control screen flashes on violations.
121     *
122     * @hide
123     */
124    public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
125
126    // Only log a duplicate stack trace to the logs every second.
127    private static final long MIN_LOG_INTERVAL_MS = 1000;
128
129    // Only show an annoying dialog at most every 30 seconds
130    private static final long MIN_DIALOG_INTERVAL_MS = 30000;
131
132    // How many Span tags (e.g. animations) to report.
133    private static final int MAX_SPAN_TAGS = 20;
134
135    // How many offending stacks to keep track of (and time) per loop
136    // of the Looper.
137    private static final int MAX_OFFENSES_PER_LOOP = 10;
138
139    // Thread-policy:
140
141    /**
142     * @hide
143     */
144    public static final int DETECT_DISK_WRITE = 0x01;  // for ThreadPolicy
145
146    /**
147      * @hide
148     */
149    public static final int DETECT_DISK_READ = 0x02;  // for ThreadPolicy
150
151    /**
152     * @hide
153     */
154    public static final int DETECT_NETWORK = 0x04;  // for ThreadPolicy
155
156    /**
157     * For StrictMode.noteSlowCall()
158     *
159     * @hide
160     */
161    public static final int DETECT_CUSTOM = 0x08;  // for ThreadPolicy
162
163    private static final int ALL_THREAD_DETECT_BITS =
164            DETECT_DISK_WRITE | DETECT_DISK_READ | DETECT_NETWORK | DETECT_CUSTOM;
165
166    // Process-policy:
167
168    /**
169     * Note, a "VM_" bit, not thread.
170     * @hide
171     */
172    public static final int DETECT_VM_CURSOR_LEAKS = 0x200;  // for VmPolicy
173
174    /**
175     * Note, a "VM_" bit, not thread.
176     * @hide
177     */
178    public static final int DETECT_VM_CLOSABLE_LEAKS = 0x400;  // for VmPolicy
179
180    /**
181     * Note, a "VM_" bit, not thread.
182     * @hide
183     */
184    public static final int DETECT_VM_ACTIVITY_LEAKS = 0x800;  // for VmPolicy
185
186    /**
187     * @hide
188     */
189    private static final int DETECT_VM_INSTANCE_LEAKS = 0x1000;  // for VmPolicy
190
191    private static final int ALL_VM_DETECT_BITS =
192            DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS |
193            DETECT_VM_ACTIVITY_LEAKS | DETECT_VM_INSTANCE_LEAKS;
194
195    /**
196     * @hide
197     */
198    public static final int PENALTY_LOG = 0x10;  // normal android.util.Log
199
200    // Used for both process and thread policy:
201
202    /**
203     * @hide
204     */
205    public static final int PENALTY_DIALOG = 0x20;
206
207    /**
208     * Death on any detected violation.
209     *
210     * @hide
211     */
212    public static final int PENALTY_DEATH = 0x40;
213
214    /**
215     * Death just for detected network usage.
216     *
217     * @hide
218     */
219    public static final int PENALTY_DEATH_ON_NETWORK = 0x200;
220
221    /**
222     * Flash the screen during violations.
223     *
224     * @hide
225     */
226    public static final int PENALTY_FLASH = 0x800;
227
228    /**
229     * @hide
230     */
231    public static final int PENALTY_DROPBOX = 0x80;
232
233    /**
234     * Non-public penalty mode which overrides all the other penalty
235     * bits and signals that we're in a Binder call and we should
236     * ignore the other penalty bits and instead serialize back all
237     * our offending stack traces to the caller to ultimately handle
238     * in the originating process.
239     *
240     * This must be kept in sync with the constant in libs/binder/Parcel.cpp
241     *
242     * @hide
243     */
244    public static final int PENALTY_GATHER = 0x100;
245
246    /**
247     * Mask of all the penalty bits valid for thread policies.
248     */
249    private static final int THREAD_PENALTY_MASK =
250            PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER |
251            PENALTY_DEATH_ON_NETWORK | PENALTY_FLASH;
252
253
254    /**
255     * Mask of all the penalty bits valid for VM policies.
256     */
257    private static final int VM_PENALTY_MASK =
258            PENALTY_LOG | PENALTY_DEATH | PENALTY_DROPBOX;
259
260
261    // TODO: wrap in some ImmutableHashMap thing.
262    // Note: must be before static initialization of sVmPolicy.
263    private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP = new HashMap<Class, Integer>();
264
265    /**
266     * The current VmPolicy in effect.
267     *
268     * TODO: these are redundant (mask is in VmPolicy).  Should remove sVmPolicyMask.
269     */
270    private static volatile int sVmPolicyMask = 0;
271    private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
272
273    /**
274     * The number of threads trying to do an async dropbox write.
275     * Just to limit ourselves out of paranoia.
276     */
277    private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
278
279    private StrictMode() {}
280
281    /**
282     * {@link StrictMode} policy applied to a certain thread.
283     *
284     * <p>The policy is enabled by {@link #setThreadPolicy}.  The current policy
285     * can be retrieved with {@link #getThreadPolicy}.
286     *
287     * <p>Note that multiple penalties may be provided and they're run
288     * in order from least to most severe (logging before process
289     * death, for example).  There's currently no mechanism to choose
290     * different penalties for different detected actions.
291     */
292    public static final class ThreadPolicy {
293        /**
294         * The default, lax policy which doesn't catch anything.
295         */
296        public static final ThreadPolicy LAX = new ThreadPolicy(0);
297
298        final int mask;
299
300        private ThreadPolicy(int mask) {
301            this.mask = mask;
302        }
303
304        @Override
305        public String toString() {
306            return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
307        }
308
309        /**
310         * Creates {@link ThreadPolicy} instances.  Methods whose names start
311         * with {@code detect} specify what problems we should look
312         * for.  Methods whose names start with {@code penalty} specify what
313         * we should do when we detect a problem.
314         *
315         * <p>You can call as many {@code detect} and {@code penalty}
316         * methods as you like. Currently order is insignificant: all
317         * penalties apply to all detected problems.
318         *
319         * <p>For example, detect everything and log anything that's found:
320         * <pre>
321         * StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
322         *     .detectAll()
323         *     .penaltyLog()
324         *     .build();
325         * StrictMode.setThreadPolicy(policy);
326         * </pre>
327         */
328        public static final class Builder {
329            private int mMask = 0;
330
331            /**
332             * Create a Builder that detects nothing and has no
333             * violations.  (but note that {@link #build} will default
334             * to enabling {@link #penaltyLog} if no other penalties
335             * are specified)
336             */
337            public Builder() {
338                mMask = 0;
339            }
340
341            /**
342             * Initialize a Builder from an existing ThreadPolicy.
343             */
344            public Builder(ThreadPolicy policy) {
345                mMask = policy.mask;
346            }
347
348            /**
349             * Detect everything that's potentially suspect.
350             *
351             * <p>As of the Gingerbread release this includes network and
352             * disk operations but will likely expand in future releases.
353             */
354            public Builder detectAll() {
355                return enable(ALL_THREAD_DETECT_BITS);
356            }
357
358            /**
359             * Disable the detection of everything.
360             */
361            public Builder permitAll() {
362                return disable(ALL_THREAD_DETECT_BITS);
363            }
364
365            /**
366             * Enable detection of network operations.
367             */
368            public Builder detectNetwork() {
369                return enable(DETECT_NETWORK);
370            }
371
372            /**
373             * Disable detection of network operations.
374             */
375            public Builder permitNetwork() {
376                return disable(DETECT_NETWORK);
377            }
378
379            /**
380             * Enable detection of disk reads.
381             */
382            public Builder detectDiskReads() {
383                return enable(DETECT_DISK_READ);
384            }
385
386            /**
387             * Disable detection of disk reads.
388             */
389            public Builder permitDiskReads() {
390                return disable(DETECT_DISK_READ);
391            }
392
393            /**
394             * Enable detection of disk reads.
395             */
396            public Builder detectCustomSlowCalls() {
397                return enable(DETECT_CUSTOM);
398            }
399
400            /**
401             * Enable detection of disk reads.
402             */
403            public Builder permitCustomSlowCalls() {
404                return enable(DETECT_CUSTOM);
405            }
406
407            /**
408             * Enable detection of disk writes.
409             */
410            public Builder detectDiskWrites() {
411                return enable(DETECT_DISK_WRITE);
412            }
413
414            /**
415             * Disable detection of disk writes.
416             */
417            public Builder permitDiskWrites() {
418                return disable(DETECT_DISK_WRITE);
419            }
420
421            /**
422             * Show an annoying dialog to the developer on detected
423             * violations, rate-limited to be only a little annoying.
424             */
425            public Builder penaltyDialog() {
426                return enable(PENALTY_DIALOG);
427            }
428
429            /**
430             * Crash the whole process on violation.  This penalty runs at
431             * the end of all enabled penalties so you'll still get
432             * see logging or other violations before the process dies.
433             *
434             * <p>Unlike {@link #penaltyDeathOnNetwork}, this applies
435             * to disk reads, disk writes, and network usage if their
436             * corresponding detect flags are set.
437             */
438            public Builder penaltyDeath() {
439                return enable(PENALTY_DEATH);
440            }
441
442            /**
443             * Crash the whole process on any network usage.  Unlike
444             * {@link #penaltyDeath}, this penalty runs
445             * <em>before</em> anything else.  You must still have
446             * called {@link #detectNetwork} to enable this.
447             *
448             * <p>In the Honeycomb or later SDKs, this is on by default.
449             */
450            public Builder penaltyDeathOnNetwork() {
451                return enable(PENALTY_DEATH_ON_NETWORK);
452            }
453
454            /**
455             * Flash the screen during a violation.
456             */
457            public Builder penaltyFlashScreen() {
458                return enable(PENALTY_FLASH);
459            }
460
461            /**
462             * Log detected violations to the system log.
463             */
464            public Builder penaltyLog() {
465                return enable(PENALTY_LOG);
466            }
467
468            /**
469             * Enable detected violations log a stacktrace and timing data
470             * to the {@link android.os.DropBoxManager DropBox} on policy
471             * violation.  Intended mostly for platform integrators doing
472             * beta user field data collection.
473             */
474            public Builder penaltyDropBox() {
475                return enable(PENALTY_DROPBOX);
476            }
477
478            private Builder enable(int bit) {
479                mMask |= bit;
480                return this;
481            }
482
483            private Builder disable(int bit) {
484                mMask &= ~bit;
485                return this;
486            }
487
488            /**
489             * Construct the ThreadPolicy instance.
490             *
491             * <p>Note: if no penalties are enabled before calling
492             * <code>build</code>, {@link #penaltyLog} is implicitly
493             * set.
494             */
495            public ThreadPolicy build() {
496                // If there are detection bits set but no violation bits
497                // set, enable simple logging.
498                if (mMask != 0 &&
499                    (mMask & (PENALTY_DEATH | PENALTY_LOG |
500                              PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
501                    penaltyLog();
502                }
503                return new ThreadPolicy(mMask);
504            }
505        }
506    }
507
508    /**
509     * {@link StrictMode} policy applied to all threads in the virtual machine's process.
510     *
511     * <p>The policy is enabled by {@link #setVmPolicy}.
512     */
513    public static final class VmPolicy {
514        /**
515         * The default, lax policy which doesn't catch anything.
516         */
517        public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP);
518
519        final int mask;
520
521        // Map from class to max number of allowed instances in memory.
522        final HashMap<Class, Integer> classInstanceLimit;
523
524        private VmPolicy(int mask, HashMap<Class, Integer> classInstanceLimit) {
525            if (classInstanceLimit == null) {
526                throw new NullPointerException("classInstanceLimit == null");
527            }
528            this.mask = mask;
529            this.classInstanceLimit = classInstanceLimit;
530        }
531
532        @Override
533        public String toString() {
534            return "[StrictMode.VmPolicy; mask=" + mask + "]";
535        }
536
537        /**
538         * Creates {@link VmPolicy} instances.  Methods whose names start
539         * with {@code detect} specify what problems we should look
540         * for.  Methods whose names start with {@code penalty} specify what
541         * we should do when we detect a problem.
542         *
543         * <p>You can call as many {@code detect} and {@code penalty}
544         * methods as you like. Currently order is insignificant: all
545         * penalties apply to all detected problems.
546         *
547         * <p>For example, detect everything and log anything that's found:
548         * <pre>
549         * StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
550         *     .detectAll()
551         *     .penaltyLog()
552         *     .build();
553         * StrictMode.setVmPolicy(policy);
554         * </pre>
555         */
556        public static final class Builder {
557            private int mMask;
558
559            private HashMap<Class, Integer> mClassInstanceLimit;  // null until needed
560            private boolean mClassInstanceLimitNeedCow = false;  // need copy-on-write
561
562            public Builder() {
563                mMask = 0;
564            }
565
566            /**
567             * Build upon an existing VmPolicy.
568             */
569            public Builder(VmPolicy base) {
570                mMask = base.mask;
571                mClassInstanceLimitNeedCow = true;
572                mClassInstanceLimit = base.classInstanceLimit;
573            }
574
575            /**
576             * Set an upper bound on how many instances of a class can be in memory
577             * at once.  Helps to prevent object leaks.
578             */
579            public Builder setClassInstanceLimit(Class klass, int instanceLimit) {
580                if (klass == null) {
581                    throw new NullPointerException("klass == null");
582                }
583                if (mClassInstanceLimitNeedCow) {
584                    if (mClassInstanceLimit.containsKey(klass) &&
585                        mClassInstanceLimit.get(klass) == instanceLimit) {
586                        // no-op; don't break COW
587                        return this;
588                    }
589                    mClassInstanceLimitNeedCow = false;
590                    mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
591                } else if (mClassInstanceLimit == null) {
592                    mClassInstanceLimit = new HashMap<Class, Integer>();
593                }
594                mMask |= DETECT_VM_INSTANCE_LEAKS;
595                mClassInstanceLimit.put(klass, instanceLimit);
596                return this;
597            }
598
599            /**
600             * Detect leaks of {@link android.app.Activity} subclasses.
601             */
602            public Builder detectActivityLeaks() {
603                return enable(DETECT_VM_ACTIVITY_LEAKS);
604            }
605
606            /**
607             * Detect everything that's potentially suspect.
608             *
609             * <p>In the Honeycomb release this includes leaks of
610             * SQLite cursors, Activities, and other closable objects
611             * but will likely expand in future releases.
612             */
613            public Builder detectAll() {
614                return enable(DETECT_VM_ACTIVITY_LEAKS |
615                        DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS);
616            }
617
618            /**
619             * Detect when an
620             * {@link android.database.sqlite.SQLiteCursor} or other
621             * SQLite object is finalized without having been closed.
622             *
623             * <p>You always want to explicitly close your SQLite
624             * cursors to avoid unnecessary database contention and
625             * temporary memory leaks.
626             */
627            public Builder detectLeakedSqlLiteObjects() {
628                return enable(DETECT_VM_CURSOR_LEAKS);
629            }
630
631            /**
632             * Detect when an {@link java.io.Closeable} or other
633             * object with a explict termination method is finalized
634             * without having been closed.
635             *
636             * <p>You always want to explicitly close such objects to
637             * avoid unnecessary resources leaks.
638             */
639            public Builder detectLeakedClosableObjects() {
640                return enable(DETECT_VM_CLOSABLE_LEAKS);
641            }
642
643            /**
644             * Crashes the whole process on violation.  This penalty runs at
645             * the end of all enabled penalties so yo you'll still get
646             * your logging or other violations before the process dies.
647             */
648            public Builder penaltyDeath() {
649                return enable(PENALTY_DEATH);
650            }
651
652            /**
653             * Log detected violations to the system log.
654             */
655            public Builder penaltyLog() {
656                return enable(PENALTY_LOG);
657            }
658
659            /**
660             * Enable detected violations log a stacktrace and timing data
661             * to the {@link android.os.DropBoxManager DropBox} on policy
662             * violation.  Intended mostly for platform integrators doing
663             * beta user field data collection.
664             */
665            public Builder penaltyDropBox() {
666                return enable(PENALTY_DROPBOX);
667            }
668
669            private Builder enable(int bit) {
670                mMask |= bit;
671                return this;
672            }
673
674            /**
675             * Construct the VmPolicy instance.
676             *
677             * <p>Note: if no penalties are enabled before calling
678             * <code>build</code>, {@link #penaltyLog} is implicitly
679             * set.
680             */
681            public VmPolicy build() {
682                // If there are detection bits set but no violation bits
683                // set, enable simple logging.
684                if (mMask != 0 &&
685                    (mMask & (PENALTY_DEATH | PENALTY_LOG |
686                              PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
687                    penaltyLog();
688                }
689                return new VmPolicy(mMask,
690                        mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP);
691            }
692        }
693    }
694
695    /**
696     * Log of strict mode violation stack traces that have occurred
697     * during a Binder call, to be serialized back later to the caller
698     * via Parcel.writeNoException() (amusingly) where the caller can
699     * choose how to react.
700     */
701    private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
702            new ThreadLocal<ArrayList<ViolationInfo>>() {
703        @Override protected ArrayList<ViolationInfo> initialValue() {
704            // Starts null to avoid unnecessary allocations when
705            // checking whether there are any violations or not in
706            // hasGatheredViolations() below.
707            return null;
708        }
709    };
710
711    /**
712     * Sets the policy for what actions on the current thread should
713     * be detected, as well as the penalty if such actions occur.
714     *
715     * <p>Internally this sets a thread-local variable which is
716     * propagated across cross-process IPC calls, meaning you can
717     * catch violations when a system service or another process
718     * accesses the disk or network on your behalf.
719     *
720     * @param policy the policy to put into place
721     */
722    public static void setThreadPolicy(final ThreadPolicy policy) {
723        setThreadPolicyMask(policy.mask);
724    }
725
726    private static void setThreadPolicyMask(final int policyMask) {
727        // In addition to the Java-level thread-local in Dalvik's
728        // BlockGuard, we also need to keep a native thread-local in
729        // Binder in order to propagate the value across Binder calls,
730        // even across native-only processes.  The two are kept in
731        // sync via the callback to onStrictModePolicyChange, below.
732        setBlockGuardPolicy(policyMask);
733
734        // And set the Android native version...
735        Binder.setThreadStrictModePolicy(policyMask);
736    }
737
738    // Sets the policy in Dalvik/libcore (BlockGuard)
739    private static void setBlockGuardPolicy(final int policyMask) {
740        if (policyMask == 0) {
741            BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
742            return;
743        }
744        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
745        if (!(policy instanceof AndroidBlockGuardPolicy)) {
746            BlockGuard.setThreadPolicy(new AndroidBlockGuardPolicy(policyMask));
747        } else {
748            AndroidBlockGuardPolicy androidPolicy = (AndroidBlockGuardPolicy) policy;
749            androidPolicy.setPolicyMask(policyMask);
750        }
751    }
752
753    // Sets up CloseGuard in Dalvik/libcore
754    private static void setCloseGuardEnabled(boolean enabled) {
755        if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
756            CloseGuard.setReporter(new AndroidCloseGuardReporter());
757        }
758        CloseGuard.setEnabled(enabled);
759    }
760
761    /**
762     * @hide
763     */
764    public static class StrictModeViolation extends BlockGuard.BlockGuardPolicyException {
765        public StrictModeViolation(int policyState, int policyViolated, String message) {
766            super(policyState, policyViolated, message);
767        }
768    }
769
770    /**
771     * @hide
772     */
773    public static class StrictModeNetworkViolation extends StrictModeViolation {
774        public StrictModeNetworkViolation(int policyMask) {
775            super(policyMask, DETECT_NETWORK, null);
776        }
777    }
778
779    /**
780     * @hide
781     */
782    private static class StrictModeDiskReadViolation extends StrictModeViolation {
783        public StrictModeDiskReadViolation(int policyMask) {
784            super(policyMask, DETECT_DISK_READ, null);
785        }
786    }
787
788     /**
789     * @hide
790     */
791   private static class StrictModeDiskWriteViolation extends StrictModeViolation {
792        public StrictModeDiskWriteViolation(int policyMask) {
793            super(policyMask, DETECT_DISK_WRITE, null);
794        }
795    }
796
797    /**
798     * @hide
799     */
800    private static class StrictModeCustomViolation extends StrictModeViolation {
801        public StrictModeCustomViolation(int policyMask, String name) {
802            super(policyMask, DETECT_CUSTOM, name);
803        }
804    }
805
806    /**
807     * Returns the bitmask of the current thread's policy.
808     *
809     * @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
810     *
811     * @hide
812     */
813    public static int getThreadPolicyMask() {
814        return BlockGuard.getThreadPolicy().getPolicyMask();
815    }
816
817    /**
818     * Returns the current thread's policy.
819     */
820    public static ThreadPolicy getThreadPolicy() {
821        // TODO: this was a last minute Gingerbread API change (to
822        // introduce VmPolicy cleanly) but this isn't particularly
823        // optimal for users who might call this method often.  This
824        // should be in a thread-local and not allocate on each call.
825        return new ThreadPolicy(getThreadPolicyMask());
826    }
827
828    /**
829     * A convenience wrapper that takes the current
830     * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
831     * to permit both disk reads &amp; writes, and sets the new policy
832     * with {@link #setThreadPolicy}, returning the old policy so you
833     * can restore it at the end of a block.
834     *
835     * @return the old policy, to be passed to {@link #setThreadPolicy} to
836     *         restore the policy at the end of a block
837     */
838    public static ThreadPolicy allowThreadDiskWrites() {
839        int oldPolicyMask = getThreadPolicyMask();
840        int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_WRITE | DETECT_DISK_READ);
841        if (newPolicyMask != oldPolicyMask) {
842            setThreadPolicyMask(newPolicyMask);
843        }
844        return new ThreadPolicy(oldPolicyMask);
845    }
846
847    /**
848     * A convenience wrapper that takes the current
849     * {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
850     * to permit disk reads, and sets the new policy
851     * with {@link #setThreadPolicy}, returning the old policy so you
852     * can restore it at the end of a block.
853     *
854     * @return the old policy, to be passed to setThreadPolicy to
855     *         restore the policy.
856     */
857    public static ThreadPolicy allowThreadDiskReads() {
858        int oldPolicyMask = getThreadPolicyMask();
859        int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_READ);
860        if (newPolicyMask != oldPolicyMask) {
861            setThreadPolicyMask(newPolicyMask);
862        }
863        return new ThreadPolicy(oldPolicyMask);
864    }
865
866    // We don't want to flash the screen red in the system server
867    // process, nor do we want to modify all the call sites of
868    // conditionallyEnableDebugLogging() in the system server,
869    // so instead we use this to determine if we are the system server.
870    private static boolean amTheSystemServerProcess() {
871        // Fast path.  Most apps don't have the system server's UID.
872        if (Process.myUid() != Process.SYSTEM_UID) {
873            return false;
874        }
875
876        // The settings app, though, has the system server's UID so
877        // look up our stack to see if we came from the system server.
878        Throwable stack = new Throwable();
879        stack.fillInStackTrace();
880        for (StackTraceElement ste : stack.getStackTrace()) {
881            String clsName = ste.getClassName();
882            if (clsName != null && clsName.startsWith("com.android.server.")) {
883                return true;
884            }
885        }
886        return false;
887    }
888
889    /**
890     * Enable DropBox logging for debug phone builds.
891     *
892     * @hide
893     */
894    public static boolean conditionallyEnableDebugLogging() {
895        boolean doFlashes = !amTheSystemServerProcess() &&
896                SystemProperties.getBoolean(VISUAL_PROPERTY, IS_ENG_BUILD);
897
898        // For debug builds, log event loop stalls to dropbox for analysis.
899        // Similar logic also appears in ActivityThread.java for system apps.
900        if (IS_USER_BUILD && !doFlashes) {
901            setCloseGuardEnabled(false);
902            return false;
903        }
904
905        int threadPolicyMask = StrictMode.DETECT_DISK_WRITE |
906                StrictMode.DETECT_DISK_READ |
907                StrictMode.DETECT_NETWORK;
908
909        if (!IS_USER_BUILD) {
910            threadPolicyMask |= StrictMode.PENALTY_DROPBOX;
911        }
912        if (doFlashes) {
913            threadPolicyMask |= StrictMode.PENALTY_FLASH;
914        }
915
916        StrictMode.setThreadPolicyMask(threadPolicyMask);
917
918        if (IS_USER_BUILD) {
919            setCloseGuardEnabled(false);
920        } else {
921            setVmPolicy(new VmPolicy.Builder().detectAll().penaltyDropBox().build());
922            setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
923        }
924        return true;
925    }
926
927    /**
928     * Used by the framework to make network usage on the main
929     * thread a fatal error.
930     *
931     * @hide
932     */
933    public static void enableDeathOnNetwork() {
934        int oldPolicy = getThreadPolicyMask();
935        int newPolicy = oldPolicy | DETECT_NETWORK | PENALTY_DEATH_ON_NETWORK;
936        setThreadPolicyMask(newPolicy);
937    }
938
939    /**
940     * Parses the BlockGuard policy mask out from the Exception's
941     * getMessage() String value.  Kinda gross, but least
942     * invasive.  :/
943     *
944     * Input is of the following forms:
945     *     "policy=137 violation=64"
946     *     "policy=137 violation=64 msg=Arbitrary text"
947     *
948     * Returns 0 on failure, which is a valid policy, but not a
949     * valid policy during a violation (else there must've been
950     * some policy in effect to violate).
951     */
952    private static int parsePolicyFromMessage(String message) {
953        if (message == null || !message.startsWith("policy=")) {
954            return 0;
955        }
956        int spaceIndex = message.indexOf(' ');
957        if (spaceIndex == -1) {
958            return 0;
959        }
960        String policyString = message.substring(7, spaceIndex);
961        try {
962            return Integer.valueOf(policyString).intValue();
963        } catch (NumberFormatException e) {
964            return 0;
965        }
966    }
967
968    /**
969     * Like parsePolicyFromMessage(), but returns the violation.
970     */
971    private static int parseViolationFromMessage(String message) {
972        if (message == null) {
973            return 0;
974        }
975        int violationIndex = message.indexOf("violation=");
976        if (violationIndex == -1) {
977            return 0;
978        }
979        int numberStartIndex = violationIndex + "violation=".length();
980        int numberEndIndex = message.indexOf(' ', numberStartIndex);
981        if (numberEndIndex == -1) {
982            numberEndIndex = message.length();
983        }
984        String violationString = message.substring(numberStartIndex, numberEndIndex);
985        try {
986            return Integer.valueOf(violationString).intValue();
987        } catch (NumberFormatException e) {
988            return 0;
989        }
990    }
991
992    private static final ThreadLocal<ArrayList<ViolationInfo>> violationsBeingTimed =
993            new ThreadLocal<ArrayList<ViolationInfo>>() {
994        @Override protected ArrayList<ViolationInfo> initialValue() {
995            return new ArrayList<ViolationInfo>();
996        }
997    };
998
999    // Note: only access this once verifying the thread has a Looper.
1000    private static final ThreadLocal<Handler> threadHandler = new ThreadLocal<Handler>() {
1001        @Override protected Handler initialValue() {
1002            return new Handler();
1003        }
1004    };
1005
1006    private static boolean tooManyViolationsThisLoop() {
1007        return violationsBeingTimed.get().size() >= MAX_OFFENSES_PER_LOOP;
1008    }
1009
1010    private static class AndroidBlockGuardPolicy implements BlockGuard.Policy {
1011        private int mPolicyMask;
1012
1013        // Map from violation stacktrace hashcode -> uptimeMillis of
1014        // last violation.  No locking needed, as this is only
1015        // accessed by the same thread.
1016        private final HashMap<Integer, Long> mLastViolationTime = new HashMap<Integer, Long>();
1017
1018        public AndroidBlockGuardPolicy(final int policyMask) {
1019            mPolicyMask = policyMask;
1020        }
1021
1022        @Override
1023        public String toString() {
1024            return "AndroidBlockGuardPolicy; mPolicyMask=" + mPolicyMask;
1025        }
1026
1027        // Part of BlockGuard.Policy interface:
1028        public int getPolicyMask() {
1029            return mPolicyMask;
1030        }
1031
1032        // Part of BlockGuard.Policy interface:
1033        public void onWriteToDisk() {
1034            if ((mPolicyMask & DETECT_DISK_WRITE) == 0) {
1035                return;
1036            }
1037            if (tooManyViolationsThisLoop()) {
1038                return;
1039            }
1040            BlockGuard.BlockGuardPolicyException e = new StrictModeDiskWriteViolation(mPolicyMask);
1041            e.fillInStackTrace();
1042            startHandlingViolationException(e);
1043        }
1044
1045        // Not part of BlockGuard.Policy; just part of StrictMode:
1046        void onCustomSlowCall(String name) {
1047            if ((mPolicyMask & DETECT_CUSTOM) == 0) {
1048                return;
1049            }
1050            if (tooManyViolationsThisLoop()) {
1051                return;
1052            }
1053            BlockGuard.BlockGuardPolicyException e = new StrictModeCustomViolation(mPolicyMask, name);
1054            e.fillInStackTrace();
1055            startHandlingViolationException(e);
1056        }
1057
1058        // Part of BlockGuard.Policy interface:
1059        public void onReadFromDisk() {
1060            if ((mPolicyMask & DETECT_DISK_READ) == 0) {
1061                return;
1062            }
1063            if (tooManyViolationsThisLoop()) {
1064                return;
1065            }
1066            BlockGuard.BlockGuardPolicyException e = new StrictModeDiskReadViolation(mPolicyMask);
1067            e.fillInStackTrace();
1068            startHandlingViolationException(e);
1069        }
1070
1071        // Part of BlockGuard.Policy interface:
1072        public void onNetwork() {
1073            if ((mPolicyMask & DETECT_NETWORK) == 0) {
1074                return;
1075            }
1076            if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) {
1077                throw new NetworkOnMainThreadException();
1078            }
1079            if (tooManyViolationsThisLoop()) {
1080                return;
1081            }
1082            BlockGuard.BlockGuardPolicyException e = new StrictModeNetworkViolation(mPolicyMask);
1083            e.fillInStackTrace();
1084            startHandlingViolationException(e);
1085        }
1086
1087        public void setPolicyMask(int policyMask) {
1088            mPolicyMask = policyMask;
1089        }
1090
1091        // Start handling a violation that just started and hasn't
1092        // actually run yet (e.g. no disk write or network operation
1093        // has yet occurred).  This sees if we're in an event loop
1094        // thread and, if so, uses it to roughly measure how long the
1095        // violation took.
1096        void startHandlingViolationException(BlockGuard.BlockGuardPolicyException e) {
1097            final ViolationInfo info = new ViolationInfo(e, e.getPolicy());
1098            info.violationUptimeMillis = SystemClock.uptimeMillis();
1099            handleViolationWithTimingAttempt(info);
1100        }
1101
1102        // Attempts to fill in the provided ViolationInfo's
1103        // durationMillis field if this thread has a Looper we can use
1104        // to measure with.  We measure from the time of violation
1105        // until the time the looper is idle again (right before
1106        // the next epoll_wait)
1107        void handleViolationWithTimingAttempt(final ViolationInfo info) {
1108            Looper looper = Looper.myLooper();
1109
1110            // Without a Looper, we're unable to time how long the
1111            // violation takes place.  This case should be rare, as
1112            // most users will care about timing violations that
1113            // happen on their main UI thread.  Note that this case is
1114            // also hit when a violation takes place in a Binder
1115            // thread, in "gather" mode.  In this case, the duration
1116            // of the violation is computed by the ultimate caller and
1117            // its Looper, if any.
1118            //
1119            // Also, as a special short-cut case when the only penalty
1120            // bit is death, we die immediately, rather than timing
1121            // the violation's duration.  This makes it convenient to
1122            // use in unit tests too, rather than waiting on a Looper.
1123            //
1124            // TODO: if in gather mode, ignore Looper.myLooper() and always
1125            //       go into this immediate mode?
1126            if (looper == null ||
1127                (info.policy & THREAD_PENALTY_MASK) == PENALTY_DEATH) {
1128                info.durationMillis = -1;  // unknown (redundant, already set)
1129                handleViolation(info);
1130                return;
1131            }
1132
1133            final ArrayList<ViolationInfo> records = violationsBeingTimed.get();
1134            if (records.size() >= MAX_OFFENSES_PER_LOOP) {
1135                // Not worth measuring.  Too many offenses in one loop.
1136                return;
1137            }
1138            records.add(info);
1139            if (records.size() > 1) {
1140                // There's already been a violation this loop, so we've already
1141                // registered an idle handler to process the list of violations
1142                // at the end of this Looper's loop.
1143                return;
1144            }
1145
1146            final IWindowManager windowManager = (info.policy & PENALTY_FLASH) != 0 ?
1147                    sWindowManager.get() : null;
1148            if (windowManager != null) {
1149                try {
1150                    windowManager.showStrictModeViolation(true);
1151                } catch (RemoteException unused) {
1152                }
1153            }
1154
1155            // We post a runnable to a Handler (== delay 0 ms) for
1156            // measuring the end time of a violation instead of using
1157            // an IdleHandler (as was previously used) because an
1158            // IdleHandler may not run for quite a long period of time
1159            // if an ongoing animation is happening and continually
1160            // posting ASAP (0 ms) animation steps.  Animations are
1161            // throttled back to 60fps via SurfaceFlinger/View
1162            // invalidates, _not_ by posting frame updates every 16
1163            // milliseconds.
1164            threadHandler.get().post(new Runnable() {
1165                    public void run() {
1166                        long loopFinishTime = SystemClock.uptimeMillis();
1167
1168                        // Note: we do this early, before handling the
1169                        // violation below, as handling the violation
1170                        // may include PENALTY_DEATH and we don't want
1171                        // to keep the red border on.
1172                        if (windowManager != null) {
1173                            try {
1174                                windowManager.showStrictModeViolation(false);
1175                            } catch (RemoteException unused) {
1176                            }
1177                        }
1178
1179                        for (int n = 0; n < records.size(); ++n) {
1180                            ViolationInfo v = records.get(n);
1181                            v.violationNumThisLoop = n + 1;
1182                            v.durationMillis =
1183                                    (int) (loopFinishTime - v.violationUptimeMillis);
1184                            handleViolation(v);
1185                        }
1186                        records.clear();
1187                    }
1188                });
1189        }
1190
1191        // Note: It's possible (even quite likely) that the
1192        // thread-local policy mask has changed from the time the
1193        // violation fired and now (after the violating code ran) due
1194        // to people who push/pop temporary policy in regions of code,
1195        // hence the policy being passed around.
1196        void handleViolation(final ViolationInfo info) {
1197            if (info == null || info.crashInfo == null || info.crashInfo.stackTrace == null) {
1198                Log.wtf(TAG, "unexpected null stacktrace");
1199                return;
1200            }
1201
1202            if (LOG_V) Log.d(TAG, "handleViolation; policy=" + info.policy);
1203
1204            if ((info.policy & PENALTY_GATHER) != 0) {
1205                ArrayList<ViolationInfo> violations = gatheredViolations.get();
1206                if (violations == null) {
1207                    violations = new ArrayList<ViolationInfo>(1);
1208                    gatheredViolations.set(violations);
1209                } else if (violations.size() >= 5) {
1210                    // Too many.  In a loop or something?  Don't gather them all.
1211                    return;
1212                }
1213                for (ViolationInfo previous : violations) {
1214                    if (info.crashInfo.stackTrace.equals(previous.crashInfo.stackTrace)) {
1215                        // Duplicate. Don't log.
1216                        return;
1217                    }
1218                }
1219                violations.add(info);
1220                return;
1221            }
1222
1223            // Not perfect, but fast and good enough for dup suppression.
1224            Integer crashFingerprint = info.hashCode();
1225            long lastViolationTime = 0;
1226            if (mLastViolationTime.containsKey(crashFingerprint)) {
1227                lastViolationTime = mLastViolationTime.get(crashFingerprint);
1228            }
1229            long now = SystemClock.uptimeMillis();
1230            mLastViolationTime.put(crashFingerprint, now);
1231            long timeSinceLastViolationMillis = lastViolationTime == 0 ?
1232                    Long.MAX_VALUE : (now - lastViolationTime);
1233
1234            if ((info.policy & PENALTY_LOG) != 0 &&
1235                timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1236                if (info.durationMillis != -1) {
1237                    Log.d(TAG, "StrictMode policy violation; ~duration=" +
1238                          info.durationMillis + " ms: " + info.crashInfo.stackTrace);
1239                } else {
1240                    Log.d(TAG, "StrictMode policy violation: " + info.crashInfo.stackTrace);
1241                }
1242            }
1243
1244            // The violationMaskSubset, passed to ActivityManager, is a
1245            // subset of the original StrictMode policy bitmask, with
1246            // only the bit violated and penalty bits to be executed
1247            // by the ActivityManagerService remaining set.
1248            int violationMaskSubset = 0;
1249
1250            if ((info.policy & PENALTY_DIALOG) != 0 &&
1251                timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
1252                violationMaskSubset |= PENALTY_DIALOG;
1253            }
1254
1255            if ((info.policy & PENALTY_DROPBOX) != 0 && lastViolationTime == 0) {
1256                violationMaskSubset |= PENALTY_DROPBOX;
1257            }
1258
1259            if (violationMaskSubset != 0) {
1260                int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
1261                violationMaskSubset |= violationBit;
1262                final int savedPolicyMask = getThreadPolicyMask();
1263
1264                final boolean justDropBox = (info.policy & THREAD_PENALTY_MASK) == PENALTY_DROPBOX;
1265                if (justDropBox) {
1266                    // If all we're going to ask the activity manager
1267                    // to do is dropbox it (the common case during
1268                    // platform development), we can avoid doing this
1269                    // call synchronously which Binder data suggests
1270                    // isn't always super fast, despite the implementation
1271                    // in the ActivityManager trying to be mostly async.
1272                    dropboxViolationAsync(violationMaskSubset, info);
1273                    return;
1274                }
1275
1276                // Normal synchronous call to the ActivityManager.
1277                try {
1278                    // First, remove any policy before we call into the Activity Manager,
1279                    // otherwise we'll infinite recurse as we try to log policy violations
1280                    // to disk, thus violating policy, thus requiring logging, etc...
1281                    // We restore the current policy below, in the finally block.
1282                    setThreadPolicyMask(0);
1283
1284                    ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1285                        RuntimeInit.getApplicationObject(),
1286                        violationMaskSubset,
1287                        info);
1288                } catch (RemoteException e) {
1289                    Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1290                } finally {
1291                    // Restore the policy.
1292                    setThreadPolicyMask(savedPolicyMask);
1293                }
1294            }
1295
1296            if ((info.policy & PENALTY_DEATH) != 0) {
1297                executeDeathPenalty(info);
1298            }
1299        }
1300    }
1301
1302    private static void executeDeathPenalty(ViolationInfo info) {
1303        int violationBit = parseViolationFromMessage(info.crashInfo.exceptionMessage);
1304        throw new StrictModeViolation(info.policy, violationBit, null);
1305    }
1306
1307    /**
1308     * In the common case, as set by conditionallyEnableDebugLogging,
1309     * we're just dropboxing any violations but not showing a dialog,
1310     * not loggging, and not killing the process.  In these cases we
1311     * don't need to do a synchronous call to the ActivityManager.
1312     * This is used by both per-thread and vm-wide violations when
1313     * applicable.
1314     */
1315    private static void dropboxViolationAsync(
1316            final int violationMaskSubset, final ViolationInfo info) {
1317        int outstanding = sDropboxCallsInFlight.incrementAndGet();
1318        if (outstanding > 20) {
1319            // What's going on?  Let's not make make the situation
1320            // worse and just not log.
1321            sDropboxCallsInFlight.decrementAndGet();
1322            return;
1323        }
1324
1325        if (LOG_V) Log.d(TAG, "Dropboxing async; in-flight=" + outstanding);
1326
1327        new Thread("callActivityManagerForStrictModeDropbox") {
1328            public void run() {
1329                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1330                try {
1331                    IActivityManager am = ActivityManagerNative.getDefault();
1332                    if (am == null) {
1333                        Log.d(TAG, "No activity manager; failed to Dropbox violation.");
1334                    } else {
1335                        am.handleApplicationStrictModeViolation(
1336                            RuntimeInit.getApplicationObject(),
1337                            violationMaskSubset,
1338                            info);
1339                    }
1340                } catch (RemoteException e) {
1341                    Log.e(TAG, "RemoteException handling StrictMode violation", e);
1342                }
1343                int outstanding = sDropboxCallsInFlight.decrementAndGet();
1344                if (LOG_V) Log.d(TAG, "Dropbox complete; in-flight=" + outstanding);
1345            }
1346        }.start();
1347    }
1348
1349    private static class AndroidCloseGuardReporter implements CloseGuard.Reporter {
1350        public void report (String message, Throwable allocationSite) {
1351            onVmPolicyViolation(message, allocationSite);
1352        }
1353    }
1354
1355    /**
1356     * Called from Parcel.writeNoException()
1357     */
1358    /* package */ static boolean hasGatheredViolations() {
1359        return gatheredViolations.get() != null;
1360    }
1361
1362    /**
1363     * Called from Parcel.writeException(), so we drop this memory and
1364     * don't incorrectly attribute it to the wrong caller on the next
1365     * Binder call on this thread.
1366     */
1367    /* package */ static void clearGatheredViolations() {
1368        gatheredViolations.set(null);
1369    }
1370
1371    /**
1372     * @hide
1373     */
1374    public static void conditionallyCheckInstanceCounts() {
1375        VmPolicy policy = getVmPolicy();
1376        if (policy.classInstanceLimit.size() == 0) {
1377            return;
1378        }
1379        Runtime.getRuntime().gc();
1380        // Note: classInstanceLimit is immutable, so this is lock-free
1381        for (Map.Entry<Class, Integer> entry : policy.classInstanceLimit.entrySet()) {
1382            Class klass = entry.getKey();
1383            int limit = entry.getValue();
1384            long instances = VMDebug.countInstancesOfClass(klass, false);
1385            if (instances <= limit) {
1386                continue;
1387            }
1388            Throwable tr = new InstanceCountViolation(klass, instances, limit);
1389            onVmPolicyViolation(tr.getMessage(), tr);
1390        }
1391    }
1392
1393    private static long sLastInstanceCountCheckMillis = 0;
1394    private static boolean sIsIdlerRegistered = false;  // guarded by StrictMode.class
1395    private static final MessageQueue.IdleHandler sProcessIdleHandler =
1396            new MessageQueue.IdleHandler() {
1397                public boolean queueIdle() {
1398                    long now = SystemClock.uptimeMillis();
1399                    if (now - sLastInstanceCountCheckMillis > 30 * 1000) {
1400                        sLastInstanceCountCheckMillis = now;
1401                        conditionallyCheckInstanceCounts();
1402                    }
1403                    return true;
1404                }
1405            };
1406
1407    /**
1408     * Sets the policy for what actions in the VM process (on any
1409     * thread) should be detected, as well as the penalty if such
1410     * actions occur.
1411     *
1412     * @param policy the policy to put into place
1413     */
1414    public static void setVmPolicy(final VmPolicy policy) {
1415        synchronized (StrictMode.class) {
1416            sVmPolicy = policy;
1417            sVmPolicyMask = policy.mask;
1418            setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
1419
1420            Looper looper = Looper.getMainLooper();
1421            if (looper != null) {
1422                MessageQueue mq = looper.mQueue;
1423                if (policy.classInstanceLimit.size() == 0 ||
1424                    (sVmPolicyMask & VM_PENALTY_MASK) == 0) {
1425                    mq.removeIdleHandler(sProcessIdleHandler);
1426                    sIsIdlerRegistered = false;
1427                } else if (!sIsIdlerRegistered) {
1428                    mq.addIdleHandler(sProcessIdleHandler);
1429                    sIsIdlerRegistered = true;
1430                }
1431            }
1432        }
1433    }
1434
1435    /**
1436     * Gets the current VM policy.
1437     */
1438    public static VmPolicy getVmPolicy() {
1439        synchronized (StrictMode.class) {
1440            return sVmPolicy;
1441        }
1442    }
1443
1444    /**
1445     * Enable the recommended StrictMode defaults, with violations just being logged.
1446     *
1447     * <p>This catches disk and network access on the main thread, as
1448     * well as leaked SQLite cursors and unclosed resources.  This is
1449     * simply a wrapper around {@link #setVmPolicy} and {@link
1450     * #setThreadPolicy}.
1451     */
1452    public static void enableDefaults() {
1453        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
1454                                   .detectAll()
1455                                   .penaltyLog()
1456                                   .build());
1457        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
1458                               .detectAll()
1459                               .penaltyLog()
1460                               .build());
1461    }
1462
1463    /**
1464     * @hide
1465     */
1466    public static boolean vmSqliteObjectLeaksEnabled() {
1467        return (sVmPolicyMask & DETECT_VM_CURSOR_LEAKS) != 0;
1468    }
1469
1470    /**
1471     * @hide
1472     */
1473    public static boolean vmClosableObjectLeaksEnabled() {
1474        return (sVmPolicyMask & DETECT_VM_CLOSABLE_LEAKS) != 0;
1475    }
1476
1477    /**
1478     * @hide
1479     */
1480    public static void onSqliteObjectLeaked(String message, Throwable originStack) {
1481        onVmPolicyViolation(message, originStack);
1482    }
1483
1484    /**
1485     * @hide
1486     */
1487    public static void onWebViewMethodCalledOnWrongThread(Throwable originStack) {
1488        onVmPolicyViolation(null, originStack);
1489    }
1490
1491    // Map from VM violation fingerprint to uptime millis.
1492    private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<Integer, Long>();
1493
1494    /**
1495     * @hide
1496     */
1497    public static void onVmPolicyViolation(String message, Throwable originStack) {
1498        final boolean penaltyDropbox = (sVmPolicyMask & PENALTY_DROPBOX) != 0;
1499        final boolean penaltyDeath = (sVmPolicyMask & PENALTY_DEATH) != 0;
1500        final boolean penaltyLog = (sVmPolicyMask & PENALTY_LOG) != 0;
1501        final ViolationInfo info = new ViolationInfo(originStack, sVmPolicyMask);
1502
1503        // Erase stuff not relevant for process-wide violations
1504        info.numAnimationsRunning = 0;
1505        info.tags = null;
1506        info.broadcastIntentAction = null;
1507
1508        final Integer fingerprint = info.hashCode();
1509        final long now = SystemClock.uptimeMillis();
1510        long lastViolationTime = 0;
1511        long timeSinceLastViolationMillis = Long.MAX_VALUE;
1512        synchronized (sLastVmViolationTime) {
1513            if (sLastVmViolationTime.containsKey(fingerprint)) {
1514                lastViolationTime = sLastVmViolationTime.get(fingerprint);
1515                timeSinceLastViolationMillis = now - lastViolationTime;
1516            }
1517            if (timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1518                sLastVmViolationTime.put(fingerprint, now);
1519            }
1520        }
1521
1522        if (penaltyLog && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1523            Log.e(TAG, message, originStack);
1524        }
1525
1526        int violationMaskSubset = PENALTY_DROPBOX | (ALL_VM_DETECT_BITS & sVmPolicyMask);
1527
1528        if (penaltyDropbox && !penaltyDeath) {
1529            // Common case for userdebug/eng builds.  If no death and
1530            // just dropboxing, we can do the ActivityManager call
1531            // asynchronously.
1532            dropboxViolationAsync(violationMaskSubset, info);
1533            return;
1534        }
1535
1536        if (penaltyDropbox && lastViolationTime == 0) {
1537            // The violationMask, passed to ActivityManager, is a
1538            // subset of the original StrictMode policy bitmask, with
1539            // only the bit violated and penalty bits to be executed
1540            // by the ActivityManagerService remaining set.
1541            final int savedPolicyMask = getThreadPolicyMask();
1542            try {
1543                // First, remove any policy before we call into the Activity Manager,
1544                // otherwise we'll infinite recurse as we try to log policy violations
1545                // to disk, thus violating policy, thus requiring logging, etc...
1546                // We restore the current policy below, in the finally block.
1547                setThreadPolicyMask(0);
1548
1549                ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1550                    RuntimeInit.getApplicationObject(),
1551                    violationMaskSubset,
1552                    info);
1553            } catch (RemoteException e) {
1554                Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1555            } finally {
1556                // Restore the policy.
1557                setThreadPolicyMask(savedPolicyMask);
1558            }
1559        }
1560
1561        if (penaltyDeath) {
1562            System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
1563            Process.killProcess(Process.myPid());
1564            System.exit(10);
1565        }
1566    }
1567
1568    /**
1569     * Called from Parcel.writeNoException()
1570     */
1571    /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
1572        ArrayList<ViolationInfo> violations = gatheredViolations.get();
1573        if (violations == null) {
1574            p.writeInt(0);
1575        } else {
1576            p.writeInt(violations.size());
1577            for (int i = 0; i < violations.size(); ++i) {
1578                violations.get(i).writeToParcel(p, 0 /* unused flags? */);
1579            }
1580            if (LOG_V) Log.d(TAG, "wrote violations to response parcel; num=" + violations.size());
1581            violations.clear(); // somewhat redundant, as we're about to null the threadlocal
1582        }
1583        gatheredViolations.set(null);
1584    }
1585
1586    private static class LogStackTrace extends Exception {}
1587
1588    /**
1589     * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS,
1590     * we here read back all the encoded violations.
1591     */
1592    /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
1593        // Our own stack trace to append
1594        StringWriter sw = new StringWriter();
1595        new LogStackTrace().printStackTrace(new PrintWriter(sw));
1596        String ourStack = sw.toString();
1597
1598        int policyMask = getThreadPolicyMask();
1599        boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
1600
1601        int numViolations = p.readInt();
1602        for (int i = 0; i < numViolations; ++i) {
1603            if (LOG_V) Log.d(TAG, "strict mode violation stacks read from binder call.  i=" + i);
1604            ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
1605            info.crashInfo.stackTrace += "# via Binder call with stack:\n" + ourStack;
1606            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1607            if (policy instanceof AndroidBlockGuardPolicy) {
1608                ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
1609            }
1610        }
1611    }
1612
1613    /**
1614     * Called from android_util_Binder.cpp's
1615     * android_os_Parcel_enforceInterface when an incoming Binder call
1616     * requires changing the StrictMode policy mask.  The role of this
1617     * function is to ask Binder for its current (native) thread-local
1618     * policy value and synchronize it to libcore's (Java)
1619     * thread-local policy value.
1620     */
1621    private static void onBinderStrictModePolicyChange(int newPolicy) {
1622        setBlockGuardPolicy(newPolicy);
1623    }
1624
1625    /**
1626     * A tracked, critical time span.  (e.g. during an animation.)
1627     *
1628     * The object itself is a linked list node, to avoid any allocations
1629     * during rapid span entries and exits.
1630     *
1631     * @hide
1632     */
1633    public static class Span {
1634        private String mName;
1635        private long mCreateMillis;
1636        private Span mNext;
1637        private Span mPrev;  // not used when in freeList, only active
1638        private final ThreadSpanState mContainerState;
1639
1640        Span(ThreadSpanState threadState) {
1641            mContainerState = threadState;
1642        }
1643
1644        // Empty constructor for the NO_OP_SPAN
1645        protected Span() {
1646            mContainerState = null;
1647        }
1648
1649        /**
1650         * To be called when the critical span is complete (i.e. the
1651         * animation is done animating).  This can be called on any
1652         * thread (even a different one from where the animation was
1653         * taking place), but that's only a defensive implementation
1654         * measure.  It really makes no sense for you to call this on
1655         * thread other than that where you created it.
1656         *
1657         * @hide
1658         */
1659        public void finish() {
1660            ThreadSpanState state = mContainerState;
1661            synchronized (state) {
1662                if (mName == null) {
1663                    // Duplicate finish call.  Ignore.
1664                    return;
1665                }
1666
1667                // Remove ourselves from the active list.
1668                if (mPrev != null) {
1669                    mPrev.mNext = mNext;
1670                }
1671                if (mNext != null) {
1672                    mNext.mPrev = mPrev;
1673                }
1674                if (state.mActiveHead == this) {
1675                    state.mActiveHead = mNext;
1676                }
1677
1678                state.mActiveSize--;
1679
1680                if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
1681
1682                this.mCreateMillis = -1;
1683                this.mName = null;
1684                this.mPrev = null;
1685                this.mNext = null;
1686
1687                // Add ourselves to the freeList, if it's not already
1688                // too big.
1689                if (state.mFreeListSize < 5) {
1690                    this.mNext = state.mFreeListHead;
1691                    state.mFreeListHead = this;
1692                    state.mFreeListSize++;
1693                }
1694            }
1695        }
1696    }
1697
1698    // The no-op span that's used in user builds.
1699    private static final Span NO_OP_SPAN = new Span() {
1700            public void finish() {
1701                // Do nothing.
1702            }
1703        };
1704
1705    /**
1706     * Linked lists of active spans and a freelist.
1707     *
1708     * Locking notes: there's one of these structures per thread and
1709     * all members of this structure (as well as the Span nodes under
1710     * it) are guarded by the ThreadSpanState object instance.  While
1711     * in theory there'd be no locking required because it's all local
1712     * per-thread, the finish() method above is defensive against
1713     * people calling it on a different thread from where they created
1714     * the Span, hence the locking.
1715     */
1716    private static class ThreadSpanState {
1717        public Span mActiveHead;    // doubly-linked list.
1718        public int mActiveSize;
1719        public Span mFreeListHead;  // singly-linked list.  only changes at head.
1720        public int mFreeListSize;
1721    }
1722
1723    private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
1724            new ThreadLocal<ThreadSpanState>() {
1725        @Override protected ThreadSpanState initialValue() {
1726            return new ThreadSpanState();
1727        }
1728    };
1729
1730    private static Singleton<IWindowManager> sWindowManager = new Singleton<IWindowManager>() {
1731        protected IWindowManager create() {
1732            return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
1733        }
1734    };
1735
1736    /**
1737     * Enter a named critical span (e.g. an animation)
1738     *
1739     * <p>The name is an arbitary label (or tag) that will be applied
1740     * to any strictmode violation that happens while this span is
1741     * active.  You must call finish() on the span when done.
1742     *
1743     * <p>This will never return null, but on devices without debugging
1744     * enabled, this may return a dummy object on which the finish()
1745     * method is a no-op.
1746     *
1747     * <p>TODO: add CloseGuard to this, verifying callers call finish.
1748     *
1749     * @hide
1750     */
1751    public static Span enterCriticalSpan(String name) {
1752        if (IS_USER_BUILD) {
1753            return NO_OP_SPAN;
1754        }
1755        if (name == null || name.isEmpty()) {
1756            throw new IllegalArgumentException("name must be non-null and non-empty");
1757        }
1758        ThreadSpanState state = sThisThreadSpanState.get();
1759        Span span = null;
1760        synchronized (state) {
1761            if (state.mFreeListHead != null) {
1762                span = state.mFreeListHead;
1763                state.mFreeListHead = span.mNext;
1764                state.mFreeListSize--;
1765            } else {
1766                // Shouldn't have to do this often.
1767                span = new Span(state);
1768            }
1769            span.mName = name;
1770            span.mCreateMillis = SystemClock.uptimeMillis();
1771            span.mNext = state.mActiveHead;
1772            span.mPrev = null;
1773            state.mActiveHead = span;
1774            state.mActiveSize++;
1775            if (span.mNext != null) {
1776                span.mNext.mPrev = span;
1777            }
1778            if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
1779        }
1780        return span;
1781    }
1782
1783    /**
1784     * For code to note that it's slow.  This is a no-op unless the
1785     * current thread's {@link android.os.StrictMode.ThreadPolicy} has
1786     * {@link android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls}
1787     * enabled.
1788     *
1789     * @param name a short string for the exception stack trace that's
1790     *             built if when this fires.
1791     */
1792    public static void noteSlowCall(String name) {
1793        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1794        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1795            // StrictMode not enabled.
1796            return;
1797        }
1798        ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
1799    }
1800
1801    /**
1802     * @hide
1803     */
1804    public static void noteDiskRead() {
1805        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1806        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1807            // StrictMode not enabled.
1808            return;
1809        }
1810        ((AndroidBlockGuardPolicy) policy).onReadFromDisk();
1811    }
1812
1813    /**
1814     * @hide
1815     */
1816    public static void noteDiskWrite() {
1817        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1818        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1819            // StrictMode not enabled.
1820            return;
1821        }
1822        ((AndroidBlockGuardPolicy) policy).onWriteToDisk();
1823    }
1824
1825    // Guarded by StrictMode.class
1826    private static final HashMap<Class, Integer> sExpectedActivityInstanceCount =
1827            new HashMap<Class, Integer>();
1828
1829    /**
1830     * @hide
1831     */
1832    public static void incrementExpectedActivityCount(Class klass) {
1833        if (klass == null || (sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
1834            return;
1835        }
1836        synchronized (StrictMode.class) {
1837            Integer expected = sExpectedActivityInstanceCount.get(klass);
1838            Integer newExpected = expected == null ? 1 : expected + 1;
1839            sExpectedActivityInstanceCount.put(klass, newExpected);
1840            // Note: adding 1 here to give some breathing room during
1841            // orientation changes.  (shouldn't be necessary, though?)
1842            setExpectedClassInstanceCount(klass, newExpected + 1);
1843        }
1844    }
1845
1846    /**
1847     * @hide
1848     */
1849    public static void decrementExpectedActivityCount(Class klass) {
1850        if (klass == null || (sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
1851            return;
1852        }
1853        synchronized (StrictMode.class) {
1854            Integer expected = sExpectedActivityInstanceCount.get(klass);
1855            Integer newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
1856            if (newExpected == 0) {
1857                sExpectedActivityInstanceCount.remove(klass);
1858            } else {
1859                sExpectedActivityInstanceCount.put(klass, newExpected);
1860            }
1861            // Note: adding 1 here to give some breathing room during
1862            // orientation changes.  (shouldn't be necessary, though?)
1863            setExpectedClassInstanceCount(klass, newExpected + 1);
1864        }
1865    }
1866
1867    /**
1868     * @hide
1869     */
1870    public static void setExpectedClassInstanceCount(Class klass, int count) {
1871        synchronized (StrictMode.class) {
1872            setVmPolicy(new VmPolicy.Builder(sVmPolicy)
1873                        .setClassInstanceLimit(klass, count)
1874                        .build());
1875        }
1876    }
1877
1878    /**
1879     * Parcelable that gets sent in Binder call headers back to callers
1880     * to report violations that happened during a cross-process call.
1881     *
1882     * @hide
1883     */
1884    public static class ViolationInfo {
1885        /**
1886         * Stack and other stuff info.
1887         */
1888        public final ApplicationErrorReport.CrashInfo crashInfo;
1889
1890        /**
1891         * The strict mode policy mask at the time of violation.
1892         */
1893        public final int policy;
1894
1895        /**
1896         * The wall time duration of the violation, when known.  -1 when
1897         * not known.
1898         */
1899        public int durationMillis = -1;
1900
1901        /**
1902         * The number of animations currently running.
1903         */
1904        public int numAnimationsRunning = 0;
1905
1906        /**
1907         * List of tags from active Span instances during this
1908         * violation, or null for none.
1909         */
1910        public String[] tags;
1911
1912        /**
1913         * Which violation number this was (1-based) since the last Looper loop,
1914         * from the perspective of the root caller (if it crossed any processes
1915         * via Binder calls).  The value is 0 if the root caller wasn't on a Looper
1916         * thread.
1917         */
1918        public int violationNumThisLoop;
1919
1920        /**
1921         * The time (in terms of SystemClock.uptimeMillis()) that the
1922         * violation occurred.
1923         */
1924        public long violationUptimeMillis;
1925
1926        /**
1927         * The action of the Intent being broadcast to somebody's onReceive
1928         * on this thread right now, or null.
1929         */
1930        public String broadcastIntentAction;
1931
1932        /**
1933         * If this is a instance count violation, the number of instances in memory,
1934         * else -1.
1935         */
1936        public long numInstances = -1;
1937
1938        /**
1939         * Create an uninitialized instance of ViolationInfo
1940         */
1941        public ViolationInfo() {
1942            crashInfo = null;
1943            policy = 0;
1944        }
1945
1946        /**
1947         * Create an instance of ViolationInfo initialized from an exception.
1948         */
1949        public ViolationInfo(Throwable tr, int policy) {
1950            crashInfo = new ApplicationErrorReport.CrashInfo(tr);
1951            violationUptimeMillis = SystemClock.uptimeMillis();
1952            this.policy = policy;
1953            this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
1954            Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
1955            if (broadcastIntent != null) {
1956                broadcastIntentAction = broadcastIntent.getAction();
1957            }
1958            ThreadSpanState state = sThisThreadSpanState.get();
1959            if (tr instanceof InstanceCountViolation) {
1960                this.numInstances = ((InstanceCountViolation) tr).mInstances;
1961            }
1962            synchronized (state) {
1963                int spanActiveCount = state.mActiveSize;
1964                if (spanActiveCount > MAX_SPAN_TAGS) {
1965                    spanActiveCount = MAX_SPAN_TAGS;
1966                }
1967                if (spanActiveCount != 0) {
1968                    this.tags = new String[spanActiveCount];
1969                    Span iter = state.mActiveHead;
1970                    int index = 0;
1971                    while (iter != null && index < spanActiveCount) {
1972                        this.tags[index] = iter.mName;
1973                        index++;
1974                        iter = iter.mNext;
1975                    }
1976                }
1977            }
1978        }
1979
1980        @Override
1981        public int hashCode() {
1982            int result = 17;
1983            result = 37 * result + crashInfo.stackTrace.hashCode();
1984            if (numAnimationsRunning != 0) {
1985                result *= 37;
1986            }
1987            if (broadcastIntentAction != null) {
1988                result = 37 * result + broadcastIntentAction.hashCode();
1989            }
1990            if (tags != null) {
1991                for (String tag : tags) {
1992                    result = 37 * result + tag.hashCode();
1993                }
1994            }
1995            return result;
1996        }
1997
1998        /**
1999         * Create an instance of ViolationInfo initialized from a Parcel.
2000         */
2001        public ViolationInfo(Parcel in) {
2002            this(in, false);
2003        }
2004
2005        /**
2006         * Create an instance of ViolationInfo initialized from a Parcel.
2007         *
2008         * @param unsetGatheringBit if true, the caller is the root caller
2009         *   and the gathering penalty should be removed.
2010         */
2011        public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
2012            crashInfo = new ApplicationErrorReport.CrashInfo(in);
2013            int rawPolicy = in.readInt();
2014            if (unsetGatheringBit) {
2015                policy = rawPolicy & ~PENALTY_GATHER;
2016            } else {
2017                policy = rawPolicy;
2018            }
2019            durationMillis = in.readInt();
2020            violationNumThisLoop = in.readInt();
2021            numAnimationsRunning = in.readInt();
2022            violationUptimeMillis = in.readLong();
2023            numInstances = in.readLong();
2024            broadcastIntentAction = in.readString();
2025            tags = in.readStringArray();
2026        }
2027
2028        /**
2029         * Save a ViolationInfo instance to a parcel.
2030         */
2031        public void writeToParcel(Parcel dest, int flags) {
2032            crashInfo.writeToParcel(dest, flags);
2033            dest.writeInt(policy);
2034            dest.writeInt(durationMillis);
2035            dest.writeInt(violationNumThisLoop);
2036            dest.writeInt(numAnimationsRunning);
2037            dest.writeLong(violationUptimeMillis);
2038            dest.writeLong(numInstances);
2039            dest.writeString(broadcastIntentAction);
2040            dest.writeStringArray(tags);
2041        }
2042
2043
2044        /**
2045         * Dump a ViolationInfo instance to a Printer.
2046         */
2047        public void dump(Printer pw, String prefix) {
2048            crashInfo.dump(pw, prefix);
2049            pw.println(prefix + "policy: " + policy);
2050            if (durationMillis != -1) {
2051                pw.println(prefix + "durationMillis: " + durationMillis);
2052            }
2053            if (numInstances != -1) {
2054                pw.println(prefix + "numInstances: " + numInstances);
2055            }
2056            if (violationNumThisLoop != 0) {
2057                pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
2058            }
2059            if (numAnimationsRunning != 0) {
2060                pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
2061            }
2062            pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
2063            if (broadcastIntentAction != null) {
2064                pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
2065            }
2066            if (tags != null) {
2067                int index = 0;
2068                for (String tag : tags) {
2069                    pw.println(prefix + "tag[" + (index++) + "]: " + tag);
2070                }
2071            }
2072        }
2073
2074    }
2075
2076    // Dummy throwable, for now, since we don't know when or where the
2077    // leaked instances came from.  We might in the future, but for
2078    // now we suppress the stack trace because it's useless and/or
2079    // misleading.
2080    private static class InstanceCountViolation extends Throwable {
2081        final Class mClass;
2082        final long mInstances;
2083        final int mLimit;
2084
2085        private static final StackTraceElement[] FAKE_STACK = {
2086            new StackTraceElement("android.os.StrictMode", "setClassInstanceLimit",
2087                                  "StrictMode.java", 1)
2088        };
2089
2090        public InstanceCountViolation(Class klass, long instances, int limit) {
2091            super(klass.toString() + "; instances=" + instances + "; limit=" + limit);
2092            setStackTrace(FAKE_STACK);
2093            mClass = klass;
2094            mInstances = instances;
2095            mLimit = limit;
2096        }
2097    }
2098}
2099