• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static android.app.ActivityManager.RunningAppProcessInfo.procStateToImportance;
20 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
21 import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
22 
23 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
24 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
25 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
26 
27 import android.annotation.CurrentTimeMillisLong;
28 import android.annotation.Nullable;
29 import android.app.ApplicationExitInfo;
30 import android.app.ApplicationExitInfo.Reason;
31 import android.app.ApplicationExitInfo.SubReason;
32 import android.app.IAppTraceRetriever;
33 import android.content.BroadcastReceiver;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.pm.PackageManager;
38 import android.icu.text.SimpleDateFormat;
39 import android.os.Binder;
40 import android.os.FileUtils;
41 import android.os.Handler;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.ParcelFileDescriptor;
45 import android.os.Process;
46 import android.os.SystemProperties;
47 import android.os.UserHandle;
48 import android.system.OsConstants;
49 import android.text.TextUtils;
50 import android.util.ArrayMap;
51 import android.util.ArraySet;
52 import android.util.AtomicFile;
53 import android.util.Pair;
54 import android.util.Pools.SynchronizedPool;
55 import android.util.Slog;
56 import android.util.SparseArray;
57 import android.util.proto.ProtoInputStream;
58 import android.util.proto.ProtoOutputStream;
59 import android.util.proto.WireTypeMismatchException;
60 
61 import com.android.internal.annotations.GuardedBy;
62 import com.android.internal.annotations.VisibleForTesting;
63 import com.android.internal.app.ProcessMap;
64 import com.android.internal.util.ArrayUtils;
65 import com.android.internal.util.FrameworkStatsLog;
66 import com.android.internal.util.function.pooled.PooledLambda;
67 import com.android.server.IoThread;
68 import com.android.server.LocalServices;
69 import com.android.server.ServiceThread;
70 import com.android.server.SystemServiceManager;
71 import com.android.server.os.NativeTombstoneManager;
72 
73 import java.io.BufferedInputStream;
74 import java.io.BufferedOutputStream;
75 import java.io.File;
76 import java.io.FileInputStream;
77 import java.io.FileNotFoundException;
78 import java.io.FileOutputStream;
79 import java.io.IOException;
80 import java.io.PrintWriter;
81 import java.util.ArrayList;
82 import java.util.Collections;
83 import java.util.Date;
84 import java.util.List;
85 import java.util.Optional;
86 import java.util.concurrent.TimeUnit;
87 import java.util.concurrent.atomic.AtomicBoolean;
88 import java.util.function.BiConsumer;
89 import java.util.function.BiFunction;
90 import java.util.function.Consumer;
91 import java.util.function.Predicate;
92 import java.util.function.Supplier;
93 import java.util.zip.GZIPOutputStream;
94 
95 /**
96  * A class to manage all the {@link android.app.ApplicationExitInfo} records.
97  */
98 public final class AppExitInfoTracker {
99     private static final String TAG = TAG_WITH_CLASS_NAME ? "AppExitInfoTracker" : TAG_AM;
100 
101     /**
102      * Interval of persisting the app exit info to persistent storage.
103      */
104     private static final long APP_EXIT_INFO_PERSIST_INTERVAL = TimeUnit.MINUTES.toMillis(30);
105 
106     /** These are actions that the forEach* should take after each iteration */
107     private static final int FOREACH_ACTION_NONE = 0;
108     private static final int FOREACH_ACTION_REMOVE_ITEM = 1;
109     private static final int FOREACH_ACTION_STOP_ITERATION = 2;
110 
111     private static final int APP_EXIT_RAW_INFO_POOL_SIZE = 8;
112 
113     /**
114      * How long we're going to hold before logging an app exit info into statsd;
115      * we do this is because there could be multiple sources signaling an app exit, we'd like to
116      * gather the most accurate information before logging into statsd.
117      */
118     private static final long APP_EXIT_INFO_STATSD_LOG_DEBOUNCE = TimeUnit.SECONDS.toMillis(15);
119 
120     @VisibleForTesting
121     static final String APP_EXIT_STORE_DIR = "procexitstore";
122 
123     @VisibleForTesting
124     static final String APP_EXIT_INFO_FILE = "procexitinfo";
125 
126     private static final String APP_TRACE_FILE_SUFFIX = ".gz";
127 
128     private final Object mLock = new Object();
129 
130     /**
131      * Initialized in {@link #init} and read-only after that.
132      */
133     private ActivityManagerService mService;
134 
135     /**
136      * Initialized in {@link #init} and read-only after that.
137      */
138     private KillHandler mKillHandler;
139 
140     /**
141      * The task to persist app process exit info
142      */
143     @GuardedBy("mLock")
144     private Runnable mAppExitInfoPersistTask = null;
145 
146     /**
147      * Last time(in ms) since epoch that the app exit info was persisted into persistent storage.
148      */
149     @GuardedBy("mLock")
150     private long mLastAppExitInfoPersistTimestamp = 0L;
151 
152     /**
153      * Retention policy: keep up to X historical exit info per package.
154      *
155      * Initialized in {@link #init} and read-only after that.
156      * Not lock is needed.
157      */
158     private int mAppExitInfoHistoryListSize;
159 
160     /*
161      * PackageName/uid -> [pid/info, ...] holder, the uid here is the package uid.
162      */
163     @GuardedBy("mLock")
164     private final ProcessMap<AppExitInfoContainer> mData;
165 
166     /** A pool of raw {@link android.app.ApplicationExitInfo} records. */
167     @GuardedBy("mLock")
168     private final SynchronizedPool<ApplicationExitInfo> mRawRecordsPool;
169 
170     /**
171      * Wheather or not we've loaded the historical app process exit info from
172      * persistent storage.
173      */
174     @VisibleForTesting
175     AtomicBoolean mAppExitInfoLoaded = new AtomicBoolean();
176 
177     /**
178      * Temporary list being used to filter/sort intermediate results in {@link #getExitInfo}.
179      */
180     @GuardedBy("mLock")
181     final ArrayList<ApplicationExitInfo> mTmpInfoList = new ArrayList<ApplicationExitInfo>();
182 
183     /**
184      * Temporary list being used to filter/sort intermediate results in {@link #getExitInfo}.
185      */
186     @GuardedBy("mLock")
187     final ArrayList<ApplicationExitInfo> mTmpInfoList2 = new ArrayList<ApplicationExitInfo>();
188 
189     /**
190      * The path to the directory which includes the historical proc exit info file
191      * as specified in {@link #mProcExitInfoFile}, as well as the associated trace files.
192      */
193     @VisibleForTesting
194     File mProcExitStoreDir;
195 
196     /**
197      * The path to the historical proc exit info file, persisted in the storage.
198      */
199     @VisibleForTesting
200     File mProcExitInfoFile;
201 
202     /**
203      * Mapping between the isolated UID to its application uid.
204      */
205     final IsolatedUidRecords mIsolatedUidRecords =
206             new IsolatedUidRecords();
207 
208     /**
209      * Bookkeeping app process exit info from Zygote.
210      */
211     final AppExitInfoExternalSource mAppExitInfoSourceZygote =
212             new AppExitInfoExternalSource("zygote", null);
213 
214     /**
215      * Bookkeeping low memory kills info from lmkd.
216      */
217     final AppExitInfoExternalSource mAppExitInfoSourceLmkd =
218             new AppExitInfoExternalSource("lmkd", ApplicationExitInfo.REASON_LOW_MEMORY);
219 
220     /**
221      * The active per-UID/PID state data set by
222      * {@link android.app.ActivityManager#setProcessStateSummary};
223      * these state data are to be "claimed" when its process dies, by then the data will be moved
224      * from this list to the new instance of ApplicationExitInfo.
225      *
226      * <p> The mapping here is UID -> PID -> state </p>
227      *
228      * @see android.app.ActivityManager#setProcessStateSummary(byte[])
229      */
230     @GuardedBy("mLock")
231     final SparseArray<SparseArray<byte[]>> mActiveAppStateSummary = new SparseArray<>();
232 
233     /**
234      * The active per-UID/PID trace file when an ANR occurs but the process hasn't been killed yet,
235      * each record is a path to the actual trace file;  these files are to be "claimed"
236      * when its process dies, by then the "ownership" of the files will be transferred
237      * from this list to the new instance of ApplicationExitInfo.
238      *
239      * <p> The mapping here is UID -> PID -> file </p>
240      */
241     @GuardedBy("mLock")
242     final SparseArray<SparseArray<File>> mActiveAppTraces = new SparseArray<>();
243 
244     /**
245      * The implementation of the interface IAppTraceRetriever.
246      */
247     final AppTraceRetriever mAppTraceRetriever = new AppTraceRetriever();
248 
AppExitInfoTracker()249     AppExitInfoTracker() {
250         mData = new ProcessMap<AppExitInfoContainer>();
251         mRawRecordsPool = new SynchronizedPool<ApplicationExitInfo>(APP_EXIT_RAW_INFO_POOL_SIZE);
252     }
253 
init(ActivityManagerService service)254     void init(ActivityManagerService service) {
255         mService = service;
256         ServiceThread thread = new ServiceThread(TAG + ":killHandler",
257                 THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
258         thread.start();
259         mKillHandler = new KillHandler(thread.getLooper());
260 
261         mProcExitStoreDir = new File(SystemServiceManager.ensureSystemDir(), APP_EXIT_STORE_DIR);
262         if (!FileUtils.createDir(mProcExitStoreDir)) {
263             Slog.e(TAG, "Unable to create " + mProcExitStoreDir);
264             return;
265         }
266         mProcExitInfoFile = new File(mProcExitStoreDir, APP_EXIT_INFO_FILE);
267 
268         mAppExitInfoHistoryListSize = service.mContext.getResources().getInteger(
269                 com.android.internal.R.integer.config_app_exit_info_history_list_size);
270     }
271 
onSystemReady()272     void onSystemReady() {
273         registerForUserRemoval();
274         registerForPackageRemoval();
275         IoThread.getHandler().post(() -> {
276             // Read the sysprop set by lmkd and set this to persist so app could read it.
277             SystemProperties.set("persist.sys.lmk.reportkills",
278                     Boolean.toString(SystemProperties.getBoolean("sys.lmk.reportkills", false)));
279             loadExistingProcessExitInfo();
280         });
281     }
282 
scheduleNoteProcessDied(final ProcessRecord app)283     void scheduleNoteProcessDied(final ProcessRecord app) {
284         if (app == null || app.info == null) {
285             return;
286         }
287 
288         if (!mAppExitInfoLoaded.get()) {
289             return;
290         }
291         mKillHandler.obtainMessage(KillHandler.MSG_PROC_DIED,
292                 obtainRawRecord(app, System.currentTimeMillis())).sendToTarget();
293     }
294 
scheduleNoteAppKill(final ProcessRecord app, final @Reason int reason, final @SubReason int subReason, final String msg)295     void scheduleNoteAppKill(final ProcessRecord app, final @Reason int reason,
296             final @SubReason int subReason, final String msg) {
297         if (!mAppExitInfoLoaded.get()) {
298             return;
299         }
300         if (app == null || app.info == null) {
301             return;
302         }
303 
304         ApplicationExitInfo raw = obtainRawRecord(app, System.currentTimeMillis());
305         raw.setReason(reason);
306         raw.setSubReason(subReason);
307         raw.setDescription(msg);
308         mKillHandler.obtainMessage(KillHandler.MSG_APP_KILL, raw).sendToTarget();
309     }
310 
scheduleNoteAppKill(final int pid, final int uid, final @Reason int reason, final @SubReason int subReason, final String msg)311     void scheduleNoteAppKill(final int pid, final int uid, final @Reason int reason,
312             final @SubReason int subReason, final String msg) {
313         if (!mAppExitInfoLoaded.get()) {
314             return;
315         }
316         ProcessRecord app;
317         synchronized (mService.mPidsSelfLocked) {
318             app = mService.mPidsSelfLocked.get(pid);
319         }
320         if (app == null) {
321             if (DEBUG_PROCESSES) {
322                 Slog.w(TAG, "Skipping saving the kill reason for pid " + pid
323                         + "(uid=" + uid + ") since its process record is not found");
324             }
325         } else {
326             scheduleNoteAppKill(app, reason, subReason, msg);
327         }
328     }
329 
330     interface LmkdKillListener {
331         /**
332          * Called when there is a process kill by lmkd.
333          */
onLmkdKillOccurred(int pid, int uid)334         void onLmkdKillOccurred(int pid, int uid);
335     }
336 
setLmkdKillListener(final LmkdKillListener listener)337     void setLmkdKillListener(final LmkdKillListener listener) {
338         synchronized (mLock) {
339             mAppExitInfoSourceLmkd.setOnProcDiedListener((pid, uid) ->
340                     listener.onLmkdKillOccurred(pid, uid));
341         }
342     }
343 
344     /** Called when there is a low memory kill */
scheduleNoteLmkdProcKilled(final int pid, final int uid)345     void scheduleNoteLmkdProcKilled(final int pid, final int uid) {
346         mKillHandler.obtainMessage(KillHandler.MSG_LMKD_PROC_KILLED, pid, uid)
347                 .sendToTarget();
348     }
349 
scheduleChildProcDied(int pid, int uid, int status)350     private void scheduleChildProcDied(int pid, int uid, int status) {
351         mKillHandler.obtainMessage(KillHandler.MSG_CHILD_PROC_DIED, pid, uid, (Integer) status)
352                 .sendToTarget();
353     }
354 
355     /** Calls when zygote sends us SIGCHLD */
handleZygoteSigChld(int pid, int uid, int status)356     void handleZygoteSigChld(int pid, int uid, int status) {
357         if (DEBUG_PROCESSES) {
358             Slog.i(TAG, "Got SIGCHLD from zygote: pid=" + pid + ", uid=" + uid
359                     + ", status=" + Integer.toHexString(status));
360         }
361         scheduleChildProcDied(pid, uid, status);
362     }
363 
364     /**
365      * Main routine to create or update the {@link android.app.ApplicationExitInfo} for the given
366      * ProcessRecord, also query the zygote and lmkd records to make the information more accurate.
367      */
368     @VisibleForTesting
369     @GuardedBy("mLock")
handleNoteProcessDiedLocked(final ApplicationExitInfo raw)370     void handleNoteProcessDiedLocked(final ApplicationExitInfo raw) {
371         if (raw != null) {
372             if (DEBUG_PROCESSES) {
373                 Slog.i(TAG, "Update process exit info for " + raw.getPackageName()
374                         + "(" + raw.getPid() + "/u" + raw.getRealUid() + ")");
375             }
376 
377             ApplicationExitInfo info = getExitInfoLocked(raw.getPackageName(),
378                     raw.getPackageUid(), raw.getPid());
379 
380             // query zygote and lmkd to get the exit info, and clear the saved info
381             Pair<Long, Object> zygote = mAppExitInfoSourceZygote.remove(
382                     raw.getPid(), raw.getRealUid());
383             Pair<Long, Object> lmkd = mAppExitInfoSourceLmkd.remove(
384                     raw.getPid(), raw.getRealUid());
385             mIsolatedUidRecords.removeIsolatedUidLocked(raw.getRealUid());
386 
387             if (info == null) {
388                 info = addExitInfoLocked(raw);
389             }
390 
391             if (lmkd != null) {
392                 updateExistingExitInfoRecordLocked(info, null,
393                         ApplicationExitInfo.REASON_LOW_MEMORY);
394             } else if (zygote != null) {
395                 updateExistingExitInfoRecordLocked(info, (Integer) zygote.second, null);
396             } else {
397                 scheduleLogToStatsdLocked(info, false);
398             }
399         }
400     }
401 
402     /**
403      * Make note when ActivityManagerService decides to kill an application process.
404      */
405     @VisibleForTesting
406     @GuardedBy("mLock")
handleNoteAppKillLocked(final ApplicationExitInfo raw)407     void handleNoteAppKillLocked(final ApplicationExitInfo raw) {
408         ApplicationExitInfo info = getExitInfoLocked(
409                 raw.getPackageName(), raw.getPackageUid(), raw.getPid());
410 
411         if (info == null) {
412             info = addExitInfoLocked(raw);
413         } else {
414             // always override the existing info since we are now more informational.
415             info.setReason(raw.getReason());
416             info.setSubReason(raw.getSubReason());
417             info.setStatus(0);
418             info.setTimestamp(System.currentTimeMillis());
419             info.setDescription(raw.getDescription());
420         }
421         scheduleLogToStatsdLocked(info, true);
422     }
423 
424     @GuardedBy("mLock")
addExitInfoLocked(ApplicationExitInfo raw)425     private ApplicationExitInfo addExitInfoLocked(ApplicationExitInfo raw) {
426         if (!mAppExitInfoLoaded.get()) {
427             Slog.w(TAG, "Skipping saving the exit info due to ongoing loading from storage");
428             return null;
429         }
430 
431         final ApplicationExitInfo info = new ApplicationExitInfo(raw);
432         final String[] packages = raw.getPackageList();
433         int uid = raw.getRealUid();
434         if (UserHandle.isIsolated(uid)) {
435             Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
436             if (k != null) {
437                 uid = k;
438             }
439         }
440         for (int i = 0; i < packages.length; i++) {
441             addExitInfoInnerLocked(packages[i], uid, info);
442         }
443 
444         schedulePersistProcessExitInfo(false);
445 
446         return info;
447     }
448 
449     /**
450      * Update an existing {@link android.app.ApplicationExitInfo} record with given information.
451      */
452     @GuardedBy("mLock")
updateExistingExitInfoRecordLocked(ApplicationExitInfo info, Integer status, Integer reason)453     private void updateExistingExitInfoRecordLocked(ApplicationExitInfo info,
454             Integer status, Integer reason) {
455         if (info == null || !isFresh(info.getTimestamp())) {
456             // if the record is way outdated, don't update it then (because of potential pid reuse)
457             return;
458         }
459         boolean immediateLog = false;
460         if (status != null) {
461             if (OsConstants.WIFEXITED(status)) {
462                 info.setReason(ApplicationExitInfo.REASON_EXIT_SELF);
463                 info.setStatus(OsConstants.WEXITSTATUS(status));
464                 immediateLog = true;
465             } else if (OsConstants.WIFSIGNALED(status)) {
466                 if (info.getReason() == ApplicationExitInfo.REASON_UNKNOWN) {
467                     info.setReason(ApplicationExitInfo.REASON_SIGNALED);
468                     info.setStatus(OsConstants.WTERMSIG(status));
469                 } else if (info.getReason() == ApplicationExitInfo.REASON_CRASH_NATIVE) {
470                     info.setStatus(OsConstants.WTERMSIG(status));
471                     immediateLog = true;
472                 }
473             }
474         }
475         if (reason != null) {
476             info.setReason(reason);
477             if (reason == ApplicationExitInfo.REASON_LOW_MEMORY) {
478                 immediateLog = true;
479             }
480         }
481         scheduleLogToStatsdLocked(info, immediateLog);
482     }
483 
484     /**
485      * Update an existing {@link android.app.ApplicationExitInfo} record with given information.
486      *
487      * @return true if a recond is updated
488      */
489     @GuardedBy("mLock")
updateExitInfoIfNecessaryLocked( int pid, int uid, Integer status, Integer reason)490     private boolean updateExitInfoIfNecessaryLocked(
491             int pid, int uid, Integer status, Integer reason) {
492         Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
493         if (k != null) {
494             uid = k;
495         }
496         ArrayList<ApplicationExitInfo> tlist = mTmpInfoList;
497         tlist.clear();
498         final int targetUid = uid;
499         forEachPackageLocked((packageName, records) -> {
500             AppExitInfoContainer container = records.get(targetUid);
501             if (container == null) {
502                 return FOREACH_ACTION_NONE;
503             }
504             tlist.clear();
505             container.getExitInfoLocked(pid, 1, tlist);
506             if (tlist.size() == 0) {
507                 return FOREACH_ACTION_NONE;
508             }
509             ApplicationExitInfo info = tlist.get(0);
510             if (info.getRealUid() != targetUid) {
511                 tlist.clear();
512                 return FOREACH_ACTION_NONE;
513             }
514             // Okay found it, update its reason.
515             updateExistingExitInfoRecordLocked(info, status, reason);
516 
517             return FOREACH_ACTION_STOP_ITERATION;
518         });
519         return tlist.size() > 0;
520     }
521 
522     /**
523      * Get the exit info with matching package name, filterUid and filterPid (if > 0)
524      */
525     @VisibleForTesting
getExitInfo(final String packageName, final int filterUid, final int filterPid, final int maxNum, final ArrayList<ApplicationExitInfo> results)526     void getExitInfo(final String packageName, final int filterUid,
527             final int filterPid, final int maxNum, final ArrayList<ApplicationExitInfo> results) {
528         final long identity = Binder.clearCallingIdentity();
529         try {
530             synchronized (mLock) {
531                 boolean emptyPackageName = TextUtils.isEmpty(packageName);
532                 if (!emptyPackageName) {
533                     // fast path
534                     AppExitInfoContainer container = mData.get(packageName, filterUid);
535                     if (container != null) {
536                         container.getExitInfoLocked(filterPid, maxNum, results);
537                     }
538                 } else {
539                     // slow path
540                     final ArrayList<ApplicationExitInfo> list = mTmpInfoList2;
541                     list.clear();
542                     // get all packages
543                     forEachPackageLocked((name, records) -> {
544                         AppExitInfoContainer container = records.get(filterUid);
545                         if (container != null) {
546                             mTmpInfoList.clear();
547                             list.addAll(container.toListLocked(mTmpInfoList, filterPid));
548                         }
549                         return AppExitInfoTracker.FOREACH_ACTION_NONE;
550                     });
551 
552                     Collections.sort(list,
553                             (a, b) -> Long.compare(b.getTimestamp(), a.getTimestamp()));
554                     int size = list.size();
555                     if (maxNum > 0) {
556                         size = Math.min(size, maxNum);
557                     }
558                     for (int i = 0; i < size; i++) {
559                         results.add(list.get(i));
560                     }
561                     list.clear();
562                 }
563             }
564         } finally {
565             Binder.restoreCallingIdentity(identity);
566         }
567     }
568 
569     /**
570      * Return the first matching exit info record, for internal use, the parameters are not supposed
571      * to be empty.
572      */
573     @GuardedBy("mLock")
getExitInfoLocked(final String packageName, final int filterUid, final int filterPid)574     private ApplicationExitInfo getExitInfoLocked(final String packageName,
575             final int filterUid, final int filterPid) {
576         ArrayList<ApplicationExitInfo> list = mTmpInfoList;
577         list.clear();
578         getExitInfo(packageName, filterUid, filterPid, 1, list);
579 
580         ApplicationExitInfo info = list.size() > 0 ? list.get(0) : null;
581         list.clear();
582         return info;
583     }
584 
585     @VisibleForTesting
onUserRemoved(int userId)586     void onUserRemoved(int userId) {
587         mAppExitInfoSourceZygote.removeByUserId(userId);
588         mAppExitInfoSourceLmkd.removeByUserId(userId);
589         mIsolatedUidRecords.removeByUserId(userId);
590         synchronized (mLock) {
591             removeByUserIdLocked(userId);
592             schedulePersistProcessExitInfo(true);
593         }
594     }
595 
596     @VisibleForTesting
onPackageRemoved(String packageName, int uid, boolean allUsers)597     void onPackageRemoved(String packageName, int uid, boolean allUsers) {
598         if (packageName != null) {
599             final boolean removeUid = TextUtils.isEmpty(
600                     mService.mPackageManagerInt.getNameForUid(uid));
601             synchronized (mLock) {
602                 if (removeUid) {
603                     mAppExitInfoSourceZygote.removeByUidLocked(uid, allUsers);
604                     mAppExitInfoSourceLmkd.removeByUidLocked(uid, allUsers);
605                     mIsolatedUidRecords.removeAppUid(uid, allUsers);
606                 }
607                 removePackageLocked(packageName, uid, removeUid,
608                         allUsers ? UserHandle.USER_ALL : UserHandle.getUserId(uid));
609                 schedulePersistProcessExitInfo(true);
610             }
611         }
612     }
613 
registerForUserRemoval()614     private void registerForUserRemoval() {
615         IntentFilter filter = new IntentFilter();
616         filter.addAction(Intent.ACTION_USER_REMOVED);
617         mService.mContext.registerReceiverForAllUsers(new BroadcastReceiver() {
618             @Override
619             public void onReceive(Context context, Intent intent) {
620                 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
621                 if (userId < 1) return;
622                 onUserRemoved(userId);
623             }
624         }, filter, null, mKillHandler);
625     }
626 
registerForPackageRemoval()627     private void registerForPackageRemoval() {
628         IntentFilter filter = new IntentFilter();
629         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
630         filter.addDataScheme("package");
631         mService.mContext.registerReceiverForAllUsers(new BroadcastReceiver() {
632             @Override
633             public void onReceive(Context context, Intent intent) {
634                 boolean replacing = intent.getBooleanExtra(
635                         Intent.EXTRA_REPLACING, false);
636                 if (replacing) {
637                     return;
638                 }
639                 int uid = intent.getIntExtra(Intent.EXTRA_UID, UserHandle.USER_NULL);
640                 boolean allUsers = intent.getBooleanExtra(
641                         Intent.EXTRA_REMOVED_FOR_ALL_USERS, false);
642                 onPackageRemoved(intent.getData().getSchemeSpecificPart(), uid, allUsers);
643             }
644         }, filter, null, mKillHandler);
645     }
646 
647     /**
648      * Load the existing {@link android.app.ApplicationExitInfo} records from persistent storage.
649      */
650     @VisibleForTesting
loadExistingProcessExitInfo()651     void loadExistingProcessExitInfo() {
652         if (!mProcExitInfoFile.canRead()) {
653             mAppExitInfoLoaded.set(true);
654             return;
655         }
656 
657         FileInputStream fin = null;
658         try {
659             AtomicFile af = new AtomicFile(mProcExitInfoFile);
660             fin = af.openRead();
661             ProtoInputStream proto = new ProtoInputStream(fin);
662             for (int next = proto.nextField();
663                     next != ProtoInputStream.NO_MORE_FIELDS;
664                     next = proto.nextField()) {
665                 switch (next) {
666                     case (int) AppsExitInfoProto.LAST_UPDATE_TIMESTAMP:
667                         synchronized (mLock) {
668                             mLastAppExitInfoPersistTimestamp =
669                                     proto.readLong(AppsExitInfoProto.LAST_UPDATE_TIMESTAMP);
670                         }
671                         break;
672                     case (int) AppsExitInfoProto.PACKAGES:
673                         loadPackagesFromProto(proto, next);
674                         break;
675                 }
676             }
677         } catch (IOException | IllegalArgumentException | WireTypeMismatchException e) {
678             Slog.w(TAG, "Error in loading historical app exit info from persistent storage: " + e);
679         } finally {
680             if (fin != null) {
681                 try {
682                     fin.close();
683                 } catch (IOException e) {
684                 }
685             }
686         }
687         synchronized (mLock) {
688             pruneAnrTracesIfNecessaryLocked();
689             mAppExitInfoLoaded.set(true);
690         }
691     }
692 
loadPackagesFromProto(ProtoInputStream proto, long fieldId)693     private void loadPackagesFromProto(ProtoInputStream proto, long fieldId)
694             throws IOException, WireTypeMismatchException {
695         long token = proto.start(fieldId);
696         String pkgName = "";
697         for (int next = proto.nextField();
698                 next != ProtoInputStream.NO_MORE_FIELDS;
699                 next = proto.nextField()) {
700             switch (next) {
701                 case (int) AppsExitInfoProto.Package.PACKAGE_NAME:
702                     pkgName = proto.readString(AppsExitInfoProto.Package.PACKAGE_NAME);
703                     break;
704                 case (int) AppsExitInfoProto.Package.USERS:
705                     AppExitInfoContainer container = new AppExitInfoContainer(
706                             mAppExitInfoHistoryListSize);
707                     int uid = container.readFromProto(proto, AppsExitInfoProto.Package.USERS);
708                     synchronized (mLock) {
709                         mData.put(pkgName, uid, container);
710                     }
711                     break;
712             }
713         }
714         proto.end(token);
715     }
716 
717     /**
718      * Persist the existing {@link android.app.ApplicationExitInfo} records to storage.
719      */
720     @VisibleForTesting
persistProcessExitInfo()721     void persistProcessExitInfo() {
722         AtomicFile af = new AtomicFile(mProcExitInfoFile);
723         FileOutputStream out = null;
724         long now = System.currentTimeMillis();
725         try {
726             out = af.startWrite();
727             ProtoOutputStream proto = new ProtoOutputStream(out);
728             proto.write(AppsExitInfoProto.LAST_UPDATE_TIMESTAMP, now);
729             synchronized (mLock) {
730                 forEachPackageLocked((packageName, records) -> {
731                     long token = proto.start(AppsExitInfoProto.PACKAGES);
732                     proto.write(AppsExitInfoProto.Package.PACKAGE_NAME, packageName);
733                     int uidArraySize = records.size();
734                     for (int j = 0; j < uidArraySize; j++) {
735                         records.valueAt(j).writeToProto(proto, AppsExitInfoProto.Package.USERS);
736                     }
737                     proto.end(token);
738                     return AppExitInfoTracker.FOREACH_ACTION_NONE;
739                 });
740                 mLastAppExitInfoPersistTimestamp = now;
741             }
742             proto.flush();
743             af.finishWrite(out);
744         } catch (IOException e) {
745             Slog.w(TAG, "Unable to write historical app exit info into persistent storage: " + e);
746             af.failWrite(out);
747         }
748         synchronized (mLock) {
749             mAppExitInfoPersistTask = null;
750         }
751     }
752 
753     /**
754      * Schedule a task to persist the {@link android.app.ApplicationExitInfo} records to storage.
755      */
756     @VisibleForTesting
schedulePersistProcessExitInfo(boolean immediately)757     void schedulePersistProcessExitInfo(boolean immediately) {
758         synchronized (mLock) {
759             if (mAppExitInfoPersistTask == null || immediately) {
760                 if (mAppExitInfoPersistTask != null) {
761                     IoThread.getHandler().removeCallbacks(mAppExitInfoPersistTask);
762                 }
763                 mAppExitInfoPersistTask = this::persistProcessExitInfo;
764                 IoThread.getHandler().postDelayed(mAppExitInfoPersistTask,
765                         immediately ? 0 : APP_EXIT_INFO_PERSIST_INTERVAL);
766             }
767         }
768     }
769 
770     /**
771      * Helper function for testing only.
772      */
773     @VisibleForTesting
clearProcessExitInfo(boolean removeFile)774     void clearProcessExitInfo(boolean removeFile) {
775         synchronized (mLock) {
776             if (mAppExitInfoPersistTask != null) {
777                 IoThread.getHandler().removeCallbacks(mAppExitInfoPersistTask);
778                 mAppExitInfoPersistTask = null;
779             }
780             if (removeFile && mProcExitInfoFile != null) {
781                 mProcExitInfoFile.delete();
782             }
783             mData.getMap().clear();
784             mActiveAppStateSummary.clear();
785             mActiveAppTraces.clear();
786             pruneAnrTracesIfNecessaryLocked();
787         }
788     }
789 
790     /**
791      * Helper function for shell command
792      */
clearHistoryProcessExitInfo(String packageName, int userId)793     void clearHistoryProcessExitInfo(String packageName, int userId) {
794         NativeTombstoneManager tombstoneService = LocalServices.getService(
795                 NativeTombstoneManager.class);
796         Optional<Integer> appId = Optional.empty();
797 
798         if (TextUtils.isEmpty(packageName)) {
799             synchronized (mLock) {
800                 removeByUserIdLocked(userId);
801             }
802         } else {
803             final int uid = mService.mPackageManagerInt.getPackageUid(packageName,
804                     PackageManager.MATCH_ALL, userId);
805             appId = Optional.of(UserHandle.getAppId(uid));
806             synchronized (mLock) {
807                 removePackageLocked(packageName, uid, true, userId);
808             }
809         }
810 
811         tombstoneService.purge(Optional.of(userId), appId);
812         schedulePersistProcessExitInfo(true);
813     }
814 
dumpHistoryProcessExitInfo(PrintWriter pw, String packageName)815     void dumpHistoryProcessExitInfo(PrintWriter pw, String packageName) {
816         pw.println("ACTIVITY MANAGER PROCESS EXIT INFO (dumpsys activity exit-info)");
817         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
818         synchronized (mLock) {
819             pw.println("Last Timestamp of Persistence Into Persistent Storage: "
820                     + sdf.format(new Date(mLastAppExitInfoPersistTimestamp)));
821             if (TextUtils.isEmpty(packageName)) {
822                 forEachPackageLocked((name, records) -> {
823                     dumpHistoryProcessExitInfoLocked(pw, "  ", name, records, sdf);
824                     return AppExitInfoTracker.FOREACH_ACTION_NONE;
825                 });
826             } else {
827                 SparseArray<AppExitInfoContainer> array = mData.getMap().get(packageName);
828                 if (array != null) {
829                     dumpHistoryProcessExitInfoLocked(pw, "  ", packageName, array, sdf);
830                 }
831             }
832         }
833     }
834 
835     @GuardedBy("mLock")
dumpHistoryProcessExitInfoLocked(PrintWriter pw, String prefix, String packageName, SparseArray<AppExitInfoContainer> array, SimpleDateFormat sdf)836     private void dumpHistoryProcessExitInfoLocked(PrintWriter pw, String prefix,
837             String packageName, SparseArray<AppExitInfoContainer> array,
838             SimpleDateFormat sdf) {
839         pw.println(prefix + "package: " + packageName);
840         int size = array.size();
841         for (int i = 0; i < size; i++) {
842             pw.println(prefix + "  Historical Process Exit for uid=" + array.keyAt(i));
843             array.valueAt(i).dumpLocked(pw, prefix + "    ", sdf);
844         }
845     }
846 
847     @GuardedBy("mLock")
addExitInfoInnerLocked(String packageName, int uid, ApplicationExitInfo info)848     private void addExitInfoInnerLocked(String packageName, int uid, ApplicationExitInfo info) {
849         AppExitInfoContainer container = mData.get(packageName, uid);
850         if (container == null) {
851             container = new AppExitInfoContainer(mAppExitInfoHistoryListSize);
852             if (UserHandle.isIsolated(info.getRealUid())) {
853                 Integer k = mIsolatedUidRecords.getUidByIsolatedUid(info.getRealUid());
854                 if (k != null) {
855                     container.mUid = k;
856                 }
857             } else {
858                 container.mUid = info.getRealUid();
859             }
860             mData.put(packageName, uid, container);
861         }
862         container.addExitInfoLocked(info);
863     }
864 
865     @GuardedBy("mLock")
scheduleLogToStatsdLocked(ApplicationExitInfo info, boolean immediate)866     private void scheduleLogToStatsdLocked(ApplicationExitInfo info, boolean immediate) {
867         if (info.isLoggedInStatsd()) {
868             return;
869         }
870         if (immediate) {
871             mKillHandler.removeMessages(KillHandler.MSG_STATSD_LOG, info);
872             performLogToStatsdLocked(info);
873         } else if (!mKillHandler.hasMessages(KillHandler.MSG_STATSD_LOG, info)) {
874             mKillHandler.sendMessageDelayed(mKillHandler.obtainMessage(
875                     KillHandler.MSG_STATSD_LOG, info), APP_EXIT_INFO_STATSD_LOG_DEBOUNCE);
876         }
877     }
878 
879     @GuardedBy("mLock")
performLogToStatsdLocked(ApplicationExitInfo info)880     private void performLogToStatsdLocked(ApplicationExitInfo info) {
881         if (info.isLoggedInStatsd()) {
882             return;
883         }
884         info.setLoggedInStatsd(true);
885         final String pkgName = info.getPackageName();
886         String processName = info.getProcessName();
887         if (TextUtils.equals(pkgName, processName)) {
888             // Omit the process name here to save space
889             processName = null;
890         } else if (processName != null && pkgName != null && processName.startsWith(pkgName)) {
891             // Strip the prefix to save space
892             processName = processName.substring(pkgName.length());
893         }
894         FrameworkStatsLog.write(FrameworkStatsLog.APP_PROCESS_DIED,
895                 info.getPackageUid(), processName, info.getReason(), info.getSubReason(),
896                 info.getImportance(), (int) info.getPss(), (int) info.getRss());
897     }
898 
899     @GuardedBy("mLock")
forEachPackageLocked( BiFunction<String, SparseArray<AppExitInfoContainer>, Integer> callback)900     private void forEachPackageLocked(
901             BiFunction<String, SparseArray<AppExitInfoContainer>, Integer> callback) {
902         if (callback != null) {
903             ArrayMap<String, SparseArray<AppExitInfoContainer>> map = mData.getMap();
904             for (int i = map.size() - 1; i >= 0; i--) {
905                 switch (callback.apply(map.keyAt(i), map.valueAt(i))) {
906                     case FOREACH_ACTION_REMOVE_ITEM:
907                         final SparseArray<AppExitInfoContainer> records = map.valueAt(i);
908                         for (int j = records.size() - 1; j >= 0; j--) {
909                             records.valueAt(j).destroyLocked();
910                         }
911                         map.removeAt(i);
912                         break;
913                     case FOREACH_ACTION_STOP_ITERATION:
914                         i = 0;
915                         break;
916                     case FOREACH_ACTION_NONE:
917                     default:
918                         break;
919                 }
920             }
921         }
922     }
923 
924     @GuardedBy("mLock")
removePackageLocked(String packageName, int uid, boolean removeUid, int userId)925     private void removePackageLocked(String packageName, int uid, boolean removeUid, int userId) {
926         if (removeUid) {
927             mActiveAppStateSummary.remove(uid);
928             final int idx = mActiveAppTraces.indexOfKey(uid);
929             if (idx >= 0) {
930                 final SparseArray<File> array = mActiveAppTraces.valueAt(idx);
931                 for (int i = array.size() - 1; i >= 0; i--) {
932                     array.valueAt(i).delete();
933                 }
934                 mActiveAppTraces.removeAt(idx);
935             }
936         }
937         ArrayMap<String, SparseArray<AppExitInfoContainer>> map = mData.getMap();
938         SparseArray<AppExitInfoContainer> array = map.get(packageName);
939         if (array == null) {
940             return;
941         }
942         if (userId == UserHandle.USER_ALL) {
943             for (int i = array.size() - 1; i >= 0; i--) {
944                 array.valueAt(i).destroyLocked();
945             }
946             mData.getMap().remove(packageName);
947         } else {
948             for (int i = array.size() - 1; i >= 0; i--) {
949                 if (UserHandle.getUserId(array.keyAt(i)) == userId) {
950                     array.valueAt(i).destroyLocked();
951                     array.removeAt(i);
952                     break;
953                 }
954             }
955             if (array.size() == 0) {
956                 map.remove(packageName);
957             }
958         }
959     }
960 
961     @GuardedBy("mLock")
removeByUserIdLocked(final int userId)962     private void removeByUserIdLocked(final int userId) {
963         if (userId == UserHandle.USER_ALL) {
964             mData.getMap().clear();
965             mActiveAppStateSummary.clear();
966             mActiveAppTraces.clear();
967             pruneAnrTracesIfNecessaryLocked();
968             return;
969         }
970         removeFromSparse2dArray(mActiveAppStateSummary,
971                 (v) -> UserHandle.getUserId(v) == userId, null, null);
972         removeFromSparse2dArray(mActiveAppTraces,
973                 (v) -> UserHandle.getUserId(v) == userId, null, (v) -> v.delete());
974         forEachPackageLocked((packageName, records) -> {
975             for (int i = records.size() - 1; i >= 0; i--) {
976                 if (UserHandle.getUserId(records.keyAt(i)) == userId) {
977                     records.valueAt(i).destroyLocked();
978                     records.removeAt(i);
979                     break;
980                 }
981             }
982             return records.size() == 0 ? FOREACH_ACTION_REMOVE_ITEM : FOREACH_ACTION_NONE;
983         });
984     }
985 
986     @VisibleForTesting
obtainRawRecord(ProcessRecord app, @CurrentTimeMillisLong long timestamp)987     ApplicationExitInfo obtainRawRecord(ProcessRecord app, @CurrentTimeMillisLong long timestamp) {
988         ApplicationExitInfo info = mRawRecordsPool.acquire();
989         if (info == null) {
990             info = new ApplicationExitInfo();
991         }
992 
993         synchronized (mService.mProcLock) {
994             final int definingUid = app.getHostingRecord() != null
995                     ? app.getHostingRecord().getDefiningUid() : 0;
996             info.setPid(app.getPid());
997             info.setRealUid(app.uid);
998             info.setPackageUid(app.info.uid);
999             info.setDefiningUid(definingUid > 0 ? definingUid : app.info.uid);
1000             info.setProcessName(app.processName);
1001             info.setConnectionGroup(app.mServices.getConnectionGroup());
1002             info.setPackageName(app.info.packageName);
1003             info.setPackageList(app.getPackageList());
1004             info.setReason(ApplicationExitInfo.REASON_UNKNOWN);
1005             info.setStatus(0);
1006             info.setImportance(procStateToImportance(app.mState.getReportedProcState()));
1007             info.setPss(app.mProfile.getLastPss());
1008             info.setRss(app.mProfile.getLastRss());
1009             info.setTimestamp(timestamp);
1010         }
1011 
1012         return info;
1013     }
1014 
1015     @VisibleForTesting
recycleRawRecord(ApplicationExitInfo info)1016     void recycleRawRecord(ApplicationExitInfo info) {
1017         info.setProcessName(null);
1018         info.setDescription(null);
1019         info.setPackageList(null);
1020 
1021         mRawRecordsPool.release(info);
1022     }
1023 
1024     /**
1025      * Called from {@link ActivityManagerService#setProcessStateSummary}.
1026      */
1027     @VisibleForTesting
setProcessStateSummary(int uid, final int pid, final byte[] data)1028     void setProcessStateSummary(int uid, final int pid, final byte[] data) {
1029         synchronized (mLock) {
1030             Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1031             if (k != null) {
1032                 uid = k;
1033             }
1034             putToSparse2dArray(mActiveAppStateSummary, uid, pid, data, SparseArray::new, null);
1035         }
1036     }
1037 
1038     @VisibleForTesting
getProcessStateSummary(int uid, final int pid)1039     @Nullable byte[] getProcessStateSummary(int uid, final int pid) {
1040         synchronized (mLock) {
1041             Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1042             if (k != null) {
1043                 uid = k;
1044             }
1045             int index = mActiveAppStateSummary.indexOfKey(uid);
1046             if (index < 0) {
1047                 return null;
1048             }
1049             return mActiveAppStateSummary.valueAt(index).get(pid);
1050         }
1051     }
1052 
1053     /**
1054      * Called from ProcessRecord when an ANR occurred and the ANR trace is taken.
1055      */
scheduleLogAnrTrace(final int pid, final int uid, final String[] packageList, final File traceFile, final long startOff, final long endOff)1056     void scheduleLogAnrTrace(final int pid, final int uid, final String[] packageList,
1057             final File traceFile, final long startOff, final long endOff) {
1058         mKillHandler.sendMessage(PooledLambda.obtainMessage(
1059                 this::handleLogAnrTrace, pid, uid, packageList,
1060                 traceFile, startOff, endOff));
1061     }
1062 
1063     /**
1064      * Copy and compress the given ANR trace file
1065      */
1066     @VisibleForTesting
handleLogAnrTrace(final int pid, int uid, final String[] packageList, final File traceFile, final long startOff, final long endOff)1067     void handleLogAnrTrace(final int pid, int uid, final String[] packageList,
1068             final File traceFile, final long startOff, final long endOff) {
1069         if (!traceFile.exists() || ArrayUtils.isEmpty(packageList)) {
1070             return;
1071         }
1072         final long size = traceFile.length();
1073         final long length = endOff - startOff;
1074         if (startOff >= size || endOff > size || length <= 0) {
1075             return;
1076         }
1077 
1078         final File outFile = new File(mProcExitStoreDir, traceFile.getName()
1079                 + APP_TRACE_FILE_SUFFIX);
1080         // Copy & compress
1081         if (copyToGzFile(traceFile, outFile, startOff, length)) {
1082             // Wrote successfully.
1083             synchronized (mLock) {
1084                 Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1085                 if (k != null) {
1086                     uid = k;
1087                 }
1088                 if (DEBUG_PROCESSES) {
1089                     Slog.i(TAG, "Stored ANR traces of " + pid + "/u" + uid + " in " + outFile);
1090                 }
1091                 boolean pending = true;
1092                 // Unlikely but possible: the app has died
1093                 for (int i = 0; i < packageList.length; i++) {
1094                     final AppExitInfoContainer container = mData.get(packageList[i], uid);
1095                     // Try to see if we could append this trace to an existing record
1096                     if (container != null && container.appendTraceIfNecessaryLocked(pid, outFile)) {
1097                         // Okay someone took it
1098                         pending = false;
1099                     }
1100                 }
1101                 if (pending) {
1102                     // Save it into a temporary list for later use (when the app dies).
1103                     putToSparse2dArray(mActiveAppTraces, uid, pid, outFile,
1104                             SparseArray::new, (v) -> v.delete());
1105                 }
1106             }
1107         }
1108     }
1109 
1110     /**
1111      * Copy the given portion of the file into a gz file.
1112      *
1113      * @param inFile The source file.
1114      * @param outFile The destination file, which will be compressed in gzip format.
1115      * @param start The start offset where the copy should start from.
1116      * @param length The number of bytes that should be copied.
1117      * @return If the copy was successful or not.
1118      */
copyToGzFile(final File inFile, final File outFile, final long start, final long length)1119     private static boolean copyToGzFile(final File inFile, final File outFile,
1120             final long start, final long length) {
1121         long remaining = length;
1122         try (
1123             BufferedInputStream in = new BufferedInputStream(new FileInputStream(inFile));
1124             GZIPOutputStream out = new GZIPOutputStream(new BufferedOutputStream(
1125                     new FileOutputStream(outFile)))) {
1126             final byte[] buffer = new byte[8192];
1127             in.skip(start);
1128             while (remaining > 0) {
1129                 int t = in.read(buffer, 0, (int) Math.min(buffer.length, remaining));
1130                 if (t < 0) {
1131                     break;
1132                 }
1133                 out.write(buffer, 0, t);
1134                 remaining -= t;
1135             }
1136         } catch (IOException e) {
1137             if (DEBUG_PROCESSES) {
1138                 Slog.e(TAG, "Error in copying ANR trace from " + inFile + " to " + outFile, e);
1139             }
1140             return false;
1141         }
1142         return remaining == 0 && outFile.exists();
1143     }
1144 
1145     /**
1146      * In case there is any orphan ANR trace file, remove it.
1147      */
1148     @GuardedBy("mLock")
pruneAnrTracesIfNecessaryLocked()1149     private void pruneAnrTracesIfNecessaryLocked() {
1150         final ArraySet<String> allFiles = new ArraySet();
1151         final File[] files = mProcExitStoreDir.listFiles((f) -> {
1152             final String name = f.getName();
1153             boolean trace = name.startsWith(ActivityManagerService.ANR_FILE_PREFIX)
1154                     && name.endsWith(APP_TRACE_FILE_SUFFIX);
1155             if (trace) {
1156                 allFiles.add(name);
1157             }
1158             return trace;
1159         });
1160         if (ArrayUtils.isEmpty(files)) {
1161             return;
1162         }
1163         // Find out the owners from the existing records
1164         forEachPackageLocked((name, records) -> {
1165             for (int i = records.size() - 1; i >= 0; i--) {
1166                 final AppExitInfoContainer container = records.valueAt(i);
1167                 container.forEachRecordLocked((pid, info) -> {
1168                     final File traceFile = info.getTraceFile();
1169                     if (traceFile != null) {
1170                         allFiles.remove(traceFile.getName());
1171                     }
1172                     return FOREACH_ACTION_NONE;
1173                 });
1174             }
1175             return AppExitInfoTracker.FOREACH_ACTION_NONE;
1176         });
1177         // See if there is any active process owns it.
1178         forEachSparse2dArray(mActiveAppTraces, (v) -> allFiles.remove(v.getName()));
1179 
1180         // Remove orphan traces if nobody claims it.
1181         for (int i = allFiles.size() - 1; i >= 0; i--) {
1182             (new File(mProcExitStoreDir, allFiles.valueAt(i))).delete();
1183         }
1184     }
1185 
1186     /**
1187      * A utility function to add the given value to the given 2d SparseArray
1188      */
putToSparse2dArray(final SparseArray<T> array, final int outerKey, final int innerKey, final U value, final Supplier<T> newInstance, final Consumer<U> actionToOldValue)1189     private static <T extends SparseArray<U>, U> void putToSparse2dArray(final SparseArray<T> array,
1190             final int outerKey, final int innerKey, final U value, final Supplier<T> newInstance,
1191             final Consumer<U> actionToOldValue) {
1192         int idx = array.indexOfKey(outerKey);
1193         T innerArray = null;
1194         if (idx < 0) {
1195             innerArray = newInstance.get();
1196             array.put(outerKey, innerArray);
1197         } else {
1198             innerArray = array.valueAt(idx);
1199         }
1200         idx = innerArray.indexOfKey(innerKey);
1201         if (idx >= 0) {
1202             if (actionToOldValue != null) {
1203                 actionToOldValue.accept(innerArray.valueAt(idx));
1204             }
1205             innerArray.setValueAt(idx, value);
1206         } else {
1207             innerArray.put(innerKey, value);
1208         }
1209     }
1210 
1211     /**
1212      * A utility function to iterate through the given 2d SparseArray
1213      */
forEachSparse2dArray( final SparseArray<T> array, final Consumer<U> action)1214     private static <T extends SparseArray<U>, U> void forEachSparse2dArray(
1215             final SparseArray<T> array, final Consumer<U> action) {
1216         if (action != null) {
1217             for (int i = array.size() - 1; i >= 0; i--) {
1218                 T innerArray = array.valueAt(i);
1219                 if (innerArray == null) {
1220                     continue;
1221                 }
1222                 for (int j = innerArray.size() - 1; j >= 0; j--) {
1223                     action.accept(innerArray.valueAt(j));
1224                 }
1225             }
1226         }
1227     }
1228 
1229     /**
1230      * A utility function to remove elements from the given 2d SparseArray
1231      */
removeFromSparse2dArray( final SparseArray<T> array, final Predicate<Integer> outerPredicate, final Predicate<Integer> innerPredicate, final Consumer<U> action)1232     private static <T extends SparseArray<U>, U> void removeFromSparse2dArray(
1233             final SparseArray<T> array, final Predicate<Integer> outerPredicate,
1234             final Predicate<Integer> innerPredicate, final Consumer<U> action) {
1235         for (int i = array.size() - 1; i >= 0; i--) {
1236             if (outerPredicate == null || outerPredicate.test(array.keyAt(i))) {
1237                 final T innerArray = array.valueAt(i);
1238                 if (innerArray == null) {
1239                     continue;
1240                 }
1241                 for (int j = innerArray.size() - 1; j >= 0; j--) {
1242                     if (innerPredicate == null || innerPredicate.test(innerArray.keyAt(j))) {
1243                         if (action != null) {
1244                             action.accept(innerArray.valueAt(j));
1245                         }
1246                         innerArray.removeAt(j);
1247                     }
1248                 }
1249                 if (innerArray.size() == 0) {
1250                     array.removeAt(i);
1251                 }
1252             }
1253         }
1254     }
1255 
1256     /**
1257      * A utility function to find and remove elements from the given 2d SparseArray.
1258      */
findAndRemoveFromSparse2dArray( final SparseArray<T> array, final int outerKey, final int innerKey)1259     private static <T extends SparseArray<U>, U> U findAndRemoveFromSparse2dArray(
1260             final SparseArray<T> array, final int outerKey, final int innerKey) {
1261         final int idx = array.indexOfKey(outerKey);
1262         if (idx >= 0) {
1263             T p = array.valueAt(idx);
1264             if (p == null) {
1265                 return null;
1266             }
1267             final int innerIdx = p.indexOfKey(innerKey);
1268             if (innerIdx >= 0) {
1269                 final U ret = p.valueAt(innerIdx);
1270                 p.removeAt(innerIdx);
1271                 if (p.size() == 0) {
1272                     array.removeAt(idx);
1273                 }
1274                 return ret;
1275             }
1276         }
1277         return null;
1278     }
1279 
1280     /**
1281      * A container class of {@link android.app.ApplicationExitInfo}
1282      */
1283     final class AppExitInfoContainer {
1284         private SparseArray<ApplicationExitInfo> mInfos; // index is pid
1285         private int mMaxCapacity;
1286         private int mUid; // Application uid, not isolated uid.
1287 
AppExitInfoContainer(final int maxCapacity)1288         AppExitInfoContainer(final int maxCapacity) {
1289             mInfos = new SparseArray<ApplicationExitInfo>();
1290             mMaxCapacity = maxCapacity;
1291         }
1292 
1293         @GuardedBy("mLock")
getExitInfoLocked(final int filterPid, final int maxNum, ArrayList<ApplicationExitInfo> results)1294         void getExitInfoLocked(final int filterPid, final int maxNum,
1295                 ArrayList<ApplicationExitInfo> results) {
1296             if (filterPid > 0) {
1297                 ApplicationExitInfo r = mInfos.get(filterPid);
1298                 if (r != null) {
1299                     results.add(r);
1300                 }
1301             } else {
1302                 final int numRep = mInfos.size();
1303                 if (maxNum <= 0 || numRep <= maxNum) {
1304                     // Return all records.
1305                     for (int i = 0; i < numRep; i++) {
1306                         results.add(mInfos.valueAt(i));
1307                     }
1308                     Collections.sort(results,
1309                             (a, b) -> Long.compare(b.getTimestamp(), a.getTimestamp()));
1310                 } else {
1311                     if (maxNum == 1) {
1312                         // Most of the caller might be only interested with the most recent one
1313                         ApplicationExitInfo r = mInfos.valueAt(0);
1314                         for (int i = 1; i < numRep; i++) {
1315                             ApplicationExitInfo t = mInfos.valueAt(i);
1316                             if (r.getTimestamp() < t.getTimestamp()) {
1317                                 r = t;
1318                             }
1319                         }
1320                         results.add(r);
1321                     } else {
1322                         // Huh, need to sort it out then.
1323                         ArrayList<ApplicationExitInfo> list = mTmpInfoList2;
1324                         list.clear();
1325                         for (int i = 0; i < numRep; i++) {
1326                             list.add(mInfos.valueAt(i));
1327                         }
1328                         Collections.sort(list,
1329                                 (a, b) -> Long.compare(b.getTimestamp(), a.getTimestamp()));
1330                         for (int i = 0; i < maxNum; i++) {
1331                             results.add(list.get(i));
1332                         }
1333                         list.clear();
1334                     }
1335                 }
1336             }
1337         }
1338 
1339         @GuardedBy("mLock")
addExitInfoLocked(ApplicationExitInfo info)1340         void addExitInfoLocked(ApplicationExitInfo info) {
1341             int size;
1342             if ((size = mInfos.size()) >= mMaxCapacity) {
1343                 int oldestIndex = -1;
1344                 long oldestTimeStamp = Long.MAX_VALUE;
1345                 for (int i = 0; i < size; i++) {
1346                     ApplicationExitInfo r = mInfos.valueAt(i);
1347                     if (r.getTimestamp() < oldestTimeStamp) {
1348                         oldestTimeStamp = r.getTimestamp();
1349                         oldestIndex = i;
1350                     }
1351                 }
1352                 if (oldestIndex >= 0) {
1353                     final File traceFile = mInfos.valueAt(oldestIndex).getTraceFile();
1354                     if (traceFile != null) {
1355                         traceFile.delete();
1356                     }
1357                     mInfos.removeAt(oldestIndex);
1358                 }
1359             }
1360             // Claim the state information if there is any
1361             final int uid = info.getPackageUid();
1362             final int pid = info.getPid();
1363             info.setProcessStateSummary(findAndRemoveFromSparse2dArray(
1364                     mActiveAppStateSummary, uid, pid));
1365             info.setTraceFile(findAndRemoveFromSparse2dArray(mActiveAppTraces, uid, pid));
1366             info.setAppTraceRetriever(mAppTraceRetriever);
1367             mInfos.append(pid, info);
1368         }
1369 
1370         @GuardedBy("mLock")
appendTraceIfNecessaryLocked(final int pid, final File traceFile)1371         boolean appendTraceIfNecessaryLocked(final int pid, final File traceFile) {
1372             final ApplicationExitInfo r = mInfos.get(pid);
1373             if (r != null) {
1374                 r.setTraceFile(traceFile);
1375                 r.setAppTraceRetriever(mAppTraceRetriever);
1376                 return true;
1377             }
1378             return false;
1379         }
1380 
1381         @GuardedBy("mLock")
destroyLocked()1382         void destroyLocked() {
1383             for (int i = mInfos.size() - 1; i >= 0; i--) {
1384                 ApplicationExitInfo ai = mInfos.valueAt(i);
1385                 final File traceFile = ai.getTraceFile();
1386                 if (traceFile != null) {
1387                     traceFile.delete();
1388                 }
1389                 ai.setTraceFile(null);
1390                 ai.setAppTraceRetriever(null);
1391             }
1392         }
1393 
1394         @GuardedBy("mLock")
forEachRecordLocked(final BiFunction<Integer, ApplicationExitInfo, Integer> callback)1395         void forEachRecordLocked(final BiFunction<Integer, ApplicationExitInfo, Integer> callback) {
1396             if (callback != null) {
1397                 for (int i = mInfos.size() - 1; i >= 0; i--) {
1398                     switch (callback.apply(mInfos.keyAt(i), mInfos.valueAt(i))) {
1399                         case FOREACH_ACTION_REMOVE_ITEM:
1400                             final File traceFile = mInfos.valueAt(i).getTraceFile();
1401                             if (traceFile != null) {
1402                                 traceFile.delete();
1403                             }
1404                             mInfos.removeAt(i);
1405                             break;
1406                         case FOREACH_ACTION_STOP_ITERATION:
1407                             i = 0;
1408                             break;
1409                         case FOREACH_ACTION_NONE:
1410                         default:
1411                             break;
1412                     }
1413                 }
1414             }
1415         }
1416 
1417         @GuardedBy("mLock")
dumpLocked(PrintWriter pw, String prefix, SimpleDateFormat sdf)1418         void dumpLocked(PrintWriter pw, String prefix, SimpleDateFormat sdf) {
1419             ArrayList<ApplicationExitInfo> list = new ArrayList<ApplicationExitInfo>();
1420             for (int i = mInfos.size() - 1; i >= 0; i--) {
1421                 list.add(mInfos.valueAt(i));
1422             }
1423             Collections.sort(list, (a, b) -> Long.compare(b.getTimestamp(), a.getTimestamp()));
1424             int size = list.size();
1425             for (int i = 0; i < size; i++) {
1426                 list.get(i).dump(pw, prefix + "  ", "#" + i, sdf);
1427             }
1428         }
1429 
1430         @GuardedBy("mLock")
writeToProto(ProtoOutputStream proto, long fieldId)1431         void writeToProto(ProtoOutputStream proto, long fieldId) {
1432             long token = proto.start(fieldId);
1433             proto.write(AppsExitInfoProto.Package.User.UID, mUid);
1434             int size = mInfos.size();
1435             for (int i = 0; i < size; i++) {
1436                 mInfos.valueAt(i).writeToProto(proto, AppsExitInfoProto.Package.User.APP_EXIT_INFO);
1437             }
1438             proto.end(token);
1439         }
1440 
readFromProto(ProtoInputStream proto, long fieldId)1441         int readFromProto(ProtoInputStream proto, long fieldId)
1442                 throws IOException, WireTypeMismatchException {
1443             long token = proto.start(fieldId);
1444             for (int next = proto.nextField();
1445                     next != ProtoInputStream.NO_MORE_FIELDS;
1446                     next = proto.nextField()) {
1447                 switch (next) {
1448                     case (int) AppsExitInfoProto.Package.User.UID:
1449                         mUid = proto.readInt(AppsExitInfoProto.Package.User.UID);
1450                         break;
1451                     case (int) AppsExitInfoProto.Package.User.APP_EXIT_INFO:
1452                         ApplicationExitInfo info = new ApplicationExitInfo();
1453                         info.readFromProto(proto, AppsExitInfoProto.Package.User.APP_EXIT_INFO);
1454                         mInfos.put(info.getPid(), info);
1455                         break;
1456                 }
1457             }
1458             proto.end(token);
1459             return mUid;
1460         }
1461 
1462         @GuardedBy("mLock")
toListLocked(List<ApplicationExitInfo> list, int filterPid)1463         List<ApplicationExitInfo> toListLocked(List<ApplicationExitInfo> list, int filterPid) {
1464             if (list == null) {
1465                 list = new ArrayList<ApplicationExitInfo>();
1466             }
1467             for (int i = mInfos.size() - 1; i >= 0; i--) {
1468                 if (filterPid == 0 || filterPid == mInfos.keyAt(i)) {
1469                     list.add(mInfos.valueAt(i));
1470                 }
1471             }
1472             return list;
1473         }
1474     }
1475 
1476     /**
1477      * Maintains the mapping between real UID and the application uid.
1478      */
1479     final class IsolatedUidRecords {
1480         /**
1481          * A mapping from application uid (with the userId) to isolated uids.
1482          */
1483         @GuardedBy("mLock")
1484         private final SparseArray<ArraySet<Integer>> mUidToIsolatedUidMap;
1485 
1486         /**
1487          * A mapping from isolated uids to application uid (with the userId)
1488          */
1489         @GuardedBy("mLock")
1490         private final SparseArray<Integer> mIsolatedUidToUidMap;
1491 
IsolatedUidRecords()1492         IsolatedUidRecords() {
1493             mUidToIsolatedUidMap = new SparseArray<ArraySet<Integer>>();
1494             mIsolatedUidToUidMap = new SparseArray<Integer>();
1495         }
1496 
addIsolatedUid(int isolatedUid, int uid)1497         void addIsolatedUid(int isolatedUid, int uid) {
1498             synchronized (mLock) {
1499                 ArraySet<Integer> set = mUidToIsolatedUidMap.get(uid);
1500                 if (set == null) {
1501                     set = new ArraySet<Integer>();
1502                     mUidToIsolatedUidMap.put(uid, set);
1503                 }
1504                 set.add(isolatedUid);
1505 
1506                 mIsolatedUidToUidMap.put(isolatedUid, uid);
1507             }
1508         }
1509 
1510         @GuardedBy("mLock")
getUidByIsolatedUid(int isolatedUid)1511         Integer getUidByIsolatedUid(int isolatedUid) {
1512             if (UserHandle.isIsolated(isolatedUid)) {
1513                 synchronized (mLock) {
1514                     return mIsolatedUidToUidMap.get(isolatedUid);
1515                 }
1516             }
1517             return isolatedUid;
1518         }
1519 
1520         @GuardedBy("mLock")
removeAppUidLocked(int uid)1521         private void removeAppUidLocked(int uid) {
1522             ArraySet<Integer> set = mUidToIsolatedUidMap.get(uid);
1523             if (set != null) {
1524                 for (int i = set.size() - 1; i >= 0; i--) {
1525                     int isolatedUid = set.removeAt(i);
1526                     mIsolatedUidToUidMap.remove(isolatedUid);
1527                 }
1528             }
1529         }
1530 
1531         @VisibleForTesting
removeAppUid(int uid, boolean allUsers)1532         void removeAppUid(int uid, boolean allUsers) {
1533             synchronized (mLock) {
1534                 if (allUsers) {
1535                     uid = UserHandle.getAppId(uid);
1536                     for (int i = mUidToIsolatedUidMap.size() - 1; i >= 0; i--) {
1537                         int u = mUidToIsolatedUidMap.keyAt(i);
1538                         if (uid == UserHandle.getAppId(u)) {
1539                             removeAppUidLocked(u);
1540                         }
1541                         mUidToIsolatedUidMap.removeAt(i);
1542                     }
1543                 } else {
1544                     removeAppUidLocked(uid);
1545                     mUidToIsolatedUidMap.remove(uid);
1546                 }
1547             }
1548         }
1549 
1550         @GuardedBy("mLock")
removeIsolatedUidLocked(int isolatedUid)1551         int removeIsolatedUidLocked(int isolatedUid) {
1552             if (!UserHandle.isIsolated(isolatedUid)) {
1553                 return isolatedUid;
1554             }
1555             int uid = mIsolatedUidToUidMap.get(isolatedUid, -1);
1556             if (uid == -1) {
1557                 return isolatedUid;
1558             }
1559             mIsolatedUidToUidMap.remove(isolatedUid);
1560             ArraySet<Integer> set = mUidToIsolatedUidMap.get(uid);
1561             if (set != null) {
1562                 set.remove(isolatedUid);
1563             }
1564             // let the ArraySet stay in the mUidToIsolatedUidMap even if it's empty
1565             return uid;
1566         }
1567 
removeByUserId(int userId)1568         void removeByUserId(int userId) {
1569             if (userId == UserHandle.USER_CURRENT) {
1570                 userId = mService.mUserController.getCurrentUserId();
1571             }
1572             synchronized (mLock) {
1573                 if (userId == UserHandle.USER_ALL) {
1574                     mIsolatedUidToUidMap.clear();
1575                     mUidToIsolatedUidMap.clear();
1576                     return;
1577                 }
1578                 for (int i = mIsolatedUidToUidMap.size() - 1; i >= 0; i--) {
1579                     int isolatedUid = mIsolatedUidToUidMap.keyAt(i);
1580                     int uid = mIsolatedUidToUidMap.valueAt(i);
1581                     if (UserHandle.getUserId(uid) == userId) {
1582                         mIsolatedUidToUidMap.removeAt(i);
1583                         mUidToIsolatedUidMap.remove(uid);
1584                     }
1585                 }
1586             }
1587         }
1588     }
1589 
1590     final class KillHandler extends Handler {
1591         static final int MSG_LMKD_PROC_KILLED = 4101;
1592         static final int MSG_CHILD_PROC_DIED = 4102;
1593         static final int MSG_PROC_DIED = 4103;
1594         static final int MSG_APP_KILL = 4104;
1595         static final int MSG_STATSD_LOG = 4105;
1596 
KillHandler(Looper looper)1597         KillHandler(Looper looper) {
1598             super(looper, null, true);
1599         }
1600 
1601         @Override
handleMessage(Message msg)1602         public void handleMessage(Message msg) {
1603             switch (msg.what) {
1604                 case MSG_LMKD_PROC_KILLED:
1605                     mAppExitInfoSourceLmkd.onProcDied(msg.arg1 /* pid */, msg.arg2 /* uid */,
1606                             null /* status */);
1607                     break;
1608                 case MSG_CHILD_PROC_DIED:
1609                     mAppExitInfoSourceZygote.onProcDied(msg.arg1 /* pid */, msg.arg2 /* uid */,
1610                             (Integer) msg.obj /* status */);
1611                     break;
1612                 case MSG_PROC_DIED: {
1613                     ApplicationExitInfo raw = (ApplicationExitInfo) msg.obj;
1614                     synchronized (mLock) {
1615                         handleNoteProcessDiedLocked(raw);
1616                     }
1617                     recycleRawRecord(raw);
1618                 }
1619                 break;
1620                 case MSG_APP_KILL: {
1621                     ApplicationExitInfo raw = (ApplicationExitInfo) msg.obj;
1622                     synchronized (mLock) {
1623                         handleNoteAppKillLocked(raw);
1624                     }
1625                     recycleRawRecord(raw);
1626                 }
1627                 break;
1628                 case MSG_STATSD_LOG: {
1629                     synchronized (mLock) {
1630                         performLogToStatsdLocked((ApplicationExitInfo) msg.obj);
1631                     }
1632                 }
1633                 break;
1634                 default:
1635                     super.handleMessage(msg);
1636             }
1637         }
1638     }
1639 
1640     @VisibleForTesting
isFresh(long timestamp)1641     boolean isFresh(long timestamp) {
1642         // A process could be dying but being stuck in some state, i.e.,
1643         // being TRACED by tombstoned, thus the zygote receives SIGCHILD
1644         // way after we already knew the kill (maybe because we did the kill :P),
1645         // so here check if the last known kill information is "fresh" enough.
1646         long now = System.currentTimeMillis();
1647 
1648         return (timestamp + AppExitInfoExternalSource.APP_EXIT_INFO_FRESHNESS_MS) >= now;
1649     }
1650 
1651     /**
1652      * Keep the raw information about app kills from external sources, i.e., lmkd
1653      */
1654     final class AppExitInfoExternalSource {
1655         private static final long APP_EXIT_INFO_FRESHNESS_MS = 300 * 1000;
1656 
1657         /**
1658          * A mapping between uid -> pid -> {timestamp, extra info(Nullable)}.
1659          * The uid here is the application uid, not the isolated uid.
1660          */
1661         @GuardedBy("mLock")
1662         private final SparseArray<SparseArray<Pair<Long, Object>>> mData;
1663 
1664         /** A tag for logging only */
1665         private final String mTag;
1666 
1667         /** A preset reason in case a proc dies */
1668         private final Integer mPresetReason;
1669 
1670         /** A callback that will be notified when a proc dies */
1671         private BiConsumer<Integer, Integer> mProcDiedListener;
1672 
AppExitInfoExternalSource(String tag, Integer reason)1673         AppExitInfoExternalSource(String tag, Integer reason) {
1674             mData = new SparseArray<SparseArray<Pair<Long, Object>>>();
1675             mTag = tag;
1676             mPresetReason = reason;
1677         }
1678 
1679         @GuardedBy("mLock")
addLocked(int pid, int uid, Object extra)1680         private void addLocked(int pid, int uid, Object extra) {
1681             Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1682             if (k != null) {
1683                 uid = k;
1684             }
1685 
1686             SparseArray<Pair<Long, Object>> array = mData.get(uid);
1687             if (array == null) {
1688                 array = new SparseArray<Pair<Long, Object>>();
1689                 mData.put(uid, array);
1690             }
1691             array.put(pid, new Pair<Long, Object>(System.currentTimeMillis(), extra));
1692         }
1693 
1694         @VisibleForTesting
remove(int pid, int uid)1695         Pair<Long, Object> remove(int pid, int uid) {
1696             synchronized (mLock) {
1697                 Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1698                 if (k != null) {
1699                     uid = k;
1700                 }
1701 
1702                 SparseArray<Pair<Long, Object>> array = mData.get(uid);
1703                 if (array != null) {
1704                     Pair<Long, Object> p = array.get(pid);
1705                     if (p != null) {
1706                         array.remove(pid);
1707                         return isFresh(p.first) ? p : null;
1708                     }
1709                 }
1710                 return null;
1711             }
1712         }
1713 
removeByUserId(int userId)1714         void removeByUserId(int userId) {
1715             if (userId == UserHandle.USER_CURRENT) {
1716                 userId = mService.mUserController.getCurrentUserId();
1717             }
1718             synchronized (mLock) {
1719                 if (userId == UserHandle.USER_ALL) {
1720                     mData.clear();
1721                     return;
1722                 }
1723                 for (int i = mData.size() - 1; i >= 0; i--) {
1724                     int uid = mData.keyAt(i);
1725                     if (UserHandle.getUserId(uid) == userId) {
1726                         mData.removeAt(i);
1727                     }
1728                 }
1729             }
1730         }
1731 
1732         @GuardedBy("mLock")
removeByUidLocked(int uid, boolean allUsers)1733         void removeByUidLocked(int uid, boolean allUsers) {
1734             if (UserHandle.isIsolated(uid)) {
1735                 Integer k = mIsolatedUidRecords.getUidByIsolatedUid(uid);
1736                 if (k != null) {
1737                     uid = k;
1738                 }
1739             }
1740 
1741             if (allUsers) {
1742                 uid = UserHandle.getAppId(uid);
1743                 for (int i = mData.size() - 1; i >= 0; i--) {
1744                     if (UserHandle.getAppId(mData.keyAt(i)) == uid) {
1745                         mData.removeAt(i);
1746                     }
1747                 }
1748             } else {
1749                 mData.remove(uid);
1750             }
1751         }
1752 
setOnProcDiedListener(BiConsumer<Integer, Integer> listener)1753         void setOnProcDiedListener(BiConsumer<Integer, Integer> listener) {
1754             synchronized (mLock) {
1755                 mProcDiedListener = listener;
1756             }
1757         }
1758 
onProcDied(final int pid, final int uid, final Integer status)1759         void onProcDied(final int pid, final int uid, final Integer status) {
1760             if (DEBUG_PROCESSES) {
1761                 Slog.i(TAG, mTag + ": proc died: pid=" + pid + " uid=" + uid
1762                         + ", status=" + status);
1763             }
1764 
1765             if (mService == null) {
1766                 return;
1767             }
1768 
1769             // Unlikely but possible: the record has been created
1770             // Let's update it if we could find a ApplicationExitInfo record
1771             synchronized (mLock) {
1772                 if (!updateExitInfoIfNecessaryLocked(pid, uid, status, mPresetReason)) {
1773                     addLocked(pid, uid, status);
1774                 }
1775 
1776                 // Notify any interesed party regarding the lmkd kills
1777                 final BiConsumer<Integer, Integer> listener = mProcDiedListener;
1778                 if (listener != null) {
1779                     mService.mHandler.post(()-> listener.accept(pid, uid));
1780                 }
1781             }
1782         }
1783     }
1784 
1785     /**
1786      * The implementation to the IAppTraceRetriever interface.
1787      */
1788     @VisibleForTesting
1789     class AppTraceRetriever extends IAppTraceRetriever.Stub {
1790         @Override
getTraceFileDescriptor(final String packageName, final int uid, final int pid)1791         public ParcelFileDescriptor getTraceFileDescriptor(final String packageName,
1792                 final int uid, final int pid) {
1793             mService.enforceNotIsolatedCaller("getTraceFileDescriptor");
1794 
1795             if (TextUtils.isEmpty(packageName)) {
1796                 throw new IllegalArgumentException("Invalid package name");
1797             }
1798             final int callingPid = Binder.getCallingPid();
1799             final int callingUid = Binder.getCallingUid();
1800             final int callingUserId = UserHandle.getCallingUserId();
1801             final int userId = UserHandle.getUserId(uid);
1802 
1803             mService.mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
1804                     ALLOW_NON_FULL, "getTraceFileDescriptor", null);
1805             if (mService.enforceDumpPermissionForPackage(packageName, userId,
1806                     callingUid, "getTraceFileDescriptor") != Process.INVALID_UID) {
1807                 synchronized (mLock) {
1808                     final ApplicationExitInfo info = getExitInfoLocked(packageName, uid, pid);
1809                     if (info == null) {
1810                         return null;
1811                     }
1812                     final File traceFile = info.getTraceFile();
1813                     if (traceFile == null) {
1814                         return null;
1815                     }
1816                     final long identity = Binder.clearCallingIdentity();
1817                     try {
1818                         // The fd will be closed after being written into Parcel
1819                         return ParcelFileDescriptor.open(traceFile,
1820                                 ParcelFileDescriptor.MODE_READ_ONLY);
1821                     } catch (FileNotFoundException e) {
1822                         return null;
1823                     } finally {
1824                         Binder.restoreCallingIdentity(identity);
1825                     }
1826                 }
1827             }
1828             return null;
1829         }
1830     }
1831 }
1832