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