AppErrors.java revision 9046222cb2b1bd57278ddbf71d9f628f8dd254ae
1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17package com.android.server.am; 18 19import com.android.internal.app.ProcessMap; 20import com.android.internal.logging.MetricsLogger; 21import com.android.internal.logging.MetricsProto; 22import com.android.internal.os.ProcessCpuTracker; 23import com.android.server.Watchdog; 24 25import android.app.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; 64import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 65import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 66import static com.android.server.am.ActivityManagerService.MY_PID; 67import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE; 68 69/** 70 * Controls error conditions in applications. 71 */ 72class AppErrors { 73 74 private static final String TAG = TAG_WITH_CLASS_NAME ? "AppErrors" : TAG_AM; 75 76 private final ActivityManagerService mService; 77 private final Context mContext; 78 79 private ArraySet<String> mAppsNotReportingCrashes; 80 81 /** 82 * The last time that various processes have crashed since they were last explicitly started. 83 */ 84 private final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<>(); 85 86 /** 87 * The last time that various processes have crashed (not reset even when explicitly started). 88 */ 89 private final ProcessMap<Long> mProcessCrashTimesPersistent = new ProcessMap<>(); 90 91 /** 92 * Set of applications that we consider to be bad, and will reject 93 * incoming broadcasts from (which the user has no control over). 94 * Processes are added to this set when they have crashed twice within 95 * a minimum amount of time; they are removed from it when they are 96 * later restarted (hopefully due to some user action). The value is the 97 * time it was added to the list. 98 */ 99 private final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<>(); 100 101 102 AppErrors(Context context, ActivityManagerService service) { 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 void scheduleAppCrashLocked(int uid, int initialPid, String packageName, 265 String message) { 266 ProcessRecord proc = null; 267 268 // Figure out which process to kill. We don't trust that initialPid 269 // still has any relation to current pids, so must scan through the 270 // list. 271 272 synchronized (mService.mPidsSelfLocked) { 273 for (int i=0; i<mService.mPidsSelfLocked.size(); i++) { 274 ProcessRecord p = mService.mPidsSelfLocked.valueAt(i); 275 if (p.uid != uid) { 276 continue; 277 } 278 if (p.pid == initialPid) { 279 proc = p; 280 break; 281 } 282 if (p.pkgList.containsKey(packageName)) { 283 proc = p; 284 } 285 } 286 } 287 288 if (proc == null) { 289 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 290 + " initialPid=" + initialPid 291 + " packageName=" + packageName); 292 return; 293 } 294 295 if (proc.thread != null) { 296 if (proc.pid == Process.myPid()) { 297 Log.w(TAG, "crashApplication: trying to crash self!"); 298 return; 299 } 300 long ident = Binder.clearCallingIdentity(); 301 try { 302 proc.thread.scheduleCrash(message); 303 } catch (RemoteException e) { 304 } finally { 305 Binder.restoreCallingIdentity(ident); 306 } 307 } 308 } 309 310 /** 311 * Bring up the "unexpected error" dialog box for a crashing app. 312 * Deal with edge cases (intercepts from instrumented applications, 313 * ActivityController, error intent receivers, that sort of thing). 314 * @param r the application crashing 315 * @param crashInfo describing the failure 316 */ 317 void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) { 318 long timeMillis = System.currentTimeMillis(); 319 String shortMsg = crashInfo.exceptionClassName; 320 String longMsg = crashInfo.exceptionMessage; 321 String stackTrace = crashInfo.stackTrace; 322 if (shortMsg != null && longMsg != null) { 323 longMsg = shortMsg + ": " + longMsg; 324 } else if (shortMsg != null) { 325 longMsg = shortMsg; 326 } 327 328 AppErrorResult result = new AppErrorResult(); 329 TaskRecord task; 330 synchronized (mService) { 331 if (mService.mController != null) { 332 try { 333 String name = r != null ? r.processName : null; 334 int pid = r != null ? r.pid : Binder.getCallingPid(); 335 int uid = r != null ? r.info.uid : Binder.getCallingUid(); 336 if (!mService.mController.appCrashed(name, pid, 337 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) { 338 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")) 339 && "Native crash".equals(crashInfo.exceptionClassName)) { 340 Slog.w(TAG, "Skip killing native crashed app " + name 341 + "(" + pid + ") during testing"); 342 } else { 343 Slog.w(TAG, "Force-killing crashed app " + name 344 + " at watcher's request"); 345 if (r != null) { 346 r.kill("crash", true); 347 } else { 348 // Huh. 349 Process.killProcess(pid); 350 ActivityManagerService.killProcessGroup(uid, pid); 351 } 352 } 353 return; 354 } 355 } catch (RemoteException e) { 356 mService.mController = null; 357 Watchdog.getInstance().setActivityController(null); 358 } 359 } 360 361 final long origId = Binder.clearCallingIdentity(); 362 363 // If this process is running instrumentation, finish it. 364 if (r != null && r.instrumentationClass != null) { 365 Slog.w(TAG, "Error in app " + r.processName 366 + " running instrumentation " + r.instrumentationClass + ":"); 367 if (shortMsg != null) Slog.w(TAG, " " + shortMsg); 368 if (longMsg != null) Slog.w(TAG, " " + longMsg); 369 Bundle info = new Bundle(); 370 info.putString("shortMsg", shortMsg); 371 info.putString("longMsg", longMsg); 372 mService.finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info); 373 Binder.restoreCallingIdentity(origId); 374 return; 375 } 376 377 // Log crash in battery stats. 378 if (r != null) { 379 mService.mBatteryStatsService.noteProcessCrash(r.processName, r.uid); 380 } 381 382 AppErrorDialog.Data data = new AppErrorDialog.Data(); 383 data.result = result; 384 data.proc = r; 385 386 // If we can't identify the process or it's already exceeded its crash quota, 387 // quit right away without showing a crash dialog. 388 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) { 389 Binder.restoreCallingIdentity(origId); 390 return; 391 } 392 393 Message msg = Message.obtain(); 394 msg.what = ActivityManagerService.SHOW_ERROR_UI_MSG; 395 396 task = data.task; 397 msg.obj = data; 398 mService.mUiHandler.sendMessage(msg); 399 400 Binder.restoreCallingIdentity(origId); 401 } 402 403 int res = result.get(); 404 405 Intent appErrorIntent = null; 406 final long ident = Binder.clearCallingIdentity(); 407 try { 408 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res); 409 if (res == AppErrorDialog.TIMEOUT) { 410 res = AppErrorDialog.FORCE_QUIT; 411 } 412 if (res == AppErrorDialog.RESET) { 413 String[] packageList = r.getPackageList(); 414 if (packageList != null) { 415 PackageManager pm = mContext.getPackageManager(); 416 final Semaphore s = new Semaphore(0); 417 for (int i = 0; i < packageList.length; i++) { 418 if (i < packageList.length - 1) { 419 pm.deleteApplicationCacheFiles(packageList[i], null); 420 } else { 421 pm.deleteApplicationCacheFiles(packageList[i], 422 new IPackageDataObserver.Stub() { 423 @Override 424 public void onRemoveCompleted(String packageName, 425 boolean succeeded) { 426 s.release(); 427 } 428 }); 429 430 // Wait until cache has been cleared before we restart. 431 try { 432 s.acquire(); 433 } catch (InterruptedException e) { 434 } 435 } 436 } 437 } 438 // If there was nothing to reset, just restart; 439 res = AppErrorDialog.RESTART; 440 } 441 synchronized (mService) { 442 if (res == AppErrorDialog.MUTE) { 443 stopReportingCrashesLocked(r); 444 } 445 if (res == AppErrorDialog.RESTART) { 446 mService.removeProcessLocked(r, false, true, "crash"); 447 if (task != null) { 448 try { 449 mService.startActivityFromRecents(task.taskId, 450 ActivityOptions.makeBasic().toBundle()); 451 } catch (IllegalArgumentException e) { 452 // Hmm, that didn't work, app might have crashed before creating a 453 // recents entry. Let's see if we have a safe-to-restart intent. 454 if (task.intent.getCategories().contains( 455 Intent.CATEGORY_LAUNCHER)) { 456 mService.startActivityInPackage(task.mCallingUid, 457 task.mCallingPackage, task.intent, 458 null, null, null, 0, 0, 459 ActivityOptions.makeBasic().toBundle(), 460 task.userId, null, null); 461 } 462 } 463 } 464 } 465 if (res == AppErrorDialog.FORCE_QUIT) { 466 long orig = Binder.clearCallingIdentity(); 467 try { 468 // Kill it with fire! 469 mService.mStackSupervisor.handleAppCrashLocked(r); 470 if (!r.persistent) { 471 mService.removeProcessLocked(r, false, false, "crash"); 472 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked(); 473 } 474 } finally { 475 Binder.restoreCallingIdentity(orig); 476 } 477 } 478 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) { 479 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo); 480 } 481 if (r != null && !r.isolated && res != AppErrorDialog.RESTART) { 482 // XXX Can't keep track of crash time for isolated processes, 483 // since they don't have a persistent identity. 484 mProcessCrashTimes.put(r.info.processName, r.uid, 485 SystemClock.uptimeMillis()); 486 } 487 } 488 } finally { 489 Binder.restoreCallingIdentity(ident); 490 } 491 492 if (appErrorIntent != null) { 493 try { 494 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId)); 495 } catch (ActivityNotFoundException e) { 496 Slog.w(TAG, "bug report receiver dissappeared", e); 497 } 498 } 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.getCurrentProfileIdsLocked()) { 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.AppErrorStateInfo 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 AppErrorStateInfo 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 long now = SystemClock.uptimeMillis(); 604 605 Long crashTime; 606 Long crashTimePersistent; 607 if (!app.isolated) { 608 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid); 609 crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid); 610 } else { 611 crashTime = crashTimePersistent = null; 612 } 613 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) { 614 // This process loses! 615 Slog.w(TAG, "Process " + app.info.processName 616 + " has crashed too many times: killing!"); 617 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, 618 app.userId, app.info.processName, app.uid); 619 mService.mStackSupervisor.handleAppCrashLocked(app); 620 if (!app.persistent) { 621 // We don't want to start this process again until the user 622 // explicitly does so... but for persistent process, we really 623 // need to keep it running. If a persistent process is actually 624 // repeatedly crashing, then badness for everyone. 625 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, 626 app.info.processName); 627 if (!app.isolated) { 628 // XXX We don't have a way to mark isolated processes 629 // as bad, since they don't have a peristent identity. 630 mBadProcesses.put(app.info.processName, app.uid, 631 new BadProcessInfo(now, shortMsg, longMsg, stackTrace)); 632 mProcessCrashTimes.remove(app.info.processName, app.uid); 633 } 634 app.bad = true; 635 app.removed = true; 636 // Don't let services in this process be restarted and potentially 637 // annoy the user repeatedly. Unless it is persistent, since those 638 // processes run critical code. 639 mService.removeProcessLocked(app, false, false, "crash"); 640 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked(); 641 return false; 642 } 643 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked(); 644 } else { 645 TaskRecord affectedTask = 646 mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason); 647 if (data != null) { 648 data.task = affectedTask; 649 } 650 if (data != null && crashTimePersistent != null 651 && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) { 652 data.repeating = true; 653 } 654 } 655 656 // Bump up the crash count of any services currently running in the proc. 657 for (int i=app.services.size()-1; i>=0; i--) { 658 // Any services running in the application need to be placed 659 // back in the pending list. 660 ServiceRecord sr = app.services.valueAt(i); 661 sr.crashCount++; 662 } 663 664 // If the crashing process is what we consider to be the "home process" and it has been 665 // replaced by a third-party app, clear the package preferred activities from packages 666 // with a home activity running in the process to prevent a repeatedly crashing app 667 // from blocking the user to manually clear the list. 668 final ArrayList<ActivityRecord> activities = app.activities; 669 if (app == mService.mHomeProcess && activities.size() > 0 670 && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 671 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 672 final ActivityRecord r = activities.get(activityNdx); 673 if (r.isHomeActivity()) { 674 Log.i(TAG, "Clearing package preferred activities from " + r.packageName); 675 try { 676 ActivityThread.getPackageManager() 677 .clearPackagePreferredActivities(r.packageName); 678 } catch (RemoteException c) { 679 // pm is in same process, this will never happen. 680 } 681 } 682 } 683 } 684 685 if (!app.isolated) { 686 // XXX Can't keep track of crash times for isolated processes, 687 // because they don't have a perisistent identity. 688 mProcessCrashTimes.put(app.info.processName, app.uid, now); 689 mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now); 690 } 691 692 if (app.crashHandler != null) mService.mHandler.post(app.crashHandler); 693 return true; 694 } 695 696 void handleShowAppErrorUi(Message msg) { 697 AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj; 698 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 699 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 700 synchronized (mService) { 701 ProcessRecord proc = data.proc; 702 AppErrorResult res = data.result; 703 if (proc != null && proc.crashDialog != null) { 704 Slog.e(TAG, "App already has crash dialog: " + proc); 705 if (res != null) { 706 res.set(AppErrorDialog.ALREADY_SHOWING); 707 } 708 return; 709 } 710 boolean isBackground = (UserHandle.getAppId(proc.uid) 711 >= Process.FIRST_APPLICATION_UID 712 && proc.pid != MY_PID); 713 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) { 714 isBackground &= (proc.userId != userId); 715 } 716 if (isBackground && !showBackground) { 717 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 718 if (res != null) { 719 res.set(AppErrorDialog.BACKGROUND_USER); 720 } 721 return; 722 } 723 final boolean crashSilenced = mAppsNotReportingCrashes != null && 724 mAppsNotReportingCrashes.contains(proc.info.packageName); 725 if (mService.canShowErrorDialogs() && !crashSilenced) { 726 Dialog d = new AppErrorDialog(mContext, mService, data); 727 d.show(); 728 proc.crashDialog = d; 729 } else { 730 // The device is asleep, so just pretend that the user 731 // saw a crash dialog and hit "force quit". 732 if (res != null) { 733 res.set(AppErrorDialog.CANT_SHOW); 734 } 735 } 736 } 737 } 738 739 void stopReportingCrashesLocked(ProcessRecord proc) { 740 if (mAppsNotReportingCrashes == null) { 741 mAppsNotReportingCrashes = new ArraySet<>(); 742 } 743 mAppsNotReportingCrashes.add(proc.info.packageName); 744 } 745 746 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 747 ActivityRecord parent, boolean aboveSystem, final String annotation) { 748 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 749 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 750 751 if (mService.mController != null) { 752 try { 753 // 0 == continue, -1 = kill process immediately 754 int res = mService.mController.appEarlyNotResponding( 755 app.processName, app.pid, annotation); 756 if (res < 0 && app.pid != MY_PID) { 757 app.kill("anr", true); 758 } 759 } catch (RemoteException e) { 760 mService.mController = null; 761 Watchdog.getInstance().setActivityController(null); 762 } 763 } 764 765 long anrTime = SystemClock.uptimeMillis(); 766 if (ActivityManagerService.MONITOR_CPU_USAGE) { 767 mService.updateCpuStatsNow(); 768 } 769 770 synchronized (mService) { 771 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 772 if (mService.mShuttingDown) { 773 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 774 return; 775 } else if (app.notResponding) { 776 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 777 return; 778 } else if (app.crashing) { 779 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 780 return; 781 } 782 783 // In case we come through here for the same app before completing 784 // this one, mark as anring now so we will bail out. 785 app.notResponding = true; 786 787 // Log the ANR to the event log. 788 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 789 app.processName, app.info.flags, annotation); 790 791 // Dump thread traces as quickly as we can, starting with "interesting" processes. 792 firstPids.add(app.pid); 793 794 int parentPid = app.pid; 795 if (parent != null && parent.app != null && parent.app.pid > 0) { 796 parentPid = parent.app.pid; 797 } 798 if (parentPid != app.pid) firstPids.add(parentPid); 799 800 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 801 802 for (int i = mService.mLruProcesses.size() - 1; i >= 0; i--) { 803 ProcessRecord r = mService.mLruProcesses.get(i); 804 if (r != null && r.thread != null) { 805 int pid = r.pid; 806 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 807 if (r.persistent) { 808 firstPids.add(pid); 809 } else { 810 lastPids.put(pid, Boolean.TRUE); 811 } 812 } 813 } 814 } 815 } 816 817 // Log the ANR to the main log. 818 StringBuilder info = new StringBuilder(); 819 info.setLength(0); 820 info.append("ANR in ").append(app.processName); 821 if (activity != null && activity.shortComponentName != null) { 822 info.append(" (").append(activity.shortComponentName).append(")"); 823 } 824 info.append("\n"); 825 info.append("PID: ").append(app.pid).append("\n"); 826 if (annotation != null) { 827 info.append("Reason: ").append(annotation).append("\n"); 828 } 829 if (parent != null && parent != activity) { 830 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 831 } 832 833 final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true); 834 835 File tracesFile = mService.dumpStackTraces(true, firstPids, processCpuTracker, lastPids, 836 NATIVE_STACKS_OF_INTEREST); 837 838 String cpuInfo = null; 839 if (ActivityManagerService.MONITOR_CPU_USAGE) { 840 mService.updateCpuStatsNow(); 841 synchronized (mService.mProcessCpuTracker) { 842 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime); 843 } 844 info.append(processCpuTracker.printCurrentLoad()); 845 info.append(cpuInfo); 846 } 847 848 info.append(processCpuTracker.printCurrentState(anrTime)); 849 850 Slog.e(TAG, info.toString()); 851 if (tracesFile == null) { 852 // There is no trace file, so dump (only) the alleged culprit's threads to the log 853 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 854 } 855 856 mService.addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 857 cpuInfo, tracesFile, null); 858 859 if (mService.mController != null) { 860 try { 861 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 862 int res = mService.mController.appNotResponding( 863 app.processName, app.pid, info.toString()); 864 if (res != 0) { 865 if (res < 0 && app.pid != MY_PID) { 866 app.kill("anr", true); 867 } else { 868 synchronized (mService) { 869 mService.mServices.scheduleServiceTimeoutLocked(app); 870 } 871 } 872 return; 873 } 874 } catch (RemoteException e) { 875 mService.mController = null; 876 Watchdog.getInstance().setActivityController(null); 877 } 878 } 879 880 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 881 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 882 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 883 884 synchronized (mService) { 885 mService.mBatteryStatsService.noteProcessAnr(app.processName, app.uid); 886 887 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 888 app.kill("bg anr", true); 889 return; 890 } 891 892 // Set the app's notResponding state, and look up the errorReportReceiver 893 makeAppNotRespondingLocked(app, 894 activity != null ? activity.shortComponentName : null, 895 annotation != null ? "ANR " + annotation : "ANR", 896 info.toString()); 897 898 // Bring up the infamous App Not Responding dialog 899 Message msg = Message.obtain(); 900 HashMap<String, Object> map = new HashMap<String, Object>(); 901 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG; 902 msg.obj = map; 903 msg.arg1 = aboveSystem ? 1 : 0; 904 map.put("app", app); 905 if (activity != null) { 906 map.put("activity", activity); 907 } 908 909 mService.mUiHandler.sendMessage(msg); 910 } 911 } 912 913 private void makeAppNotRespondingLocked(ProcessRecord app, 914 String activity, String shortMsg, String longMsg) { 915 app.notResponding = true; 916 app.notRespondingReport = generateProcessError(app, 917 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 918 activity, shortMsg, longMsg, null); 919 startAppProblemLocked(app); 920 app.stopFreezingAllLocked(); 921 } 922 923 void handleShowAnrUi(Message msg) { 924 synchronized (mService) { 925 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 926 ProcessRecord proc = (ProcessRecord)data.get("app"); 927 if (proc != null && proc.anrDialog != null) { 928 Slog.e(TAG, "App already has anr dialog: " + proc); 929 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR, 930 AppNotRespondingDialog.ALREADY_SHOWING); 931 return; 932 } 933 934 Intent intent = new Intent("android.intent.action.ANR"); 935 if (!mService.mProcessesReady) { 936 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 937 | Intent.FLAG_RECEIVER_FOREGROUND); 938 } 939 mService.broadcastIntentLocked(null, null, intent, 940 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 941 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 942 943 if (mService.canShowErrorDialogs()) { 944 Dialog d = new AppNotRespondingDialog(mService, 945 mContext, proc, (ActivityRecord)data.get("activity"), 946 msg.arg1 != 0); 947 d.show(); 948 proc.anrDialog = d; 949 } else { 950 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR, 951 AppNotRespondingDialog.CANT_SHOW); 952 // Just kill the app if there is no dialog to be shown. 953 mService.killAppAtUsersRequest(proc, null); 954 } 955 } 956 } 957 958 /** 959 * Information about a process that is currently marked as bad. 960 */ 961 static final class BadProcessInfo { 962 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) { 963 this.time = time; 964 this.shortMsg = shortMsg; 965 this.longMsg = longMsg; 966 this.stack = stack; 967 } 968 969 final long time; 970 final String shortMsg; 971 final String longMsg; 972 final String stack; 973 } 974 975} 976