• 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 com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
20 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
21 import static com.android.server.am.ActivityManagerService.MY_PID;
22 
23 import android.annotation.Nullable;
24 import android.app.ActivityManager;
25 import android.app.ApplicationExitInfo;
26 import android.app.ApplicationExitInfo.Reason;
27 import android.app.ApplicationExitInfo.SubReason;
28 import android.app.IApplicationThread;
29 import android.app.RemoteServiceException;
30 import android.content.pm.ApplicationInfo;
31 import android.content.pm.ProcessInfo;
32 import android.content.pm.VersionedPackage;
33 import android.content.res.CompatibilityInfo;
34 import android.os.Binder;
35 import android.os.IBinder;
36 import android.os.Process;
37 import android.os.RemoteException;
38 import android.os.SystemClock;
39 import android.os.Trace;
40 import android.os.UserHandle;
41 import android.server.ServerProtoEnums;
42 import android.util.ArrayMap;
43 import android.util.ArraySet;
44 import android.util.DebugUtils;
45 import android.util.EventLog;
46 import android.util.Slog;
47 import android.util.TimeUtils;
48 import android.util.proto.ProtoOutputStream;
49 
50 import com.android.internal.annotations.CompositeRWLock;
51 import com.android.internal.annotations.GuardedBy;
52 import com.android.internal.annotations.VisibleForTesting;
53 import com.android.internal.app.procstats.ProcessState;
54 import com.android.internal.app.procstats.ProcessStats;
55 import com.android.internal.os.Zygote;
56 import com.android.internal.util.FrameworkStatsLog;
57 import com.android.server.wm.WindowProcessController;
58 import com.android.server.wm.WindowProcessListener;
59 
60 import java.io.PrintWriter;
61 import java.util.Arrays;
62 import java.util.List;
63 import java.util.Objects;
64 
65 /**
66  * Full information about a particular process that
67  * is currently running.
68  */
69 class ProcessRecord implements WindowProcessListener {
70     static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;
71 
72     final ActivityManagerService mService; // where we came from
73     private final ActivityManagerGlobalLock mProcLock;
74 
75     // =========================================================
76     // Basic info of the process, immutable or semi-immutable over
77     // the lifecycle of the process
78     // =========================================================
79     volatile ApplicationInfo info; // all about the first app in the process
80     final ProcessInfo processInfo; // if non-null, process-specific manifest info
81     final boolean isolated;     // true if this is a special isolated process
82     final boolean appZygote;    // true if this is forked from the app zygote
83     final int uid;              // uid of process; may be different from 'info' if isolated
84     final int userId;           // user of process.
85     final String processName;   // name of the process
86 
87     /**
88      * Overall state of process's uid.
89      */
90     @CompositeRWLock({"mService", "mProcLock"})
91     private UidRecord mUidRecord;
92 
93     /**
94      * List of packages running in the process.
95      */
96     private final PackageList mPkgList = new PackageList(this);
97 
98     /**
99      * Additional packages we have a dependency on.
100      */
101     @CompositeRWLock({"mService", "mProcLock"})
102     private ArraySet<String> mPkgDeps;
103 
104     /**
105      * The process of this application; 0 if none.
106      */
107     @CompositeRWLock({"mService", "mProcLock"})
108     int mPid;
109 
110     /**
111      * The process ID which will be set when we're killing this process.
112      */
113     @GuardedBy("mService")
114     private int mDyingPid;
115 
116     /**
117      * The gids this process was launched with.
118      */
119     @GuardedBy("mService")
120     private int[] mGids;
121 
122     /**
123      * The ABI this process was launched with.
124      */
125     @GuardedBy("mService")
126     private String mRequiredAbi;
127 
128     /**
129      * The instruction set this process was launched with.
130      */
131     @GuardedBy("mService")
132     private String mInstructionSet;
133 
134     /**
135      * The actual proc...  may be null only if 'persistent' is true
136      * (in which case we are in the process of launching the app).
137      */
138     @CompositeRWLock({"mService", "mProcLock"})
139     private IApplicationThread mThread;
140 
141     /**
142      * Always keep this application running?
143      */
144     private volatile boolean mPersistent;
145 
146     /**
147      * Caching of toShortString() result.
148      * <p>Note: No lock here, it doesn't matter in case of race condition</p>
149      */
150     private String mShortStringName;
151 
152     /**
153      * Caching of toString() result.
154      * <p>Note: No lock here, it doesn't matter in case of race condition</p>
155      */
156     private String mStringName;
157 
158     /**
159      * Process start is pending.
160      */
161     @GuardedBy("mService")
162     private boolean mPendingStart;
163 
164     /**
165      * Seq no. Indicating the latest process start associated with this process record.
166      */
167     @GuardedBy("mService")
168     private long mStartSeq;
169 
170     /**
171      * Params used in starting this process.
172      */
173     private volatile HostingRecord mHostingRecord;
174 
175     /**
176      * Selinux info of this process.
177      */
178     private volatile String mSeInfo;
179 
180     /**
181      * When the process is started.
182      */
183     private volatile long mStartTime;
184 
185     /**
186      * This will be same as {@link #uid} usually except for some apps used during factory testing.
187      */
188     private volatile int mStartUid;
189 
190     /**
191      * Indicates how the external storage was mounted for this process.
192      */
193     private volatile int mMountMode;
194 
195     /**
196      * True if Android/obb and Android/data need to be bind mount.
197      */
198     private volatile boolean mBindMountPending;
199 
200     /**
201      * True when proc was started in user unlocked state.
202      */
203     @GuardedBy("mProcLock")
204     private boolean mUnlocked;
205 
206     /**
207      * TID for RenderThread.
208      */
209     @GuardedBy("mProcLock")
210     private int mRenderThreadTid;
211 
212     /**
213      * Last used compatibility mode.
214      */
215     @GuardedBy("mService")
216     private CompatibilityInfo mCompat;
217 
218     /**
219      * Set of disabled compat changes for the process (all others are enabled).
220      */
221     @GuardedBy("mService")
222     private long[] mDisabledCompatChanges;
223 
224     /**
225      * Who is watching for the death.
226      */
227     @GuardedBy("mService")
228     private IBinder.DeathRecipient mDeathRecipient;
229 
230     /**
231      * Set to currently active instrumentation running in process.
232      */
233     @CompositeRWLock({"mService", "mProcLock"})
234     private ActiveInstrumentation mInstr;
235 
236     /**
237      * True when proc has been killed by activity manager, not for RAM.
238      */
239     @CompositeRWLock({"mService", "mProcLock"})
240     private boolean mKilledByAm;
241 
242     /**
243      * True once we know the process has been killed.
244      */
245     @CompositeRWLock({"mService", "mProcLock"})
246     private boolean mKilled;
247 
248     /**
249      * The timestamp in uptime when this process was killed.
250      */
251     @CompositeRWLock({"mService", "mProcLock"})
252     private long mKillTime;
253 
254     /**
255      * Process is waiting to be killed when in the bg, and reason.
256      */
257     @GuardedBy("mService")
258     private String mWaitingToKill;
259 
260     /**
261      * Whether this process should be killed and removed from process list.
262      * It is set when the package is force-stopped or the process has crashed too many times.
263      */
264     private volatile boolean mRemoved;
265 
266     /**
267      * Was app launched for debugging?
268      */
269     @GuardedBy("mService")
270     private boolean mDebugging;
271 
272     /**
273      * Has process show wait for debugger dialog?
274      */
275     @GuardedBy("mProcLock")
276     private boolean mWaitedForDebugger;
277 
278     /**
279      * For managing the LRU list.
280      */
281     @CompositeRWLock({"mService", "mProcLock"})
282     private long mLastActivityTime;
283 
284     /**
285      * Set to true when process was launched with a wrapper attached.
286      */
287     @GuardedBy("mService")
288     private boolean mUsingWrapper;
289 
290     /**
291      * Sequence id for identifying LRU update cycles.
292      */
293     @GuardedBy("mService")
294     private int mLruSeq;
295 
296     /**
297      * Class to run on start if this is a special isolated process.
298      */
299     @GuardedBy("mService")
300     private String mIsolatedEntryPoint;
301 
302     /**
303      * Arguments to pass to isolatedEntryPoint's main().
304      */
305     @GuardedBy("mService")
306     private String[] mIsolatedEntryPointArgs;
307 
308     /**
309      * Process is currently hosting a backup agent for backup or restore.
310      */
311     @GuardedBy("mService")
312     private boolean mInFullBackup;
313 
314     /**
315      * Controller for driving the process state on the window manager side.
316      */
317     private final WindowProcessController mWindowProcessController;
318 
319     /**
320      * Profiling info of the process, such as PSS, cpu, etc.
321      */
322     final ProcessProfileRecord mProfile;
323 
324     /**
325      * All about the services in this process.
326      */
327     final ProcessServiceRecord mServices;
328 
329     /**
330      * All about the providers in this process.
331      */
332     final ProcessProviderRecord mProviders;
333 
334     /**
335      * All about the receivers in this process.
336      */
337     final ProcessReceiverRecord mReceivers;
338 
339     /**
340      * All about the error state(crash, ANR) in this process.
341      */
342     final ProcessErrorStateRecord mErrorState;
343 
344     /**
345      * All about the process state info (proc state, oom adj score) in this process.
346      */
347     final ProcessStateRecord mState;
348 
349     /**
350      * All about the state info of the optimizer when the process is cached.
351      */
352     final ProcessCachedOptimizerRecord mOptRecord;
353 
354     /**
355      * The preceding instance of the process, which would exist when the previous process is killed
356      * but not fully dead yet; in this case, the new instance of the process should be held until
357      * this preceding instance is fully dead.
358      */
359     volatile ProcessRecord mPredecessor;
360 
361     /**
362      * The succeeding instance of the process, which is going to be started after this process
363      * is killed successfully.
364      */
365     volatile ProcessRecord mSuccessor;
366 
setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, long startTime)367     void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo,
368             long startTime) {
369         this.mStartUid = startUid;
370         this.mHostingRecord = hostingRecord;
371         this.mSeInfo = seInfo;
372         this.mStartTime = startTime;
373     }
374 
375     @GuardedBy({"mService", "mProcLock"})
dump(PrintWriter pw, String prefix)376     void dump(PrintWriter pw, String prefix) {
377         final long nowUptime = SystemClock.uptimeMillis();
378 
379         pw.print(prefix); pw.print("user #"); pw.print(userId);
380                 pw.print(" uid="); pw.print(info.uid);
381         if (uid != info.uid) {
382             pw.print(" ISOLATED uid="); pw.print(uid);
383         }
384         pw.print(" gids={");
385         if (mGids != null) {
386             for (int gi = 0; gi < mGids.length; gi++) {
387                 if (gi != 0) pw.print(", ");
388                 pw.print(mGids[gi]);
389 
390             }
391         }
392         pw.println("}");
393         if (processInfo != null) {
394             pw.print(prefix); pw.println("processInfo:");
395             if (processInfo.deniedPermissions != null) {
396                 for (int i = 0; i < processInfo.deniedPermissions.size(); i++) {
397                     pw.print(prefix); pw.print("  deny: ");
398                     pw.println(processInfo.deniedPermissions.valueAt(i));
399                 }
400             }
401             if (processInfo.gwpAsanMode != ApplicationInfo.GWP_ASAN_DEFAULT) {
402                 pw.print(prefix); pw.println("  gwpAsanMode=" + processInfo.gwpAsanMode);
403             }
404             if (processInfo.memtagMode != ApplicationInfo.MEMTAG_DEFAULT) {
405                 pw.print(prefix); pw.println("  memtagMode=" + processInfo.memtagMode);
406             }
407         }
408         pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi);
409         pw.print(" instructionSet="); pw.println(mInstructionSet);
410         if (info.className != null) {
411             pw.print(prefix); pw.print("class="); pw.println(info.className);
412         }
413         if (info.manageSpaceActivityName != null) {
414             pw.print(prefix); pw.print("manageSpaceActivityName=");
415             pw.println(info.manageSpaceActivityName);
416         }
417 
418         pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
419                 pw.print(" publicDir="); pw.print(info.publicSourceDir);
420                 pw.print(" data="); pw.println(info.dataDir);
421         mPkgList.dump(pw, prefix);
422         if (mPkgDeps != null) {
423             pw.print(prefix); pw.print("packageDependencies={");
424             for (int i = 0; i < mPkgDeps.size(); i++) {
425                 if (i > 0) pw.print(", ");
426                 pw.print(mPkgDeps.valueAt(i));
427             }
428             pw.println("}");
429         }
430         pw.print(prefix); pw.print("compat="); pw.println(mCompat);
431         if (mInstr != null) {
432             pw.print(prefix); pw.print("mInstr="); pw.println(mInstr);
433         }
434         pw.print(prefix); pw.print("thread="); pw.println(mThread);
435         pw.print(prefix); pw.print("pid="); pw.println(mPid);
436         pw.print(prefix); pw.print("lastActivityTime=");
437         TimeUtils.formatDuration(mLastActivityTime, nowUptime, pw);
438         pw.println();
439         if (mPersistent || mRemoved) {
440             pw.print(prefix); pw.print("persistent="); pw.print(mPersistent);
441             pw.print(" removed="); pw.println(mRemoved);
442         }
443         if (mDebugging) {
444             pw.print(prefix); pw.print("mDebugging="); pw.println(mDebugging);
445         }
446         if (mPendingStart) {
447             pw.print(prefix); pw.print("pendingStart="); pw.println(mPendingStart);
448         }
449         pw.print(prefix); pw.print("startSeq="); pw.println(mStartSeq);
450         pw.print(prefix); pw.print("mountMode="); pw.println(
451                 DebugUtils.valueToString(Zygote.class, "MOUNT_EXTERNAL_", mMountMode));
452         if (mKilled || mKilledByAm || mWaitingToKill != null) {
453             pw.print(prefix); pw.print("killed="); pw.print(mKilled);
454             pw.print(" killedByAm="); pw.print(mKilledByAm);
455             pw.print(" waitingToKill="); pw.println(mWaitingToKill);
456         }
457         if (mIsolatedEntryPoint != null || mIsolatedEntryPointArgs != null) {
458             pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(mIsolatedEntryPoint);
459             pw.print(prefix); pw.print("isolatedEntryPointArgs=");
460             pw.println(Arrays.toString(mIsolatedEntryPointArgs));
461         }
462         if (mState.getSetProcState() > ActivityManager.PROCESS_STATE_SERVICE) {
463             mProfile.dumpCputime(pw, prefix);
464         }
465         mProfile.dumpPss(pw, prefix, nowUptime);
466         mState.dump(pw, prefix, nowUptime);
467         mErrorState.dump(pw, prefix, nowUptime);
468         mServices.dump(pw, prefix, nowUptime);
469         mProviders.dump(pw, prefix, nowUptime);
470         mReceivers.dump(pw, prefix, nowUptime);
471         mOptRecord.dump(pw, prefix, nowUptime);
472         mWindowProcessController.dump(pw, prefix);
473     }
474 
ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid)475     ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName,
476             int _uid) {
477         mService = _service;
478         mProcLock = _service.mProcLock;
479         info = _info;
480         ProcessInfo procInfo = null;
481         if (_service.mPackageManagerInt != null) {
482             ArrayMap<String, ProcessInfo> processes =
483                     _service.mPackageManagerInt.getProcessesForUid(_uid);
484             if (processes != null) {
485                 procInfo = processes.get(_processName);
486                 if (procInfo != null && procInfo.deniedPermissions == null
487                         && procInfo.gwpAsanMode == ApplicationInfo.GWP_ASAN_DEFAULT
488                         && procInfo.memtagMode == ApplicationInfo.MEMTAG_DEFAULT
489                         && procInfo.nativeHeapZeroInitialized == ApplicationInfo.ZEROINIT_DEFAULT) {
490                     // If this process hasn't asked for permissions to be denied, or for a
491                     // non-default GwpAsan mode, or any other non-default setting, then we don't
492                     // care about it.
493                     procInfo = null;
494                 }
495             }
496         }
497         processInfo = procInfo;
498         isolated = _info.uid != _uid;
499         appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID
500                 && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID);
501         uid = _uid;
502         userId = UserHandle.getUserId(_uid);
503         processName = _processName;
504         mPersistent = false;
505         mRemoved = false;
506         mProfile = new ProcessProfileRecord(this);
507         mServices = new ProcessServiceRecord(this);
508         mProviders = new ProcessProviderRecord(this);
509         mReceivers = new ProcessReceiverRecord(this);
510         mErrorState = new ProcessErrorStateRecord(this);
511         mState = new ProcessStateRecord(this);
512         mOptRecord = new ProcessCachedOptimizerRecord(this);
513         final long now = SystemClock.uptimeMillis();
514         mProfile.init(now);
515         mOptRecord.init(now);
516         mState.init(now);
517         mWindowProcessController = new WindowProcessController(
518                 mService.mActivityTaskManager, info, processName, uid, userId, this, this);
519         mPkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode));
520     }
521 
522     @GuardedBy(anyOf = {"mService", "mProcLock"})
getUidRecord()523     UidRecord getUidRecord() {
524         return mUidRecord;
525     }
526 
527     @GuardedBy({"mService", "mProcLock"})
setUidRecord(UidRecord uidRecord)528     void setUidRecord(UidRecord uidRecord) {
529         mUidRecord = uidRecord;
530     }
531 
getPkgList()532     PackageList getPkgList() {
533         return mPkgList;
534     }
535 
536     @GuardedBy(anyOf = {"mService", "mProcLock"})
getPkgDeps()537     ArraySet<String> getPkgDeps() {
538         return mPkgDeps;
539     }
540 
541     @GuardedBy({"mService", "mProcLock"})
setPkgDeps(ArraySet<String> pkgDeps)542     void setPkgDeps(ArraySet<String> pkgDeps) {
543         mPkgDeps = pkgDeps;
544     }
545 
546     @GuardedBy(anyOf = {"mService", "mProcLock"})
getPid()547     int getPid() {
548         return mPid;
549     }
550 
551     @GuardedBy({"mService", "mProcLock"})
setPid(int pid)552     void setPid(int pid) {
553         mPid = pid;
554         mWindowProcessController.setPid(pid);
555         mShortStringName = null;
556         mStringName = null;
557         synchronized (mProfile.mProfilerLock) {
558             mProfile.setPid(pid);
559         }
560     }
561 
562     @GuardedBy(anyOf = {"mService", "mProcLock"})
getThread()563     IApplicationThread getThread() {
564         return mThread;
565     }
566 
567     @GuardedBy({"mService", "mProcLock"})
makeActive(IApplicationThread thread, ProcessStatsService tracker)568     public void makeActive(IApplicationThread thread, ProcessStatsService tracker) {
569         mProfile.onProcessActive(thread, tracker);
570         mThread = thread;
571         mWindowProcessController.setThread(thread);
572     }
573 
574     @GuardedBy({"mService", "mProcLock"})
makeInactive(ProcessStatsService tracker)575     public void makeInactive(ProcessStatsService tracker) {
576         mThread = null;
577         mWindowProcessController.setThread(null);
578         mProfile.onProcessInactive(tracker);
579     }
580 
581     @GuardedBy("mService")
getDyingPid()582     int getDyingPid() {
583         return mDyingPid;
584     }
585 
586     @GuardedBy("mService")
setDyingPid(int dyingPid)587     void setDyingPid(int dyingPid) {
588         mDyingPid = dyingPid;
589     }
590 
591     @GuardedBy("mService")
getGids()592     int[] getGids() {
593         return mGids;
594     }
595 
596     @GuardedBy("mService")
setGids(int[] gids)597     void setGids(int[] gids) {
598         mGids = gids;
599     }
600 
601     @GuardedBy("mService")
getRequiredAbi()602     String getRequiredAbi() {
603         return mRequiredAbi;
604     }
605 
606     @GuardedBy("mService")
setRequiredAbi(String requiredAbi)607     void setRequiredAbi(String requiredAbi) {
608         mRequiredAbi = requiredAbi;
609         mWindowProcessController.setRequiredAbi(requiredAbi);
610     }
611 
612     @GuardedBy("mService")
getInstructionSet()613     String getInstructionSet() {
614         return mInstructionSet;
615     }
616 
617     @GuardedBy("mService")
setInstructionSet(String instructionSet)618     void setInstructionSet(String instructionSet) {
619         mInstructionSet = instructionSet;
620     }
621 
setPersistent(boolean persistent)622     void setPersistent(boolean persistent) {
623         mPersistent = persistent;
624         mWindowProcessController.setPersistent(persistent);
625     }
626 
isPersistent()627     boolean isPersistent() {
628         return mPersistent;
629     }
630 
631     @GuardedBy("mService")
isPendingStart()632     boolean isPendingStart() {
633         return mPendingStart;
634     }
635 
636     @GuardedBy("mService")
setPendingStart(boolean pendingStart)637     void setPendingStart(boolean pendingStart) {
638         mPendingStart = pendingStart;
639     }
640 
641     @GuardedBy("mService")
getStartSeq()642     long getStartSeq() {
643         return mStartSeq;
644     }
645 
646     @GuardedBy("mService")
setStartSeq(long startSeq)647     void setStartSeq(long startSeq) {
648         mStartSeq = startSeq;
649     }
650 
getHostingRecord()651     HostingRecord getHostingRecord() {
652         return mHostingRecord;
653     }
654 
setHostingRecord(HostingRecord hostingRecord)655     void setHostingRecord(HostingRecord hostingRecord) {
656         mHostingRecord = hostingRecord;
657     }
658 
getSeInfo()659     String getSeInfo() {
660         return mSeInfo;
661     }
662 
setSeInfo(String seInfo)663     void setSeInfo(String seInfo) {
664         mSeInfo = seInfo;
665     }
666 
getStartTime()667     long getStartTime() {
668         return mStartTime;
669     }
670 
setStartTime(long startTime)671     void setStartTime(long startTime) {
672         mStartTime = startTime;
673     }
674 
getStartUid()675     int getStartUid() {
676         return mStartUid;
677     }
678 
setStartUid(int startUid)679     void setStartUid(int startUid) {
680         mStartUid = startUid;
681     }
682 
getMountMode()683     int getMountMode() {
684         return mMountMode;
685     }
686 
setMountMode(int mountMode)687     void setMountMode(int mountMode) {
688         mMountMode = mountMode;
689     }
690 
isBindMountPending()691     boolean isBindMountPending() {
692         return mBindMountPending;
693     }
694 
setBindMountPending(boolean bindMountPending)695     void setBindMountPending(boolean bindMountPending) {
696         mBindMountPending = bindMountPending;
697     }
698 
699     @GuardedBy("mProcLock")
isUnlocked()700     boolean isUnlocked() {
701         return mUnlocked;
702     }
703 
704     @GuardedBy("mProcLock")
setUnlocked(boolean unlocked)705     void setUnlocked(boolean unlocked) {
706         mUnlocked = unlocked;
707     }
708 
709     @GuardedBy("mProcLock")
getRenderThreadTid()710     int getRenderThreadTid() {
711         return mRenderThreadTid;
712     }
713 
714     @GuardedBy("mProcLock")
setRenderThreadTid(int renderThreadTid)715     void setRenderThreadTid(int renderThreadTid) {
716         mRenderThreadTid = renderThreadTid;
717     }
718 
719     @GuardedBy("mService")
getCompat()720     CompatibilityInfo getCompat() {
721         return mCompat;
722     }
723 
724     @GuardedBy("mService")
setCompat(CompatibilityInfo compat)725     void setCompat(CompatibilityInfo compat) {
726         mCompat = compat;
727     }
728 
729     @GuardedBy("mService")
getDisabledCompatChanges()730     long[] getDisabledCompatChanges() {
731         return mDisabledCompatChanges;
732     }
733 
734     @GuardedBy("mService")
setDisabledCompatChanges(long[] disabledCompatChanges)735     void setDisabledCompatChanges(long[] disabledCompatChanges) {
736         mDisabledCompatChanges = disabledCompatChanges;
737     }
738 
739     @GuardedBy("mService")
unlinkDeathRecipient()740     void unlinkDeathRecipient() {
741         if (mDeathRecipient != null && mThread != null) {
742             mThread.asBinder().unlinkToDeath(mDeathRecipient, 0);
743         }
744         mDeathRecipient = null;
745     }
746 
747     @GuardedBy("mService")
setDeathRecipient(IBinder.DeathRecipient deathRecipient)748     void setDeathRecipient(IBinder.DeathRecipient deathRecipient) {
749         mDeathRecipient = deathRecipient;
750     }
751 
752     @GuardedBy("mService")
getDeathRecipient()753     IBinder.DeathRecipient getDeathRecipient() {
754         return mDeathRecipient;
755     }
756 
757     @GuardedBy({"mService", "mProcLock"})
setActiveInstrumentation(ActiveInstrumentation instr)758     void setActiveInstrumentation(ActiveInstrumentation instr) {
759         mInstr = instr;
760         boolean isInstrumenting = instr != null;
761         mWindowProcessController.setInstrumenting(
762                 isInstrumenting,
763                 isInstrumenting ? instr.mSourceUid : -1,
764                 isInstrumenting && instr.mHasBackgroundActivityStartsPermission);
765     }
766 
767     @GuardedBy(anyOf = {"mService", "mProcLock"})
getActiveInstrumentation()768     ActiveInstrumentation getActiveInstrumentation() {
769         return mInstr;
770     }
771 
772     @GuardedBy(anyOf = {"mService", "mProcLock"})
isKilledByAm()773     boolean isKilledByAm() {
774         return mKilledByAm;
775     }
776 
777     @GuardedBy({"mService", "mProcLock"})
setKilledByAm(boolean killedByAm)778     void setKilledByAm(boolean killedByAm) {
779         mKilledByAm = killedByAm;
780     }
781 
782     @GuardedBy(anyOf = {"mService", "mProcLock"})
isKilled()783     boolean isKilled() {
784         return mKilled;
785     }
786 
787     @GuardedBy({"mService", "mProcLock"})
setKilled(boolean killed)788     void setKilled(boolean killed) {
789         mKilled = killed;
790     }
791 
792     @GuardedBy(anyOf = {"mService", "mProcLock"})
getKillTime()793     long getKillTime() {
794         return mKillTime;
795     }
796 
797     @GuardedBy({"mService", "mProcLock"})
setKillTime(long killTime)798     void setKillTime(long killTime) {
799         mKillTime = killTime;
800     }
801 
802     @GuardedBy("mService")
getWaitingToKill()803     String getWaitingToKill() {
804         return mWaitingToKill;
805     }
806 
807     @GuardedBy("mService")
setWaitingToKill(String waitingToKill)808     void setWaitingToKill(String waitingToKill) {
809         mWaitingToKill = waitingToKill;
810     }
811 
812     @Override
isRemoved()813     public boolean isRemoved() {
814         return mRemoved;
815     }
816 
setRemoved(boolean removed)817     void setRemoved(boolean removed) {
818         mRemoved = removed;
819     }
820 
821     @GuardedBy("mService")
isDebugging()822     boolean isDebugging() {
823         return mDebugging;
824     }
825 
826     @GuardedBy("mService")
setDebugging(boolean debugging)827     void setDebugging(boolean debugging) {
828         mDebugging = debugging;
829         mWindowProcessController.setDebugging(debugging);
830     }
831 
832     @GuardedBy("mProcLock")
hasWaitedForDebugger()833     boolean hasWaitedForDebugger() {
834         return mWaitedForDebugger;
835     }
836 
837     @GuardedBy("mProcLock")
setWaitedForDebugger(boolean waitedForDebugger)838     void setWaitedForDebugger(boolean waitedForDebugger) {
839         mWaitedForDebugger = waitedForDebugger;
840     }
841 
842     @GuardedBy(anyOf = {"mService", "mProcLock"})
getLastActivityTime()843     long getLastActivityTime() {
844         return mLastActivityTime;
845     }
846 
847     @GuardedBy({"mService", "mProcLock"})
setLastActivityTime(long lastActivityTime)848     void setLastActivityTime(long lastActivityTime) {
849         mLastActivityTime = lastActivityTime;
850     }
851 
852     @GuardedBy("mService")
isUsingWrapper()853     boolean isUsingWrapper() {
854         return mUsingWrapper;
855     }
856 
857     @GuardedBy("mService")
setUsingWrapper(boolean usingWrapper)858     void setUsingWrapper(boolean usingWrapper) {
859         mUsingWrapper = usingWrapper;
860         mWindowProcessController.setUsingWrapper(usingWrapper);
861     }
862 
863     @GuardedBy("mService")
getLruSeq()864     int getLruSeq() {
865         return mLruSeq;
866     }
867 
868     @GuardedBy("mService")
setLruSeq(int lruSeq)869     void setLruSeq(int lruSeq) {
870         mLruSeq = lruSeq;
871     }
872 
873     @GuardedBy("mService")
getIsolatedEntryPoint()874     String getIsolatedEntryPoint() {
875         return mIsolatedEntryPoint;
876     }
877 
878     @GuardedBy("mService")
setIsolatedEntryPoint(String isolatedEntryPoint)879     void setIsolatedEntryPoint(String isolatedEntryPoint) {
880         mIsolatedEntryPoint = isolatedEntryPoint;
881     }
882 
883     @GuardedBy("mService")
getIsolatedEntryPointArgs()884     String[] getIsolatedEntryPointArgs() {
885         return mIsolatedEntryPointArgs;
886     }
887 
888     @GuardedBy("mService")
setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs)889     void setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs) {
890         mIsolatedEntryPointArgs = isolatedEntryPointArgs;
891     }
892 
893     @GuardedBy("mService")
isInFullBackup()894     boolean isInFullBackup() {
895         return mInFullBackup;
896     }
897 
898     @GuardedBy("mService")
setInFullBackup(boolean inFullBackup)899     void setInFullBackup(boolean inFullBackup) {
900         mInFullBackup = inFullBackup;
901     }
902 
903     @Override
isCached()904     public boolean isCached() {
905         return mState.isCached();
906     }
907 
hasActivities()908     boolean hasActivities() {
909         return mWindowProcessController.hasActivities();
910     }
911 
hasActivitiesOrRecentTasks()912     boolean hasActivitiesOrRecentTasks() {
913         return mWindowProcessController.hasActivitiesOrRecentTasks();
914     }
915 
hasRecentTasks()916     boolean hasRecentTasks() {
917         return mWindowProcessController.hasRecentTasks();
918     }
919 
920     @GuardedBy({"mService", "mProcLock"})
onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart, boolean unlinkDeath)921     boolean onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart,
922             boolean unlinkDeath) {
923         mErrorState.onCleanupApplicationRecordLSP();
924 
925         resetPackageList(processStats);
926         if (unlinkDeath) {
927             unlinkDeathRecipient();
928         }
929         makeInactive(processStats);
930         setWaitingToKill(null);
931 
932         mState.onCleanupApplicationRecordLSP();
933         mServices.onCleanupApplicationRecordLocked();
934         mReceivers.onCleanupApplicationRecordLocked();
935 
936         return mProviders.onCleanupApplicationRecordLocked(allowRestart);
937     }
938 
939     /**
940      * This method returns true if any of the activities within the process record are interesting
941      * to the user. See HistoryRecord.isInterestingToUserLocked()
942      */
isInterestingToUserLocked()943     public boolean isInterestingToUserLocked() {
944         if (mWindowProcessController.isInterestingToUser()) {
945             return true;
946         }
947 
948         return mServices.hasForegroundServices();
949     }
950 
951     @GuardedBy("mService")
scheduleCrashLocked(String message)952     void scheduleCrashLocked(String message) {
953         scheduleCrashLocked(message, RemoteServiceException.TYPE_ID);
954     }
955 
956     /**
957      * Let an app process throw an exception on a binder thread, which typically crashes the
958      * process, unless it has an unhandled exception handler.
959      *
960      * See {@link ActivityThread#throwRemoteServiceException}.
961      *
962      * @param message exception message
963      * @param exceptionTypeId ID defined in {@link android.app.RemoteServiceException} or one
964      *                        of its subclasses.
965      */
966     @GuardedBy("mService")
scheduleCrashLocked(String message, int exceptionTypeId)967     void scheduleCrashLocked(String message, int exceptionTypeId) {
968         // Checking killedbyAm should keep it from showing the crash dialog if the process
969         // was already dead for a good / normal reason.
970         if (!mKilledByAm) {
971             if (mThread != null) {
972                 if (mPid == Process.myPid()) {
973                     Slog.w(TAG, "scheduleCrash: trying to crash system process!");
974                     return;
975                 }
976                 final long ident = Binder.clearCallingIdentity();
977                 try {
978                     mThread.scheduleCrash(message, exceptionTypeId);
979                 } catch (RemoteException e) {
980                     // If it's already dead our work is done. If it's wedged just kill it.
981                     // We won't get the crash dialog or the error reporting.
982                     killLocked("scheduleCrash for '" + message + "' failed",
983                             ApplicationExitInfo.REASON_CRASH, true);
984                 } finally {
985                     Binder.restoreCallingIdentity(ident);
986                 }
987             }
988         }
989     }
990 
991     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, boolean noisy)992     void killLocked(String reason, @Reason int reasonCode, boolean noisy) {
993         killLocked(reason, reasonCode, ApplicationExitInfo.SUBREASON_UNKNOWN, noisy);
994     }
995 
996     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy)997     void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason,
998             boolean noisy) {
999         if (!mKilledByAm) {
1000             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
1001             if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
1002                 mService.reportUidInfoMessageLocked(TAG,
1003                         "Killing " + toShortString() + " (adj " + mState.getSetAdj()
1004                         + "): " + reason, info.uid);
1005             }
1006             if (mPid > 0) {
1007                 mService.mProcessList.noteAppKill(this, reasonCode, subReason, reason);
1008                 EventLog.writeEvent(EventLogTags.AM_KILL,
1009                         userId, mPid, processName, mState.getSetAdj(), reason);
1010                 Process.killProcessQuiet(mPid);
1011                 ProcessList.killProcessGroup(uid, mPid);
1012             } else {
1013                 mPendingStart = false;
1014             }
1015             if (!mPersistent) {
1016                 synchronized (mProcLock) {
1017                     mKilled = true;
1018                     mKilledByAm = true;
1019                     mKillTime = SystemClock.uptimeMillis();
1020                 }
1021             }
1022             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1023         }
1024     }
1025 
1026     @Override
dumpDebug(ProtoOutputStream proto, long fieldId)1027     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1028         dumpDebug(proto, fieldId, -1);
1029     }
1030 
dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex)1031     public void dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex) {
1032         long token = proto.start(fieldId);
1033         proto.write(ProcessRecordProto.PID, mPid);
1034         proto.write(ProcessRecordProto.PROCESS_NAME, processName);
1035         proto.write(ProcessRecordProto.UID, info.uid);
1036         if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) {
1037             proto.write(ProcessRecordProto.USER_ID, userId);
1038             proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid));
1039         }
1040         if (uid != info.uid) {
1041             proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid));
1042         }
1043         proto.write(ProcessRecordProto.PERSISTENT, mPersistent);
1044         if (lruIndex >= 0) {
1045             proto.write(ProcessRecordProto.LRU_INDEX, lruIndex);
1046         }
1047         proto.end(token);
1048     }
1049 
toShortString()1050     public String toShortString() {
1051         final String shortStringName = mShortStringName;
1052         if (shortStringName != null) {
1053             return shortStringName;
1054         }
1055         StringBuilder sb = new StringBuilder(128);
1056         toShortString(sb);
1057         return mShortStringName = sb.toString();
1058     }
1059 
toShortString(StringBuilder sb)1060     void toShortString(StringBuilder sb) {
1061         sb.append(mPid);
1062         sb.append(':');
1063         sb.append(processName);
1064         sb.append('/');
1065         if (info.uid < Process.FIRST_APPLICATION_UID) {
1066             sb.append(uid);
1067         } else {
1068             sb.append('u');
1069             sb.append(userId);
1070             int appId = UserHandle.getAppId(info.uid);
1071             if (appId >= Process.FIRST_APPLICATION_UID) {
1072                 sb.append('a');
1073                 sb.append(appId - Process.FIRST_APPLICATION_UID);
1074             } else {
1075                 sb.append('s');
1076                 sb.append(appId);
1077             }
1078             if (uid != info.uid) {
1079                 sb.append('i');
1080                 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
1081             }
1082         }
1083     }
1084 
toString()1085     public String toString() {
1086         final String stringName = mStringName;
1087         if (stringName != null) {
1088             return stringName;
1089         }
1090         StringBuilder sb = new StringBuilder(128);
1091         sb.append("ProcessRecord{");
1092         sb.append(Integer.toHexString(System.identityHashCode(this)));
1093         sb.append(' ');
1094         toShortString(sb);
1095         sb.append('}');
1096         return mStringName = sb.toString();
1097     }
1098 
1099     /*
1100      *  Return true if package has been added false if not
1101      */
addPackage(String pkg, long versionCode, ProcessStatsService tracker)1102     public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) {
1103         synchronized (tracker.mLock) {
1104             synchronized (mPkgList) {
1105                 if (!mPkgList.containsKey(pkg)) {
1106                     ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
1107                             versionCode);
1108                     final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1109                     if (baseProcessTracker != null) {
1110                         tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode,
1111                                 processName);
1112                         mPkgList.put(pkg, holder);
1113                         if (holder.state != baseProcessTracker) {
1114                             holder.state.makeActive();
1115                         }
1116                     } else {
1117                         mPkgList.put(pkg, holder);
1118                     }
1119                     return true;
1120                 }
1121             }
1122         }
1123         return false;
1124     }
1125 
1126     /*
1127      *  Delete all packages from list except the package indicated in info
1128      */
resetPackageList(ProcessStatsService tracker)1129     public void resetPackageList(ProcessStatsService tracker) {
1130         synchronized (tracker.mLock) {
1131             final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1132             synchronized (mPkgList) {
1133                 final int numOfPkgs = mPkgList.size();
1134                 if (baseProcessTracker != null) {
1135                     long now = SystemClock.uptimeMillis();
1136                     baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
1137                             tracker.getMemFactorLocked(), now, mPkgList.getPackageListLocked());
1138                     mPkgList.forEachPackage((pkgName, holder) ->
1139                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_STATE_CHANGED,
1140                                 uid, processName, pkgName,
1141                                 ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING),
1142                                 holder.appVersion)
1143                     );
1144                     if (numOfPkgs != 1) {
1145                         mPkgList.forEachPackageProcessStats(holder -> {
1146                             if (holder.state != null && holder.state != baseProcessTracker) {
1147                                 holder.state.makeInactive();
1148                             }
1149                         });
1150                         mPkgList.clear();
1151                         ProcessStats.ProcessStateHolder holder =
1152                                 new ProcessStats.ProcessStateHolder(info.longVersionCode);
1153                         tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid,
1154                                 info.longVersionCode, processName);
1155                         mPkgList.put(info.packageName, holder);
1156                         if (holder.state != baseProcessTracker) {
1157                             holder.state.makeActive();
1158                         }
1159                     }
1160                 } else if (numOfPkgs != 1) {
1161                     mPkgList.clear();
1162                     mPkgList.put(info.packageName,
1163                             new ProcessStats.ProcessStateHolder(info.longVersionCode));
1164                 }
1165             }
1166         }
1167     }
1168 
getPackageList()1169     String[] getPackageList() {
1170         return mPkgList.getPackageList();
1171     }
1172 
getPackageListWithVersionCode()1173     List<VersionedPackage> getPackageListWithVersionCode() {
1174         return mPkgList.getPackageListWithVersionCode();
1175     }
1176 
getWindowProcessController()1177     WindowProcessController getWindowProcessController() {
1178         return mWindowProcessController;
1179     }
1180 
1181     /**
1182      * Allows background activity starts using token {@param entity}. Optionally, you can provide
1183      * {@param originatingToken} if you have one such originating token, this is useful for tracing
1184      * back the grant in the case of the notification token.
1185      */
addOrUpdateAllowBackgroundActivityStartsToken(Binder entity, @Nullable IBinder originatingToken)1186     void addOrUpdateAllowBackgroundActivityStartsToken(Binder entity,
1187             @Nullable IBinder originatingToken) {
1188         Objects.requireNonNull(entity);
1189         mWindowProcessController.addOrUpdateAllowBackgroundActivityStartsToken(entity,
1190                 originatingToken);
1191     }
1192 
removeAllowBackgroundActivityStartsToken(Binder entity)1193     void removeAllowBackgroundActivityStartsToken(Binder entity) {
1194         Objects.requireNonNull(entity);
1195         mWindowProcessController.removeAllowBackgroundActivityStartsToken(entity);
1196     }
1197 
1198     @Override
clearProfilerIfNeeded()1199     public void clearProfilerIfNeeded() {
1200         synchronized (mService.mAppProfiler.mProfilerLock) {
1201             mService.mAppProfiler.clearProfilerLPf();
1202         }
1203     }
1204 
1205     @Override
updateServiceConnectionActivities()1206     public void updateServiceConnectionActivities() {
1207         synchronized (mService) {
1208             mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1209         }
1210     }
1211 
1212     @Override
setPendingUiClean(boolean pendingUiClean)1213     public void setPendingUiClean(boolean pendingUiClean) {
1214         synchronized (mProcLock) {
1215             mProfile.setPendingUiClean(pendingUiClean);
1216         }
1217     }
1218 
1219     @Override
setPendingUiCleanAndForceProcessStateUpTo(int newState)1220     public void setPendingUiCleanAndForceProcessStateUpTo(int newState) {
1221         synchronized (mService) {
1222             setPendingUiClean(true);
1223             mState.forceProcessStateUpTo(newState);
1224         }
1225     }
1226 
1227     @Override
updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1228     public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange,
1229             boolean updateOomAdj) {
1230         synchronized (mService) {
1231             if (updateServiceConnectionActivities) {
1232                 mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1233             }
1234             if (mThread == null) {
1235                 // Only update lru and oom-adj if the process is alive. Because it may be called
1236                 // when cleaning up the last activity from handling process died, the dead process
1237                 // should not be added to lru list again.
1238                 return;
1239             }
1240             mService.updateLruProcessLocked(this, activityChange, null /* client */);
1241             if (updateOomAdj) {
1242                 mService.updateOomAdjLocked(this, OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
1243             }
1244         }
1245     }
1246 
1247     /**
1248      * Returns the total time (in milliseconds) spent executing in both user and system code.
1249      * Safe to call without lock held.
1250      */
1251     @Override
getCpuTime()1252     public long getCpuTime() {
1253         return mService.mAppProfiler.getCpuTimeForPid(mPid);
1254     }
1255 
1256     @Override
onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1257     public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName,
1258             long versionCode) {
1259         synchronized (mService) {
1260             mWaitingToKill = null;
1261             if (setProfileProc) {
1262                 synchronized (mService.mAppProfiler.mProfilerLock) {
1263                     mService.mAppProfiler.setProfileProcLPf(this);
1264                 }
1265             }
1266             if (packageName != null) {
1267                 addPackage(packageName, versionCode, mService.mProcessStats);
1268             }
1269 
1270             // Update oom adj first, we don't want the additional states are involved in this round.
1271             updateProcessInfo(false /* updateServiceConnectionActivities */,
1272                     true /* activityChange */, true /* updateOomAdj */);
1273             setPendingUiClean(true);
1274             mState.setHasShownUi(true);
1275             mState.forceProcessStateUpTo(topProcessState);
1276         }
1277     }
1278 
1279     @Override
appDied(String reason)1280     public void appDied(String reason) {
1281         synchronized (mService) {
1282             mService.appDiedLocked(this, reason);
1283         }
1284     }
1285 
1286     @Override
setRunningRemoteAnimation(boolean runningRemoteAnimation)1287     public void setRunningRemoteAnimation(boolean runningRemoteAnimation) {
1288         if (mPid == Process.myPid()) {
1289             Slog.wtf(TAG, "system can't run remote animation");
1290             return;
1291         }
1292         synchronized (mService) {
1293             mState.setRunningRemoteAnimation(runningRemoteAnimation);
1294         }
1295     }
1296 
getInputDispatchingTimeoutMillis()1297     public long getInputDispatchingTimeoutMillis() {
1298         return mWindowProcessController.getInputDispatchingTimeoutMillis();
1299     }
1300 
getProcessClassEnum()1301     public int getProcessClassEnum() {
1302         if (mPid == MY_PID) {
1303             return ServerProtoEnums.SYSTEM_SERVER;
1304         }
1305         if (info == null) {
1306             return ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
1307         }
1308         return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP :
1309             ServerProtoEnums.DATA_APP;
1310     }
1311 
1312     /** Non-private access is for tests only. */
1313     @VisibleForTesting
getLruProcessList()1314     List<ProcessRecord> getLruProcessList() {
1315         return mService.mProcessList.getLruProcessesLOSP();
1316     }
1317 }
1318