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.content.pm.ApplicationInfo;
30 import android.content.pm.ProcessInfo;
31 import android.content.pm.VersionedPackage;
32 import android.content.res.CompatibilityInfo;
33 import android.os.Binder;
34 import android.os.Bundle;
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     /**
952      * Let an app process throw an exception on a binder thread, which typically crashes the
953      * process, unless it has an unhandled exception handler.
954      *
955      * See {@link ActivityThread#throwRemoteServiceException}.
956      *
957      * @param message exception message
958      * @param exceptionTypeId ID defined in {@link android.app.RemoteServiceException} or one
959      *                        of its subclasses.
960      */
961     @GuardedBy("mService")
scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras)962     void scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras) {
963         // Checking killedbyAm should keep it from showing the crash dialog if the process
964         // was already dead for a good / normal reason.
965         if (!mKilledByAm) {
966             if (mThread != null) {
967                 if (mPid == Process.myPid()) {
968                     Slog.w(TAG, "scheduleCrash: trying to crash system process!");
969                     return;
970                 }
971                 final long ident = Binder.clearCallingIdentity();
972                 try {
973                     mThread.scheduleCrash(message, exceptionTypeId, extras);
974                 } catch (RemoteException e) {
975                     // If it's already dead our work is done. If it's wedged just kill it.
976                     // We won't get the crash dialog or the error reporting.
977                     killLocked("scheduleCrash for '" + message + "' failed",
978                             ApplicationExitInfo.REASON_CRASH, true);
979                 } finally {
980                     Binder.restoreCallingIdentity(ident);
981                 }
982             }
983         }
984     }
985 
986     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, boolean noisy)987     void killLocked(String reason, @Reason int reasonCode, boolean noisy) {
988         killLocked(reason, reasonCode, ApplicationExitInfo.SUBREASON_UNKNOWN, noisy);
989     }
990 
991     @GuardedBy("mService")
killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy)992     void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason,
993             boolean noisy) {
994         if (!mKilledByAm) {
995             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
996             if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
997                 mService.reportUidInfoMessageLocked(TAG,
998                         "Killing " + toShortString() + " (adj " + mState.getSetAdj()
999                         + "): " + reason, info.uid);
1000             }
1001             if (mPid > 0) {
1002                 mService.mProcessList.noteAppKill(this, reasonCode, subReason, reason);
1003                 EventLog.writeEvent(EventLogTags.AM_KILL,
1004                         userId, mPid, processName, mState.getSetAdj(), reason);
1005                 Process.killProcessQuiet(mPid);
1006                 ProcessList.killProcessGroup(uid, mPid);
1007             } else {
1008                 mPendingStart = false;
1009             }
1010             if (!mPersistent) {
1011                 synchronized (mProcLock) {
1012                     mKilled = true;
1013                     mKilledByAm = true;
1014                     mKillTime = SystemClock.uptimeMillis();
1015                 }
1016             }
1017             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1018         }
1019     }
1020 
1021     @Override
dumpDebug(ProtoOutputStream proto, long fieldId)1022     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1023         dumpDebug(proto, fieldId, -1);
1024     }
1025 
dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex)1026     public void dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex) {
1027         long token = proto.start(fieldId);
1028         proto.write(ProcessRecordProto.PID, mPid);
1029         proto.write(ProcessRecordProto.PROCESS_NAME, processName);
1030         proto.write(ProcessRecordProto.UID, info.uid);
1031         if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) {
1032             proto.write(ProcessRecordProto.USER_ID, userId);
1033             proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid));
1034         }
1035         if (uid != info.uid) {
1036             proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid));
1037         }
1038         proto.write(ProcessRecordProto.PERSISTENT, mPersistent);
1039         if (lruIndex >= 0) {
1040             proto.write(ProcessRecordProto.LRU_INDEX, lruIndex);
1041         }
1042         proto.end(token);
1043     }
1044 
toShortString()1045     public String toShortString() {
1046         final String shortStringName = mShortStringName;
1047         if (shortStringName != null) {
1048             return shortStringName;
1049         }
1050         StringBuilder sb = new StringBuilder(128);
1051         toShortString(sb);
1052         return mShortStringName = sb.toString();
1053     }
1054 
toShortString(StringBuilder sb)1055     void toShortString(StringBuilder sb) {
1056         sb.append(mPid);
1057         sb.append(':');
1058         sb.append(processName);
1059         sb.append('/');
1060         if (info.uid < Process.FIRST_APPLICATION_UID) {
1061             sb.append(uid);
1062         } else {
1063             sb.append('u');
1064             sb.append(userId);
1065             int appId = UserHandle.getAppId(info.uid);
1066             if (appId >= Process.FIRST_APPLICATION_UID) {
1067                 sb.append('a');
1068                 sb.append(appId - Process.FIRST_APPLICATION_UID);
1069             } else {
1070                 sb.append('s');
1071                 sb.append(appId);
1072             }
1073             if (uid != info.uid) {
1074                 sb.append('i');
1075                 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
1076             }
1077         }
1078     }
1079 
toString()1080     public String toString() {
1081         final String stringName = mStringName;
1082         if (stringName != null) {
1083             return stringName;
1084         }
1085         StringBuilder sb = new StringBuilder(128);
1086         sb.append("ProcessRecord{");
1087         sb.append(Integer.toHexString(System.identityHashCode(this)));
1088         sb.append(' ');
1089         toShortString(sb);
1090         sb.append('}');
1091         return mStringName = sb.toString();
1092     }
1093 
1094     /*
1095      *  Return true if package has been added false if not
1096      */
addPackage(String pkg, long versionCode, ProcessStatsService tracker)1097     public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) {
1098         synchronized (tracker.mLock) {
1099             synchronized (mPkgList) {
1100                 if (!mPkgList.containsKey(pkg)) {
1101                     ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
1102                             versionCode);
1103                     final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1104                     if (baseProcessTracker != null) {
1105                         tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode,
1106                                 processName);
1107                         mPkgList.put(pkg, holder);
1108                         if (holder.state != baseProcessTracker) {
1109                             holder.state.makeActive();
1110                         }
1111                     } else {
1112                         mPkgList.put(pkg, holder);
1113                     }
1114                     return true;
1115                 }
1116             }
1117         }
1118         return false;
1119     }
1120 
1121     /*
1122      *  Delete all packages from list except the package indicated in info
1123      */
resetPackageList(ProcessStatsService tracker)1124     public void resetPackageList(ProcessStatsService tracker) {
1125         synchronized (tracker.mLock) {
1126             final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker();
1127             synchronized (mPkgList) {
1128                 final int numOfPkgs = mPkgList.size();
1129                 if (baseProcessTracker != null) {
1130                     long now = SystemClock.uptimeMillis();
1131                     baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
1132                             tracker.getMemFactorLocked(), now, mPkgList.getPackageListLocked());
1133                     mPkgList.forEachPackage((pkgName, holder) ->
1134                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_STATE_CHANGED,
1135                                 uid, processName, pkgName,
1136                                 ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING),
1137                                 holder.appVersion)
1138                     );
1139                     if (numOfPkgs != 1) {
1140                         mPkgList.forEachPackageProcessStats(holder -> {
1141                             if (holder.state != null && holder.state != baseProcessTracker) {
1142                                 holder.state.makeInactive();
1143                             }
1144                         });
1145                         mPkgList.clear();
1146                         ProcessStats.ProcessStateHolder holder =
1147                                 new ProcessStats.ProcessStateHolder(info.longVersionCode);
1148                         tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid,
1149                                 info.longVersionCode, processName);
1150                         mPkgList.put(info.packageName, holder);
1151                         if (holder.state != baseProcessTracker) {
1152                             holder.state.makeActive();
1153                         }
1154                     }
1155                 } else if (numOfPkgs != 1) {
1156                     mPkgList.clear();
1157                     mPkgList.put(info.packageName,
1158                             new ProcessStats.ProcessStateHolder(info.longVersionCode));
1159                 }
1160             }
1161         }
1162     }
1163 
getPackageList()1164     String[] getPackageList() {
1165         return mPkgList.getPackageList();
1166     }
1167 
getPackageListWithVersionCode()1168     List<VersionedPackage> getPackageListWithVersionCode() {
1169         return mPkgList.getPackageListWithVersionCode();
1170     }
1171 
getWindowProcessController()1172     WindowProcessController getWindowProcessController() {
1173         return mWindowProcessController;
1174     }
1175 
1176     /**
1177      * Allows background activity starts using token {@param entity}. Optionally, you can provide
1178      * {@param originatingToken} if you have one such originating token, this is useful for tracing
1179      * back the grant in the case of the notification token.
1180      */
addOrUpdateAllowBackgroundActivityStartsToken(Binder entity, @Nullable IBinder originatingToken)1181     void addOrUpdateAllowBackgroundActivityStartsToken(Binder entity,
1182             @Nullable IBinder originatingToken) {
1183         Objects.requireNonNull(entity);
1184         mWindowProcessController.addOrUpdateAllowBackgroundActivityStartsToken(entity,
1185                 originatingToken);
1186     }
1187 
removeAllowBackgroundActivityStartsToken(Binder entity)1188     void removeAllowBackgroundActivityStartsToken(Binder entity) {
1189         Objects.requireNonNull(entity);
1190         mWindowProcessController.removeAllowBackgroundActivityStartsToken(entity);
1191     }
1192 
1193     @Override
clearProfilerIfNeeded()1194     public void clearProfilerIfNeeded() {
1195         synchronized (mService.mAppProfiler.mProfilerLock) {
1196             mService.mAppProfiler.clearProfilerLPf();
1197         }
1198     }
1199 
1200     @Override
updateServiceConnectionActivities()1201     public void updateServiceConnectionActivities() {
1202         synchronized (mService) {
1203             mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1204         }
1205     }
1206 
1207     @Override
setPendingUiClean(boolean pendingUiClean)1208     public void setPendingUiClean(boolean pendingUiClean) {
1209         synchronized (mProcLock) {
1210             mProfile.setPendingUiClean(pendingUiClean);
1211         }
1212     }
1213 
1214     @Override
setPendingUiCleanAndForceProcessStateUpTo(int newState)1215     public void setPendingUiCleanAndForceProcessStateUpTo(int newState) {
1216         synchronized (mService) {
1217             setPendingUiClean(true);
1218             mState.forceProcessStateUpTo(newState);
1219         }
1220     }
1221 
1222     @Override
updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1223     public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange,
1224             boolean updateOomAdj) {
1225         synchronized (mService) {
1226             if (updateServiceConnectionActivities) {
1227                 mService.mServices.updateServiceConnectionActivitiesLocked(mServices);
1228             }
1229             if (mThread == null) {
1230                 // Only update lru and oom-adj if the process is alive. Because it may be called
1231                 // when cleaning up the last activity from handling process died, the dead process
1232                 // should not be added to lru list again.
1233                 return;
1234             }
1235             mService.updateLruProcessLocked(this, activityChange, null /* client */);
1236             if (updateOomAdj) {
1237                 mService.updateOomAdjLocked(this, OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
1238             }
1239         }
1240     }
1241 
1242     /**
1243      * Returns the total time (in milliseconds) spent executing in both user and system code.
1244      * Safe to call without lock held.
1245      */
1246     @Override
getCpuTime()1247     public long getCpuTime() {
1248         return mService.mAppProfiler.getCpuTimeForPid(mPid);
1249     }
1250 
1251     @Override
onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1252     public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName,
1253             long versionCode) {
1254         synchronized (mService) {
1255             mWaitingToKill = null;
1256             if (setProfileProc) {
1257                 synchronized (mService.mAppProfiler.mProfilerLock) {
1258                     mService.mAppProfiler.setProfileProcLPf(this);
1259                 }
1260             }
1261             if (packageName != null) {
1262                 addPackage(packageName, versionCode, mService.mProcessStats);
1263             }
1264 
1265             // Update oom adj first, we don't want the additional states are involved in this round.
1266             updateProcessInfo(false /* updateServiceConnectionActivities */,
1267                     true /* activityChange */, true /* updateOomAdj */);
1268             setPendingUiClean(true);
1269             mState.setHasShownUi(true);
1270             mState.forceProcessStateUpTo(topProcessState);
1271         }
1272     }
1273 
1274     @Override
appDied(String reason)1275     public void appDied(String reason) {
1276         synchronized (mService) {
1277             mService.appDiedLocked(this, reason);
1278         }
1279     }
1280 
1281     @Override
setRunningRemoteAnimation(boolean runningRemoteAnimation)1282     public void setRunningRemoteAnimation(boolean runningRemoteAnimation) {
1283         if (mPid == Process.myPid()) {
1284             Slog.wtf(TAG, "system can't run remote animation");
1285             return;
1286         }
1287         synchronized (mService) {
1288             mState.setRunningRemoteAnimation(runningRemoteAnimation);
1289         }
1290     }
1291 
getInputDispatchingTimeoutMillis()1292     public long getInputDispatchingTimeoutMillis() {
1293         return mWindowProcessController.getInputDispatchingTimeoutMillis();
1294     }
1295 
getProcessClassEnum()1296     public int getProcessClassEnum() {
1297         if (mPid == MY_PID) {
1298             return ServerProtoEnums.SYSTEM_SERVER;
1299         }
1300         if (info == null) {
1301             return ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
1302         }
1303         return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP :
1304             ServerProtoEnums.DATA_APP;
1305     }
1306 
1307     /** Non-private access is for tests only. */
1308     @VisibleForTesting
getLruProcessList()1309     List<ProcessRecord> getLruProcessList() {
1310         return mService.mProcessList.getLruProcessesLOSP();
1311     }
1312 }
1313