1 /*
2  * Copyright (C) 2006 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  */
16 
17 package com.android.server.am;
18 
19 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
20 
21 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
22 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
23 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
24 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
25 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
26 import static com.android.server.am.ActivityManagerService.MY_PID;
27 
28 import android.app.ActivityManager;
29 import android.app.ApplicationErrorReport;
30 import android.app.Dialog;
31 import android.app.IApplicationThread;
32 import android.content.ComponentName;
33 import android.content.Context;
34 import android.content.pm.ApplicationInfo;
35 import android.content.pm.ServiceInfo;
36 import android.content.pm.VersionedPackage;
37 import android.content.res.CompatibilityInfo;
38 import android.os.Binder;
39 import android.os.Debug;
40 import android.os.IBinder;
41 import android.os.Message;
42 import android.os.Process;
43 import android.os.RemoteException;
44 import android.os.SystemClock;
45 import android.os.Trace;
46 import android.os.UserHandle;
47 import android.provider.Settings;
48 import android.server.ServerProtoEnums;
49 import android.util.ArrayMap;
50 import android.util.ArraySet;
51 import android.util.DebugUtils;
52 import android.util.EventLog;
53 import android.util.Slog;
54 import android.util.SparseArray;
55 import android.util.StatsLog;
56 import android.util.TimeUtils;
57 import android.util.proto.ProtoOutputStream;
58 
59 import com.android.internal.annotations.VisibleForTesting;
60 import com.android.internal.app.procstats.ProcessState;
61 import com.android.internal.app.procstats.ProcessStats;
62 import com.android.internal.os.BatteryStatsImpl;
63 import com.android.internal.os.ProcessCpuTracker;
64 import com.android.internal.os.Zygote;
65 import com.android.server.wm.WindowProcessController;
66 import com.android.server.wm.WindowProcessListener;
67 
68 import java.io.File;
69 import java.io.PrintWriter;
70 import java.util.ArrayList;
71 import java.util.Arrays;
72 import java.util.List;
73 
74 /**
75  * Full information about a particular process that
76  * is currently running.
77  */
78 class ProcessRecord implements WindowProcessListener {
79     private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;
80 
81     private final ActivityManagerService mService; // where we came from
82     final ApplicationInfo info; // all about the first app in the process
83     final boolean isolated;     // true if this is a special isolated process
84     final boolean appZygote;    // true if this is forked from the app zygote
85     final int uid;              // uid of process; may be different from 'info' if isolated
86     final int userId;           // user of process.
87     final String processName;   // name of the process
88     // List of packages running in the process
89     final PackageList pkgList = new PackageList();
90     final class PackageList {
91         final ArrayMap<String, ProcessStats.ProcessStateHolder> mPkgList = new ArrayMap<>();
92 
put(String key, ProcessStats.ProcessStateHolder value)93         ProcessStats.ProcessStateHolder put(String key, ProcessStats.ProcessStateHolder value) {
94             mWindowProcessController.addPackage(key);
95             return mPkgList.put(key, value);
96         }
97 
clear()98         void clear() {
99             mPkgList.clear();
100             mWindowProcessController.clearPackageList();
101         }
102 
size()103         int size() {
104             return mPkgList.size();
105         }
106 
keyAt(int index)107         String keyAt(int index) {
108             return mPkgList.keyAt(index);
109         }
110 
valueAt(int index)111         public ProcessStats.ProcessStateHolder valueAt(int index) {
112             return mPkgList.valueAt(index);
113         }
114 
get(String pkgName)115         ProcessStats.ProcessStateHolder get(String pkgName) {
116             return mPkgList.get(pkgName);
117         }
118 
containsKey(Object key)119         boolean containsKey(Object key) {
120             return mPkgList.containsKey(key);
121         }
122     }
123 
124     final ProcessList.ProcStateMemTracker procStateMemTracker
125             = new ProcessList.ProcStateMemTracker();
126     UidRecord uidRecord;        // overall state of process's uid.
127     ArraySet<String> pkgDeps;   // additional packages we have a dependency on
128     IApplicationThread thread;  // the actual proc...  may be null only if
129                                 // 'persistent' is true (in which case we
130                                 // are in the process of launching the app)
131     ProcessState baseProcessTracker;
132     BatteryStatsImpl.Uid.Proc curProcBatteryStats;
133     int pid;                    // The process of this application; 0 if none
134     String procStatFile;        // path to /proc/<pid>/stat
135     int[] gids;                 // The gids this process was launched with
136     private String mRequiredAbi;// The ABI this process was launched with
137     String instructionSet;      // The instruction set this process was launched with
138     boolean starting;           // True if the process is being started
139     long lastActivityTime;      // For managing the LRU list
140     long lastPssTime;           // Last time we retrieved PSS data
141     long nextPssTime;           // Next time we want to request PSS data
142     long lastStateTime;         // Last time setProcState changed
143     long initialIdlePss;        // Initial memory pss of process for idle maintenance.
144     long lastPss;               // Last computed memory pss.
145     long lastSwapPss;           // Last computed SwapPss.
146     long lastCachedPss;         // Last computed pss when in cached state.
147     long lastCachedSwapPss;     // Last computed SwapPss when in cached state.
148     int maxAdj;                 // Maximum OOM adjustment for this process
149     private int mCurRawAdj;     // Current OOM unlimited adjustment for this process
150     int setRawAdj;              // Last set OOM unlimited adjustment for this process
151     int curAdj;                 // Current OOM adjustment for this process
152     int setAdj;                 // Last set OOM adjustment for this process
153     int verifiedAdj;            // The last adjustment that was verified as actually being set
154     long lastCompactTime;       // The last time that this process was compacted
155     int reqCompactAction;       // The most recent compaction action requested for this app.
156     int lastCompactAction;      // The most recent compaction action performed for this app.
157     private int mCurSchedGroup; // Currently desired scheduling class
158     int setSchedGroup;          // Last set to background scheduling class
159     int trimMemoryLevel;        // Last selected memory trimming level
160     private int mCurProcState = PROCESS_STATE_NONEXISTENT; // Currently computed process state
161     private int mRepProcState = PROCESS_STATE_NONEXISTENT; // Last reported process state
162     private int mCurRawProcState = PROCESS_STATE_NONEXISTENT; // Temp state during computation
163     int setProcState = PROCESS_STATE_NONEXISTENT; // Last set process state in process tracker
164     int pssProcState = PROCESS_STATE_NONEXISTENT; // Currently requesting pss for
165     int pssStatType;            // The type of stat collection that we are currently requesting
166     int savedPriority;          // Previous priority value if we're switching to non-SCHED_OTHER
167     int renderThreadTid;        // TID for RenderThread
168     ServiceRecord connectionService; // Service that applied current connectionGroup/Importance
169     int connectionGroup;        // Last group set by a connection
170     int connectionImportance;   // Last importance set by a connection
171     boolean serviceb;           // Process currently is on the service B list
172     boolean serviceHighRam;     // We are forcing to service B list due to its RAM use
173     boolean notCachedSinceIdle; // Has this process not been in a cached state since last idle?
174     private boolean mHasClientActivities;  // Are there any client services with activities?
175     boolean hasStartedServices; // Are there any started services running in this process?
176     private boolean mHasForegroundServices; // Running any services that are foreground?
177     private int mFgServiceTypes; // Type of foreground service, if there is a foreground service.
178     private int mRepFgServiceTypes; // Last reported foreground service types.
179     private boolean mHasForegroundActivities; // Running any activities that are foreground?
180     boolean repForegroundActivities; // Last reported foreground activities.
181     boolean systemNoUi;         // This is a system process, but not currently showing UI.
182     boolean hasShownUi;         // Has UI been shown in this process since it was started?
183     private boolean mHasTopUi;  // Is this process currently showing a non-activity UI that the user
184                                 // is interacting with? E.g. The status bar when it is expanded, but
185                                 // not when it is minimized. When true the
186                                 // process will be set to use the ProcessList#SCHED_GROUP_TOP_APP
187                                 // scheduling group to boost performance.
188     private boolean mHasOverlayUi; // Is the process currently showing a non-activity UI that
189                                 // overlays on-top of activity UIs on screen. E.g. display a window
190                                 // of type
191                                 // android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
192                                 // When true the process will oom adj score will be set to
193                                 // ProcessList#PERCEPTIBLE_APP_ADJ at minimum to reduce the chance
194                                 // of the process getting killed.
195     boolean runningRemoteAnimation; // Is the process currently running a RemoteAnimation? When true
196                                 // the process will be set to use the
197                                 // ProcessList#SCHED_GROUP_TOP_APP scheduling group to boost
198                                 // performance, as well as oom adj score will be set to
199                                 // ProcessList#VISIBLE_APP_ADJ at minimum to reduce the chance
200                                 // of the process getting killed.
201     private boolean mPendingUiClean; // Want to clean up resources from showing UI?
202     boolean hasAboveClient;     // Bound using BIND_ABOVE_CLIENT, so want to be lower
203     boolean treatLikeActivity;  // Bound using BIND_TREAT_LIKE_ACTIVITY
204     boolean bad;                // True if disabled in the bad process list
205     boolean killedByAm;         // True when proc has been killed by activity manager, not for RAM
206     boolean killed;             // True once we know the process has been killed
207     boolean procStateChanged;   // Keep track of whether we changed 'setAdj'.
208     boolean reportedInteraction;// Whether we have told usage stats about it being an interaction
209     boolean unlocked;           // True when proc was started in user unlocked state
210     private long mInteractionEventTime; // The time we sent the last interaction event
211     private long mFgInteractionTime; // When we became foreground for interaction purposes
212     String waitingToKill;       // Process is waiting to be killed when in the bg, and reason
213     Object forcingToImportant;  // Token that is forcing this process to be important
214     int adjSeq;                 // Sequence id for identifying oom_adj assignment cycles
215     int completedAdjSeq;        // Sequence id for identifying oom_adj assignment cycles
216     boolean containsCycle;      // Whether this app has encountered a cycle in the most recent update
217     int lruSeq;                 // Sequence id for identifying LRU update cycles
218     CompatibilityInfo compat;   // last used compatibility mode
219     IBinder.DeathRecipient deathRecipient; // Who is watching for the death.
220     private ActiveInstrumentation mInstr; // Set to currently active instrumentation running in
221                                           // process.
222     private boolean mUsingWrapper; // Set to true when process was launched with a wrapper attached
223     final ArraySet<BroadcastRecord> curReceivers = new ArraySet<BroadcastRecord>();// receivers currently running in the app
224     private long mWhenUnimportant; // When (uptime) the process last became unimportant
225     long lastCpuTime;           // How long proc has run CPU at last check
226     long curCpuTime;            // How long proc has run CPU most recently
227     long lastRequestedGc;       // When we last asked the app to do a gc
228     long lastLowMemory;         // When we last told the app that memory is low
229     long lastProviderTime;      // The last time someone else was using a provider in this process.
230     long lastTopTime;           // The last time the process was in the TOP state or greater.
231     boolean reportLowMemory;    // Set to true when waiting to report low mem
232     boolean empty;              // Is this an empty background process?
233     boolean cached;             // Is this a cached process?
234     String adjType;             // Debugging: primary thing impacting oom_adj.
235     int adjTypeCode;            // Debugging: adj code to report to app.
236     Object adjSource;           // Debugging: option dependent object.
237     int adjSourceProcState;     // Debugging: proc state of adjSource's process.
238     Object adjTarget;           // Debugging: target component impacting oom_adj.
239     Runnable crashHandler;      // Optional local handler to be invoked in the process crash.
240 
241     // Cache of last retrieve memory info and uptime, to throttle how frequently
242     // apps can requyest it.
243     Debug.MemoryInfo lastMemInfo;
244     long lastMemInfoTime;
245 
246     // Controller for driving the process state on the window manager side.
247     final private WindowProcessController mWindowProcessController;
248     // all ServiceRecord running in this process
249     final ArraySet<ServiceRecord> services = new ArraySet<>();
250     // services that are currently executing code (need to remain foreground).
251     final ArraySet<ServiceRecord> executingServices = new ArraySet<>();
252     // All ConnectionRecord this process holds
253     final ArraySet<ConnectionRecord> connections = new ArraySet<>();
254     // all IIntentReceivers that are registered from this process.
255     final ArraySet<ReceiverList> receivers = new ArraySet<>();
256     // class (String) -> ContentProviderRecord
257     final ArrayMap<String, ContentProviderRecord> pubProviders = new ArrayMap<>();
258     // All ContentProviderRecord process is using
259     final ArrayList<ContentProviderConnection> conProviders = new ArrayList<>();
260     // A set of tokens that currently contribute to this process being temporarily whitelisted
261     // to start activities even if it's not in the foreground
262     final ArraySet<Binder> mAllowBackgroundActivityStartsTokens = new ArraySet<>();
263     // a set of UIDs of all bound clients
264     private ArraySet<Integer> mBoundClientUids = new ArraySet<>();
265 
266     String isolatedEntryPoint;  // Class to run on start if this is a special isolated process.
267     String[] isolatedEntryPointArgs; // Arguments to pass to isolatedEntryPoint's main().
268 
269     boolean execServicesFg;     // do we need to be executing services in the foreground?
270     private boolean mPersistent;// always keep this application running?
271     private boolean mCrashing;  // are we in the process of crashing?
272     Dialog crashDialog;         // dialog being displayed due to crash.
273     boolean forceCrashReport;   // suppress normal auto-dismiss of crash dialog & report UI?
274     private boolean mNotResponding; // does the app have a not responding dialog?
275     Dialog anrDialog;           // dialog being displayed due to app not resp.
276     volatile boolean removed;   // Whether this process should be killed and removed from process
277                                 // list. It is set when the package is force-stopped or the process
278                                 // has crashed too many times.
279     private boolean mDebugging; // was app launched for debugging?
280     boolean waitedForDebugger;  // has process show wait for debugger dialog?
281     Dialog waitDialog;          // current wait for debugger dialog
282 
283     String shortStringName;     // caching of toShortString() result.
284     String stringName;          // caching of toString() result.
285     boolean pendingStart;       // Process start is pending.
286     long startSeq;              // Seq no. indicating the latest process start associated with
287                                 // this process record.
288     int mountMode;              // Indicates how the external storage was mounted for this process.
289 
290     // These reports are generated & stored when an app gets into an error condition.
291     // They will be "null" when all is OK.
292     ActivityManager.ProcessErrorStateInfo crashingReport;
293     ActivityManager.ProcessErrorStateInfo notRespondingReport;
294 
295     // Who will be notified of the error. This is usually an activity in the
296     // app that installed the package.
297     ComponentName errorReportReceiver;
298 
299     // Process is currently hosting a backup agent for backup or restore
300     public boolean inFullBackup;
301     // App is allowed to manage whitelists such as temporary Power Save mode whitelist.
302     boolean whitelistManager;
303 
304     // Params used in starting this process.
305     HostingRecord hostingRecord;
306     String seInfo;
307     long startTime;
308     // This will be same as {@link #uid} usually except for some apps used during factory testing.
309     int startUid;
310     // set of disabled compat changes for the process (all others are enabled)
311     long[] mDisabledCompatChanges;
312 
setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, long startTime)313     void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo,
314             long startTime) {
315         this.startUid = startUid;
316         this.hostingRecord = hostingRecord;
317         this.seInfo = seInfo;
318         this.startTime = startTime;
319     }
320 
dump(PrintWriter pw, String prefix)321     void dump(PrintWriter pw, String prefix) {
322         final long nowUptime = SystemClock.uptimeMillis();
323 
324         pw.print(prefix); pw.print("user #"); pw.print(userId);
325                 pw.print(" uid="); pw.print(info.uid);
326         if (uid != info.uid) {
327             pw.print(" ISOLATED uid="); pw.print(uid);
328         }
329         pw.print(" gids={");
330         if (gids != null) {
331             for (int gi=0; gi<gids.length; gi++) {
332                 if (gi != 0) pw.print(", ");
333                 pw.print(gids[gi]);
334 
335             }
336         }
337         pw.println("}");
338         pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi);
339                 pw.print(" instructionSet="); pw.println(instructionSet);
340         if (info.className != null) {
341             pw.print(prefix); pw.print("class="); pw.println(info.className);
342         }
343         if (info.manageSpaceActivityName != null) {
344             pw.print(prefix); pw.print("manageSpaceActivityName=");
345             pw.println(info.manageSpaceActivityName);
346         }
347 
348         pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
349                 pw.print(" publicDir="); pw.print(info.publicSourceDir);
350                 pw.print(" data="); pw.println(info.dataDir);
351         pw.print(prefix); pw.print("packageList={");
352         for (int i=0; i<pkgList.size(); i++) {
353             if (i > 0) pw.print(", ");
354             pw.print(pkgList.keyAt(i));
355         }
356         pw.println("}");
357         if (pkgDeps != null) {
358             pw.print(prefix); pw.print("packageDependencies={");
359             for (int i=0; i<pkgDeps.size(); i++) {
360                 if (i > 0) pw.print(", ");
361                 pw.print(pkgDeps.valueAt(i));
362             }
363             pw.println("}");
364         }
365         pw.print(prefix); pw.print("compat="); pw.println(compat);
366         if (mInstr != null) {
367             pw.print(prefix); pw.print("mInstr="); pw.println(mInstr);
368         }
369         pw.print(prefix); pw.print("thread="); pw.println(thread);
370         pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting=");
371                 pw.println(starting);
372         pw.print(prefix); pw.print("lastActivityTime=");
373                 TimeUtils.formatDuration(lastActivityTime, nowUptime, pw);
374                 pw.print(" lastPssTime=");
375                 TimeUtils.formatDuration(lastPssTime, nowUptime, pw);
376                 pw.print(" pssStatType="); pw.print(pssStatType);
377                 pw.print(" nextPssTime=");
378                 TimeUtils.formatDuration(nextPssTime, nowUptime, pw);
379                 pw.println();
380         pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq);
381                 pw.print(" lruSeq="); pw.print(lruSeq);
382                 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, lastPss*1024);
383                 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, lastSwapPss*1024);
384                 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, lastCachedPss*1024);
385                 pw.print(" lastCachedSwapPss="); DebugUtils.printSizeValue(pw, lastCachedSwapPss*1024);
386                 pw.println();
387         pw.print(prefix); pw.print("procStateMemTracker: ");
388         procStateMemTracker.dumpLine(pw);
389         pw.print(prefix); pw.print("cached="); pw.print(cached);
390                 pw.print(" empty="); pw.println(empty);
391         if (serviceb) {
392             pw.print(prefix); pw.print("serviceb="); pw.print(serviceb);
393                     pw.print(" serviceHighRam="); pw.println(serviceHighRam);
394         }
395         if (notCachedSinceIdle) {
396             pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(notCachedSinceIdle);
397                     pw.print(" initialIdlePss="); pw.println(initialIdlePss);
398         }
399         pw.print(prefix); pw.print("oom: max="); pw.print(maxAdj);
400                 pw.print(" curRaw="); pw.print(mCurRawAdj);
401                 pw.print(" setRaw="); pw.print(setRawAdj);
402                 pw.print(" cur="); pw.print(curAdj);
403                 pw.print(" set="); pw.println(setAdj);
404         pw.print(prefix); pw.print("lastCompactTime="); pw.print(lastCompactTime);
405                 pw.print(" lastCompactAction="); pw.print(lastCompactAction);
406         pw.print(prefix); pw.print("mCurSchedGroup="); pw.print(mCurSchedGroup);
407                 pw.print(" setSchedGroup="); pw.print(setSchedGroup);
408                 pw.print(" systemNoUi="); pw.print(systemNoUi);
409                 pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel);
410         pw.print(prefix); pw.print("curProcState="); pw.print(getCurProcState());
411                 pw.print(" mRepProcState="); pw.print(mRepProcState);
412                 pw.print(" pssProcState="); pw.print(pssProcState);
413                 pw.print(" setProcState="); pw.print(setProcState);
414                 pw.print(" lastStateTime=");
415                 TimeUtils.formatDuration(lastStateTime, nowUptime, pw);
416                 pw.println();
417         if (hasShownUi || mPendingUiClean || hasAboveClient || treatLikeActivity) {
418             pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi);
419                     pw.print(" pendingUiClean="); pw.print(mPendingUiClean);
420                     pw.print(" hasAboveClient="); pw.print(hasAboveClient);
421                     pw.print(" treatLikeActivity="); pw.println(treatLikeActivity);
422         }
423         if (connectionService != null || connectionGroup != 0) {
424             pw.print(prefix); pw.print("connectionGroup="); pw.print(connectionGroup);
425             pw.print(" Importance="); pw.print(connectionImportance);
426             pw.print(" Service="); pw.println(connectionService);
427         }
428         if (hasTopUi() || hasOverlayUi() || runningRemoteAnimation) {
429             pw.print(prefix); pw.print("hasTopUi="); pw.print(hasTopUi());
430                     pw.print(" hasOverlayUi="); pw.print(hasOverlayUi());
431                     pw.print(" runningRemoteAnimation="); pw.println(runningRemoteAnimation);
432         }
433         if (mHasForegroundServices || forcingToImportant != null) {
434             pw.print(prefix); pw.print("mHasForegroundServices="); pw.print(mHasForegroundServices);
435                     pw.print(" forcingToImportant="); pw.println(forcingToImportant);
436         }
437         if (reportedInteraction || mFgInteractionTime != 0) {
438             pw.print(prefix); pw.print("reportedInteraction=");
439             pw.print(reportedInteraction);
440             if (mInteractionEventTime != 0) {
441                 pw.print(" time=");
442                 TimeUtils.formatDuration(mInteractionEventTime, SystemClock.elapsedRealtime(), pw);
443             }
444             if (mFgInteractionTime != 0) {
445                 pw.print(" fgInteractionTime=");
446                 TimeUtils.formatDuration(mFgInteractionTime, SystemClock.elapsedRealtime(), pw);
447             }
448             pw.println();
449         }
450         if (mPersistent || removed) {
451             pw.print(prefix); pw.print("persistent="); pw.print(mPersistent);
452                     pw.print(" removed="); pw.println(removed);
453         }
454         if (mHasClientActivities || mHasForegroundActivities || repForegroundActivities) {
455             pw.print(prefix); pw.print("hasClientActivities="); pw.print(mHasClientActivities);
456                     pw.print(" foregroundActivities="); pw.print(mHasForegroundActivities);
457                     pw.print(" (rep="); pw.print(repForegroundActivities); pw.println(")");
458         }
459         if (lastProviderTime > 0) {
460             pw.print(prefix); pw.print("lastProviderTime=");
461             TimeUtils.formatDuration(lastProviderTime, nowUptime, pw);
462             pw.println();
463         }
464         if (lastTopTime > 0) {
465             pw.print(prefix); pw.print("lastTopTime=");
466             TimeUtils.formatDuration(lastTopTime, nowUptime, pw);
467             pw.println();
468         }
469         if (hasStartedServices) {
470             pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices);
471         }
472         if (pendingStart) {
473             pw.print(prefix); pw.print("pendingStart="); pw.println(pendingStart);
474         }
475         pw.print(prefix); pw.print("startSeq="); pw.println(startSeq);
476         pw.print(prefix); pw.print("mountMode="); pw.println(
477                 DebugUtils.valueToString(Zygote.class, "MOUNT_EXTERNAL_", mountMode));
478         if (setProcState > ActivityManager.PROCESS_STATE_SERVICE) {
479             pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime);
480                     if (lastCpuTime > 0) {
481                         pw.print(" timeUsed=");
482                         TimeUtils.formatDuration(curCpuTime - lastCpuTime, pw);
483                     }
484                     pw.print(" whenUnimportant=");
485                     TimeUtils.formatDuration(mWhenUnimportant - nowUptime, pw);
486                     pw.println();
487         }
488         pw.print(prefix); pw.print("lastRequestedGc=");
489                 TimeUtils.formatDuration(lastRequestedGc, nowUptime, pw);
490                 pw.print(" lastLowMemory=");
491                 TimeUtils.formatDuration(lastLowMemory, nowUptime, pw);
492                 pw.print(" reportLowMemory="); pw.println(reportLowMemory);
493         if (killed || killedByAm || waitingToKill != null) {
494             pw.print(prefix); pw.print("killed="); pw.print(killed);
495                     pw.print(" killedByAm="); pw.print(killedByAm);
496                     pw.print(" waitingToKill="); pw.println(waitingToKill);
497         }
498         if (mDebugging || mCrashing || crashDialog != null || mNotResponding
499                 || anrDialog != null || bad) {
500             pw.print(prefix); pw.print("mDebugging="); pw.print(mDebugging);
501                     pw.print(" mCrashing="); pw.print(mCrashing);
502                     pw.print(" "); pw.print(crashDialog);
503                     pw.print(" mNotResponding="); pw.print(mNotResponding);
504                     pw.print(" " ); pw.print(anrDialog);
505                     pw.print(" bad="); pw.print(bad);
506 
507                     // mCrashing or mNotResponding is always set before errorReportReceiver
508                     if (errorReportReceiver != null) {
509                         pw.print(" errorReportReceiver=");
510                         pw.print(errorReportReceiver.flattenToShortString());
511                     }
512                     pw.println();
513         }
514         if (whitelistManager) {
515             pw.print(prefix); pw.print("whitelistManager="); pw.println(whitelistManager);
516         }
517         if (isolatedEntryPoint != null || isolatedEntryPointArgs != null) {
518             pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(isolatedEntryPoint);
519             pw.print(prefix); pw.print("isolatedEntryPointArgs=");
520             pw.println(Arrays.toString(isolatedEntryPointArgs));
521         }
522         mWindowProcessController.dump(pw, prefix);
523         if (services.size() > 0) {
524             pw.print(prefix); pw.println("Services:");
525             for (int i=0; i<services.size(); i++) {
526                 pw.print(prefix); pw.print("  - "); pw.println(services.valueAt(i));
527             }
528         }
529         if (executingServices.size() > 0) {
530             pw.print(prefix); pw.print("Executing Services (fg=");
531             pw.print(execServicesFg); pw.println(")");
532             for (int i=0; i<executingServices.size(); i++) {
533                 pw.print(prefix); pw.print("  - "); pw.println(executingServices.valueAt(i));
534             }
535         }
536         if (connections.size() > 0) {
537             pw.print(prefix); pw.println("Connections:");
538             for (int i=0; i<connections.size(); i++) {
539                 pw.print(prefix); pw.print("  - "); pw.println(connections.valueAt(i));
540             }
541         }
542         if (pubProviders.size() > 0) {
543             pw.print(prefix); pw.println("Published Providers:");
544             for (int i=0; i<pubProviders.size(); i++) {
545                 pw.print(prefix); pw.print("  - "); pw.println(pubProviders.keyAt(i));
546                 pw.print(prefix); pw.print("    -> "); pw.println(pubProviders.valueAt(i));
547             }
548         }
549         if (conProviders.size() > 0) {
550             pw.print(prefix); pw.println("Connected Providers:");
551             for (int i=0; i<conProviders.size(); i++) {
552                 pw.print(prefix); pw.print("  - "); pw.println(conProviders.get(i).toShortString());
553             }
554         }
555         if (!curReceivers.isEmpty()) {
556             pw.print(prefix); pw.println("Current Receivers:");
557             for (int i=0; i < curReceivers.size(); i++) {
558                 pw.print(prefix); pw.print("  - "); pw.println(curReceivers.valueAt(i));
559             }
560         }
561         if (receivers.size() > 0) {
562             pw.print(prefix); pw.println("Receivers:");
563             for (int i=0; i<receivers.size(); i++) {
564                 pw.print(prefix); pw.print("  - "); pw.println(receivers.valueAt(i));
565             }
566         }
567         if (mAllowBackgroundActivityStartsTokens.size() > 0) {
568             pw.print(prefix); pw.println("Background activity start whitelist tokens:");
569             for (int i = 0; i < mAllowBackgroundActivityStartsTokens.size(); i++) {
570                 pw.print(prefix); pw.print("  - ");
571                 pw.println(mAllowBackgroundActivityStartsTokens.valueAt(i));
572             }
573         }
574     }
575 
ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid)576     ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName,
577             int _uid) {
578         mService = _service;
579         info = _info;
580         isolated = _info.uid != _uid;
581         appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID
582                 && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID);
583         uid = _uid;
584         userId = UserHandle.getUserId(_uid);
585         processName = _processName;
586         maxAdj = ProcessList.UNKNOWN_ADJ;
587         mCurRawAdj = setRawAdj = ProcessList.INVALID_ADJ;
588         curAdj = setAdj = verifiedAdj = ProcessList.INVALID_ADJ;
589         mPersistent = false;
590         removed = false;
591         lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis();
592         mWindowProcessController = new WindowProcessController(
593                 mService.mActivityTaskManager, info, processName, uid, userId, this, this);
594         pkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode));
595     }
596 
setPid(int _pid)597     public void setPid(int _pid) {
598         pid = _pid;
599         mWindowProcessController.setPid(pid);
600         procStatFile = null;
601         shortStringName = null;
602         stringName = null;
603     }
604 
makeActive(IApplicationThread _thread, ProcessStatsService tracker)605     public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
606         if (thread == null) {
607             final ProcessState origBase = baseProcessTracker;
608             if (origBase != null) {
609                 origBase.setState(ProcessStats.STATE_NOTHING,
610                         tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList.mPkgList);
611                 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) {
612                     StatsLog.write(StatsLog.PROCESS_STATE_CHANGED,
613                             uid, processName, pkgList.keyAt(ipkg),
614                             ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING),
615                             pkgList.valueAt(ipkg).appVersion);
616                 }
617                 origBase.makeInactive();
618             }
619             baseProcessTracker = tracker.getProcessStateLocked(info.packageName, info.uid,
620                     info.longVersionCode, processName);
621             baseProcessTracker.makeActive();
622             for (int i=0; i<pkgList.size(); i++) {
623                 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
624                 if (holder.state != null && holder.state != origBase) {
625                     holder.state.makeInactive();
626                 }
627                 tracker.updateProcessStateHolderLocked(holder, pkgList.keyAt(i), info.uid,
628                         info.longVersionCode, processName);
629                 if (holder.state != baseProcessTracker) {
630                     holder.state.makeActive();
631                 }
632             }
633         }
634         thread = _thread;
635         mWindowProcessController.setThread(thread);
636     }
637 
makeInactive(ProcessStatsService tracker)638     public void makeInactive(ProcessStatsService tracker) {
639         thread = null;
640         mWindowProcessController.setThread(null);
641         final ProcessState origBase = baseProcessTracker;
642         if (origBase != null) {
643             if (origBase != null) {
644                 origBase.setState(ProcessStats.STATE_NOTHING,
645                         tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList.mPkgList);
646                 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) {
647                     StatsLog.write(StatsLog.PROCESS_STATE_CHANGED,
648                             uid, processName, pkgList.keyAt(ipkg),
649                             ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING),
650                             pkgList.valueAt(ipkg).appVersion);
651                 }
652                 origBase.makeInactive();
653             }
654             baseProcessTracker = null;
655             for (int i=0; i<pkgList.size(); i++) {
656                 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
657                 if (holder.state != null && holder.state != origBase) {
658                     holder.state.makeInactive();
659                 }
660                 holder.pkg = null;
661                 holder.state = null;
662             }
663         }
664     }
665 
hasActivities()666     boolean hasActivities() {
667         return mWindowProcessController.hasActivities();
668     }
669 
hasActivitiesOrRecentTasks()670     boolean hasActivitiesOrRecentTasks() {
671         return mWindowProcessController.hasActivitiesOrRecentTasks();
672     }
673 
hasRecentTasks()674     boolean hasRecentTasks() {
675         return mWindowProcessController.hasRecentTasks();
676     }
677 
678     /**
679      * This method returns true if any of the activities within the process record are interesting
680      * to the user. See HistoryRecord.isInterestingToUserLocked()
681      */
isInterestingToUserLocked()682     public boolean isInterestingToUserLocked() {
683         if (mWindowProcessController.isInterestingToUser()) {
684             return true;
685         }
686 
687         final int servicesSize = services.size();
688         for (int i = 0; i < servicesSize; i++) {
689             ServiceRecord r = services.valueAt(i);
690             if (r.isForeground) {
691                 return true;
692             }
693         }
694         return false;
695     }
696 
unlinkDeathRecipient()697     public void unlinkDeathRecipient() {
698         if (deathRecipient != null && thread != null) {
699             thread.asBinder().unlinkToDeath(deathRecipient, 0);
700         }
701         deathRecipient = null;
702     }
703 
updateHasAboveClientLocked()704     void updateHasAboveClientLocked() {
705         hasAboveClient = false;
706         for (int i=connections.size()-1; i>=0; i--) {
707             ConnectionRecord cr = connections.valueAt(i);
708             if ((cr.flags&Context.BIND_ABOVE_CLIENT) != 0) {
709                 hasAboveClient = true;
710                 break;
711             }
712         }
713     }
714 
modifyRawOomAdj(int adj)715     int modifyRawOomAdj(int adj) {
716         if (hasAboveClient) {
717             // If this process has bound to any services with BIND_ABOVE_CLIENT,
718             // then we need to drop its adjustment to be lower than the service's
719             // in order to honor the request.  We want to drop it by one adjustment
720             // level...  but there is special meaning applied to various levels so
721             // we will skip some of them.
722             if (adj < ProcessList.FOREGROUND_APP_ADJ) {
723                 // System process will not get dropped, ever
724             } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
725                 adj = ProcessList.VISIBLE_APP_ADJ;
726             } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
727                 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
728             } else if (adj < ProcessList.PERCEPTIBLE_LOW_APP_ADJ) {
729                 adj = ProcessList.PERCEPTIBLE_LOW_APP_ADJ;
730             } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) {
731                 adj = ProcessList.CACHED_APP_MIN_ADJ;
732             } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) {
733                 adj++;
734             }
735         }
736         return adj;
737     }
738 
scheduleCrash(String message)739     void scheduleCrash(String message) {
740         // Checking killedbyAm should keep it from showing the crash dialog if the process
741         // was already dead for a good / normal reason.
742         if (!killedByAm) {
743             if (thread != null) {
744                 if (pid == Process.myPid()) {
745                     Slog.w(TAG, "scheduleCrash: trying to crash system process!");
746                     return;
747                 }
748                 long ident = Binder.clearCallingIdentity();
749                 try {
750                     thread.scheduleCrash(message);
751                 } catch (RemoteException e) {
752                     // If it's already dead our work is done. If it's wedged just kill it.
753                     // We won't get the crash dialog or the error reporting.
754                     kill("scheduleCrash for '" + message + "' failed", true);
755                 } finally {
756                     Binder.restoreCallingIdentity(ident);
757                 }
758             }
759         }
760     }
761 
kill(String reason, boolean noisy)762     void kill(String reason, boolean noisy) {
763         if (!killedByAm) {
764             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
765             if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
766                 mService.reportUidInfoMessageLocked(TAG,
767                         "Killing " + toShortString() + " (adj " + setAdj + "): " + reason,
768                         info.uid);
769             }
770             if (pid > 0) {
771                 EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
772                 Process.killProcessQuiet(pid);
773                 ProcessList.killProcessGroup(uid, pid);
774             } else {
775                 pendingStart = false;
776             }
777             if (!mPersistent) {
778                 killed = true;
779                 killedByAm = true;
780             }
781             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
782         }
783     }
784 
785     @Override
writeToProto(ProtoOutputStream proto, long fieldId)786     public void writeToProto(ProtoOutputStream proto, long fieldId) {
787         writeToProto(proto, fieldId, -1);
788     }
789 
writeToProto(ProtoOutputStream proto, long fieldId, int lruIndex)790     public void writeToProto(ProtoOutputStream proto, long fieldId, int lruIndex) {
791         long token = proto.start(fieldId);
792         proto.write(ProcessRecordProto.PID, pid);
793         proto.write(ProcessRecordProto.PROCESS_NAME, processName);
794         proto.write(ProcessRecordProto.UID, info.uid);
795         if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) {
796             proto.write(ProcessRecordProto.USER_ID, userId);
797             proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid));
798         }
799         if (uid != info.uid) {
800             proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid));
801         }
802         proto.write(ProcessRecordProto.PERSISTENT, mPersistent);
803         if (lruIndex >= 0) {
804             proto.write(ProcessRecordProto.LRU_INDEX, lruIndex);
805         }
806         proto.end(token);
807     }
808 
toShortString()809     public String toShortString() {
810         if (shortStringName != null) {
811             return shortStringName;
812         }
813         StringBuilder sb = new StringBuilder(128);
814         toShortString(sb);
815         return shortStringName = sb.toString();
816     }
817 
toShortString(StringBuilder sb)818     void toShortString(StringBuilder sb) {
819         sb.append(pid);
820         sb.append(':');
821         sb.append(processName);
822         sb.append('/');
823         if (info.uid < Process.FIRST_APPLICATION_UID) {
824             sb.append(uid);
825         } else {
826             sb.append('u');
827             sb.append(userId);
828             int appId = UserHandle.getAppId(info.uid);
829             if (appId >= Process.FIRST_APPLICATION_UID) {
830                 sb.append('a');
831                 sb.append(appId - Process.FIRST_APPLICATION_UID);
832             } else {
833                 sb.append('s');
834                 sb.append(appId);
835             }
836             if (uid != info.uid) {
837                 sb.append('i');
838                 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
839             }
840         }
841     }
842 
toString()843     public String toString() {
844         if (stringName != null) {
845             return stringName;
846         }
847         StringBuilder sb = new StringBuilder(128);
848         sb.append("ProcessRecord{");
849         sb.append(Integer.toHexString(System.identityHashCode(this)));
850         sb.append(' ');
851         toShortString(sb);
852         sb.append('}');
853         return stringName = sb.toString();
854     }
855 
makeAdjReason()856     public String makeAdjReason() {
857         if (adjSource != null || adjTarget != null) {
858             StringBuilder sb = new StringBuilder(128);
859             sb.append(' ');
860             if (adjTarget instanceof ComponentName) {
861                 sb.append(((ComponentName)adjTarget).flattenToShortString());
862             } else if (adjTarget != null) {
863                 sb.append(adjTarget.toString());
864             } else {
865                 sb.append("{null}");
866             }
867             sb.append("<=");
868             if (adjSource instanceof ProcessRecord) {
869                 sb.append("Proc{");
870                 sb.append(((ProcessRecord)adjSource).toShortString());
871                 sb.append("}");
872             } else if (adjSource != null) {
873                 sb.append(adjSource.toString());
874             } else {
875                 sb.append("{null}");
876             }
877             return sb.toString();
878         }
879         return null;
880     }
881 
882     /*
883      *  Return true if package has been added false if not
884      */
addPackage(String pkg, long versionCode, ProcessStatsService tracker)885     public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) {
886         if (!pkgList.containsKey(pkg)) {
887             ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
888                     versionCode);
889             if (baseProcessTracker != null) {
890                 tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode,
891                         processName);
892                 pkgList.put(pkg, holder);
893                 if (holder.state != baseProcessTracker) {
894                     holder.state.makeActive();
895                 }
896             } else {
897                 pkgList.put(pkg, holder);
898             }
899             return true;
900         }
901         return false;
902     }
903 
getSetAdjWithServices()904     public int getSetAdjWithServices() {
905         if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
906             if (hasStartedServices) {
907                 return ProcessList.SERVICE_B_ADJ;
908             }
909         }
910         return setAdj;
911     }
912 
forceProcessStateUpTo(int newState)913     public void forceProcessStateUpTo(int newState) {
914         if (mRepProcState > newState) {
915             mRepProcState = newState;
916             setCurProcState(newState);
917             setCurRawProcState(newState);
918             for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) {
919                 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED,
920                         uid, processName, pkgList.keyAt(ipkg),
921                         ActivityManager.processStateAmToProto(mRepProcState),
922                         pkgList.valueAt(ipkg).appVersion);
923             }
924         }
925     }
926 
927     /*
928      *  Delete all packages from list except the package indicated in info
929      */
resetPackageList(ProcessStatsService tracker)930     public void resetPackageList(ProcessStatsService tracker) {
931         final int N = pkgList.size();
932         if (baseProcessTracker != null) {
933             long now = SystemClock.uptimeMillis();
934             baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
935                     tracker.getMemFactorLocked(), now, pkgList.mPkgList);
936             for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) {
937                 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED,
938                         uid, processName, pkgList.keyAt(ipkg),
939                         ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING),
940                         pkgList.valueAt(ipkg).appVersion);
941             }
942             if (N != 1) {
943                 for (int i=0; i<N; i++) {
944                     ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
945                     if (holder.state != null && holder.state != baseProcessTracker) {
946                         holder.state.makeInactive();
947                     }
948 
949                 }
950                 pkgList.clear();
951                 ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
952                         info.longVersionCode);
953                 tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid,
954                         info.longVersionCode, processName);
955                 pkgList.put(info.packageName, holder);
956                 if (holder.state != baseProcessTracker) {
957                     holder.state.makeActive();
958                 }
959             }
960         } else if (N != 1) {
961             pkgList.clear();
962             pkgList.put(info.packageName, new ProcessStats.ProcessStateHolder(info.longVersionCode));
963         }
964     }
965 
getPackageList()966     public String[] getPackageList() {
967         int size = pkgList.size();
968         if (size == 0) {
969             return null;
970         }
971         String list[] = new String[size];
972         for (int i=0; i<pkgList.size(); i++) {
973             list[i] = pkgList.keyAt(i);
974         }
975         return list;
976     }
977 
getPackageListWithVersionCode()978     public List<VersionedPackage> getPackageListWithVersionCode() {
979         int size = pkgList.size();
980         if (size == 0) {
981             return null;
982         }
983         List<VersionedPackage> list = new ArrayList<>();
984         for (int i = 0; i < pkgList.size(); i++) {
985             list.add(new VersionedPackage(pkgList.keyAt(i), pkgList.valueAt(i).appVersion));
986         }
987         return list;
988     }
989 
getWindowProcessController()990     WindowProcessController getWindowProcessController() {
991         return mWindowProcessController;
992     }
993 
setCurrentSchedulingGroup(int curSchedGroup)994     void setCurrentSchedulingGroup(int curSchedGroup) {
995         mCurSchedGroup = curSchedGroup;
996         mWindowProcessController.setCurrentSchedulingGroup(curSchedGroup);
997     }
998 
getCurrentSchedulingGroup()999     int getCurrentSchedulingGroup() {
1000         return mCurSchedGroup;
1001     }
1002 
setCurProcState(int curProcState)1003     void setCurProcState(int curProcState) {
1004         mCurProcState = curProcState;
1005         mWindowProcessController.setCurrentProcState(mCurProcState);
1006     }
1007 
getCurProcState()1008     int getCurProcState() {
1009         return mCurProcState;
1010     }
1011 
setCurRawProcState(int curRawProcState)1012     void setCurRawProcState(int curRawProcState) {
1013         mCurRawProcState = curRawProcState;
1014     }
1015 
getCurRawProcState()1016     int getCurRawProcState() {
1017         return mCurRawProcState;
1018     }
1019 
setReportedProcState(int repProcState)1020     void setReportedProcState(int repProcState) {
1021         mRepProcState = repProcState;
1022         for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) {
1023             StatsLog.write(StatsLog.PROCESS_STATE_CHANGED,
1024                     uid, processName, pkgList.keyAt(ipkg),
1025                     ActivityManager.processStateAmToProto(mRepProcState),
1026                     pkgList.valueAt(ipkg).appVersion);
1027         }
1028         mWindowProcessController.setReportedProcState(repProcState);
1029     }
1030 
getReportedProcState()1031     int getReportedProcState() {
1032         return mRepProcState;
1033     }
1034 
setCrashing(boolean crashing)1035     void setCrashing(boolean crashing) {
1036         mCrashing = crashing;
1037         mWindowProcessController.setCrashing(crashing);
1038     }
1039 
isCrashing()1040     boolean isCrashing() {
1041         return mCrashing;
1042     }
1043 
setNotResponding(boolean notResponding)1044     void setNotResponding(boolean notResponding) {
1045         mNotResponding = notResponding;
1046         mWindowProcessController.setNotResponding(notResponding);
1047     }
1048 
isNotResponding()1049     boolean isNotResponding() {
1050         return mNotResponding;
1051     }
1052 
setPersistent(boolean persistent)1053     void setPersistent(boolean persistent) {
1054         mPersistent = persistent;
1055         mWindowProcessController.setPersistent(persistent);
1056     }
1057 
isPersistent()1058     boolean isPersistent() {
1059         return mPersistent;
1060     }
1061 
setRequiredAbi(String requiredAbi)1062     public void setRequiredAbi(String requiredAbi) {
1063         mRequiredAbi = requiredAbi;
1064         mWindowProcessController.setRequiredAbi(requiredAbi);
1065     }
1066 
getRequiredAbi()1067     String getRequiredAbi() {
1068         return mRequiredAbi;
1069     }
1070 
setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes)1071     void setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes) {
1072         mHasForegroundServices = hasForegroundServices;
1073         mFgServiceTypes = fgServiceTypes;
1074         mWindowProcessController.setHasForegroundServices(hasForegroundServices);
1075     }
1076 
hasForegroundServices()1077     boolean hasForegroundServices() {
1078         return mHasForegroundServices;
1079     }
1080 
hasLocationForegroundServices()1081     boolean hasLocationForegroundServices() {
1082         return mHasForegroundServices
1083                 && (mFgServiceTypes & ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) != 0;
1084     }
1085 
getForegroundServiceTypes()1086     int getForegroundServiceTypes() {
1087         return mHasForegroundServices ? mFgServiceTypes : 0;
1088     }
1089 
getReportedForegroundServiceTypes()1090     int getReportedForegroundServiceTypes() {
1091         return mRepFgServiceTypes;
1092     }
1093 
setReportedForegroundServiceTypes(int foregroundServiceTypes)1094     void setReportedForegroundServiceTypes(int foregroundServiceTypes) {
1095         mRepFgServiceTypes = foregroundServiceTypes;
1096     }
1097 
setHasForegroundActivities(boolean hasForegroundActivities)1098     void setHasForegroundActivities(boolean hasForegroundActivities) {
1099         mHasForegroundActivities = hasForegroundActivities;
1100         mWindowProcessController.setHasForegroundActivities(hasForegroundActivities);
1101     }
1102 
hasForegroundActivities()1103     boolean hasForegroundActivities() {
1104         return mHasForegroundActivities;
1105     }
1106 
setHasClientActivities(boolean hasClientActivities)1107     void setHasClientActivities(boolean hasClientActivities) {
1108         mHasClientActivities = hasClientActivities;
1109         mWindowProcessController.setHasClientActivities(hasClientActivities);
1110     }
1111 
hasClientActivities()1112     boolean hasClientActivities() {
1113         return mHasClientActivities;
1114     }
1115 
setHasTopUi(boolean hasTopUi)1116     void setHasTopUi(boolean hasTopUi) {
1117         mHasTopUi = hasTopUi;
1118         mWindowProcessController.setHasTopUi(hasTopUi);
1119     }
1120 
hasTopUi()1121     boolean hasTopUi() {
1122         return mHasTopUi;
1123     }
1124 
setHasOverlayUi(boolean hasOverlayUi)1125     void setHasOverlayUi(boolean hasOverlayUi) {
1126         mHasOverlayUi = hasOverlayUi;
1127         mWindowProcessController.setHasOverlayUi(hasOverlayUi);
1128     }
1129 
hasOverlayUi()1130     boolean hasOverlayUi() {
1131         return mHasOverlayUi;
1132     }
1133 
setInteractionEventTime(long interactionEventTime)1134     void setInteractionEventTime(long interactionEventTime) {
1135         mInteractionEventTime = interactionEventTime;
1136         mWindowProcessController.setInteractionEventTime(interactionEventTime);
1137     }
1138 
getInteractionEventTime()1139     long getInteractionEventTime() {
1140         return mInteractionEventTime;
1141     }
1142 
setFgInteractionTime(long fgInteractionTime)1143     void setFgInteractionTime(long fgInteractionTime) {
1144         mFgInteractionTime = fgInteractionTime;
1145         mWindowProcessController.setFgInteractionTime(fgInteractionTime);
1146     }
1147 
getFgInteractionTime()1148     long getFgInteractionTime() {
1149         return mFgInteractionTime;
1150     }
1151 
setWhenUnimportant(long whenUnimportant)1152     void setWhenUnimportant(long whenUnimportant) {
1153         mWhenUnimportant = whenUnimportant;
1154         mWindowProcessController.setWhenUnimportant(whenUnimportant);
1155     }
1156 
getWhenUnimportant()1157     long getWhenUnimportant() {
1158         return mWhenUnimportant;
1159     }
1160 
setDebugging(boolean debugging)1161     void setDebugging(boolean debugging) {
1162         mDebugging = debugging;
1163         mWindowProcessController.setDebugging(debugging);
1164     }
1165 
isDebugging()1166     boolean isDebugging() {
1167         return mDebugging;
1168     }
1169 
setUsingWrapper(boolean usingWrapper)1170     void setUsingWrapper(boolean usingWrapper) {
1171         mUsingWrapper = usingWrapper;
1172         mWindowProcessController.setUsingWrapper(usingWrapper);
1173     }
1174 
isUsingWrapper()1175     boolean isUsingWrapper() {
1176         return mUsingWrapper;
1177     }
1178 
addAllowBackgroundActivityStartsToken(Binder entity)1179     void addAllowBackgroundActivityStartsToken(Binder entity) {
1180         if (entity == null) return;
1181         mAllowBackgroundActivityStartsTokens.add(entity);
1182         mWindowProcessController.setAllowBackgroundActivityStarts(true);
1183     }
1184 
removeAllowBackgroundActivityStartsToken(Binder entity)1185     void removeAllowBackgroundActivityStartsToken(Binder entity) {
1186         if (entity == null) return;
1187         mAllowBackgroundActivityStartsTokens.remove(entity);
1188         mWindowProcessController.setAllowBackgroundActivityStarts(
1189                 !mAllowBackgroundActivityStartsTokens.isEmpty());
1190     }
1191 
addBoundClientUid(int clientUid)1192     void addBoundClientUid(int clientUid) {
1193         mBoundClientUids.add(clientUid);
1194         mWindowProcessController.setBoundClientUids(mBoundClientUids);
1195     }
1196 
updateBoundClientUids()1197     void updateBoundClientUids() {
1198         if (services.isEmpty()) {
1199             clearBoundClientUids();
1200             return;
1201         }
1202         // grab a set of clientUids of all connections of all services
1203         ArraySet<Integer> boundClientUids = new ArraySet<>();
1204         final int K = services.size();
1205         for (int j = 0; j < K; j++) {
1206             ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns =
1207                     services.valueAt(j).getConnections();
1208             final int N = conns.size();
1209             for (int conni = 0; conni < N; conni++) {
1210                 ArrayList<ConnectionRecord> c = conns.valueAt(conni);
1211                 for (int i = 0; i < c.size(); i++) {
1212                     boundClientUids.add(c.get(i).clientUid);
1213                 }
1214             }
1215         }
1216         mBoundClientUids = boundClientUids;
1217         mWindowProcessController.setBoundClientUids(mBoundClientUids);
1218     }
1219 
addBoundClientUidsOfNewService(ServiceRecord sr)1220     void addBoundClientUidsOfNewService(ServiceRecord sr) {
1221         if (sr == null) {
1222             return;
1223         }
1224         ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = sr.getConnections();
1225         for (int conni = conns.size() - 1; conni >= 0; conni--) {
1226             ArrayList<ConnectionRecord> c = conns.valueAt(conni);
1227             for (int i = 0; i < c.size(); i++) {
1228                 mBoundClientUids.add(c.get(i).clientUid);
1229             }
1230         }
1231         mWindowProcessController.setBoundClientUids(mBoundClientUids);
1232     }
1233 
clearBoundClientUids()1234     void clearBoundClientUids() {
1235         mBoundClientUids.clear();
1236         mWindowProcessController.setBoundClientUids(mBoundClientUids);
1237     }
1238 
setActiveInstrumentation(ActiveInstrumentation instr)1239     void setActiveInstrumentation(ActiveInstrumentation instr) {
1240         mInstr = instr;
1241         boolean isInstrumenting = instr != null;
1242         mWindowProcessController.setInstrumenting(isInstrumenting,
1243                 isInstrumenting && instr.mHasBackgroundActivityStartsPermission);
1244     }
1245 
getActiveInstrumentation()1246     ActiveInstrumentation getActiveInstrumentation() {
1247         return mInstr;
1248     }
1249 
setCurRawAdj(int curRawAdj)1250     void setCurRawAdj(int curRawAdj) {
1251         mCurRawAdj = curRawAdj;
1252         mWindowProcessController.setPerceptible(curRawAdj <= ProcessList.PERCEPTIBLE_APP_ADJ);
1253     }
1254 
getCurRawAdj()1255     int getCurRawAdj() {
1256         return mCurRawAdj;
1257     }
1258 
1259     @Override
clearProfilerIfNeeded()1260     public void clearProfilerIfNeeded() {
1261         synchronized (mService) {
1262             if (mService.mProfileData.getProfileProc() == null
1263                     || mService.mProfileData.getProfilerInfo() == null
1264                     || mService.mProfileData.getProfileProc() != this) {
1265                 return;
1266             }
1267             mService.clearProfilerLocked();
1268         }
1269     }
1270 
1271     @Override
updateServiceConnectionActivities()1272     public void updateServiceConnectionActivities() {
1273         synchronized (mService) {
1274             mService.mServices.updateServiceConnectionActivitiesLocked(this);
1275         }
1276     }
1277 
1278     @Override
setPendingUiClean(boolean pendingUiClean)1279     public void setPendingUiClean(boolean pendingUiClean) {
1280         synchronized (mService) {
1281             mPendingUiClean = pendingUiClean;
1282             mWindowProcessController.setPendingUiClean(pendingUiClean);
1283         }
1284     }
1285 
hasPendingUiClean()1286     boolean hasPendingUiClean() {
1287         return mPendingUiClean;
1288     }
1289 
1290     @Override
setPendingUiCleanAndForceProcessStateUpTo(int newState)1291     public void setPendingUiCleanAndForceProcessStateUpTo(int newState) {
1292         synchronized (mService) {
1293             setPendingUiClean(true);
1294             forceProcessStateUpTo(newState);
1295         }
1296     }
1297 
1298     @Override
updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1299     public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange,
1300             boolean updateOomAdj) {
1301         synchronized (mService) {
1302             if (updateServiceConnectionActivities) {
1303                 mService.mServices.updateServiceConnectionActivitiesLocked(this);
1304             }
1305             mService.mProcessList.updateLruProcessLocked(this, activityChange, null /* client */);
1306             if (updateOomAdj) {
1307                 mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
1308             }
1309         }
1310     }
1311 
1312     @Override
isRemoved()1313     public boolean isRemoved() {
1314         return removed;
1315     }
1316 
1317     /**
1318      * Returns the total time (in milliseconds) spent executing in both user and system code.
1319      * Safe to call without lock held.
1320      */
1321     @Override
getCpuTime()1322     public long getCpuTime() {
1323         return mService.mProcessCpuTracker.getCpuTimeForPid(pid);
1324     }
1325 
1326     @Override
onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1327     public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName,
1328             long versionCode) {
1329         synchronized (mService) {
1330             waitingToKill = null;
1331             if (setProfileProc) {
1332                 mService.mProfileData.setProfileProc(this);
1333             }
1334             if (packageName != null) {
1335                 addPackage(packageName, versionCode, mService.mProcessStats);
1336             }
1337 
1338             // Update oom adj first, we don't want the additional states are involved in this round.
1339             updateProcessInfo(false /* updateServiceConnectionActivities */,
1340                     true /* activityChange */, true /* updateOomAdj */);
1341             hasShownUi = true;
1342             setPendingUiClean(true);
1343             forceProcessStateUpTo(topProcessState);
1344         }
1345     }
1346 
1347     @Override
appDied()1348     public void appDied() {
1349         synchronized (mService) {
1350             mService.appDiedLocked(this);
1351         }
1352     }
1353 
1354     @Override
setRunningRemoteAnimation(boolean runningRemoteAnimation)1355     public void setRunningRemoteAnimation(boolean runningRemoteAnimation) {
1356         if (pid == Process.myPid()) {
1357             Slog.wtf(TAG, "system can't run remote animation");
1358             return;
1359         }
1360         synchronized (mService) {
1361             if (this.runningRemoteAnimation == runningRemoteAnimation) {
1362                 return;
1363             }
1364             this.runningRemoteAnimation = runningRemoteAnimation;
1365             if (DEBUG_OOM_ADJ) {
1366                 Slog.i(TAG, "Setting runningRemoteAnimation=" + runningRemoteAnimation
1367                         + " for pid=" + pid);
1368             }
1369             mService.updateOomAdjLocked(this, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
1370         }
1371     }
1372 
getInputDispatchingTimeout()1373     public long getInputDispatchingTimeout() {
1374         return mWindowProcessController.getInputDispatchingTimeout();
1375     }
1376 
getProcessClassEnum()1377     public int getProcessClassEnum() {
1378         if (pid == MY_PID) {
1379             return ServerProtoEnums.SYSTEM_SERVER;
1380         }
1381         if (info == null) {
1382             return ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
1383         }
1384         return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP :
1385             ServerProtoEnums.DATA_APP;
1386     }
1387 
1388     /**
1389      * Unless configured otherwise, swallow ANRs in background processes & kill the process.
1390      * Non-private access is for tests only.
1391      */
1392     @VisibleForTesting
isSilentAnr()1393     boolean isSilentAnr() {
1394         return !getShowBackground() && !isInterestingForBackgroundTraces();
1395     }
1396 
1397     /** Non-private access is for tests only. */
1398     @VisibleForTesting
getLruProcessList()1399     List<ProcessRecord> getLruProcessList() {
1400         return mService.mProcessList.mLruProcesses;
1401     }
1402 
1403     /** Non-private access is for tests only. */
1404     @VisibleForTesting
isMonitorCpuUsage()1405     boolean isMonitorCpuUsage() {
1406         return mService.MONITOR_CPU_USAGE;
1407     }
1408 
appNotResponding(String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String annotation)1409     void appNotResponding(String activityShortComponentName, ApplicationInfo aInfo,
1410             String parentShortComponentName, WindowProcessController parentProcess,
1411             boolean aboveSystem, String annotation) {
1412         ArrayList<Integer> firstPids = new ArrayList<>(5);
1413         SparseArray<Boolean> lastPids = new SparseArray<>(20);
1414 
1415         mWindowProcessController.appEarlyNotResponding(annotation, () -> kill("anr", true));
1416 
1417         long anrTime = SystemClock.uptimeMillis();
1418         if (isMonitorCpuUsage()) {
1419             mService.updateCpuStatsNow();
1420         }
1421 
1422         synchronized (mService) {
1423             // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
1424             if (mService.mAtmInternal.isShuttingDown()) {
1425                 Slog.i(TAG, "During shutdown skipping ANR: " + this + " " + annotation);
1426                 return;
1427             } else if (isNotResponding()) {
1428                 Slog.i(TAG, "Skipping duplicate ANR: " + this + " " + annotation);
1429                 return;
1430             } else if (isCrashing()) {
1431                 Slog.i(TAG, "Crashing app skipping ANR: " + this + " " + annotation);
1432                 return;
1433             } else if (killedByAm) {
1434                 Slog.i(TAG, "App already killed by AM skipping ANR: " + this + " " + annotation);
1435                 return;
1436             } else if (killed) {
1437                 Slog.i(TAG, "Skipping died app ANR: " + this + " " + annotation);
1438                 return;
1439             }
1440 
1441             // In case we come through here for the same app before completing
1442             // this one, mark as anring now so we will bail out.
1443             setNotResponding(true);
1444 
1445             // Log the ANR to the event log.
1446             EventLog.writeEvent(EventLogTags.AM_ANR, userId, pid, processName, info.flags,
1447                     annotation);
1448 
1449             // Dump thread traces as quickly as we can, starting with "interesting" processes.
1450             firstPids.add(pid);
1451 
1452             // Don't dump other PIDs if it's a background ANR
1453             if (!isSilentAnr()) {
1454                 int parentPid = pid;
1455                 if (parentProcess != null && parentProcess.getPid() > 0) {
1456                     parentPid = parentProcess.getPid();
1457                 }
1458                 if (parentPid != pid) firstPids.add(parentPid);
1459 
1460                 if (MY_PID != pid && MY_PID != parentPid) firstPids.add(MY_PID);
1461 
1462                 for (int i = getLruProcessList().size() - 1; i >= 0; i--) {
1463                     ProcessRecord r = getLruProcessList().get(i);
1464                     if (r != null && r.thread != null) {
1465                         int myPid = r.pid;
1466                         if (myPid > 0 && myPid != pid && myPid != parentPid && myPid != MY_PID) {
1467                             if (r.isPersistent()) {
1468                                 firstPids.add(myPid);
1469                                 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
1470                             } else if (r.treatLikeActivity) {
1471                                 firstPids.add(myPid);
1472                                 if (DEBUG_ANR) Slog.i(TAG, "Adding likely IME: " + r);
1473                             } else {
1474                                 lastPids.put(myPid, Boolean.TRUE);
1475                                 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
1476                             }
1477                         }
1478                     }
1479                 }
1480             }
1481         }
1482 
1483         // Log the ANR to the main log.
1484         StringBuilder info = new StringBuilder();
1485         info.setLength(0);
1486         info.append("ANR in ").append(processName);
1487         if (activityShortComponentName != null) {
1488             info.append(" (").append(activityShortComponentName).append(")");
1489         }
1490         info.append("\n");
1491         info.append("PID: ").append(pid).append("\n");
1492         if (annotation != null) {
1493             info.append("Reason: ").append(annotation).append("\n");
1494         }
1495         if (parentShortComponentName != null
1496                 && parentShortComponentName.equals(activityShortComponentName)) {
1497             info.append("Parent: ").append(parentShortComponentName).append("\n");
1498         }
1499 
1500         ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
1501 
1502         // don't dump native PIDs for background ANRs unless it is the process of interest
1503         String[] nativeProcs = null;
1504         if (isSilentAnr()) {
1505             for (int i = 0; i < NATIVE_STACKS_OF_INTEREST.length; i++) {
1506                 if (NATIVE_STACKS_OF_INTEREST[i].equals(processName)) {
1507                     nativeProcs = new String[] { processName };
1508                     break;
1509                 }
1510             }
1511         } else {
1512             nativeProcs = NATIVE_STACKS_OF_INTEREST;
1513         }
1514 
1515         int[] pids = nativeProcs == null ? null : Process.getPidsForCommands(nativeProcs);
1516         ArrayList<Integer> nativePids = null;
1517 
1518         if (pids != null) {
1519             nativePids = new ArrayList<>(pids.length);
1520             for (int i : pids) {
1521                 nativePids.add(i);
1522             }
1523         }
1524 
1525         // For background ANRs, don't pass the ProcessCpuTracker to
1526         // avoid spending 1/2 second collecting stats to rank lastPids.
1527         File tracesFile = ActivityManagerService.dumpStackTraces(firstPids,
1528                 (isSilentAnr()) ? null : processCpuTracker, (isSilentAnr()) ? null : lastPids,
1529                 nativePids);
1530 
1531         String cpuInfo = null;
1532         if (isMonitorCpuUsage()) {
1533             mService.updateCpuStatsNow();
1534             synchronized (mService.mProcessCpuTracker) {
1535                 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
1536             }
1537             info.append(processCpuTracker.printCurrentLoad());
1538             info.append(cpuInfo);
1539         }
1540 
1541         info.append(processCpuTracker.printCurrentState(anrTime));
1542 
1543         Slog.e(TAG, info.toString());
1544         if (tracesFile == null) {
1545             // There is no trace file, so dump (only) the alleged culprit's threads to the log
1546             Process.sendSignal(pid, Process.SIGNAL_QUIT);
1547         }
1548 
1549         StatsLog.write(StatsLog.ANR_OCCURRED, uid, processName,
1550                 activityShortComponentName == null ? "unknown": activityShortComponentName,
1551                 annotation,
1552                 (this.info != null) ? (this.info.isInstantApp()
1553                         ? StatsLog.ANROCCURRED__IS_INSTANT_APP__TRUE
1554                         : StatsLog.ANROCCURRED__IS_INSTANT_APP__FALSE)
1555                         : StatsLog.ANROCCURRED__IS_INSTANT_APP__UNAVAILABLE,
1556                 isInterestingToUserLocked()
1557                         ? StatsLog.ANROCCURRED__FOREGROUND_STATE__FOREGROUND
1558                         : StatsLog.ANROCCURRED__FOREGROUND_STATE__BACKGROUND,
1559                 getProcessClassEnum(),
1560                 (this.info != null) ? this.info.packageName : "");
1561         final ProcessRecord parentPr = parentProcess != null
1562                 ? (ProcessRecord) parentProcess.mOwner : null;
1563         mService.addErrorToDropBox("anr", this, processName, activityShortComponentName,
1564                 parentShortComponentName, parentPr, annotation, cpuInfo, tracesFile, null);
1565 
1566         if (mWindowProcessController.appNotResponding(info.toString(), () -> kill("anr", true),
1567                 () -> {
1568                     synchronized (mService) {
1569                         mService.mServices.scheduleServiceTimeoutLocked(this);
1570                     }
1571                 })) {
1572             return;
1573         }
1574 
1575         synchronized (mService) {
1576             // mBatteryStatsService can be null if the AMS is constructed with injector only. This
1577             // will only happen in tests.
1578             if (mService.mBatteryStatsService != null) {
1579                 mService.mBatteryStatsService.noteProcessAnr(processName, uid);
1580             }
1581 
1582             if (isSilentAnr() && !isDebugging()) {
1583                 kill("bg anr", true);
1584                 return;
1585             }
1586 
1587             // Set the app's notResponding state, and look up the errorReportReceiver
1588             makeAppNotRespondingLocked(activityShortComponentName,
1589                     annotation != null ? "ANR " + annotation : "ANR", info.toString());
1590 
1591             // mUiHandler can be null if the AMS is constructed with injector only. This will only
1592             // happen in tests.
1593             if (mService.mUiHandler != null) {
1594                 // Bring up the infamous App Not Responding dialog
1595                 Message msg = Message.obtain();
1596                 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
1597                 msg.obj = new AppNotRespondingDialog.Data(this, aInfo, aboveSystem);
1598 
1599                 mService.mUiHandler.sendMessage(msg);
1600             }
1601         }
1602     }
1603 
makeAppNotRespondingLocked(String activity, String shortMsg, String longMsg)1604     private void makeAppNotRespondingLocked(String activity, String shortMsg, String longMsg) {
1605         setNotResponding(true);
1606         // mAppErrors can be null if the AMS is constructed with injector only. This will only
1607         // happen in tests.
1608         if (mService.mAppErrors != null) {
1609             notRespondingReport = mService.mAppErrors.generateProcessError(this,
1610                     ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
1611                     activity, shortMsg, longMsg, null);
1612         }
1613         startAppProblemLocked();
1614         getWindowProcessController().stopFreezingActivities();
1615     }
1616 
startAppProblemLocked()1617     void startAppProblemLocked() {
1618         // If this app is not running under the current user, then we can't give it a report button
1619         // because that would require launching the report UI under a different user.
1620         errorReportReceiver = null;
1621 
1622         for (int userId : mService.mUserController.getCurrentProfileIds()) {
1623             if (this.userId == userId) {
1624                 errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
1625                         mService.mContext, info.packageName, info.flags);
1626             }
1627         }
1628         mService.skipCurrentReceiverLocked(this);
1629     }
1630 
isInterestingForBackgroundTraces()1631     private boolean isInterestingForBackgroundTraces() {
1632         // The system_server is always considered interesting.
1633         if (pid == MY_PID) {
1634             return true;
1635         }
1636 
1637         // A package is considered interesting if any of the following is true :
1638         //
1639         // - It's displaying an activity.
1640         // - It's the SystemUI.
1641         // - It has an overlay or a top UI visible.
1642         //
1643         // NOTE: The check whether a given ProcessRecord belongs to the systemui
1644         // process is a bit of a kludge, but the same pattern seems repeated at
1645         // several places in the system server.
1646         return isInterestingToUserLocked() ||
1647                 (info != null && "com.android.systemui".equals(info.packageName))
1648                 || (hasTopUi() || hasOverlayUi());
1649     }
1650 
getShowBackground()1651     private boolean getShowBackground() {
1652         return Settings.Secure.getInt(mService.mContext.getContentResolver(),
1653                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1654     }
1655 }
1656