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