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