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