• 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.ActivityManagerInternal.OOM_ADJ_REASON_ACTIVITY;
20 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UI_VISIBILITY;
21 
22 import static com.android.internal.util.Preconditions.checkArgument;
23 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
24 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
25 import static com.android.server.am.ActivityManagerService.MY_PID;
26 import static com.android.server.am.OomAdjusterModernImpl.ProcessRecordNode.NUM_NODE_TYPE;
27 
28 import static java.util.Objects.requireNonNull;
29 
30 import android.annotation.NonNull;
31 import android.annotation.Nullable;
32 import android.app.ActivityManager;
33 import android.app.ApplicationExitInfo;
34 import android.app.ApplicationExitInfo.Reason;
35 import android.app.ApplicationExitInfo.SubReason;
36 import android.app.BackgroundStartPrivileges;
37 import android.app.IApplicationThread;
38 import android.content.pm.ApplicationInfo;
39 import android.content.pm.PackageManagerInternal;
40 import android.content.pm.ProcessInfo;
41 import android.content.pm.VersionedPackage;
42 import android.content.res.CompatibilityInfo;
43 import android.os.Binder;
44 import android.os.Bundle;
45 import android.os.IBinder;
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.server.ServerProtoEnums;
52 import android.system.OsConstants;
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.TimeUtils;
59 import android.util.proto.ProtoOutputStream;
60 
61 import com.android.internal.annotations.CompositeRWLock;
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.Zygote;
67 import com.android.server.FgThread;
68 import com.android.server.am.OomAdjusterModernImpl.ProcessRecordNode;
69 import com.android.server.wm.WindowProcessController;
70 import com.android.server.wm.WindowProcessListener;
71 
72 import java.io.PrintWriter;
73 import java.io.StringWriter;
74 import java.util.Arrays;
75 import java.util.List;
76 import java.util.function.Consumer;
77 
78 /**
79  * Full information about a particular process that
80  * is currently running.
81  */
82 class ProcessRecord implements WindowProcessListener {
83     static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;
84 
85     final ActivityManagerService mService; // where we came from
86     private final ActivityManagerGlobalLock mProcLock;
87 
88     // =========================================================
89     // Basic info of the process, immutable or semi-immutable over
90     // the lifecycle of the process
91     // =========================================================
92     volatile ApplicationInfo info; // all about the first app in the process
93     final ProcessInfo processInfo; // if non-null, process-specific manifest info
94     final boolean isolated;     // true if this is a special isolated process
95     public final boolean isSdkSandbox; // true if this is an SDK sandbox process
96     final boolean appZygote;    // true if this is forked from the app zygote
97     final int uid;              // uid of process; may be different from 'info' if isolated
98     final int userId;           // user of process.
99     final String processName;   // name of the process
100     final String sdkSandboxClientAppPackage; // if this is an sdk sandbox process, name of the
101                                              // app package for which it is running
102     final String sdkSandboxClientAppVolumeUuid; // uuid of the app for which the sandbox is running
103 
104     /**
105      * Overall state of process's uid.
106      */
107     @CompositeRWLock({"mService", "mProcLock"})
108     private UidRecord mUidRecord;
109 
110     /**
111      * List of packages running in the process.
112      */
113     private final PackageList mPkgList = new PackageList(this);
114 
115     /**
116      * Additional packages we have a dependency on.
117      */
118     @CompositeRWLock({"mService", "mProcLock"})
119     private ArraySet<String> mPkgDeps;
120 
121     /**
122      * The process of this application; 0 if none.
123      */
124     @CompositeRWLock({"mService", "mProcLock"})
125     int mPid;
126 
127     /**
128      * The process ID which will be set when we're killing this process.
129      */
130     @GuardedBy("mService")
131     private int mDyingPid;
132 
133     /**
134      * The gids this process was launched with.
135      */
136     @GuardedBy("mService")
137     private int[] mGids;
138 
139     /**
140      * The ABI this process was launched with.
141      */
142     @GuardedBy("mService")
143     private String mRequiredAbi;
144 
145     /**
146      * The instruction set this process was launched with.
147      */
148     @GuardedBy("mService")
149     private String mInstructionSet;
150 
151     /**
152      * The actual proc...  may be null only if 'persistent' is true
153      * (in which case we are in the process of launching the app).
154      */
155     @CompositeRWLock({"mService", "mProcLock"})
156     private ApplicationThreadDeferred mThread;
157 
158     /**
159      * Instance of {@link #mThread} that will always meet the {@code oneway}
160      * contract, possibly by using {@link SameProcessApplicationThread}.
161      */
162     @CompositeRWLock({"mService", "mProcLock"})
163     private IApplicationThread mOnewayThread;
164 
165     /**
166      * Always keep this application running?
167      */
168     private volatile boolean mPersistent;
169 
170     /**
171      * Caching of toShortString() result.
172      * <p>Note: No lock here, it doesn't matter in case of race condition</p>
173      */
174     private String mShortStringName;
175 
176     /**
177      * Caching of toString() result.
178      * <p>Note: No lock here, it doesn't matter in case of race condition</p>
179      */
180     private String mStringName;
181 
182     /**
183      * Process start is pending.
184      */
185     @GuardedBy("mService")
186     private boolean mPendingStart;
187 
188     /**
189      * Process finish attach application is pending.
190      */
191     @GuardedBy("mService")
192     private boolean mPendingFinishAttach;
193 
194     /**
195      * Seq no. Indicating the latest process start associated with this process record.
196      */
197     @GuardedBy("mService")
198     private long mStartSeq;
199 
200     /**
201      * Params used in starting this process.
202      */
203     private volatile HostingRecord mHostingRecord;
204 
205     /**
206      * Selinux info of this process.
207      */
208     private volatile String mSeInfo;
209 
210     /**
211      * When the process is started. (before zygote fork)
212      */
213     private volatile long mStartUptime;
214 
215     /**
216      * When the process is started. (before zygote fork)
217      */
218     private volatile long mStartElapsedTime;
219 
220     /**
221      * When the process was sent the bindApplication request
222      */
223     private volatile long mBindApplicationTime;
224 
225     /**
226      * This will be same as {@link #uid} usually except for some apps used during factory testing.
227      */
228     private volatile int mStartUid;
229 
230     /**
231      * Indicates how the external storage was mounted for this process.
232      */
233     private volatile int mMountMode;
234 
235     /**
236      * True if Android/obb and Android/data need to be bind mount.
237      */
238     private volatile boolean mBindMountPending;
239 
240     /**
241      * True when proc was started in user unlocked state.
242      */
243     @GuardedBy("mProcLock")
244     private boolean mUnlocked;
245 
246     /**
247      * TID for RenderThread.
248      */
249     @GuardedBy("mProcLock")
250     private int mRenderThreadTid;
251 
252     /**
253      * Last used compatibility mode.
254      */
255     @GuardedBy("mService")
256     private CompatibilityInfo mCompat;
257 
258     /**
259      * Set of disabled compat changes for the process (all others are enabled).
260      */
261     @GuardedBy("mService")
262     private long[] mDisabledCompatChanges;
263 
264     /**
265      * Set of compat changes for the process that are intended to be logged to logcat.
266      */
267     @GuardedBy("mService")
268     private long[] mLoggableCompatChanges;
269 
270     /**
271      * Who is watching for the death.
272      */
273     @GuardedBy("mService")
274     private IBinder.DeathRecipient mDeathRecipient;
275 
276     /**
277      * Set to currently active instrumentation running in process.
278      */
279     @CompositeRWLock({"mService", "mProcLock"})
280     private ActiveInstrumentation mInstr;
281 
282     /**
283      * True when proc has been killed by activity manager, not for RAM.
284      */
285     @CompositeRWLock({"mService", "mProcLock"})
286     private boolean mKilledByAm;
287 
288     /**
289      * True once we know the process has been killed.
290      */
291     @CompositeRWLock({"mService", "mProcLock"})
292     private boolean mKilled;
293 
294     /**
295      * The timestamp in uptime when this process was killed.
296      */
297     @CompositeRWLock({"mService", "mProcLock"})
298     private long mKillTime;
299 
300     /**
301      * Process is waiting to be killed when in the bg, and reason.
302      */
303     @GuardedBy("mService")
304     private String mWaitingToKill;
305 
306     /**
307      * Whether this process should be killed and removed from process list.
308      * It is set when the package is force-stopped or the process has crashed too many times.
309      */
310     private volatile boolean mRemoved;
311 
312     /**
313      * Was app launched for debugging?
314      */
315     @GuardedBy("mService")
316     private boolean mDebugging;
317 
318     /**
319      * Has process show wait for debugger dialog?
320      */
321     @GuardedBy("mProcLock")
322     private boolean mWaitedForDebugger;
323 
324     /**
325      * For managing the LRU list.
326      */
327     @CompositeRWLock({"mService", "mProcLock"})
328     private long mLastActivityTime;
329 
330     /**
331      * Set to true when process was launched with a wrapper attached.
332      */
333     @GuardedBy("mService")
334     private boolean mUsingWrapper;
335 
336     /**
337      * Sequence id for identifying LRU update cycles.
338      */
339     @GuardedBy("mService")
340     private int mLruSeq;
341 
342     /**
343      * Class to run on start if this is a special isolated process.
344      */
345     @GuardedBy("mService")
346     private String mIsolatedEntryPoint;
347 
348     /**
349      * Arguments to pass to isolatedEntryPoint's main().
350      */
351     @GuardedBy("mService")
352     private String[] mIsolatedEntryPointArgs;
353 
354     /**
355      * Process is currently hosting a backup agent for backup or restore. Note that this is only set
356      * when the process is put into restricted backup mode.
357      */
358     @GuardedBy("mService")
359     private boolean mInFullBackup;
360 
361     /**
362      * A set of tokens that currently contribute to this process being temporarily allowed
363      * to start certain components (eg. activities or foreground services) even if it's not
364      * in the foreground.
365      */
366     @GuardedBy("mBackgroundStartPrivileges")
367     private final ArrayMap<Binder, BackgroundStartPrivileges> mBackgroundStartPrivileges =
368             new ArrayMap<>();
369 
370     /**
371      * The merged BackgroundStartPrivileges based on what's in {@link #mBackgroundStartPrivileges}.
372      * This is lazily generated using {@link #getBackgroundStartPrivileges()}.
373      */
374     @Nullable
375     @GuardedBy("mBackgroundStartPrivileges")
376     private BackgroundStartPrivileges mBackgroundStartPrivilegesMerged =
377             BackgroundStartPrivileges.NONE;
378 
379     /**
380      * Controller for driving the process state on the window manager side.
381      */
382     private final WindowProcessController mWindowProcessController;
383 
384     /**
385      * Profiling info of the process, such as PSS, cpu, etc.
386      */
387     final ProcessProfileRecord mProfile;
388 
389     /**
390      * All about the services in this process.
391      */
392     final ProcessServiceRecord mServices;
393 
394     /**
395      * All about the providers in this process.
396      */
397     final ProcessProviderRecord mProviders;
398 
399     /**
400      * All about the receivers in this process.
401      */
402     final ProcessReceiverRecord mReceivers;
403 
404     /**
405      * All about the error state(crash, ANR) in this process.
406      */
407     final ProcessErrorStateRecord mErrorState;
408 
409     /**
410      * All about the process state info (proc state, oom adj score) in this process.
411      */
412     ProcessStateRecord mState;
413 
414     /**
415      * All about the state info of the optimizer when the process is cached.
416      */
417     final ProcessCachedOptimizerRecord mOptRecord;
418 
419     /**
420      * The preceding instance of the process, which would exist when the previous process is killed
421      * but not fully dead yet; in this case, the new instance of the process should be held until
422      * this preceding instance is fully dead.
423      */
424     volatile ProcessRecord mPredecessor;
425 
426     /**
427      * The succeeding instance of the process, which is going to be started after this process
428      * is killed successfully.
429      */
430     volatile ProcessRecord mSuccessor;
431 
432     /**
433      * The routine to start its successor process.
434      *
435      * <p>Note: It should be accessed from process start thread only.</p>
436      */
437     Runnable mSuccessorStartRunnable;
438 
439     /**
440      * Whether or not the process group of this process has been created.
441      */
442     volatile boolean mProcessGroupCreated;
443 
444     /**
445      * Whether or not we should skip the process group creation.
446      */
447     volatile boolean mSkipProcessGroupCreation;
448 
449     final ProcessRecordNode[] mLinkedNodes = new ProcessRecordNode[NUM_NODE_TYPE];
450 
451     /** Whether the app was launched from a stopped state and is being unstopped. */
452     @GuardedBy("mService")
453     volatile boolean mWasForceStopped;
454 
setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, long startUptime, long startElapsedTime)455     void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo,
456             long startUptime, long startElapsedTime) {
457         this.mStartUid = startUid;
458         this.mHostingRecord = hostingRecord;
459         this.mSeInfo = seInfo;
460         this.mStartUptime = startUptime;
461         this.mStartElapsedTime = startElapsedTime;
462     }
463 
464     @GuardedBy({"mService", "mProcLock"})
dump(PrintWriter pw, String prefix)465     void dump(PrintWriter pw, String prefix) {
466         final long nowUptime = SystemClock.uptimeMillis();
467         final long nowElapsedTime = SystemClock.elapsedRealtime();
468 
469         pw.print(prefix); pw.print("user #"); pw.print(userId);
470                 pw.print(" uid="); pw.print(info.uid);
471         if (uid != info.uid) {
472             pw.print(" ISOLATED uid="); pw.print(uid);
473         }
474         pw.print(" gids={");
475         if (mGids != null) {
476             for (int gi = 0; gi < mGids.length; gi++) {
477                 if (gi != 0) pw.print(", ");
478                 pw.print(mGids[gi]);
479 
480             }
481         }
482         pw.println("}");
483         if (processInfo != null) {
484             pw.print(prefix); pw.println("processInfo:");
485             if (processInfo.deniedPermissions != null) {
486                 for (int i = 0; i < processInfo.deniedPermissions.size(); i++) {
487                     pw.print(prefix); pw.print("  deny: ");
488                     pw.println(processInfo.deniedPermissions.valueAt(i));
489                 }
490             }
491             if (processInfo.gwpAsanMode != ApplicationInfo.GWP_ASAN_DEFAULT) {
492                 pw.print(prefix); pw.println("  gwpAsanMode=" + processInfo.gwpAsanMode);
493             }
494             if (processInfo.memtagMode != ApplicationInfo.MEMTAG_DEFAULT) {
495                 pw.print(prefix); pw.println("  memtagMode=" + processInfo.memtagMode);
496             }
497         }
498         pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi);
499         pw.print(" instructionSet="); pw.println(mInstructionSet);
500         if (info.className != null) {
501             pw.print(prefix); pw.print("class="); pw.println(info.className);
502         }
503         if (info.manageSpaceActivityName != null) {
504             pw.print(prefix); pw.print("manageSpaceActivityName=");
505             pw.println(info.manageSpaceActivityName);
506         }
507 
508         pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
509                 pw.print(" publicDir="); pw.print(info.publicSourceDir);
510                 pw.print(" data="); pw.println(info.dataDir);
511         mPkgList.dump(pw, prefix);
512         if (mPkgDeps != null) {
513             pw.print(prefix); pw.print("packageDependencies={");
514             for (int i = 0; i < mPkgDeps.size(); i++) {
515                 if (i > 0) pw.print(", ");
516                 pw.print(mPkgDeps.valueAt(i));
517             }
518             pw.println("}");
519         }
520         pw.print(prefix); pw.print("compat="); pw.println(mCompat);
521         if (mInstr != null) {
522             pw.print(prefix); pw.print("mInstr="); pw.println(mInstr);
523         }
524         pw.print(prefix); pw.print("thread="); pw.println(mThread);
525         pw.print(prefix); pw.print("pid="); pw.println(mPid);
526         pw.print(prefix); pw.print("lastActivityTime=");
527         TimeUtils.formatDuration(mLastActivityTime, nowUptime, pw);
528         pw.print(prefix); pw.print("startUpTime=");
529         TimeUtils.formatDuration(mStartUptime, nowUptime, pw);
530         pw.print(prefix); pw.print("startElapsedTime=");
531         TimeUtils.formatDuration(mStartElapsedTime, nowElapsedTime, pw);
532         pw.println();
533         if (mPersistent || mRemoved) {
534             pw.print(prefix); pw.print("persistent="); pw.print(mPersistent);
535             pw.print(" removed="); pw.println(mRemoved);
536         }
537         if (mDebugging) {
538             pw.print(prefix); pw.print("mDebugging="); pw.println(mDebugging);
539         }
540         if (mPendingStart) {
541             pw.print(prefix); pw.print("pendingStart="); pw.println(mPendingStart);
542         }
543         pw.print(prefix); pw.print("startSeq="); pw.println(mStartSeq);
544         pw.print(prefix); pw.print("mountMode="); pw.println(
545                 DebugUtils.valueToString(Zygote.class, "MOUNT_EXTERNAL_", mMountMode));
546         if (mKilled || mKilledByAm || mWaitingToKill != null) {
547             pw.print(prefix); pw.print("killed="); pw.print(mKilled);
548             pw.print(" killedByAm="); pw.print(mKilledByAm);
549             pw.print(" waitingToKill="); pw.println(mWaitingToKill);
550         }
551         if (mIsolatedEntryPoint != null || mIsolatedEntryPointArgs != null) {
552             pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(mIsolatedEntryPoint);
553             pw.print(prefix); pw.print("isolatedEntryPointArgs=");
554             pw.println(Arrays.toString(mIsolatedEntryPointArgs));
555         }
556         if (mState.getSetProcState() > ActivityManager.PROCESS_STATE_SERVICE) {
557             mProfile.dumpCputime(pw, prefix);
558         }
559         mProfile.dumpPss(pw, prefix, nowUptime);
560         mState.dump(pw, prefix, nowUptime);
561         mErrorState.dump(pw, prefix, nowUptime);
562         mServices.dump(pw, prefix, nowUptime);
563         mProviders.dump(pw, prefix, nowUptime);
564         mReceivers.dump(pw, prefix, nowUptime);
565         mOptRecord.dump(pw, prefix, nowUptime);
566         mWindowProcessController.dump(pw, prefix);
567     }
568 
ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid)569     ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName,
570             int _uid) {
571         this(_service, _info, _processName, _uid, null, -1, null);
572     }
573 
ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid, String _sdkSandboxClientAppPackage, int _definingUid, String _definingProcessName)574     ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName,
575             int _uid, String _sdkSandboxClientAppPackage, int _definingUid,
576             String _definingProcessName) {
577         mService = _service;
578         mProcLock = _service.mProcLock;
579         info = _info;
580         ProcessInfo procInfo = null;
581         if (_service.mPackageManagerInt != null) {
582             if (_definingUid > 0) {
583                 ArrayMap<String, ProcessInfo> processes =
584                         _service.mPackageManagerInt.getProcessesForUid(_definingUid);
585                 if (processes != null) procInfo = processes.get(_definingProcessName);
586             } else {
587                 ArrayMap<String, ProcessInfo> processes =
588                         _service.mPackageManagerInt.getProcessesForUid(_uid);
589                 if (processes != null) procInfo = processes.get(_processName);
590             }
591             if (procInfo != null && procInfo.deniedPermissions == null
592                     && procInfo.gwpAsanMode == ApplicationInfo.GWP_ASAN_DEFAULT
593                     && procInfo.memtagMode == ApplicationInfo.MEMTAG_DEFAULT
594                     && procInfo.nativeHeapZeroInitialized == ApplicationInfo.ZEROINIT_DEFAULT) {
595                 // If this process hasn't asked for permissions to be denied, or for a
596                 // non-default GwpAsan mode, or any other non-default setting, then we don't
597                 // care about it.
598                 procInfo = null;
599             }
600         }
601         processInfo = procInfo;
602         isolated = Process.isIsolated(_uid);
603         isSdkSandbox = Process.isSdkSandboxUid(_uid);
604         appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID
605                 && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID);
606         uid = _uid;
607         userId = UserHandle.getUserId(_uid);
608         processName = _processName;
609         sdkSandboxClientAppPackage = _sdkSandboxClientAppPackage;
610         if (isSdkSandbox) {
611             final ApplicationInfo clientInfo = getClientInfoForSdkSandbox();
612             sdkSandboxClientAppVolumeUuid = clientInfo != null
613                     ? clientInfo.volumeUuid : null;
614         } else {
615             sdkSandboxClientAppVolumeUuid = null;
616         }
617         mPersistent = false;
618         mRemoved = false;
619         mProfile = new ProcessProfileRecord(this);
620         mServices = new ProcessServiceRecord(this);
621         mProviders = new ProcessProviderRecord(this);
622         mReceivers = new ProcessReceiverRecord(this);
623         mErrorState = new ProcessErrorStateRecord(this);
624         mState = new ProcessStateRecord(this);
625         mOptRecord = new ProcessCachedOptimizerRecord(this);
626         final long now = SystemClock.uptimeMillis();
627         mProfile.init(now);
628         mOptRecord.init(now);
629         mState.init(now);
630         mWindowProcessController = new WindowProcessController(
631                 mService.mActivityTaskManager, info, processName, uid, userId, this, this);
632         mPkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode));
633         updateProcessRecordNodes(this);
634     }
635 
636     /**
637      * Helper function to let test cases update the pointers.
638      */
639     @VisibleForTesting
updateProcessRecordNodes(@onNull ProcessRecord app)640     static void updateProcessRecordNodes(@NonNull ProcessRecord app) {
641         if (app.mService.mConstants.ENABLE_NEW_OOMADJ) {
642             for (int i = 0; i < app.mLinkedNodes.length; i++) {
643                 app.mLinkedNodes[i] = new ProcessRecordNode(app);
644             }
645         }
646     }
647 
648     /**
649      * Perform cleanups if the process record is going to be discarded in an early
650      * stage of the process lifecycle, specifically when the process has not even
651      * attached itself to the system_server.
652      */
653     @GuardedBy("mService")
doEarlyCleanupIfNecessaryLocked()654     void doEarlyCleanupIfNecessaryLocked() {
655         if (getThread() == null) {
656             // It's not even attached, make sure we unlink its process nodes.
657             mService.mOomAdjuster.onProcessEndLocked(this);
658         } else {
659             // Let the binder died callback handle the cleanup.
660         }
661     }
662 
resetCrashingOnRestart()663     void resetCrashingOnRestart() {
664         mErrorState.setCrashing(false);
665     }
666 
667     @GuardedBy(anyOf = {"mService", "mProcLock"})
getUidRecord()668     UidRecord getUidRecord() {
669         return mUidRecord;
670     }
671 
672     @GuardedBy({"mService", "mProcLock"})
setUidRecord(UidRecord uidRecord)673     void setUidRecord(UidRecord uidRecord) {
674         mUidRecord = uidRecord;
675     }
676 
getPkgList()677     PackageList getPkgList() {
678         return mPkgList;
679     }
680 
681     @GuardedBy(anyOf = {"mService", "mProcLock"})
getPkgDeps()682     ArraySet<String> getPkgDeps() {
683         return mPkgDeps;
684     }
685 
686     @GuardedBy({"mService", "mProcLock"})
setPkgDeps(ArraySet<String> pkgDeps)687     void setPkgDeps(ArraySet<String> pkgDeps) {
688         mPkgDeps = pkgDeps;
689     }
690 
691     @GuardedBy(anyOf = {"mService", "mProcLock"})
getPid()692     int getPid() {
693         return mPid;
694     }
695 
696     @GuardedBy({"mService", "mProcLock"})
setPid(int pid)697     void setPid(int pid) {
698         // If the pid is changing and not the first time pid is being assigned, clear stopped state
699         // So if the process record is re-used for a different pid, it wouldn't keep the state.
700         if (pid != mPid && mPid != 0) {
701             setWasForceStopped(false);
702         }
703         mPid = pid;
704         mWindowProcessController.setPid(pid);
705         mShortStringName = null;
706         mStringName = null;
707         synchronized (mProfile.mProfilerLock) {
708             mProfile.setPid(pid);
709         }
710     }
711 
712     @GuardedBy({"mService", "mProcLock"})
getSetAdj()713     int getSetAdj() {
714         return mState.getSetAdj();
715     }
716 
717     @GuardedBy(anyOf = {"mService", "mProcLock"})
getThread()718     IApplicationThread getThread() {
719         return mThread;
720     }
721 
722     @GuardedBy(anyOf = {"mService", "mProcLock"})
getOnewayThread()723     IApplicationThread getOnewayThread() {
724         return mOnewayThread;
725     }
726 
727     @GuardedBy(anyOf = {"mService", "mProcLock"})
getCurProcState()728     int getCurProcState() {
729         return mState.getCurProcState();
730     }
731 
732     @GuardedBy(anyOf = {"mService", "mProcLock"})
getSetProcState()733     int getSetProcState() {
734         return mState.getSetProcState();
735     }
736 
737     @GuardedBy(anyOf = {"mService", "mProcLock"})
getSetCapability()738     int getSetCapability() {
739         return mState.getSetCapability();
740     }
741 
742     @GuardedBy({"mService", "mProcLock"})
makeActive(ApplicationThreadDeferred thread, ProcessStatsService tracker)743     public void makeActive(ApplicationThreadDeferred thread, ProcessStatsService tracker) {
744         mProfile.onProcessActive(thread, tracker);
745         mThread = thread;
746         if (mPid == Process.myPid()) {
747             mOnewayThread = new SameProcessApplicationThread(mThread, FgThread.getHandler());
748         } else {
749             mOnewayThread = mThread;
750         }
751         mWindowProcessController.setThread(mThread);
752         if (mWindowProcessController.useFifoUiScheduling()) {
753             mService.mSpecifiedFifoProcesses.add(this);
754         }
755     }
756 
757     @GuardedBy({"mService", "mProcLock"})
makeInactive(ProcessStatsService tracker)758     public void makeInactive(ProcessStatsService tracker) {
759         mThread = null;
760         mOnewayThread = null;
761         mWindowProcessController.setThread(null);
762         if (mWindowProcessController.useFifoUiScheduling()) {
763             mService.mSpecifiedFifoProcesses.remove(this);
764         }
765         mProfile.onProcessInactive(tracker);
766     }
767 
768     @GuardedBy(anyOf = {"mService", "mProcLock"})
useFifoUiScheduling()769     boolean useFifoUiScheduling() {
770         return mService.mUseFifoUiScheduling
771                 || (mService.mAllowSpecifiedFifoScheduling
772                         && mWindowProcessController.useFifoUiScheduling());
773     }
774 
775     @GuardedBy("mService")
getDyingPid()776     int getDyingPid() {
777         return mDyingPid;
778     }
779 
780     @GuardedBy("mService")
setDyingPid(int dyingPid)781     void setDyingPid(int dyingPid) {
782         mDyingPid = dyingPid;
783     }
784 
785     @GuardedBy("mService")
getGids()786     int[] getGids() {
787         return mGids;
788     }
789 
790     @GuardedBy("mService")
setGids(int[] gids)791     void setGids(int[] gids) {
792         mGids = gids;
793     }
794 
795     @GuardedBy("mService")
getRequiredAbi()796     String getRequiredAbi() {
797         return mRequiredAbi;
798     }
799 
800     @GuardedBy("mService")
setRequiredAbi(String requiredAbi)801     void setRequiredAbi(String requiredAbi) {
802         mRequiredAbi = requiredAbi;
803         mWindowProcessController.setRequiredAbi(requiredAbi);
804     }
805 
806     @GuardedBy("mService")
getInstructionSet()807     String getInstructionSet() {
808         return mInstructionSet;
809     }
810 
811     @GuardedBy("mService")
setInstructionSet(String instructionSet)812     void setInstructionSet(String instructionSet) {
813         mInstructionSet = instructionSet;
814     }
815 
setPersistent(boolean persistent)816     void setPersistent(boolean persistent) {
817         mPersistent = persistent;
818         mWindowProcessController.setPersistent(persistent);
819     }
820 
isPersistent()821     boolean isPersistent() {
822         return mPersistent;
823     }
824 
825     @GuardedBy("mService")
isPendingStart()826     boolean isPendingStart() {
827         return mPendingStart;
828     }
829 
830     @GuardedBy("mService")
setPendingStart(boolean pendingStart)831     void setPendingStart(boolean pendingStart) {
832         mPendingStart = pendingStart;
833     }
834 
835     @GuardedBy("mService")
setPendingFinishAttach(boolean pendingFinishAttach)836     void setPendingFinishAttach(boolean pendingFinishAttach) {
837         mPendingFinishAttach = pendingFinishAttach;
838     }
839 
840     @GuardedBy("mService")
isPendingFinishAttach()841     boolean isPendingFinishAttach() {
842         return mPendingFinishAttach;
843     }
844 
845     @GuardedBy("mService")
isThreadReady()846     boolean isThreadReady() {
847         return mThread != null && !mPendingFinishAttach;
848     }
849 
850     @GuardedBy("mService")
getStartSeq()851     long getStartSeq() {
852         return mStartSeq;
853     }
854 
855     @GuardedBy("mService")
setStartSeq(long startSeq)856     void setStartSeq(long startSeq) {
857         mStartSeq = startSeq;
858     }
859 
getHostingRecord()860     HostingRecord getHostingRecord() {
861         return mHostingRecord;
862     }
863 
setHostingRecord(HostingRecord hostingRecord)864     void setHostingRecord(HostingRecord hostingRecord) {
865         mHostingRecord = hostingRecord;
866     }
867 
getSeInfo()868     String getSeInfo() {
869         return mSeInfo;
870     }
871 
setSeInfo(String seInfo)872     void setSeInfo(String seInfo) {
873         mSeInfo = seInfo;
874     }
875 
getStartUptime()876     long getStartUptime() {
877         return mStartUptime;
878     }
879 
880     /**
881      * Same as {@link #getStartUptime()}.
882      * @deprecated use {@link #getStartUptime()} instead for clarity.
883      */
884     @Deprecated
getStartTime()885     long getStartTime() {
886         return mStartUptime;
887     }
888 
getStartElapsedTime()889     long getStartElapsedTime() {
890         return mStartElapsedTime;
891     }
892 
getBindApplicationTime()893     long getBindApplicationTime() {
894         return mBindApplicationTime;
895     }
896 
setBindApplicationTime(long bindApplicationTime)897     void setBindApplicationTime(long bindApplicationTime) {
898         mBindApplicationTime = bindApplicationTime;
899     }
900 
getStartUid()901     int getStartUid() {
902         return mStartUid;
903     }
904 
setStartUid(int startUid)905     void setStartUid(int startUid) {
906         mStartUid = startUid;
907     }
908 
getMountMode()909     int getMountMode() {
910         return mMountMode;
911     }
912 
setMountMode(int mountMode)913     void setMountMode(int mountMode) {
914         mMountMode = mountMode;
915     }
916 
isBindMountPending()917     boolean isBindMountPending() {
918         return mBindMountPending;
919     }
920 
setBindMountPending(boolean bindMountPending)921     void setBindMountPending(boolean bindMountPending) {
922         mBindMountPending = bindMountPending;
923     }
924 
925     @GuardedBy("mProcLock")
isUnlocked()926     boolean isUnlocked() {
927         return mUnlocked;
928     }
929 
930     @GuardedBy("mProcLock")
setUnlocked(boolean unlocked)931     void setUnlocked(boolean unlocked) {
932         mUnlocked = unlocked;
933     }
934 
935     @GuardedBy("mProcLock")
getRenderThreadTid()936     int getRenderThreadTid() {
937         return mRenderThreadTid;
938     }
939 
940     @GuardedBy("mProcLock")
setRenderThreadTid(int renderThreadTid)941     void setRenderThreadTid(int renderThreadTid) {
942         mRenderThreadTid = renderThreadTid;
943     }
944 
945     @GuardedBy("mService")
getCompat()946     CompatibilityInfo getCompat() {
947         return mCompat;
948     }
949 
950     @GuardedBy("mService")
setCompat(CompatibilityInfo compat)951     void setCompat(CompatibilityInfo compat) {
952         mCompat = compat;
953     }
954 
955     @GuardedBy("mService")
getDisabledCompatChanges()956     long[] getDisabledCompatChanges() {
957         return mDisabledCompatChanges;
958     }
959 
960     @GuardedBy("mService")
getLoggableCompatChanges()961     long[] getLoggableCompatChanges() {
962         return mLoggableCompatChanges;
963     }
964 
965     @GuardedBy("mService")
setDisabledCompatChanges(long[] disabledCompatChanges)966     void setDisabledCompatChanges(long[] disabledCompatChanges) {
967         mDisabledCompatChanges = disabledCompatChanges;
968     }
969 
970     @GuardedBy("mService")
setLoggableCompatChanges(long[] loggableCompatChanges)971     void setLoggableCompatChanges(long[] loggableCompatChanges) {
972         mLoggableCompatChanges = loggableCompatChanges;
973     }
974 
975     @GuardedBy("mService")
unlinkDeathRecipient()976     void unlinkDeathRecipient() {
977         if (mDeathRecipient != null && mThread != null) {
978             mThread.asBinder().unlinkToDeath(mDeathRecipient, 0);
979         }
980         mDeathRecipient = null;
981     }
982 
983     @GuardedBy("mService")
setDeathRecipient(IBinder.DeathRecipient deathRecipient)984     void setDeathRecipient(IBinder.DeathRecipient deathRecipient) {
985         mDeathRecipient = deathRecipient;
986     }
987 
988     @GuardedBy("mService")
getDeathRecipient()989     IBinder.DeathRecipient getDeathRecipient() {
990         return mDeathRecipient;
991     }
992 
993     @GuardedBy({"mService", "mProcLock"})
setActiveInstrumentation(ActiveInstrumentation instr)994     void setActiveInstrumentation(ActiveInstrumentation instr) {
995         mInstr = instr;
996         boolean isInstrumenting = instr != null;
997         mWindowProcessController.setInstrumenting(
998                 isInstrumenting,
999                 isInstrumenting ? instr.mSourceUid : -1,
1000                 isInstrumenting && instr.mHasBackgroundActivityStartsPermission);
1001     }
1002 
1003     @GuardedBy(anyOf = {"mService", "mProcLock"})
getActiveInstrumentation()1004     ActiveInstrumentation getActiveInstrumentation() {
1005         return mInstr;
1006     }
1007 
1008     @GuardedBy(anyOf = {"mService", "mProcLock"})
hasActiveInstrumentation()1009     boolean hasActiveInstrumentation() {
1010         return mInstr != null;
1011     }
1012 
1013     @GuardedBy(anyOf = {"mService", "mProcLock"})
isKilledByAm()1014     boolean isKilledByAm() {
1015         return mKilledByAm;
1016     }
1017 
1018     @GuardedBy({"mService", "mProcLock"})
setKilledByAm(boolean killedByAm)1019     void setKilledByAm(boolean killedByAm) {
1020         mKilledByAm = killedByAm;
1021     }
1022 
1023     @GuardedBy(anyOf = {"mService", "mProcLock"})
isKilled()1024     boolean isKilled() {
1025         return mKilled;
1026     }
1027 
1028     @GuardedBy({"mService", "mProcLock"})
setKilled(boolean killed)1029     void setKilled(boolean killed) {
1030         mKilled = killed;
1031     }
1032 
1033     @GuardedBy(anyOf = {"mService", "mProcLock"})
getKillTime()1034     long getKillTime() {
1035         return mKillTime;
1036     }
1037 
1038     @GuardedBy({"mService", "mProcLock"})
setKillTime(long killTime)1039     void setKillTime(long killTime) {
1040         mKillTime = killTime;
1041     }
1042 
1043     @GuardedBy("mService")
getWaitingToKill()1044     String getWaitingToKill() {
1045         return mWaitingToKill;
1046     }
1047 
1048     @GuardedBy("mService")
setWaitingToKill(String waitingToKill)1049     void setWaitingToKill(String waitingToKill) {
1050         mWaitingToKill = waitingToKill;
1051     }
1052 
1053     @Override
isRemoved()1054     public boolean isRemoved() {
1055         return mRemoved;
1056     }
1057 
setRemoved(boolean removed)1058     void setRemoved(boolean removed) {
1059         mRemoved = removed;
1060     }
1061 
1062     @GuardedBy("mService")
isDebugging()1063     boolean isDebugging() {
1064         return mDebugging;
1065     }
1066 
1067     @Nullable
getClientInfoForSdkSandbox()1068     public ApplicationInfo getClientInfoForSdkSandbox() {
1069         if (!isSdkSandbox || sdkSandboxClientAppPackage == null) {
1070             throw new IllegalStateException(
1071                     "getClientInfoForSdkSandbox called for non-sandbox process"
1072             );
1073         }
1074         PackageManagerInternal pm = mService.getPackageManagerInternal();
1075         return pm.getApplicationInfo(
1076                 sdkSandboxClientAppPackage, /* flags */0, Process.SYSTEM_UID, userId);
1077     }
1078 
isDebuggable()1079     public boolean isDebuggable() {
1080         if ((info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1081             return true;
1082         }
1083         if (isSdkSandbox) {
1084             ApplicationInfo clientInfo = getClientInfoForSdkSandbox();
1085             return clientInfo != null && (clientInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
1086         }
1087         return false;
1088     }
1089 
1090     @GuardedBy("mService")
setDebugging(boolean debugging)1091     void setDebugging(boolean debugging) {
1092         mDebugging = debugging;
1093         mWindowProcessController.setDebugging(debugging);
1094     }
1095 
1096     @GuardedBy("mProcLock")
hasWaitedForDebugger()1097     boolean hasWaitedForDebugger() {
1098         return mWaitedForDebugger;
1099     }
1100 
1101     @GuardedBy("mProcLock")
setWaitedForDebugger(boolean waitedForDebugger)1102     void setWaitedForDebugger(boolean waitedForDebugger) {
1103         mWaitedForDebugger = waitedForDebugger;
1104     }
1105 
1106     @GuardedBy(anyOf = {"mService", "mProcLock"})
getLastActivityTime()1107     long getLastActivityTime() {
1108         return mLastActivityTime;
1109     }
1110 
1111     @GuardedBy({"mService", "mProcLock"})
setLastActivityTime(long lastActivityTime)1112     void setLastActivityTime(long lastActivityTime) {
1113         mLastActivityTime = lastActivityTime;
1114     }
1115 
1116     @GuardedBy("mService")
isUsingWrapper()1117     boolean isUsingWrapper() {
1118         return mUsingWrapper;
1119     }
1120 
1121     @GuardedBy("mService")
setUsingWrapper(boolean usingWrapper)1122     void setUsingWrapper(boolean usingWrapper) {
1123         mUsingWrapper = usingWrapper;
1124         mWindowProcessController.setUsingWrapper(usingWrapper);
1125     }
1126 
1127     @GuardedBy("mService")
getLruSeq()1128     int getLruSeq() {
1129         return mLruSeq;
1130     }
1131 
1132     @GuardedBy("mService")
setLruSeq(int lruSeq)1133     void setLruSeq(int lruSeq) {
1134         mLruSeq = lruSeq;
1135     }
1136 
1137     @GuardedBy("mService")
getIsolatedEntryPoint()1138     String getIsolatedEntryPoint() {
1139         return mIsolatedEntryPoint;
1140     }
1141 
1142     @GuardedBy("mService")
setIsolatedEntryPoint(String isolatedEntryPoint)1143     void setIsolatedEntryPoint(String isolatedEntryPoint) {
1144         mIsolatedEntryPoint = isolatedEntryPoint;
1145     }
1146 
1147     @GuardedBy("mService")
getIsolatedEntryPointArgs()1148     String[] getIsolatedEntryPointArgs() {
1149         return mIsolatedEntryPointArgs;
1150     }
1151 
1152     @GuardedBy("mService")
setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs)1153     void setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs) {
1154         mIsolatedEntryPointArgs = isolatedEntryPointArgs;
1155     }
1156 
1157     @GuardedBy("mService")
isInFullBackup()1158     boolean isInFullBackup() {
1159         return mInFullBackup;
1160     }
1161 
1162     @GuardedBy("mService")
setInFullBackup(boolean inFullBackup)1163     void setInFullBackup(boolean inFullBackup) {
1164         mInFullBackup = inFullBackup;
1165     }
1166 
1167     @Override
1168     @GuardedBy("mService")
isCached()1169     public boolean isCached() {
1170         return mState.isCached();
1171     }
1172 
hasActivities()1173     boolean hasActivities() {
1174         return mWindowProcessController.hasActivities();
1175     }
1176 
hasActivitiesOrRecentTasks()1177     boolean hasActivitiesOrRecentTasks() {
1178         return mWindowProcessController.hasActivitiesOrRecentTasks();
1179     }
1180 
hasRecentTasks()1181     boolean hasRecentTasks() {
1182         return mWindowProcessController.hasRecentTasks();
1183     }
1184 
1185     @GuardedBy("mService")
getApplicationInfo()1186     public ApplicationInfo getApplicationInfo() {
1187         return info;
1188     }
1189 
1190     @GuardedBy({"mService", "mProcLock"})
onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart, boolean unlinkDeath)1191     boolean onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart,
1192             boolean unlinkDeath) {
1193         mErrorState.onCleanupApplicationRecordLSP();
1194 
1195         resetPackageList(processStats);
1196         if (unlinkDeath) {
1197             unlinkDeathRecipient();
1198         }
1199         makeInactive(processStats);
1200         setWaitingToKill(null);
1201 
1202         mState.onCleanupApplicationRecordLSP();
1203         mService.mProcessStateController.onCleanupApplicationRecord(mServices);
1204         mReceivers.onCleanupApplicationRecordLocked();
1205         mService.mOomAdjuster.onProcessEndLocked(this);
1206 
1207         return mProviders.onCleanupApplicationRecordLocked(allowRestart);
1208     }
1209 
1210     /**
1211      * This method returns true if any of the activities within the process record are interesting
1212      * to the user. See HistoryRecord.isInterestingToUserLocked()
1213      */
isInterestingToUserLocked()1214     public boolean isInterestingToUserLocked() {
1215         if (mWindowProcessController.isInterestingToUser()) {
1216             return true;
1217         }
1218 
1219         return mServices.hasForegroundServices();
1220     }
1221 
1222     /**
1223      * Let an app process throw an exception on a binder thread, which typically crashes the
1224      * process, unless it has an unhandled exception handler.
1225      *
1226      * See {@link ActivityThread#throwRemoteServiceException}.
1227      *
1228      * @param message exception message
1229      * @param exceptionTypeId ID defined in {@link android.app.RemoteServiceException} or one
1230      *                        of its subclasses.
1231      */
1232     @GuardedBy("mService")
scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras)1233     void scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras) {
1234         // Checking killedbyAm should keep it from showing the crash dialog if the process
1235         // was already dead for a good / normal reason.
1236         if (!mKilledByAm) {
1237             if (mThread != null) {
1238                 if (mPid == Process.myPid()) {
1239                     Slog.w(TAG, "scheduleCrash: trying to crash system process!");
1240                     return;
1241                 }
1242                 final long ident = Binder.clearCallingIdentity();
1243                 try {
1244                     mThread.scheduleCrash(message, exceptionTypeId, extras);
1245                 } catch (RemoteException e) {
1246                     // If it's already dead our work is done. If it's wedged just kill it.
1247                     // We won't get the crash dialog or the error reporting.
1248                     killLocked("scheduleCrash for '" + message + "' failed",
1249                             ApplicationExitInfo.REASON_CRASH, true);
1250                 } finally {
1251                     Binder.restoreCallingIdentity(ident);
1252                 }
1253             }
1254         }
1255     }
1256 
getRss(int pid)1257     public long getRss(int pid) {
1258         long[] rss = Process.getRss(pid);
1259         return (rss != null && rss.length > 0) ? rss[0] : 0;
1260     }
1261 
1262     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, boolean noisy)1263     void killLocked(String reason, @Reason int reasonCode, boolean noisy) {
1264         killLocked(reason, reasonCode, ApplicationExitInfo.SUBREASON_UNKNOWN, noisy, true);
1265     }
1266 
1267     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy)1268     void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason,
1269             boolean noisy) {
1270         killLocked(reason, reason, reasonCode, subReason, noisy, true);
1271     }
1272 
1273     @GuardedBy("mService")
killLocked(String reason, String description, @Reason int reasonCode, @SubReason int subReason, boolean noisy)1274     void killLocked(String reason, String description, @Reason int reasonCode,
1275             @SubReason int subReason, boolean noisy) {
1276         killLocked(reason, description, reasonCode, subReason, noisy, true);
1277     }
1278 
1279     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy, boolean asyncKPG)1280     void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason,
1281             boolean noisy, boolean asyncKPG) {
1282         killLocked(reason, reason, reasonCode, subReason, noisy, asyncKPG);
1283     }
1284 
1285     @GuardedBy("mService")
killLocked(String reason, String description, @Reason int reasonCode, @SubReason int subReason, boolean noisy, boolean asyncKPG)1286     void killLocked(String reason, String description, @Reason int reasonCode,
1287             @SubReason int subReason, boolean noisy, boolean asyncKPG) {
1288         if (!mKilledByAm) {
1289             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
1290             if (reasonCode == ApplicationExitInfo.REASON_ANR
1291                     && mErrorState.getAnrAnnotation() != null) {
1292                 description = description + ": " + mErrorState.getAnrAnnotation();
1293             }
1294             if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
1295                 mService.reportUidInfoMessageLocked(TAG,
1296                         "Killing " + toShortString() + " (adj " + mState.getSetAdj()
1297                         + "): " + reason, info.uid);
1298             }
1299             // Since the process is getting killed, reset the freezable related state.
1300             mOptRecord.setPendingFreeze(false);
1301             mOptRecord.setFrozen(false);
1302             if (mPid > 0) {
1303                 mService.mProcessList.noteAppKill(this, reasonCode, subReason, description);
1304                 EventLog.writeEvent(EventLogTags.AM_KILL,
1305                         userId, mPid, processName, mState.getSetAdj(), reason, getRss(mPid));
1306                 Process.killProcessQuiet(mPid);
1307                 killProcessGroupIfNecessaryLocked(asyncKPG);
1308             } else {
1309                 mPendingStart = false;
1310             }
1311             if (!mPersistent) {
1312                 synchronized (mProcLock) {
1313                     mKilled = true;
1314                     mKilledByAm = true;
1315                     mKillTime = SystemClock.uptimeMillis();
1316                 }
1317             }
1318             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1319         }
1320     }
1321 
1322     @GuardedBy("mService")
killProcessGroupIfNecessaryLocked(boolean async)1323     void killProcessGroupIfNecessaryLocked(boolean async) {
1324         final boolean killProcessGroup;
1325         if (mHostingRecord != null
1326                 && (mHostingRecord.usesWebviewZygote() || mHostingRecord.usesAppZygote())) {
1327             synchronized (ProcessRecord.this) {
1328                 killProcessGroup = mProcessGroupCreated;
1329                 if (!killProcessGroup) {
1330                     // The process group hasn't been created, request to skip it.
1331                     mSkipProcessGroupCreation = true;
1332                 }
1333             }
1334         } else {
1335             killProcessGroup = true;
1336         }
1337         if (killProcessGroup) {
1338             if (!async) {
1339                 Process.sendSignalToProcessGroup(uid, mPid, OsConstants.SIGKILL);
1340             }
1341             ProcessList.killProcessGroup(uid, mPid);
1342         }
1343     }
1344 
1345     @Override
dumpDebug(ProtoOutputStream proto, long fieldId)1346     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1347         dumpDebug(proto, fieldId, -1);
1348     }
1349 
dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex)1350     public void dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex) {
1351         long token = proto.start(fieldId);
1352         proto.write(ProcessRecordProto.PID, mPid);
1353         proto.write(ProcessRecordProto.PROCESS_NAME, processName);
1354         proto.write(ProcessRecordProto.UID, info.uid);
1355         if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) {
1356             proto.write(ProcessRecordProto.USER_ID, userId);
1357             proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid));
1358         }
1359         if (uid != info.uid) {
1360             proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid));
1361         }
1362         proto.write(ProcessRecordProto.PERSISTENT, mPersistent);
1363         if (lruIndex >= 0) {
1364             proto.write(ProcessRecordProto.LRU_INDEX, lruIndex);
1365         }
1366         proto.end(token);
1367     }
1368 
toShortString()1369     public String toShortString() {
1370         final String shortStringName = mShortStringName;
1371         if (shortStringName != null) {
1372             return shortStringName;
1373         }
1374         StringBuilder sb = new StringBuilder(128);
1375         toShortString(sb);
1376         return mShortStringName = sb.toString();
1377     }
1378 
toShortString(StringBuilder sb)1379     void toShortString(StringBuilder sb) {
1380         sb.append(mPid);
1381         sb.append(':');
1382         sb.append(processName);
1383         sb.append('/');
1384         if (info.uid < Process.FIRST_APPLICATION_UID) {
1385             sb.append(uid);
1386         } else {
1387             sb.append('u');
1388             sb.append(userId);
1389             int appId = UserHandle.getAppId(info.uid);
1390             if (appId >= Process.FIRST_APPLICATION_UID) {
1391                 sb.append('a');
1392                 sb.append(appId - Process.FIRST_APPLICATION_UID);
1393             } else {
1394                 sb.append('s');
1395                 sb.append(appId);
1396             }
1397             if (uid != info.uid) {
1398                 sb.append('i');
1399                 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
1400             }
1401         }
1402     }
1403 
toString()1404     public String toString() {
1405         final String stringName = mStringName;
1406         if (stringName != null) {
1407             return stringName;
1408         }
1409         StringBuilder sb = new StringBuilder(128);
1410         sb.append("ProcessRecord{");
1411         sb.append(Integer.toHexString(System.identityHashCode(this)));
1412         sb.append(' ');
1413         toShortString(sb);
1414         sb.append('}');
1415         return mStringName = sb.toString();
1416     }
1417 
toDetailedString()1418     String toDetailedString() {
1419         final StringBuilder sb = new StringBuilder();
1420         sb.append(this);
1421         final StringWriter sw = new StringWriter();
1422         final PrintWriter pw = new PrintWriter(sw);
1423         dump(pw, "  ");
1424         sb.append(sw);
1425         return sb.toString();
1426     }
1427 
1428     /*
1429      *  Return true if package has been added false if not
1430      */
addPackage(String pkg, long versionCode, ProcessStatsService tracker)1431     public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) {
1432         synchronized (tracker.mLock) {
1433             synchronized (mPkgList) {
1434                 if (!mPkgList.containsKey(pkg)) {
1435                     ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
1436                             versionCode);
1437                     final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1438                     if (baseProcessTracker != null) {
1439                         tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode,
1440                                 processName);
1441                         mPkgList.put(pkg, holder);
1442                         if (holder.state != baseProcessTracker) {
1443                             holder.state.makeActive();
1444                         }
1445                     } else {
1446                         mPkgList.put(pkg, holder);
1447                     }
1448                     return true;
1449                 }
1450             }
1451         }
1452         return false;
1453     }
1454 
onProcessFrozen()1455     void onProcessFrozen() {
1456         mProfile.onProcessFrozen();
1457         final ApplicationThreadDeferred t;
1458         synchronized (mService) {
1459             t = mThread;
1460         }
1461         // Release the lock before calling the notifier, in case that calls back into AM.
1462         if (t != null) t.onProcessPaused();
1463     }
1464 
onProcessUnfrozen()1465     void onProcessUnfrozen() {
1466         final ApplicationThreadDeferred t;
1467         synchronized (mService) {
1468             t = mThread;
1469         }
1470         // Release the lock before calling the notifier, in case that calls back into AM.
1471         if (t != null) t.onProcessUnpaused();
1472         mProfile.onProcessUnfrozen();
1473         mServices.onProcessUnfrozen();
1474     }
1475 
onProcessFrozenCancelled()1476     void onProcessFrozenCancelled() {
1477         final ApplicationThreadDeferred t;
1478         synchronized (mService) {
1479             t = mThread;
1480         }
1481         // Release the lock before calling the notifier, in case that calls back into AM.
1482         if (t != null) t.onProcessPausedCancelled();
1483         mServices.onProcessFrozenCancelled();
1484     }
1485 
1486     /*
1487      *  Delete all packages from list except the package indicated in info
1488      */
resetPackageList(ProcessStatsService tracker)1489     public void resetPackageList(ProcessStatsService tracker) {
1490         synchronized (tracker.mLock) {
1491             final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1492             synchronized (mPkgList) {
1493                 final int numOfPkgs = mPkgList.size();
1494                 if (baseProcessTracker != null) {
1495                     long now = SystemClock.uptimeMillis();
1496                     baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
1497                             tracker.getMemFactorLocked(), now, mPkgList.getPackageListLocked());
1498                     if (numOfPkgs != 1) {
1499                         mPkgList.forEachPackageProcessStats(holder -> {
1500                             if (holder.state != null && holder.state != baseProcessTracker) {
1501                                 holder.state.makeInactive();
1502                             }
1503                         });
1504                         mPkgList.clear();
1505                         ProcessStats.ProcessStateHolder holder =
1506                                 new ProcessStats.ProcessStateHolder(info.longVersionCode);
1507                         tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid,
1508                                 info.longVersionCode, processName);
1509                         mPkgList.put(info.packageName, holder);
1510                         if (holder.state != baseProcessTracker) {
1511                             holder.state.makeActive();
1512                         }
1513                     }
1514                 } else if (numOfPkgs != 1) {
1515                     mPkgList.clear();
1516                     mPkgList.put(info.packageName,
1517                             new ProcessStats.ProcessStateHolder(info.longVersionCode));
1518                 }
1519             }
1520         }
1521     }
1522 
getPackageList()1523     String[] getPackageList() {
1524         return mPkgList.getPackageList();
1525     }
1526 
getPackageListWithVersionCode()1527     List<VersionedPackage> getPackageListWithVersionCode() {
1528         return mPkgList.getPackageListWithVersionCode();
1529     }
1530 
getWindowProcessController()1531     WindowProcessController getWindowProcessController() {
1532         return mWindowProcessController;
1533     }
1534 
1535     /**
1536      * Allows background activity starts using token {@param entity}. Optionally, you can provide
1537      * {@param originatingToken} if you have one such originating token, this is useful for tracing
1538      * back the grant in the case of the notification token.
1539      */
addOrUpdateBackgroundStartPrivileges(@onNull Binder entity, @NonNull BackgroundStartPrivileges backgroundStartPrivileges)1540     void addOrUpdateBackgroundStartPrivileges(@NonNull Binder entity,
1541             @NonNull BackgroundStartPrivileges backgroundStartPrivileges) {
1542         requireNonNull(entity, "entity");
1543         requireNonNull(backgroundStartPrivileges, "backgroundStartPrivileges");
1544         checkArgument(backgroundStartPrivileges.allowsAny(),
1545                 "backgroundStartPrivileges does not allow anything");
1546         mWindowProcessController.addOrUpdateBackgroundStartPrivileges(entity,
1547                 backgroundStartPrivileges);
1548         setBackgroundStartPrivileges(entity, backgroundStartPrivileges);
1549     }
1550 
removeBackgroundStartPrivileges(@onNull Binder entity)1551     void removeBackgroundStartPrivileges(@NonNull Binder entity) {
1552         requireNonNull(entity, "entity");
1553         mWindowProcessController.removeBackgroundStartPrivileges(entity);
1554         setBackgroundStartPrivileges(entity, null);
1555     }
1556 
1557     @NonNull
getBackgroundStartPrivileges()1558     BackgroundStartPrivileges getBackgroundStartPrivileges() {
1559         synchronized (mBackgroundStartPrivileges) {
1560             if (mBackgroundStartPrivilegesMerged == null) {
1561                 // Lazily generate the merged version when it's actually needed.
1562                 mBackgroundStartPrivilegesMerged = BackgroundStartPrivileges.NONE;
1563                 for (int i = mBackgroundStartPrivileges.size() - 1; i >= 0; --i) {
1564                     mBackgroundStartPrivilegesMerged =
1565                             mBackgroundStartPrivilegesMerged.merge(
1566                                     mBackgroundStartPrivileges.valueAt(i));
1567                 }
1568             }
1569             return mBackgroundStartPrivilegesMerged;
1570         }
1571     }
1572 
setBackgroundStartPrivileges(@onNull Binder entity, @Nullable BackgroundStartPrivileges backgroundStartPrivileges)1573     private void setBackgroundStartPrivileges(@NonNull Binder entity,
1574             @Nullable BackgroundStartPrivileges backgroundStartPrivileges) {
1575         synchronized (mBackgroundStartPrivileges) {
1576             final boolean changed;
1577             if (backgroundStartPrivileges == null) {
1578                 changed = mBackgroundStartPrivileges.remove(entity) != null;
1579             } else {
1580                 final BackgroundStartPrivileges oldBsp =
1581                         mBackgroundStartPrivileges.put(entity, backgroundStartPrivileges);
1582                 // BackgroundStartPrivileges tries to reuse the same object and avoid creating
1583                 // additional objects. For now, we just compare the reference to see if something
1584                 // has changed.
1585                 // TODO: actually compare the individual values to see if there's a change
1586                 changed = backgroundStartPrivileges != oldBsp;
1587             }
1588             if (changed) {
1589                 mBackgroundStartPrivilegesMerged = null;
1590             }
1591         }
1592     }
1593 
1594     @Override
clearProfilerIfNeeded()1595     public void clearProfilerIfNeeded() {
1596         synchronized (mService.mAppProfiler.mProfilerLock) {
1597             mService.mAppProfiler.clearProfilerLPf();
1598         }
1599     }
1600 
1601     @Override
updateServiceConnectionActivities()1602     public void updateServiceConnectionActivities() {
1603         synchronized (mService) {
1604             mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1605         }
1606     }
1607 
1608     @Override
setPendingUiClean(boolean pendingUiClean)1609     public void setPendingUiClean(boolean pendingUiClean) {
1610         synchronized (mProcLock) {
1611             mProfile.setPendingUiClean(pendingUiClean);
1612         }
1613     }
1614 
1615     @Override
setPendingUiCleanAndForceProcessStateUpTo(int newState)1616     public void setPendingUiCleanAndForceProcessStateUpTo(int newState) {
1617         synchronized (mService) {
1618             setPendingUiClean(true);
1619             mState.forceProcessStateUpTo(newState);
1620         }
1621     }
1622 
1623     @Override
updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1624     public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange,
1625             boolean updateOomAdj) {
1626         synchronized (mService) {
1627             if (updateServiceConnectionActivities) {
1628                 mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1629             }
1630             if (mThread == null) {
1631                 // Only update lru and oom-adj if the process is alive. Because it may be called
1632                 // when cleaning up the last activity from handling process died, the dead process
1633                 // should not be added to lru list again.
1634                 return;
1635             }
1636             mService.updateLruProcessLocked(this, activityChange, null /* client */);
1637             if (updateOomAdj) {
1638                 mService.updateOomAdjLocked(this, OOM_ADJ_REASON_ACTIVITY);
1639             }
1640         }
1641     }
1642 
1643     /**
1644      * Returns the total time (in milliseconds) spent executing in both user and system code.
1645      * Safe to call without lock held.
1646      */
1647     @Override
getCpuTime()1648     public long getCpuTime() {
1649         return mService.mAppProfiler.getCpuTimeForPid(mPid);
1650     }
1651 
getCpuDelayTime()1652     public long getCpuDelayTime() {
1653         return mService.mAppProfiler.getCpuDelayTimeForPid(mPid);
1654     }
1655 
1656     @Override
onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1657     public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName,
1658             long versionCode) {
1659         synchronized (mService) {
1660             mWaitingToKill = null;
1661             if (setProfileProc) {
1662                 synchronized (mService.mAppProfiler.mProfilerLock) {
1663                     mService.mAppProfiler.setProfileProcLPf(this);
1664                 }
1665             }
1666             if (packageName != null) {
1667                 addPackage(packageName, versionCode, mService.mProcessStats);
1668             }
1669 
1670             // Update oom adj first, we don't want the additional states are involved in this round.
1671             updateProcessInfo(false /* updateServiceConnectionActivities */,
1672                     true /* activityChange */, true /* updateOomAdj */);
1673             setPendingUiClean(true);
1674             mService.mProcessStateController.setHasShownUi(this, true);
1675             mState.forceProcessStateUpTo(topProcessState);
1676         }
1677     }
1678 
1679     @Override
appDied(String reason)1680     public void appDied(String reason) {
1681         synchronized (mService) {
1682             mService.appDiedLocked(this, reason);
1683         }
1684     }
1685 
1686     @Override
setRunningRemoteAnimation(boolean runningRemoteAnimation)1687     public void setRunningRemoteAnimation(boolean runningRemoteAnimation) {
1688         if (mPid == Process.myPid()) {
1689             Slog.wtf(TAG, "system can't run remote animation");
1690             return;
1691         }
1692         synchronized (mService) {
1693             if (mService.mProcessStateController.setRunningRemoteAnimation(this,
1694                     runningRemoteAnimation)) {
1695                 mService.mProcessStateController.runUpdate(this, OOM_ADJ_REASON_UI_VISIBILITY);
1696             }
1697         }
1698     }
1699 
getInputDispatchingTimeoutMillis()1700     public long getInputDispatchingTimeoutMillis() {
1701         return mWindowProcessController.getInputDispatchingTimeoutMillis();
1702     }
1703 
getProcessClassEnum()1704     public int getProcessClassEnum() {
1705         if (mPid == MY_PID) {
1706             return ServerProtoEnums.SYSTEM_SERVER;
1707         }
1708         if (info == null) {
1709             return ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
1710         }
1711         return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP :
1712             ServerProtoEnums.DATA_APP;
1713     }
1714 
1715     /** Non-private access is for tests only. */
1716     @VisibleForTesting
getLruProcessList()1717     List<ProcessRecord> getLruProcessList() {
1718         return mService.mProcessList.getLruProcessesLOSP();
1719     }
1720 
setWasForceStopped(boolean stopped)1721     public void setWasForceStopped(boolean stopped) {
1722         mWasForceStopped = stopped;
1723     }
1724 
wasForceStopped()1725     public boolean wasForceStopped() {
1726         return mWasForceStopped;
1727     }
1728 
isFreezable()1729     boolean isFreezable() {
1730         return mService.mOomAdjuster.mCachedAppOptimizer.useFreezer()
1731                 && !mOptRecord.isFreezeExempt()
1732                 && !mOptRecord.shouldNotFreeze()
1733                 && mState.getCurAdj() >= mService.mConstants.FREEZER_CUTOFF_ADJ;
1734     }
1735 
forEachConnectionHost(Consumer<ProcessRecord> consumer)1736     public void forEachConnectionHost(Consumer<ProcessRecord> consumer) {
1737         for (int i = mServices.numberOfConnections() - 1; i >= 0; i--) {
1738             final ConnectionRecord cr = mServices.getConnectionAt(i);
1739             final ProcessRecord service = cr.binding.service.app;
1740             consumer.accept(service);
1741         }
1742         for (int i = mServices.numberOfSdkSandboxConnections() - 1; i >= 0; i--) {
1743             final ConnectionRecord cr = mServices.getSdkSandboxConnectionAt(i);
1744             final ProcessRecord service = cr.binding.service.app;
1745             consumer.accept(service);
1746         }
1747         for (int i = mProviders.numberOfProviderConnections() - 1; i >= 0; i--) {
1748             ContentProviderConnection cpc = mProviders.getProviderConnectionAt(i);
1749             ProcessRecord provider = cpc.provider.proc;
1750             consumer.accept(provider);
1751         }
1752     }
1753 }
1754