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