forked from zsol/android_frameworks_base
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStrictMode.java
More file actions
2191 lines (1956 loc) · 79.5 KB
/
Copy pathStrictMode.java
File metadata and controls
2191 lines (1956 loc) · 79.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.animation.ValueAnimator;
import android.app.ActivityManagerNative;
import android.app.ActivityThread;
import android.app.ApplicationErrorReport;
import android.app.IActivityManager;
import android.content.Intent;
import android.util.Log;
import android.util.Printer;
import android.util.Singleton;
import android.view.IWindowManager;
import com.android.internal.os.RuntimeInit;
import dalvik.system.BlockGuard;
import dalvik.system.CloseGuard;
import dalvik.system.VMDebug;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>StrictMode is a developer tool which detects things you might be
* doing by accident and brings them to your attention so you can fix
* them.
*
* <p>StrictMode is most commonly used to catch accidental disk or
* network access on the application's main thread, where UI
* operations are received and animations take place. Keeping disk
* and network operations off the main thread makes for much smoother,
* more responsive applications. By keeping your application's main thread
* responsive, you also prevent
* <a href="{@docRoot}guide/practices/design/responsiveness.html">ANR dialogs</a>
* from being shown to users.
*
* <p class="note">Note that even though an Android device's disk is
* often on flash memory, many devices run a filesystem on top of that
* memory with very limited concurrency. It's often the case that
* almost all disk accesses are fast, but may in individual cases be
* dramatically slower when certain I/O is happening in the background
* from other processes. If possible, it's best to assume that such
* things are not fast.</p>
*
* <p>Example code to enable from early in your
* {@link android.app.Application}, {@link android.app.Activity}, or
* other application component's
* {@link android.app.Application#onCreate} method:
*
* <pre>
* public void onCreate() {
* if (DEVELOPER_MODE) {
* StrictMode.setThreadPolicy(new {@link ThreadPolicy.Builder StrictMode.ThreadPolicy.Builder}()
* .detectDiskReads()
* .detectDiskWrites()
* .detectNetwork() // or .detectAll() for all detectable problems
* .penaltyLog()
* .build());
* StrictMode.setVmPolicy(new {@link VmPolicy.Builder StrictMode.VmPolicy.Builder}()
* .detectLeakedSqlLiteObjects()
* .detectLeakedClosableObjects()
* .penaltyLog()
* .penaltyDeath()
* .build());
* }
* super.onCreate();
* }
* </pre>
*
* <p>You can decide what should happen when a violation is detected.
* For example, using {@link ThreadPolicy.Builder#penaltyLog} you can
* watch the output of <code>adb logcat</code> while you use your
* application to see the violations as they happen.
*
* <p>If you find violations that you feel are problematic, there are
* a variety of tools to help solve them: threads, {@link android.os.Handler},
* {@link android.os.AsyncTask}, {@link android.app.IntentService}, etc.
* But don't feel compelled to fix everything that StrictMode finds. In particular,
* many cases of disk access are often necessary during the normal activity lifecycle. Use
* StrictMode to find things you did by accident. Network requests on the UI thread
* are almost always a problem, though.
*
* <p class="note">StrictMode is not a security mechanism and is not
* guaranteed to find all disk or network accesses. While it does
* propagate its state across process boundaries when doing
* {@link android.os.Binder} calls, it's still ultimately a best
* effort mechanism. Notably, disk or network access from JNI calls
* won't necessarily trigger it. Future versions of Android may catch
* more (or fewer) operations, so you should never leave StrictMode
* enabled in shipping applications on the Android Market.
*/
public final class StrictMode {
private static final String TAG = "StrictMode";
private static final boolean LOG_V = Log.isLoggable(TAG, Log.VERBOSE);
private static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
private static final boolean IS_ENG_BUILD = "eng".equals(Build.TYPE);
/**
* Boolean system property to disable strict mode checks outright.
* Set this to 'true' to force disable; 'false' has no effect on other
* enable/disable policy.
* @hide
*/
public static final String DISABLE_PROPERTY = "persist.sys.strictmode.disable";
/**
* The boolean system property to control screen flashes on violations.
*
* @hide
*/
public static final String VISUAL_PROPERTY = "persist.sys.strictmode.visual";
// Only log a duplicate stack trace to the logs every second.
private static final long MIN_LOG_INTERVAL_MS = 1000;
// Only show an annoying dialog at most every 30 seconds
private static final long MIN_DIALOG_INTERVAL_MS = 30000;
// How many Span tags (e.g. animations) to report.
private static final int MAX_SPAN_TAGS = 20;
// How many offending stacks to keep track of (and time) per loop
// of the Looper.
private static final int MAX_OFFENSES_PER_LOOP = 10;
// Thread-policy:
/**
* @hide
*/
public static final int DETECT_DISK_WRITE = 0x01; // for ThreadPolicy
/**
* @hide
*/
public static final int DETECT_DISK_READ = 0x02; // for ThreadPolicy
/**
* @hide
*/
public static final int DETECT_NETWORK = 0x04; // for ThreadPolicy
/**
* For StrictMode.noteSlowCall()
*
* @hide
*/
public static final int DETECT_CUSTOM = 0x08; // for ThreadPolicy
private static final int ALL_THREAD_DETECT_BITS =
DETECT_DISK_WRITE | DETECT_DISK_READ | DETECT_NETWORK | DETECT_CUSTOM;
// Process-policy:
/**
* Note, a "VM_" bit, not thread.
* @hide
*/
public static final int DETECT_VM_CURSOR_LEAKS = 0x200; // for VmPolicy
/**
* Note, a "VM_" bit, not thread.
* @hide
*/
public static final int DETECT_VM_CLOSABLE_LEAKS = 0x400; // for VmPolicy
/**
* Note, a "VM_" bit, not thread.
* @hide
*/
public static final int DETECT_VM_ACTIVITY_LEAKS = 0x800; // for VmPolicy
/**
* @hide
*/
private static final int DETECT_VM_INSTANCE_LEAKS = 0x1000; // for VmPolicy
private static final int ALL_VM_DETECT_BITS =
DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS |
DETECT_VM_ACTIVITY_LEAKS | DETECT_VM_INSTANCE_LEAKS;
/**
* @hide
*/
public static final int PENALTY_LOG = 0x10; // normal android.util.Log
// Used for both process and thread policy:
/**
* @hide
*/
public static final int PENALTY_DIALOG = 0x20;
/**
* Death on any detected violation.
*
* @hide
*/
public static final int PENALTY_DEATH = 0x40;
/**
* Death just for detected network usage.
*
* @hide
*/
public static final int PENALTY_DEATH_ON_NETWORK = 0x200;
/**
* Flash the screen during violations.
*
* @hide
*/
public static final int PENALTY_FLASH = 0x800;
/**
* @hide
*/
public static final int PENALTY_DROPBOX = 0x80;
/**
* Non-public penalty mode which overrides all the other penalty
* bits and signals that we're in a Binder call and we should
* ignore the other penalty bits and instead serialize back all
* our offending stack traces to the caller to ultimately handle
* in the originating process.
*
* This must be kept in sync with the constant in libs/binder/Parcel.cpp
*
* @hide
*/
public static final int PENALTY_GATHER = 0x100;
/**
* Mask of all the penalty bits valid for thread policies.
*/
private static final int THREAD_PENALTY_MASK =
PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER |
PENALTY_DEATH_ON_NETWORK | PENALTY_FLASH;
/**
* Mask of all the penalty bits valid for VM policies.
*/
private static final int VM_PENALTY_MASK =
PENALTY_LOG | PENALTY_DEATH | PENALTY_DROPBOX;
// TODO: wrap in some ImmutableHashMap thing.
// Note: must be before static initialization of sVmPolicy.
private static final HashMap<Class, Integer> EMPTY_CLASS_LIMIT_MAP = new HashMap<Class, Integer>();
/**
* The current VmPolicy in effect.
*
* TODO: these are redundant (mask is in VmPolicy). Should remove sVmPolicyMask.
*/
private static volatile int sVmPolicyMask = 0;
private static volatile VmPolicy sVmPolicy = VmPolicy.LAX;
/**
* The number of threads trying to do an async dropbox write.
* Just to limit ourselves out of paranoia.
*/
private static final AtomicInteger sDropboxCallsInFlight = new AtomicInteger(0);
private StrictMode() {}
/**
* {@link StrictMode} policy applied to a certain thread.
*
* <p>The policy is enabled by {@link #setThreadPolicy}. The current policy
* can be retrieved with {@link #getThreadPolicy}.
*
* <p>Note that multiple penalties may be provided and they're run
* in order from least to most severe (logging before process
* death, for example). There's currently no mechanism to choose
* different penalties for different detected actions.
*/
public static final class ThreadPolicy {
/**
* The default, lax policy which doesn't catch anything.
*/
public static final ThreadPolicy LAX = new ThreadPolicy(0);
final int mask;
private ThreadPolicy(int mask) {
this.mask = mask;
}
@Override
public String toString() {
return "[StrictMode.ThreadPolicy; mask=" + mask + "]";
}
/**
* Creates {@link ThreadPolicy} instances. Methods whose names start
* with {@code detect} specify what problems we should look
* for. Methods whose names start with {@code penalty} specify what
* we should do when we detect a problem.
*
* <p>You can call as many {@code detect} and {@code penalty}
* methods as you like. Currently order is insignificant: all
* penalties apply to all detected problems.
*
* <p>For example, detect everything and log anything that's found:
* <pre>
* StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
* .detectAll()
* .penaltyLog()
* .build();
* StrictMode.setThreadPolicy(policy);
* </pre>
*/
public static final class Builder {
private int mMask = 0;
/**
* Create a Builder that detects nothing and has no
* violations. (but note that {@link #build} will default
* to enabling {@link #penaltyLog} if no other penalties
* are specified)
*/
public Builder() {
mMask = 0;
}
/**
* Initialize a Builder from an existing ThreadPolicy.
*/
public Builder(ThreadPolicy policy) {
mMask = policy.mask;
}
/**
* Detect everything that's potentially suspect.
*
* <p>As of the Gingerbread release this includes network and
* disk operations but will likely expand in future releases.
*/
public Builder detectAll() {
return enable(ALL_THREAD_DETECT_BITS);
}
/**
* Disable the detection of everything.
*/
public Builder permitAll() {
return disable(ALL_THREAD_DETECT_BITS);
}
/**
* Enable detection of network operations.
*/
public Builder detectNetwork() {
return enable(DETECT_NETWORK);
}
/**
* Disable detection of network operations.
*/
public Builder permitNetwork() {
return disable(DETECT_NETWORK);
}
/**
* Enable detection of disk reads.
*/
public Builder detectDiskReads() {
return enable(DETECT_DISK_READ);
}
/**
* Disable detection of disk reads.
*/
public Builder permitDiskReads() {
return disable(DETECT_DISK_READ);
}
/**
* Enable detection of disk reads.
*/
public Builder detectCustomSlowCalls() {
return enable(DETECT_CUSTOM);
}
/**
* Enable detection of disk reads.
*/
public Builder permitCustomSlowCalls() {
return enable(DETECT_CUSTOM);
}
/**
* Enable detection of disk writes.
*/
public Builder detectDiskWrites() {
return enable(DETECT_DISK_WRITE);
}
/**
* Disable detection of disk writes.
*/
public Builder permitDiskWrites() {
return disable(DETECT_DISK_WRITE);
}
/**
* Show an annoying dialog to the developer on detected
* violations, rate-limited to be only a little annoying.
*/
public Builder penaltyDialog() {
return enable(PENALTY_DIALOG);
}
/**
* Crash the whole process on violation. This penalty runs at
* the end of all enabled penalties so you'll still get
* see logging or other violations before the process dies.
*
* <p>Unlike {@link #penaltyDeathOnNetwork}, this applies
* to disk reads, disk writes, and network usage if their
* corresponding detect flags are set.
*/
public Builder penaltyDeath() {
return enable(PENALTY_DEATH);
}
/**
* Crash the whole process on any network usage. Unlike
* {@link #penaltyDeath}, this penalty runs
* <em>before</em> anything else. You must still have
* called {@link #detectNetwork} to enable this.
*
* <p>In the Honeycomb or later SDKs, this is on by default.
*/
public Builder penaltyDeathOnNetwork() {
return enable(PENALTY_DEATH_ON_NETWORK);
}
/**
* Flash the screen during a violation.
*/
public Builder penaltyFlashScreen() {
return enable(PENALTY_FLASH);
}
/**
* Log detected violations to the system log.
*/
public Builder penaltyLog() {
return enable(PENALTY_LOG);
}
/**
* Enable detected violations log a stacktrace and timing data
* to the {@link android.os.DropBoxManager DropBox} on policy
* violation. Intended mostly for platform integrators doing
* beta user field data collection.
*/
public Builder penaltyDropBox() {
return enable(PENALTY_DROPBOX);
}
private Builder enable(int bit) {
mMask |= bit;
return this;
}
private Builder disable(int bit) {
mMask &= ~bit;
return this;
}
/**
* Construct the ThreadPolicy instance.
*
* <p>Note: if no penalties are enabled before calling
* <code>build</code>, {@link #penaltyLog} is implicitly
* set.
*/
public ThreadPolicy build() {
// If there are detection bits set but no violation bits
// set, enable simple logging.
if (mMask != 0 &&
(mMask & (PENALTY_DEATH | PENALTY_LOG |
PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
penaltyLog();
}
return new ThreadPolicy(mMask);
}
}
}
/**
* {@link StrictMode} policy applied to all threads in the virtual machine's process.
*
* <p>The policy is enabled by {@link #setVmPolicy}.
*/
public static final class VmPolicy {
/**
* The default, lax policy which doesn't catch anything.
*/
public static final VmPolicy LAX = new VmPolicy(0, EMPTY_CLASS_LIMIT_MAP);
final int mask;
// Map from class to max number of allowed instances in memory.
final HashMap<Class, Integer> classInstanceLimit;
private VmPolicy(int mask, HashMap<Class, Integer> classInstanceLimit) {
if (classInstanceLimit == null) {
throw new NullPointerException("classInstanceLimit == null");
}
this.mask = mask;
this.classInstanceLimit = classInstanceLimit;
}
@Override
public String toString() {
return "[StrictMode.VmPolicy; mask=" + mask + "]";
}
/**
* Creates {@link VmPolicy} instances. Methods whose names start
* with {@code detect} specify what problems we should look
* for. Methods whose names start with {@code penalty} specify what
* we should do when we detect a problem.
*
* <p>You can call as many {@code detect} and {@code penalty}
* methods as you like. Currently order is insignificant: all
* penalties apply to all detected problems.
*
* <p>For example, detect everything and log anything that's found:
* <pre>
* StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
* .detectAll()
* .penaltyLog()
* .build();
* StrictMode.setVmPolicy(policy);
* </pre>
*/
public static final class Builder {
private int mMask;
private HashMap<Class, Integer> mClassInstanceLimit; // null until needed
private boolean mClassInstanceLimitNeedCow = false; // need copy-on-write
public Builder() {
mMask = 0;
}
/**
* Build upon an existing VmPolicy.
*/
public Builder(VmPolicy base) {
mMask = base.mask;
mClassInstanceLimitNeedCow = true;
mClassInstanceLimit = base.classInstanceLimit;
}
/**
* Set an upper bound on how many instances of a class can be in memory
* at once. Helps to prevent object leaks.
*/
public Builder setClassInstanceLimit(Class klass, int instanceLimit) {
if (klass == null) {
throw new NullPointerException("klass == null");
}
if (mClassInstanceLimitNeedCow) {
if (mClassInstanceLimit.containsKey(klass) &&
mClassInstanceLimit.get(klass) == instanceLimit) {
// no-op; don't break COW
return this;
}
mClassInstanceLimitNeedCow = false;
mClassInstanceLimit = (HashMap<Class, Integer>) mClassInstanceLimit.clone();
} else if (mClassInstanceLimit == null) {
mClassInstanceLimit = new HashMap<Class, Integer>();
}
mMask |= DETECT_VM_INSTANCE_LEAKS;
mClassInstanceLimit.put(klass, instanceLimit);
return this;
}
/**
* Detect leaks of {@link android.app.Activity} subclasses.
*/
public Builder detectActivityLeaks() {
return enable(DETECT_VM_ACTIVITY_LEAKS);
}
/**
* Detect everything that's potentially suspect.
*
* <p>In the Honeycomb release this includes leaks of
* SQLite cursors, Activities, and other closable objects
* but will likely expand in future releases.
*/
public Builder detectAll() {
return enable(DETECT_VM_ACTIVITY_LEAKS |
DETECT_VM_CURSOR_LEAKS | DETECT_VM_CLOSABLE_LEAKS);
}
/**
* Detect when an
* {@link android.database.sqlite.SQLiteCursor} or other
* SQLite object is finalized without having been closed.
*
* <p>You always want to explicitly close your SQLite
* cursors to avoid unnecessary database contention and
* temporary memory leaks.
*/
public Builder detectLeakedSqlLiteObjects() {
return enable(DETECT_VM_CURSOR_LEAKS);
}
/**
* Detect when an {@link java.io.Closeable} or other
* object with a explict termination method is finalized
* without having been closed.
*
* <p>You always want to explicitly close such objects to
* avoid unnecessary resources leaks.
*/
public Builder detectLeakedClosableObjects() {
return enable(DETECT_VM_CLOSABLE_LEAKS);
}
/**
* Crashes the whole process on violation. This penalty runs at
* the end of all enabled penalties so yo you'll still get
* your logging or other violations before the process dies.
*/
public Builder penaltyDeath() {
return enable(PENALTY_DEATH);
}
/**
* Log detected violations to the system log.
*/
public Builder penaltyLog() {
return enable(PENALTY_LOG);
}
/**
* Enable detected violations log a stacktrace and timing data
* to the {@link android.os.DropBoxManager DropBox} on policy
* violation. Intended mostly for platform integrators doing
* beta user field data collection.
*/
public Builder penaltyDropBox() {
return enable(PENALTY_DROPBOX);
}
private Builder enable(int bit) {
mMask |= bit;
return this;
}
/**
* Construct the VmPolicy instance.
*
* <p>Note: if no penalties are enabled before calling
* <code>build</code>, {@link #penaltyLog} is implicitly
* set.
*/
public VmPolicy build() {
// If there are detection bits set but no violation bits
// set, enable simple logging.
if (mMask != 0 &&
(mMask & (PENALTY_DEATH | PENALTY_LOG |
PENALTY_DROPBOX | PENALTY_DIALOG)) == 0) {
penaltyLog();
}
return new VmPolicy(mMask,
mClassInstanceLimit != null ? mClassInstanceLimit : EMPTY_CLASS_LIMIT_MAP);
}
}
}
/**
* Log of strict mode violation stack traces that have occurred
* during a Binder call, to be serialized back later to the caller
* via Parcel.writeNoException() (amusingly) where the caller can
* choose how to react.
*/
private static final ThreadLocal<ArrayList<ViolationInfo>> gatheredViolations =
new ThreadLocal<ArrayList<ViolationInfo>>() {
@Override protected ArrayList<ViolationInfo> initialValue() {
// Starts null to avoid unnecessary allocations when
// checking whether there are any violations or not in
// hasGatheredViolations() below.
return null;
}
};
/**
* Sets the policy for what actions on the current thread should
* be detected, as well as the penalty if such actions occur.
*
* <p>Internally this sets a thread-local variable which is
* propagated across cross-process IPC calls, meaning you can
* catch violations when a system service or another process
* accesses the disk or network on your behalf.
*
* @param policy the policy to put into place
*/
public static void setThreadPolicy(final ThreadPolicy policy) {
setThreadPolicyMask(policy.mask);
}
private static void setThreadPolicyMask(final int policyMask) {
// In addition to the Java-level thread-local in Dalvik's
// BlockGuard, we also need to keep a native thread-local in
// Binder in order to propagate the value across Binder calls,
// even across native-only processes. The two are kept in
// sync via the callback to onStrictModePolicyChange, below.
setBlockGuardPolicy(policyMask);
// And set the Android native version...
Binder.setThreadStrictModePolicy(policyMask);
}
// Sets the policy in Dalvik/libcore (BlockGuard)
private static void setBlockGuardPolicy(final int policyMask) {
if (policyMask == 0) {
BlockGuard.setThreadPolicy(BlockGuard.LAX_POLICY);
return;
}
BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
if (!(policy instanceof AndroidBlockGuardPolicy)) {
BlockGuard.setThreadPolicy(new AndroidBlockGuardPolicy(policyMask));
} else {
AndroidBlockGuardPolicy androidPolicy = (AndroidBlockGuardPolicy) policy;
androidPolicy.setPolicyMask(policyMask);
}
}
// Sets up CloseGuard in Dalvik/libcore
private static void setCloseGuardEnabled(boolean enabled) {
if (!(CloseGuard.getReporter() instanceof AndroidCloseGuardReporter)) {
CloseGuard.setReporter(new AndroidCloseGuardReporter());
}
CloseGuard.setEnabled(enabled);
}
/**
* @hide
*/
public static class StrictModeViolation extends BlockGuard.BlockGuardPolicyException {
public StrictModeViolation(int policyState, int policyViolated, String message) {
super(policyState, policyViolated, message);
}
}
/**
* @hide
*/
public static class StrictModeNetworkViolation extends StrictModeViolation {
public StrictModeNetworkViolation(int policyMask) {
super(policyMask, DETECT_NETWORK, null);
}
}
/**
* @hide
*/
private static class StrictModeDiskReadViolation extends StrictModeViolation {
public StrictModeDiskReadViolation(int policyMask) {
super(policyMask, DETECT_DISK_READ, null);
}
}
/**
* @hide
*/
private static class StrictModeDiskWriteViolation extends StrictModeViolation {
public StrictModeDiskWriteViolation(int policyMask) {
super(policyMask, DETECT_DISK_WRITE, null);
}
}
/**
* @hide
*/
private static class StrictModeCustomViolation extends StrictModeViolation {
public StrictModeCustomViolation(int policyMask, String name) {
super(policyMask, DETECT_CUSTOM, name);
}
}
/**
* Returns the bitmask of the current thread's policy.
*
* @return the bitmask of all the DETECT_* and PENALTY_* bits currently enabled
*
* @hide
*/
public static int getThreadPolicyMask() {
return BlockGuard.getThreadPolicy().getPolicyMask();
}
/**
* Returns the current thread's policy.
*/
public static ThreadPolicy getThreadPolicy() {
// TODO: this was a last minute Gingerbread API change (to
// introduce VmPolicy cleanly) but this isn't particularly
// optimal for users who might call this method often. This
// should be in a thread-local and not allocate on each call.
return new ThreadPolicy(getThreadPolicyMask());
}
/**
* A convenience wrapper that takes the current
* {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
* to permit both disk reads & writes, and sets the new policy
* with {@link #setThreadPolicy}, returning the old policy so you
* can restore it at the end of a block.
*
* @return the old policy, to be passed to {@link #setThreadPolicy} to
* restore the policy at the end of a block
*/
public static ThreadPolicy allowThreadDiskWrites() {
int oldPolicyMask = getThreadPolicyMask();
int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_WRITE | DETECT_DISK_READ);
if (newPolicyMask != oldPolicyMask) {
setThreadPolicyMask(newPolicyMask);
}
return new ThreadPolicy(oldPolicyMask);
}
/**
* A convenience wrapper that takes the current
* {@link ThreadPolicy} from {@link #getThreadPolicy}, modifies it
* to permit disk reads, and sets the new policy
* with {@link #setThreadPolicy}, returning the old policy so you
* can restore it at the end of a block.
*
* @return the old policy, to be passed to setThreadPolicy to
* restore the policy.
*/
public static ThreadPolicy allowThreadDiskReads() {
int oldPolicyMask = getThreadPolicyMask();
int newPolicyMask = oldPolicyMask & ~(DETECT_DISK_READ);
if (newPolicyMask != oldPolicyMask) {
setThreadPolicyMask(newPolicyMask);
}
return new ThreadPolicy(oldPolicyMask);
}
// We don't want to flash the screen red in the system server
// process, nor do we want to modify all the call sites of
// conditionallyEnableDebugLogging() in the system server,
// so instead we use this to determine if we are the system server.
private static boolean amTheSystemServerProcess() {
// Fast path. Most apps don't have the system server's UID.
if (Process.myUid() != Process.SYSTEM_UID) {
return false;
}
// The settings app, though, has the system server's UID so
// look up our stack to see if we came from the system server.
Throwable stack = new Throwable();
stack.fillInStackTrace();
for (StackTraceElement ste : stack.getStackTrace()) {
String clsName = ste.getClassName();
if (clsName != null && clsName.startsWith("com.android.server.")) {
return true;
}
}
return false;
}
/**
* Enable DropBox logging for debug phone builds.
*
* @hide
*/
public static boolean conditionallyEnableDebugLogging() {
boolean doFlashes = SystemProperties.getBoolean(VISUAL_PROPERTY, false)
&& !amTheSystemServerProcess();
final boolean suppress = SystemProperties.getBoolean(DISABLE_PROPERTY, false);
// For debug builds, log event loop stalls to dropbox for analysis.
// Similar logic also appears in ActivityThread.java for system apps.
if (!doFlashes && (IS_USER_BUILD || suppress)) {
setCloseGuardEnabled(false);
return false;
}
// Eng builds have flashes on all the time. The suppression property
// overrides this, so we force the behavior only after the short-circuit
// check above.
if (IS_ENG_BUILD) {
doFlashes = true;
}
// Thread policy controls BlockGuard.
int threadPolicyMask = StrictMode.DETECT_DISK_WRITE |
StrictMode.DETECT_DISK_READ |
StrictMode.DETECT_NETWORK;
if (!IS_USER_BUILD) {
threadPolicyMask |= StrictMode.PENALTY_DROPBOX;
}
if (doFlashes) {
threadPolicyMask |= StrictMode.PENALTY_FLASH;
}
StrictMode.setThreadPolicyMask(threadPolicyMask);
// VM Policy controls CloseGuard, detection of Activity leaks,
// and instance counting.
if (IS_USER_BUILD) {
setCloseGuardEnabled(false);
} else {
VmPolicy.Builder policyBuilder = new VmPolicy.Builder().detectAll().penaltyDropBox();
if (IS_ENG_BUILD) {
policyBuilder.penaltyLog();
}
setVmPolicy(policyBuilder.build());
setCloseGuardEnabled(vmClosableObjectLeaksEnabled());
}
return true;
}
/**
* Used by the framework to make network usage on the main
* thread a fatal error.
*
* @hide
*/
public static void enableDeathOnNetwork() {
int oldPolicy = getThreadPolicyMask();
int newPolicy = oldPolicy | DETECT_NETWORK | PENALTY_DEATH_ON_NETWORK;
setThreadPolicyMask(newPolicy);
}
/**
* Parses the BlockGuard policy mask out from the Exception's
* getMessage() String value. Kinda gross, but least
* invasive. :/
*
* Input is of the following forms:
* "policy=137 violation=64"
* "policy=137 violation=64 msg=Arbitrary text"
*
* Returns 0 on failure, which is a valid policy, but not a
* valid policy during a violation (else there must've been
* some policy in effect to violate).
*/
private static int parsePolicyFromMessage(String message) {
if (message == null || !message.startsWith("policy=")) {
return 0;
}
int spaceIndex = message.indexOf(' ');
if (spaceIndex == -1) {
return 0;
}
String policyString = message.substring(7, spaceIndex);
try {
return Integer.valueOf(policyString).intValue();
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Like parsePolicyFromMessage(), but returns the violation.
*/
private static int parseViolationFromMessage(String message) {
if (message == null) {
return 0;
}
int violationIndex = message.indexOf("violation=");
if (violationIndex == -1) {
return 0;
}