StrictMode.java revision c0bb0bb5e3425b77b6e7820ebe25fe72bdd07782
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    // Map from VM violation fingerprint to uptime millis.
1485    private static final HashMap<Integer, Long> sLastVmViolationTime = new HashMap<Integer, Long>();
1486
1487    /**
1488     * @hide
1489     */
1490    public static void onVmPolicyViolation(String message, Throwable originStack) {
1491        final boolean penaltyDropbox = (sVmPolicyMask & PENALTY_DROPBOX) != 0;
1492        final boolean penaltyDeath = (sVmPolicyMask & PENALTY_DEATH) != 0;
1493        final boolean penaltyLog = (sVmPolicyMask & PENALTY_LOG) != 0;
1494        final ViolationInfo info = new ViolationInfo(originStack, sVmPolicyMask);
1495
1496        // Erase stuff not relevant for process-wide violations
1497        info.numAnimationsRunning = 0;
1498        info.tags = null;
1499        info.broadcastIntentAction = null;
1500
1501        final Integer fingerprint = info.hashCode();
1502        final long now = SystemClock.uptimeMillis();
1503        long lastViolationTime = 0;
1504        long timeSinceLastViolationMillis = Long.MAX_VALUE;
1505        synchronized (sLastVmViolationTime) {
1506            if (sLastVmViolationTime.containsKey(fingerprint)) {
1507                lastViolationTime = sLastVmViolationTime.get(fingerprint);
1508                timeSinceLastViolationMillis = now - lastViolationTime;
1509            }
1510            if (timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1511                sLastVmViolationTime.put(fingerprint, now);
1512            }
1513        }
1514
1515        if (penaltyLog && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
1516            Log.e(TAG, message, originStack);
1517        }
1518
1519        int violationMaskSubset = PENALTY_DROPBOX | (ALL_VM_DETECT_BITS & sVmPolicyMask);
1520
1521        if (penaltyDropbox && !penaltyDeath) {
1522            // Common case for userdebug/eng builds.  If no death and
1523            // just dropboxing, we can do the ActivityManager call
1524            // asynchronously.
1525            dropboxViolationAsync(violationMaskSubset, info);
1526            return;
1527        }
1528
1529        if (penaltyDropbox && lastViolationTime == 0) {
1530            // The violationMask, passed to ActivityManager, is a
1531            // subset of the original StrictMode policy bitmask, with
1532            // only the bit violated and penalty bits to be executed
1533            // by the ActivityManagerService remaining set.
1534            final int savedPolicyMask = getThreadPolicyMask();
1535            try {
1536                // First, remove any policy before we call into the Activity Manager,
1537                // otherwise we'll infinite recurse as we try to log policy violations
1538                // to disk, thus violating policy, thus requiring logging, etc...
1539                // We restore the current policy below, in the finally block.
1540                setThreadPolicyMask(0);
1541
1542                ActivityManagerNative.getDefault().handleApplicationStrictModeViolation(
1543                    RuntimeInit.getApplicationObject(),
1544                    violationMaskSubset,
1545                    info);
1546            } catch (RemoteException e) {
1547                Log.e(TAG, "RemoteException trying to handle StrictMode violation", e);
1548            } finally {
1549                // Restore the policy.
1550                setThreadPolicyMask(savedPolicyMask);
1551            }
1552        }
1553
1554        if (penaltyDeath) {
1555            System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
1556            Process.killProcess(Process.myPid());
1557            System.exit(10);
1558        }
1559    }
1560
1561    /**
1562     * Called from Parcel.writeNoException()
1563     */
1564    /* package */ static void writeGatheredViolationsToParcel(Parcel p) {
1565        ArrayList<ViolationInfo> violations = gatheredViolations.get();
1566        if (violations == null) {
1567            p.writeInt(0);
1568        } else {
1569            p.writeInt(violations.size());
1570            for (int i = 0; i < violations.size(); ++i) {
1571                violations.get(i).writeToParcel(p, 0 /* unused flags? */);
1572            }
1573            if (LOG_V) Log.d(TAG, "wrote violations to response parcel; num=" + violations.size());
1574            violations.clear(); // somewhat redundant, as we're about to null the threadlocal
1575        }
1576        gatheredViolations.set(null);
1577    }
1578
1579    private static class LogStackTrace extends Exception {}
1580
1581    /**
1582     * Called from Parcel.readException() when the exception is EX_STRICT_MODE_VIOLATIONS,
1583     * we here read back all the encoded violations.
1584     */
1585    /* package */ static void readAndHandleBinderCallViolations(Parcel p) {
1586        // Our own stack trace to append
1587        StringWriter sw = new StringWriter();
1588        new LogStackTrace().printStackTrace(new PrintWriter(sw));
1589        String ourStack = sw.toString();
1590
1591        int policyMask = getThreadPolicyMask();
1592        boolean currentlyGathering = (policyMask & PENALTY_GATHER) != 0;
1593
1594        int numViolations = p.readInt();
1595        for (int i = 0; i < numViolations; ++i) {
1596            if (LOG_V) Log.d(TAG, "strict mode violation stacks read from binder call.  i=" + i);
1597            ViolationInfo info = new ViolationInfo(p, !currentlyGathering);
1598            info.crashInfo.stackTrace += "# via Binder call with stack:\n" + ourStack;
1599            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1600            if (policy instanceof AndroidBlockGuardPolicy) {
1601                ((AndroidBlockGuardPolicy) policy).handleViolationWithTimingAttempt(info);
1602            }
1603        }
1604    }
1605
1606    /**
1607     * Called from android_util_Binder.cpp's
1608     * android_os_Parcel_enforceInterface when an incoming Binder call
1609     * requires changing the StrictMode policy mask.  The role of this
1610     * function is to ask Binder for its current (native) thread-local
1611     * policy value and synchronize it to libcore's (Java)
1612     * thread-local policy value.
1613     */
1614    private static void onBinderStrictModePolicyChange(int newPolicy) {
1615        setBlockGuardPolicy(newPolicy);
1616    }
1617
1618    /**
1619     * A tracked, critical time span.  (e.g. during an animation.)
1620     *
1621     * The object itself is a linked list node, to avoid any allocations
1622     * during rapid span entries and exits.
1623     *
1624     * @hide
1625     */
1626    public static class Span {
1627        private String mName;
1628        private long mCreateMillis;
1629        private Span mNext;
1630        private Span mPrev;  // not used when in freeList, only active
1631        private final ThreadSpanState mContainerState;
1632
1633        Span(ThreadSpanState threadState) {
1634            mContainerState = threadState;
1635        }
1636
1637        // Empty constructor for the NO_OP_SPAN
1638        protected Span() {
1639            mContainerState = null;
1640        }
1641
1642        /**
1643         * To be called when the critical span is complete (i.e. the
1644         * animation is done animating).  This can be called on any
1645         * thread (even a different one from where the animation was
1646         * taking place), but that's only a defensive implementation
1647         * measure.  It really makes no sense for you to call this on
1648         * thread other than that where you created it.
1649         *
1650         * @hide
1651         */
1652        public void finish() {
1653            ThreadSpanState state = mContainerState;
1654            synchronized (state) {
1655                if (mName == null) {
1656                    // Duplicate finish call.  Ignore.
1657                    return;
1658                }
1659
1660                // Remove ourselves from the active list.
1661                if (mPrev != null) {
1662                    mPrev.mNext = mNext;
1663                }
1664                if (mNext != null) {
1665                    mNext.mPrev = mPrev;
1666                }
1667                if (state.mActiveHead == this) {
1668                    state.mActiveHead = mNext;
1669                }
1670
1671                state.mActiveSize--;
1672
1673                if (LOG_V) Log.d(TAG, "Span finished=" + mName + "; size=" + state.mActiveSize);
1674
1675                this.mCreateMillis = -1;
1676                this.mName = null;
1677                this.mPrev = null;
1678                this.mNext = null;
1679
1680                // Add ourselves to the freeList, if it's not already
1681                // too big.
1682                if (state.mFreeListSize < 5) {
1683                    this.mNext = state.mFreeListHead;
1684                    state.mFreeListHead = this;
1685                    state.mFreeListSize++;
1686                }
1687            }
1688        }
1689    }
1690
1691    // The no-op span that's used in user builds.
1692    private static final Span NO_OP_SPAN = new Span() {
1693            public void finish() {
1694                // Do nothing.
1695            }
1696        };
1697
1698    /**
1699     * Linked lists of active spans and a freelist.
1700     *
1701     * Locking notes: there's one of these structures per thread and
1702     * all members of this structure (as well as the Span nodes under
1703     * it) are guarded by the ThreadSpanState object instance.  While
1704     * in theory there'd be no locking required because it's all local
1705     * per-thread, the finish() method above is defensive against
1706     * people calling it on a different thread from where they created
1707     * the Span, hence the locking.
1708     */
1709    private static class ThreadSpanState {
1710        public Span mActiveHead;    // doubly-linked list.
1711        public int mActiveSize;
1712        public Span mFreeListHead;  // singly-linked list.  only changes at head.
1713        public int mFreeListSize;
1714    }
1715
1716    private static final ThreadLocal<ThreadSpanState> sThisThreadSpanState =
1717            new ThreadLocal<ThreadSpanState>() {
1718        @Override protected ThreadSpanState initialValue() {
1719            return new ThreadSpanState();
1720        }
1721    };
1722
1723    private static Singleton<IWindowManager> sWindowManager = new Singleton<IWindowManager>() {
1724        protected IWindowManager create() {
1725            return IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
1726        }
1727    };
1728
1729    /**
1730     * Enter a named critical span (e.g. an animation)
1731     *
1732     * <p>The name is an arbitary label (or tag) that will be applied
1733     * to any strictmode violation that happens while this span is
1734     * active.  You must call finish() on the span when done.
1735     *
1736     * <p>This will never return null, but on devices without debugging
1737     * enabled, this may return a dummy object on which the finish()
1738     * method is a no-op.
1739     *
1740     * <p>TODO: add CloseGuard to this, verifying callers call finish.
1741     *
1742     * @hide
1743     */
1744    public static Span enterCriticalSpan(String name) {
1745        if (IS_USER_BUILD) {
1746            return NO_OP_SPAN;
1747        }
1748        if (name == null || name.isEmpty()) {
1749            throw new IllegalArgumentException("name must be non-null and non-empty");
1750        }
1751        ThreadSpanState state = sThisThreadSpanState.get();
1752        Span span = null;
1753        synchronized (state) {
1754            if (state.mFreeListHead != null) {
1755                span = state.mFreeListHead;
1756                state.mFreeListHead = span.mNext;
1757                state.mFreeListSize--;
1758            } else {
1759                // Shouldn't have to do this often.
1760                span = new Span(state);
1761            }
1762            span.mName = name;
1763            span.mCreateMillis = SystemClock.uptimeMillis();
1764            span.mNext = state.mActiveHead;
1765            span.mPrev = null;
1766            state.mActiveHead = span;
1767            state.mActiveSize++;
1768            if (span.mNext != null) {
1769                span.mNext.mPrev = span;
1770            }
1771            if (LOG_V) Log.d(TAG, "Span enter=" + name + "; size=" + state.mActiveSize);
1772        }
1773        return span;
1774    }
1775
1776    /**
1777     * For code to note that it's slow.  This is a no-op unless the
1778     * current thread's {@link android.os.StrictMode.ThreadPolicy} has
1779     * {@link android.os.StrictMode.ThreadPolicy.Builder#detectCustomSlowCalls}
1780     * enabled.
1781     *
1782     * @param name a short string for the exception stack trace that's
1783     *             built if when this fires.
1784     */
1785    public static void noteSlowCall(String name) {
1786        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1787        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1788            // StrictMode not enabled.
1789            return;
1790        }
1791        ((AndroidBlockGuardPolicy) policy).onCustomSlowCall(name);
1792    }
1793
1794    /**
1795     * @hide
1796     */
1797    public static void noteDiskRead() {
1798        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1799        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1800            // StrictMode not enabled.
1801            return;
1802        }
1803        ((AndroidBlockGuardPolicy) policy).onReadFromDisk();
1804    }
1805
1806    /**
1807     * @hide
1808     */
1809    public static void noteDiskWrite() {
1810        BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
1811        if (!(policy instanceof AndroidBlockGuardPolicy)) {
1812            // StrictMode not enabled.
1813            return;
1814        }
1815        ((AndroidBlockGuardPolicy) policy).onWriteToDisk();
1816    }
1817
1818    // Guarded by StrictMode.class
1819    private static final HashMap<Class, Integer> sExpectedActivityInstanceCount =
1820            new HashMap<Class, Integer>();
1821
1822    /**
1823     * @hide
1824     */
1825    public static void incrementExpectedActivityCount(Class klass) {
1826        if (klass == null || (sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
1827            return;
1828        }
1829        synchronized (StrictMode.class) {
1830            Integer expected = sExpectedActivityInstanceCount.get(klass);
1831            Integer newExpected = expected == null ? 1 : expected + 1;
1832            sExpectedActivityInstanceCount.put(klass, newExpected);
1833            // Note: adding 1 here to give some breathing room during
1834            // orientation changes.  (shouldn't be necessary, though?)
1835            setExpectedClassInstanceCount(klass, newExpected + 1);
1836        }
1837    }
1838
1839    /**
1840     * @hide
1841     */
1842    public static void decrementExpectedActivityCount(Class klass) {
1843        if (klass == null || (sVmPolicy.mask & DETECT_VM_ACTIVITY_LEAKS) == 0) {
1844            return;
1845        }
1846        synchronized (StrictMode.class) {
1847            Integer expected = sExpectedActivityInstanceCount.get(klass);
1848            Integer newExpected = (expected == null || expected == 0) ? 0 : expected - 1;
1849            if (newExpected == 0) {
1850                sExpectedActivityInstanceCount.remove(klass);
1851            } else {
1852                sExpectedActivityInstanceCount.put(klass, newExpected);
1853            }
1854            // Note: adding 1 here to give some breathing room during
1855            // orientation changes.  (shouldn't be necessary, though?)
1856            setExpectedClassInstanceCount(klass, newExpected + 1);
1857        }
1858    }
1859
1860    /**
1861     * @hide
1862     */
1863    public static void setExpectedClassInstanceCount(Class klass, int count) {
1864        synchronized (StrictMode.class) {
1865            setVmPolicy(new VmPolicy.Builder(sVmPolicy)
1866                        .setClassInstanceLimit(klass, count)
1867                        .build());
1868        }
1869    }
1870
1871    /**
1872     * Parcelable that gets sent in Binder call headers back to callers
1873     * to report violations that happened during a cross-process call.
1874     *
1875     * @hide
1876     */
1877    public static class ViolationInfo {
1878        /**
1879         * Stack and other stuff info.
1880         */
1881        public final ApplicationErrorReport.CrashInfo crashInfo;
1882
1883        /**
1884         * The strict mode policy mask at the time of violation.
1885         */
1886        public final int policy;
1887
1888        /**
1889         * The wall time duration of the violation, when known.  -1 when
1890         * not known.
1891         */
1892        public int durationMillis = -1;
1893
1894        /**
1895         * The number of animations currently running.
1896         */
1897        public int numAnimationsRunning = 0;
1898
1899        /**
1900         * List of tags from active Span instances during this
1901         * violation, or null for none.
1902         */
1903        public String[] tags;
1904
1905        /**
1906         * Which violation number this was (1-based) since the last Looper loop,
1907         * from the perspective of the root caller (if it crossed any processes
1908         * via Binder calls).  The value is 0 if the root caller wasn't on a Looper
1909         * thread.
1910         */
1911        public int violationNumThisLoop;
1912
1913        /**
1914         * The time (in terms of SystemClock.uptimeMillis()) that the
1915         * violation occurred.
1916         */
1917        public long violationUptimeMillis;
1918
1919        /**
1920         * The action of the Intent being broadcast to somebody's onReceive
1921         * on this thread right now, or null.
1922         */
1923        public String broadcastIntentAction;
1924
1925        /**
1926         * If this is a instance count violation, the number of instances in memory,
1927         * else -1.
1928         */
1929        public long numInstances = -1;
1930
1931        /**
1932         * Create an uninitialized instance of ViolationInfo
1933         */
1934        public ViolationInfo() {
1935            crashInfo = null;
1936            policy = 0;
1937        }
1938
1939        /**
1940         * Create an instance of ViolationInfo initialized from an exception.
1941         */
1942        public ViolationInfo(Throwable tr, int policy) {
1943            crashInfo = new ApplicationErrorReport.CrashInfo(tr);
1944            violationUptimeMillis = SystemClock.uptimeMillis();
1945            this.policy = policy;
1946            this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
1947            Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
1948            if (broadcastIntent != null) {
1949                broadcastIntentAction = broadcastIntent.getAction();
1950            }
1951            ThreadSpanState state = sThisThreadSpanState.get();
1952            if (tr instanceof InstanceCountViolation) {
1953                this.numInstances = ((InstanceCountViolation) tr).mInstances;
1954            }
1955            synchronized (state) {
1956                int spanActiveCount = state.mActiveSize;
1957                if (spanActiveCount > MAX_SPAN_TAGS) {
1958                    spanActiveCount = MAX_SPAN_TAGS;
1959                }
1960                if (spanActiveCount != 0) {
1961                    this.tags = new String[spanActiveCount];
1962                    Span iter = state.mActiveHead;
1963                    int index = 0;
1964                    while (iter != null && index < spanActiveCount) {
1965                        this.tags[index] = iter.mName;
1966                        index++;
1967                        iter = iter.mNext;
1968                    }
1969                }
1970            }
1971        }
1972
1973        @Override
1974        public int hashCode() {
1975            int result = 17;
1976            result = 37 * result + crashInfo.stackTrace.hashCode();
1977            if (numAnimationsRunning != 0) {
1978                result *= 37;
1979            }
1980            if (broadcastIntentAction != null) {
1981                result = 37 * result + broadcastIntentAction.hashCode();
1982            }
1983            if (tags != null) {
1984                for (String tag : tags) {
1985                    result = 37 * result + tag.hashCode();
1986                }
1987            }
1988            return result;
1989        }
1990
1991        /**
1992         * Create an instance of ViolationInfo initialized from a Parcel.
1993         */
1994        public ViolationInfo(Parcel in) {
1995            this(in, false);
1996        }
1997
1998        /**
1999         * Create an instance of ViolationInfo initialized from a Parcel.
2000         *
2001         * @param unsetGatheringBit if true, the caller is the root caller
2002         *   and the gathering penalty should be removed.
2003         */
2004        public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
2005            crashInfo = new ApplicationErrorReport.CrashInfo(in);
2006            int rawPolicy = in.readInt();
2007            if (unsetGatheringBit) {
2008                policy = rawPolicy & ~PENALTY_GATHER;
2009            } else {
2010                policy = rawPolicy;
2011            }
2012            durationMillis = in.readInt();
2013            violationNumThisLoop = in.readInt();
2014            numAnimationsRunning = in.readInt();
2015            violationUptimeMillis = in.readLong();
2016            numInstances = in.readLong();
2017            broadcastIntentAction = in.readString();
2018            tags = in.readStringArray();
2019        }
2020
2021        /**
2022         * Save a ViolationInfo instance to a parcel.
2023         */
2024        public void writeToParcel(Parcel dest, int flags) {
2025            crashInfo.writeToParcel(dest, flags);
2026            dest.writeInt(policy);
2027            dest.writeInt(durationMillis);
2028            dest.writeInt(violationNumThisLoop);
2029            dest.writeInt(numAnimationsRunning);
2030            dest.writeLong(violationUptimeMillis);
2031            dest.writeLong(numInstances);
2032            dest.writeString(broadcastIntentAction);
2033            dest.writeStringArray(tags);
2034        }
2035
2036
2037        /**
2038         * Dump a ViolationInfo instance to a Printer.
2039         */
2040        public void dump(Printer pw, String prefix) {
2041            crashInfo.dump(pw, prefix);
2042            pw.println(prefix + "policy: " + policy);
2043            if (durationMillis != -1) {
2044                pw.println(prefix + "durationMillis: " + durationMillis);
2045            }
2046            if (numInstances != -1) {
2047                pw.println(prefix + "numInstances: " + numInstances);
2048            }
2049            if (violationNumThisLoop != 0) {
2050                pw.println(prefix + "violationNumThisLoop: " + violationNumThisLoop);
2051            }
2052            if (numAnimationsRunning != 0) {
2053                pw.println(prefix + "numAnimationsRunning: " + numAnimationsRunning);
2054            }
2055            pw.println(prefix + "violationUptimeMillis: " + violationUptimeMillis);
2056            if (broadcastIntentAction != null) {
2057                pw.println(prefix + "broadcastIntentAction: " + broadcastIntentAction);
2058            }
2059            if (tags != null) {
2060                int index = 0;
2061                for (String tag : tags) {
2062                    pw.println(prefix + "tag[" + (index++) + "]: " + tag);
2063                }
2064            }
2065        }
2066
2067    }
2068
2069    // Dummy throwable, for now, since we don't know when or where the
2070    // leaked instances came from.  We might in the future, but for
2071    // now we suppress the stack trace because it's useless and/or
2072    // misleading.
2073    private static class InstanceCountViolation extends Throwable {
2074        final Class mClass;
2075        final long mInstances;
2076        final int mLimit;
2077
2078        private static final StackTraceElement[] FAKE_STACK = {
2079            new StackTraceElement("android.os.StrictMode", "setClassInstanceLimit",
2080                                  "StrictMode.java", 1)
2081        };
2082
2083        public InstanceCountViolation(Class klass, long instances, int limit) {
2084            super(klass.toString() + "; instances=" + instances + "; limit=" + limit);
2085            setStackTrace(FAKE_STACK);
2086            mClass = klass;
2087            mInstances = instances;
2088            mLimit = limit;
2089        }
2090    }
2091}
2092