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