OSDN Git Service

Fix ClipboardService device lock check for cross profile am: 0595b5a94b am: 9e5a4ed6c...
[android-x86/frameworks-base.git] / services / core / java / com / android / server / am / AppErrors.java
1 /*
2  * Copyright (C) 2016 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 com.android.internal.app.ProcessMap;
20 import com.android.internal.logging.MetricsLogger;
21 import com.android.internal.logging.nano.MetricsProto;
22 import com.android.internal.os.ProcessCpuTracker;
23 import com.android.server.RescueParty;
24 import com.android.server.Watchdog;
25
26 import android.app.ActivityManager;
27 import android.app.ActivityOptions;
28 import android.app.ActivityThread;
29 import android.app.AppOpsManager;
30 import android.app.ApplicationErrorReport;
31 import android.app.Dialog;
32 import android.content.ActivityNotFoundException;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.pm.ApplicationInfo;
36 import android.os.Binder;
37 import android.os.Message;
38 import android.os.Process;
39 import android.os.RemoteException;
40 import android.os.SystemClock;
41 import android.os.SystemProperties;
42 import android.os.UserHandle;
43 import android.provider.Settings;
44 import android.util.ArrayMap;
45 import android.util.ArraySet;
46 import android.util.EventLog;
47 import android.util.Log;
48 import android.util.Slog;
49 import android.util.SparseArray;
50 import android.util.TimeUtils;
51
52 import java.io.File;
53 import java.io.FileDescriptor;
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.List;
59 import java.util.Set;
60
61 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
62 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
63 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
64 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
65 import static com.android.server.am.ActivityManagerService.MY_PID;
66 import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE;
67
68 /**
69  * Controls error conditions in applications.
70  */
71 class AppErrors {
72
73     private static final String TAG = TAG_WITH_CLASS_NAME ? "AppErrors" : TAG_AM;
74
75     private final ActivityManagerService mService;
76     private final Context mContext;
77
78     private ArraySet<String> mAppsNotReportingCrashes;
79
80     /**
81      * The last time that various processes have crashed since they were last explicitly started.
82      */
83     private final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<>();
84
85     /**
86      * The last time that various processes have crashed (not reset even when explicitly started).
87      */
88     private final ProcessMap<Long> mProcessCrashTimesPersistent = new ProcessMap<>();
89
90     /**
91      * Set of applications that we consider to be bad, and will reject
92      * incoming broadcasts from (which the user has no control over).
93      * Processes are added to this set when they have crashed twice within
94      * a minimum amount of time; they are removed from it when they are
95      * later restarted (hopefully due to some user action).  The value is the
96      * time it was added to the list.
97      */
98     private final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<>();
99
100
101     AppErrors(Context context, ActivityManagerService service) {
102         context.assertRuntimeOverlayThemable();
103         mService = service;
104         mContext = context;
105     }
106
107     boolean dumpLocked(FileDescriptor fd, PrintWriter pw, boolean needSep,
108             String dumpPackage) {
109         if (!mProcessCrashTimes.getMap().isEmpty()) {
110             boolean printed = false;
111             final long now = SystemClock.uptimeMillis();
112             final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
113             final int processCount = pmap.size();
114             for (int ip = 0; ip < processCount; ip++) {
115                 final String pname = pmap.keyAt(ip);
116                 final SparseArray<Long> uids = pmap.valueAt(ip);
117                 final int uidCount = uids.size();
118                 for (int i = 0; i < uidCount; i++) {
119                     final int puid = uids.keyAt(i);
120                     final ProcessRecord r = mService.mProcessNames.get(pname, puid);
121                     if (dumpPackage != null && (r == null
122                             || !r.pkgList.containsKey(dumpPackage))) {
123                         continue;
124                     }
125                     if (!printed) {
126                         if (needSep) pw.println();
127                         needSep = true;
128                         pw.println("  Time since processes crashed:");
129                         printed = true;
130                     }
131                     pw.print("    Process "); pw.print(pname);
132                     pw.print(" uid "); pw.print(puid);
133                     pw.print(": last crashed ");
134                     TimeUtils.formatDuration(now-uids.valueAt(i), pw);
135                     pw.println(" ago");
136                 }
137             }
138         }
139
140         if (!mBadProcesses.getMap().isEmpty()) {
141             boolean printed = false;
142             final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
143             final int processCount = pmap.size();
144             for (int ip = 0; ip < processCount; ip++) {
145                 final String pname = pmap.keyAt(ip);
146                 final SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
147                 final int uidCount = uids.size();
148                 for (int i = 0; i < uidCount; i++) {
149                     final int puid = uids.keyAt(i);
150                     final ProcessRecord r = mService.mProcessNames.get(pname, puid);
151                     if (dumpPackage != null && (r == null
152                             || !r.pkgList.containsKey(dumpPackage))) {
153                         continue;
154                     }
155                     if (!printed) {
156                         if (needSep) pw.println();
157                         needSep = true;
158                         pw.println("  Bad processes:");
159                         printed = true;
160                     }
161                     final BadProcessInfo info = uids.valueAt(i);
162                     pw.print("    Bad process "); pw.print(pname);
163                     pw.print(" uid "); pw.print(puid);
164                     pw.print(": crashed at time "); pw.println(info.time);
165                     if (info.shortMsg != null) {
166                         pw.print("      Short msg: "); pw.println(info.shortMsg);
167                     }
168                     if (info.longMsg != null) {
169                         pw.print("      Long msg: "); pw.println(info.longMsg);
170                     }
171                     if (info.stack != null) {
172                         pw.println("      Stack:");
173                         int lastPos = 0;
174                         for (int pos = 0; pos < info.stack.length(); pos++) {
175                             if (info.stack.charAt(pos) == '\n') {
176                                 pw.print("        ");
177                                 pw.write(info.stack, lastPos, pos-lastPos);
178                                 pw.println();
179                                 lastPos = pos+1;
180                             }
181                         }
182                         if (lastPos < info.stack.length()) {
183                             pw.print("        ");
184                             pw.write(info.stack, lastPos, info.stack.length()-lastPos);
185                             pw.println();
186                         }
187                     }
188                 }
189             }
190         }
191         return needSep;
192     }
193
194     boolean isBadProcessLocked(ApplicationInfo info) {
195         return mBadProcesses.get(info.processName, info.uid) != null;
196     }
197
198     void clearBadProcessLocked(ApplicationInfo info) {
199         mBadProcesses.remove(info.processName, info.uid);
200     }
201
202     void resetProcessCrashTimeLocked(ApplicationInfo info) {
203         mProcessCrashTimes.remove(info.processName, info.uid);
204     }
205
206     void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) {
207         final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
208         for (int ip = pmap.size() - 1; ip >= 0; ip--) {
209             SparseArray<Long> ba = pmap.valueAt(ip);
210             for (int i = ba.size() - 1; i >= 0; i--) {
211                 boolean remove = false;
212                 final int entUid = ba.keyAt(i);
213                 if (!resetEntireUser) {
214                     if (userId == UserHandle.USER_ALL) {
215                         if (UserHandle.getAppId(entUid) == appId) {
216                             remove = true;
217                         }
218                     } else {
219                         if (entUid == UserHandle.getUid(userId, appId)) {
220                             remove = true;
221                         }
222                     }
223                 } else if (UserHandle.getUserId(entUid) == userId) {
224                     remove = true;
225                 }
226                 if (remove) {
227                     ba.removeAt(i);
228                 }
229             }
230             if (ba.size() == 0) {
231                 pmap.removeAt(ip);
232             }
233         }
234     }
235
236     void loadAppsNotReportingCrashesFromConfigLocked(String appsNotReportingCrashesConfig) {
237         if (appsNotReportingCrashesConfig != null) {
238             final String[] split = appsNotReportingCrashesConfig.split(",");
239             if (split.length > 0) {
240                 mAppsNotReportingCrashes = new ArraySet<>();
241                 Collections.addAll(mAppsNotReportingCrashes, split);
242             }
243         }
244     }
245
246     void killAppAtUserRequestLocked(ProcessRecord app, Dialog fromDialog) {
247         app.crashing = false;
248         app.crashingReport = null;
249         app.notResponding = false;
250         app.notRespondingReport = null;
251         if (app.anrDialog == fromDialog) {
252             app.anrDialog = null;
253         }
254         if (app.waitDialog == fromDialog) {
255             app.waitDialog = null;
256         }
257         if (app.pid > 0 && app.pid != MY_PID) {
258             handleAppCrashLocked(app, "user-terminated" /*reason*/,
259                     null /*shortMsg*/, null /*longMsg*/, null /*stackTrace*/, null /*data*/);
260             app.kill("user request after error", true);
261         }
262     }
263
264     /**
265      * Induce a crash in the given app.
266      *
267      * @param uid if nonnegative, the required matching uid of the target to crash
268      * @param initialPid fast-path match for the target to crash
269      * @param packageName fallback match if the stated pid is not found or doesn't match uid
270      * @param userId If nonnegative, required to identify a match by package name
271      * @param message
272      */
273     void scheduleAppCrashLocked(int uid, int initialPid, String packageName, int userId,
274             String message) {
275         ProcessRecord proc = null;
276
277         // Figure out which process to kill.  We don't trust that initialPid
278         // still has any relation to current pids, so must scan through the
279         // list.
280
281         synchronized (mService.mPidsSelfLocked) {
282             for (int i=0; i<mService.mPidsSelfLocked.size(); i++) {
283                 ProcessRecord p = mService.mPidsSelfLocked.valueAt(i);
284                 if (uid >= 0 && p.uid != uid) {
285                     continue;
286                 }
287                 if (p.pid == initialPid) {
288                     proc = p;
289                     break;
290                 }
291                 if (p.pkgList.containsKey(packageName)
292                         && (userId < 0 || p.userId == userId)) {
293                     proc = p;
294                 }
295             }
296         }
297
298         if (proc == null) {
299             Slog.w(TAG, "crashApplication: nothing for uid=" + uid
300                     + " initialPid=" + initialPid
301                     + " packageName=" + packageName
302                     + " userId=" + userId);
303             return;
304         }
305
306         proc.scheduleCrash(message);
307     }
308
309     /**
310      * Bring up the "unexpected error" dialog box for a crashing app.
311      * Deal with edge cases (intercepts from instrumented applications,
312      * ActivityController, error intent receivers, that sort of thing).
313      * @param r the application crashing
314      * @param crashInfo describing the failure
315      */
316     void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
317         final int callingPid = Binder.getCallingPid();
318         final int callingUid = Binder.getCallingUid();
319
320         final long origId = Binder.clearCallingIdentity();
321         try {
322             crashApplicationInner(r, crashInfo, callingPid, callingUid);
323         } finally {
324             Binder.restoreCallingIdentity(origId);
325         }
326     }
327
328     void crashApplicationInner(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo,
329             int callingPid, int callingUid) {
330         long timeMillis = System.currentTimeMillis();
331         String shortMsg = crashInfo.exceptionClassName;
332         String longMsg = crashInfo.exceptionMessage;
333         String stackTrace = crashInfo.stackTrace;
334         if (shortMsg != null && longMsg != null) {
335             longMsg = shortMsg + ": " + longMsg;
336         } else if (shortMsg != null) {
337             longMsg = shortMsg;
338         }
339
340         // If a persistent app is stuck in a crash loop, the device isn't very
341         // usable, so we want to consider sending out a rescue party.
342         if (r != null && r.persistent) {
343             RescueParty.notePersistentAppCrash(mContext, r.uid);
344         }
345
346         AppErrorResult result = new AppErrorResult();
347         TaskRecord task;
348         synchronized (mService) {
349             /**
350              * If crash is handled by instance of {@link android.app.IActivityController},
351              * finish now and don't show the app error dialog.
352              */
353             if (handleAppCrashInActivityController(r, crashInfo, shortMsg, longMsg, stackTrace,
354                     timeMillis, callingPid, callingUid)) {
355                 return;
356             }
357
358             /**
359              * If this process was running instrumentation, finish now - it will be handled in
360              * {@link ActivityManagerService#handleAppDiedLocked}.
361              */
362             if (r != null && r.instr != null) {
363                 return;
364             }
365
366             // Log crash in battery stats.
367             if (r != null) {
368                 mService.mBatteryStatsService.noteProcessCrash(r.processName, r.uid);
369             }
370
371             AppErrorDialog.Data data = new AppErrorDialog.Data();
372             data.result = result;
373             data.proc = r;
374
375             // If we can't identify the process or it's already exceeded its crash quota,
376             // quit right away without showing a crash dialog.
377             if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) {
378                 return;
379             }
380
381             final Message msg = Message.obtain();
382             msg.what = ActivityManagerService.SHOW_ERROR_UI_MSG;
383
384             task = data.task;
385             msg.obj = data;
386             mService.mUiHandler.sendMessage(msg);
387         }
388
389         int res = result.get();
390
391         Intent appErrorIntent = null;
392         MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
393         if (res == AppErrorDialog.TIMEOUT || res == AppErrorDialog.CANCEL) {
394             res = AppErrorDialog.FORCE_QUIT;
395         }
396         synchronized (mService) {
397             if (res == AppErrorDialog.MUTE) {
398                 stopReportingCrashesLocked(r);
399             }
400             if (res == AppErrorDialog.RESTART) {
401                 mService.removeProcessLocked(r, false, true, "crash");
402                 if (task != null) {
403                     try {
404                         mService.startActivityFromRecents(task.taskId,
405                                 ActivityOptions.makeBasic().toBundle());
406                     } catch (IllegalArgumentException e) {
407                         // Hmm, that didn't work, app might have crashed before creating a
408                         // recents entry. Let's see if we have a safe-to-restart intent.
409                         final Set<String> cats = task.intent.getCategories();
410                         if (cats != null && cats.contains(Intent.CATEGORY_LAUNCHER)) {
411                             mService.startActivityInPackage(task.mCallingUid,
412                                     task.mCallingPackage, task.intent,
413                                     null, null, null, 0, 0,
414                                     ActivityOptions.makeBasic().toBundle(),
415                                     task.userId, null, null, "AppErrors");
416                         }
417                     }
418                 }
419             }
420             if (res == AppErrorDialog.FORCE_QUIT) {
421                 long orig = Binder.clearCallingIdentity();
422                 try {
423                     // Kill it with fire!
424                     mService.mStackSupervisor.handleAppCrashLocked(r);
425                     if (!r.persistent) {
426                         mService.removeProcessLocked(r, false, false, "crash");
427                         mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
428                     }
429                 } finally {
430                     Binder.restoreCallingIdentity(orig);
431                 }
432             }
433             if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
434                 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
435             }
436             if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
437                 // XXX Can't keep track of crash time for isolated processes,
438                 // since they don't have a persistent identity.
439                 mProcessCrashTimes.put(r.info.processName, r.uid,
440                         SystemClock.uptimeMillis());
441             }
442         }
443
444         if (appErrorIntent != null) {
445             try {
446                 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
447             } catch (ActivityNotFoundException e) {
448                 Slog.w(TAG, "bug report receiver dissappeared", e);
449             }
450         }
451     }
452
453     private boolean handleAppCrashInActivityController(ProcessRecord r,
454                                                        ApplicationErrorReport.CrashInfo crashInfo,
455                                                        String shortMsg, String longMsg,
456                                                        String stackTrace, long timeMillis,
457                                                        int callingPid, int callingUid) {
458         if (mService.mController == null) {
459             return false;
460         }
461
462         try {
463             String name = r != null ? r.processName : null;
464             int pid = r != null ? r.pid : callingPid;
465             int uid = r != null ? r.info.uid : callingUid;
466             if (!mService.mController.appCrashed(name, pid,
467                     shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
468                 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
469                         && "Native crash".equals(crashInfo.exceptionClassName)) {
470                     Slog.w(TAG, "Skip killing native crashed app " + name
471                             + "(" + pid + ") during testing");
472                 } else {
473                     Slog.w(TAG, "Force-killing crashed app " + name
474                             + " at watcher's request");
475                     if (r != null) {
476                         if (!makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, null))
477                         {
478                             r.kill("crash", true);
479                         }
480                     } else {
481                         // Huh.
482                         Process.killProcess(pid);
483                         ActivityManagerService.killProcessGroup(uid, pid);
484                     }
485                 }
486                 return true;
487             }
488         } catch (RemoteException e) {
489             mService.mController = null;
490             Watchdog.getInstance().setActivityController(null);
491         }
492         return false;
493     }
494
495     private boolean makeAppCrashingLocked(ProcessRecord app,
496             String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
497         app.crashing = true;
498         app.crashingReport = generateProcessError(app,
499                 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
500         startAppProblemLocked(app);
501         app.stopFreezingAllLocked();
502         return handleAppCrashLocked(app, "force-crash" /*reason*/, shortMsg, longMsg, stackTrace,
503                 data);
504     }
505
506     void startAppProblemLocked(ProcessRecord app) {
507         // If this app is not running under the current user, then we
508         // can't give it a report button because that would require
509         // launching the report UI under a different user.
510         app.errorReportReceiver = null;
511
512         for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
513             if (app.userId == userId) {
514                 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
515                         mContext, app.info.packageName, app.info.flags);
516             }
517         }
518         mService.skipCurrentReceiverLocked(app);
519     }
520
521     /**
522      * Generate a process error record, suitable for attachment to a ProcessRecord.
523      *
524      * @param app The ProcessRecord in which the error occurred.
525      * @param condition Crashing, Application Not Responding, etc.  Values are defined in
526      *                      ActivityManager.AppErrorStateInfo
527      * @param activity The activity associated with the crash, if known.
528      * @param shortMsg Short message describing the crash.
529      * @param longMsg Long message describing the crash.
530      * @param stackTrace Full crash stack trace, may be null.
531      *
532      * @return Returns a fully-formed AppErrorStateInfo record.
533      */
534     private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
535             int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
536         ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
537
538         report.condition = condition;
539         report.processName = app.processName;
540         report.pid = app.pid;
541         report.uid = app.info.uid;
542         report.tag = activity;
543         report.shortMsg = shortMsg;
544         report.longMsg = longMsg;
545         report.stackTrace = stackTrace;
546
547         return report;
548     }
549
550     Intent createAppErrorIntentLocked(ProcessRecord r,
551             long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
552         ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
553         if (report == null) {
554             return null;
555         }
556         Intent result = new Intent(Intent.ACTION_APP_ERROR);
557         result.setComponent(r.errorReportReceiver);
558         result.putExtra(Intent.EXTRA_BUG_REPORT, report);
559         result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
560         return result;
561     }
562
563     private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
564             long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
565         if (r.errorReportReceiver == null) {
566             return null;
567         }
568
569         if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
570             return null;
571         }
572
573         ApplicationErrorReport report = new ApplicationErrorReport();
574         report.packageName = r.info.packageName;
575         report.installerPackageName = r.errorReportReceiver.getPackageName();
576         report.processName = r.processName;
577         report.time = timeMillis;
578         report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
579
580         if (r.crashing || r.forceCrashReport) {
581             report.type = ApplicationErrorReport.TYPE_CRASH;
582             report.crashInfo = crashInfo;
583         } else if (r.notResponding) {
584             report.type = ApplicationErrorReport.TYPE_ANR;
585             report.anrInfo = new ApplicationErrorReport.AnrInfo();
586
587             report.anrInfo.activity = r.notRespondingReport.tag;
588             report.anrInfo.cause = r.notRespondingReport.shortMsg;
589             report.anrInfo.info = r.notRespondingReport.longMsg;
590         }
591
592         return report;
593     }
594
595     boolean handleAppCrashLocked(ProcessRecord app, String reason,
596             String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
597         long now = SystemClock.uptimeMillis();
598         boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
599                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
600
601         Long crashTime;
602         Long crashTimePersistent;
603         if (!app.isolated) {
604             crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
605             crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid);
606         } else {
607             crashTime = crashTimePersistent = null;
608         }
609         if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
610             // This process loses!
611             Slog.w(TAG, "Process " + app.info.processName
612                     + " has crashed too many times: killing!");
613             EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
614                     app.userId, app.info.processName, app.uid);
615             mService.mStackSupervisor.handleAppCrashLocked(app);
616             if (!app.persistent) {
617                 // We don't want to start this process again until the user
618                 // explicitly does so...  but for persistent process, we really
619                 // need to keep it running.  If a persistent process is actually
620                 // repeatedly crashing, then badness for everyone.
621                 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
622                         app.info.processName);
623                 if (!app.isolated) {
624                     // XXX We don't have a way to mark isolated processes
625                     // as bad, since they don't have a peristent identity.
626                     mBadProcesses.put(app.info.processName, app.uid,
627                             new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
628                     mProcessCrashTimes.remove(app.info.processName, app.uid);
629                 }
630                 app.bad = true;
631                 app.removed = true;
632                 // Don't let services in this process be restarted and potentially
633                 // annoy the user repeatedly.  Unless it is persistent, since those
634                 // processes run critical code.
635                 mService.removeProcessLocked(app, false, false, "crash");
636                 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
637                 if (!showBackground) {
638                     return false;
639                 }
640             }
641             mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
642         } else {
643             TaskRecord affectedTask =
644                     mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason);
645             if (data != null) {
646                 data.task = affectedTask;
647             }
648             if (data != null && crashTimePersistent != null
649                     && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) {
650                 data.repeating = true;
651             }
652         }
653
654         boolean procIsBoundForeground =
655                 (app.curProcState == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
656         // Bump up the crash count of any services currently running in the proc.
657         for (int i=app.services.size()-1; i>=0; i--) {
658             // Any services running in the application need to be placed
659             // back in the pending list.
660             ServiceRecord sr = app.services.valueAt(i);
661             sr.crashCount++;
662
663             // Allow restarting for started or bound foreground services that are crashing the
664             // first time. This includes wallpapers.
665             if ((data != null) && (sr.crashCount <= 1)
666                     && (sr.isForeground || procIsBoundForeground)) {
667                 data.isRestartableForService = true;
668             }
669         }
670
671         // If the crashing process is what we consider to be the "home process" and it has been
672         // replaced by a third-party app, clear the package preferred activities from packages
673         // with a home activity running in the process to prevent a repeatedly crashing app
674         // from blocking the user to manually clear the list.
675         final ArrayList<ActivityRecord> activities = app.activities;
676         if (app == mService.mHomeProcess && activities.size() > 0
677                 && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
678             for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
679                 final ActivityRecord r = activities.get(activityNdx);
680                 if (r.isHomeActivity()) {
681                     Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
682                     try {
683                         ActivityThread.getPackageManager()
684                                 .clearPackagePreferredActivities(r.packageName);
685                     } catch (RemoteException c) {
686                         // pm is in same process, this will never happen.
687                     }
688                 }
689             }
690         }
691
692         if (!app.isolated) {
693             // XXX Can't keep track of crash times for isolated processes,
694             // because they don't have a perisistent identity.
695             mProcessCrashTimes.put(app.info.processName, app.uid, now);
696             mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now);
697         }
698
699         if (app.crashHandler != null) mService.mHandler.post(app.crashHandler);
700         return true;
701     }
702
703     void handleShowAppErrorUi(Message msg) {
704         AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj;
705         boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
706                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
707         synchronized (mService) {
708             ProcessRecord proc = data.proc;
709             AppErrorResult res = data.result;
710             if (proc != null && proc.crashDialog != null) {
711                 Slog.e(TAG, "App already has crash dialog: " + proc);
712                 if (res != null) {
713                     res.set(AppErrorDialog.ALREADY_SHOWING);
714                 }
715                 return;
716             }
717             boolean isBackground = (UserHandle.getAppId(proc.uid)
718                     >= Process.FIRST_APPLICATION_UID
719                     && proc.pid != MY_PID);
720             for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
721                 isBackground &= (proc.userId != userId);
722             }
723             if (isBackground && !showBackground) {
724                 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
725                 if (res != null) {
726                     res.set(AppErrorDialog.BACKGROUND_USER);
727                 }
728                 return;
729             }
730             final boolean crashSilenced = mAppsNotReportingCrashes != null &&
731                     mAppsNotReportingCrashes.contains(proc.info.packageName);
732             if ((mService.canShowErrorDialogs() || showBackground) && !crashSilenced) {
733                 proc.crashDialog = new AppErrorDialog(mContext, mService, data);
734             } else {
735                 // The device is asleep, so just pretend that the user
736                 // saw a crash dialog and hit "force quit".
737                 if (res != null) {
738                     res.set(AppErrorDialog.CANT_SHOW);
739                 }
740             }
741         }
742         // If we've created a crash dialog, show it without the lock held
743         if(data.proc.crashDialog != null) {
744             Slog.i(TAG, "Showing crash dialog for package " + data.proc.info.packageName
745                     + " u" + data.proc.userId);
746             data.proc.crashDialog.show();
747         }
748     }
749
750     void stopReportingCrashesLocked(ProcessRecord proc) {
751         if (mAppsNotReportingCrashes == null) {
752             mAppsNotReportingCrashes = new ArraySet<>();
753         }
754         mAppsNotReportingCrashes.add(proc.info.packageName);
755     }
756
757     static boolean isInterestingForBackgroundTraces(ProcessRecord app) {
758         // The system_server is always considered interesting.
759         if (app.pid == MY_PID) {
760             return true;
761         }
762
763         // A package is considered interesting if any of the following is true :
764         //
765         // - It's displaying an activity.
766         // - It's the SystemUI.
767         // - It has an overlay or a top UI visible.
768         //
769         // NOTE: The check whether a given ProcessRecord belongs to the systemui
770         // process is a bit of a kludge, but the same pattern seems repeated at
771         // several places in the system server.
772         return app.isInterestingToUserLocked() ||
773             (app.info != null && "com.android.systemui".equals(app.info.packageName)) ||
774             (app.hasTopUi || app.hasOverlayUi);
775     }
776
777     final void appNotResponding(ProcessRecord app, ActivityRecord activity,
778             ActivityRecord parent, boolean aboveSystem, final String annotation) {
779         ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
780         SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
781
782         if (mService.mController != null) {
783             try {
784                 // 0 == continue, -1 = kill process immediately
785                 int res = mService.mController.appEarlyNotResponding(
786                         app.processName, app.pid, annotation);
787                 if (res < 0 && app.pid != MY_PID) {
788                     app.kill("anr", true);
789                 }
790             } catch (RemoteException e) {
791                 mService.mController = null;
792                 Watchdog.getInstance().setActivityController(null);
793             }
794         }
795
796         long anrTime = SystemClock.uptimeMillis();
797         if (ActivityManagerService.MONITOR_CPU_USAGE) {
798             mService.updateCpuStatsNow();
799         }
800
801         // Unless configured otherwise, swallow ANRs in background processes & kill the process.
802         boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
803                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
804
805         boolean isSilentANR;
806
807         synchronized (mService) {
808             // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
809             if (mService.mShuttingDown) {
810                 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
811                 return;
812             } else if (app.notResponding) {
813                 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
814                 return;
815             } else if (app.crashing) {
816                 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
817                 return;
818             } else if (app.killedByAm) {
819                 Slog.i(TAG, "App already killed by AM skipping ANR: " + app + " " + annotation);
820                 return;
821             } else if (app.killed) {
822                 Slog.i(TAG, "Skipping died app ANR: " + app + " " + annotation);
823                 return;
824             }
825
826             // In case we come through here for the same app before completing
827             // this one, mark as anring now so we will bail out.
828             app.notResponding = true;
829
830             // Log the ANR to the event log.
831             EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
832                     app.processName, app.info.flags, annotation);
833
834             // Dump thread traces as quickly as we can, starting with "interesting" processes.
835             firstPids.add(app.pid);
836
837             // Don't dump other PIDs if it's a background ANR
838             isSilentANR = !showBackground && !isInterestingForBackgroundTraces(app);
839             if (!isSilentANR) {
840                 int parentPid = app.pid;
841                 if (parent != null && parent.app != null && parent.app.pid > 0) {
842                     parentPid = parent.app.pid;
843                 }
844                 if (parentPid != app.pid) firstPids.add(parentPid);
845
846                 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
847
848                 for (int i = mService.mLruProcesses.size() - 1; i >= 0; i--) {
849                     ProcessRecord r = mService.mLruProcesses.get(i);
850                     if (r != null && r.thread != null) {
851                         int pid = r.pid;
852                         if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
853                             if (r.persistent) {
854                                 firstPids.add(pid);
855                                 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
856                             } else if (r.treatLikeActivity) {
857                                 firstPids.add(pid);
858                                 if (DEBUG_ANR) Slog.i(TAG, "Adding likely IME: " + r);
859                             } else {
860                                 lastPids.put(pid, Boolean.TRUE);
861                                 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
862                             }
863                         }
864                     }
865                 }
866             }
867         }
868
869         // Log the ANR to the main log.
870         StringBuilder info = new StringBuilder();
871         info.setLength(0);
872         info.append("ANR in ").append(app.processName);
873         if (activity != null && activity.shortComponentName != null) {
874             info.append(" (").append(activity.shortComponentName).append(")");
875         }
876         info.append("\n");
877         info.append("PID: ").append(app.pid).append("\n");
878         if (annotation != null) {
879             info.append("Reason: ").append(annotation).append("\n");
880         }
881         if (parent != null && parent != activity) {
882             info.append("Parent: ").append(parent.shortComponentName).append("\n");
883         }
884
885         ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
886
887         // don't dump native PIDs for background ANRs unless it is the process of interest
888         String[] nativeProcs = null;
889         if (isSilentANR) {
890             for (int i = 0; i < NATIVE_STACKS_OF_INTEREST.length; i++) {
891                 if (NATIVE_STACKS_OF_INTEREST[i].equals(app.processName)) {
892                     nativeProcs = new String[] { app.processName };
893                     break;
894                 }
895             }
896         } else {
897             nativeProcs = NATIVE_STACKS_OF_INTEREST;
898         }
899
900         int[] pids = nativeProcs == null ? null : Process.getPidsForCommands(nativeProcs);
901         ArrayList<Integer> nativePids = null;
902
903         if (pids != null) {
904             nativePids = new ArrayList<Integer>(pids.length);
905             for (int i : pids) {
906                 nativePids.add(i);
907             }
908         }
909
910         // For background ANRs, don't pass the ProcessCpuTracker to
911         // avoid spending 1/2 second collecting stats to rank lastPids.
912         File tracesFile = ActivityManagerService.dumpStackTraces(
913                 true, firstPids,
914                 (isSilentANR) ? null : processCpuTracker,
915                 (isSilentANR) ? null : lastPids,
916                 nativePids);
917
918         String cpuInfo = null;
919         if (ActivityManagerService.MONITOR_CPU_USAGE) {
920             mService.updateCpuStatsNow();
921             synchronized (mService.mProcessCpuTracker) {
922                 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
923             }
924             info.append(processCpuTracker.printCurrentLoad());
925             info.append(cpuInfo);
926         }
927
928         info.append(processCpuTracker.printCurrentState(anrTime));
929
930         Slog.e(TAG, info.toString());
931         if (tracesFile == null) {
932             // There is no trace file, so dump (only) the alleged culprit's threads to the log
933             Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
934         }
935
936         mService.addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
937                 cpuInfo, tracesFile, null);
938
939         if (mService.mController != null) {
940             try {
941                 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
942                 int res = mService.mController.appNotResponding(
943                         app.processName, app.pid, info.toString());
944                 if (res != 0) {
945                     if (res < 0 && app.pid != MY_PID) {
946                         app.kill("anr", true);
947                     } else {
948                         synchronized (mService) {
949                             mService.mServices.scheduleServiceTimeoutLocked(app);
950                         }
951                     }
952                     return;
953                 }
954             } catch (RemoteException e) {
955                 mService.mController = null;
956                 Watchdog.getInstance().setActivityController(null);
957             }
958         }
959
960         synchronized (mService) {
961             mService.mBatteryStatsService.noteProcessAnr(app.processName, app.uid);
962
963             if (isSilentANR) {
964                 app.kill("bg anr", true);
965                 return;
966             }
967
968             // Set the app's notResponding state, and look up the errorReportReceiver
969             makeAppNotRespondingLocked(app,
970                     activity != null ? activity.shortComponentName : null,
971                     annotation != null ? "ANR " + annotation : "ANR",
972                     info.toString());
973
974             // Bring up the infamous App Not Responding dialog
975             Message msg = Message.obtain();
976             HashMap<String, Object> map = new HashMap<String, Object>();
977             msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
978             msg.obj = map;
979             msg.arg1 = aboveSystem ? 1 : 0;
980             map.put("app", app);
981             if (activity != null) {
982                 map.put("activity", activity);
983             }
984
985             mService.mUiHandler.sendMessage(msg);
986         }
987     }
988
989     private void makeAppNotRespondingLocked(ProcessRecord app,
990             String activity, String shortMsg, String longMsg) {
991         app.notResponding = true;
992         app.notRespondingReport = generateProcessError(app,
993                 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
994                 activity, shortMsg, longMsg, null);
995         startAppProblemLocked(app);
996         app.stopFreezingAllLocked();
997     }
998
999     void handleShowAnrUi(Message msg) {
1000         Dialog d = null;
1001         synchronized (mService) {
1002             HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1003             ProcessRecord proc = (ProcessRecord)data.get("app");
1004             if (proc != null && proc.anrDialog != null) {
1005                 Slog.e(TAG, "App already has anr dialog: " + proc);
1006                 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
1007                         AppNotRespondingDialog.ALREADY_SHOWING);
1008                 return;
1009             }
1010
1011             Intent intent = new Intent("android.intent.action.ANR");
1012             if (!mService.mProcessesReady) {
1013                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1014                         | Intent.FLAG_RECEIVER_FOREGROUND);
1015             }
1016             mService.broadcastIntentLocked(null, null, intent,
1017                     null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1018                     null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
1019
1020             boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
1021                     Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1022             if (mService.canShowErrorDialogs() || showBackground) {
1023                 d = new AppNotRespondingDialog(mService,
1024                         mContext, proc, (ActivityRecord)data.get("activity"),
1025                         msg.arg1 != 0);
1026                 proc.anrDialog = d;
1027             } else {
1028                 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
1029                         AppNotRespondingDialog.CANT_SHOW);
1030                 // Just kill the app if there is no dialog to be shown.
1031                 mService.killAppAtUsersRequest(proc, null);
1032             }
1033         }
1034         // If we've created a crash dialog, show it without the lock held
1035         if (d != null) {
1036             d.show();
1037         }
1038     }
1039
1040     /**
1041      * Information about a process that is currently marked as bad.
1042      */
1043     static final class BadProcessInfo {
1044         BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
1045             this.time = time;
1046             this.shortMsg = shortMsg;
1047             this.longMsg = longMsg;
1048             this.stack = stack;
1049         }
1050
1051         final long time;
1052         final String shortMsg;
1053         final String longMsg;
1054         final String stack;
1055     }
1056
1057 }