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