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