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