1 /* 2 * Copyright (C) 2006-2008 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 17 package com.android.server.am; 18 19 import com.android.internal.R; 20 import com.android.internal.os.BatteryStatsImpl; 21 import com.android.internal.os.ProcessStats; 22 import com.android.server.AttributeCache; 23 import com.android.server.IntentResolver; 24 import com.android.server.ProcessMap; 25 import com.android.server.SystemServer; 26 import com.android.server.Watchdog; 27 import com.android.server.am.ActivityStack.ActivityState; 28 import com.android.server.wm.WindowManagerService; 29 30 import dalvik.system.Zygote; 31 32 import android.app.Activity; 33 import android.app.ActivityManager; 34 import android.app.ActivityManagerNative; 35 import android.app.ActivityThread; 36 import android.app.AlertDialog; 37 import android.app.AppGlobals; 38 import android.app.ApplicationErrorReport; 39 import android.app.Dialog; 40 import android.app.IActivityController; 41 import android.app.IActivityWatcher; 42 import android.app.IApplicationThread; 43 import android.app.IInstrumentationWatcher; 44 import android.app.INotificationManager; 45 import android.app.IProcessObserver; 46 import android.app.IServiceConnection; 47 import android.app.IThumbnailReceiver; 48 import android.app.Instrumentation; 49 import android.app.Notification; 50 import android.app.NotificationManager; 51 import android.app.PendingIntent; 52 import android.app.Service; 53 import android.app.backup.IBackupManager; 54 import android.content.ActivityNotFoundException; 55 import android.content.BroadcastReceiver; 56 import android.content.ComponentCallbacks2; 57 import android.content.ComponentName; 58 import android.content.ContentResolver; 59 import android.content.Context; 60 import android.content.DialogInterface; 61 import android.content.Intent; 62 import android.content.IntentFilter; 63 import android.content.IIntentReceiver; 64 import android.content.IIntentSender; 65 import android.content.IntentSender; 66 import android.content.pm.ActivityInfo; 67 import android.content.pm.ApplicationInfo; 68 import android.content.pm.ConfigurationInfo; 69 import android.content.pm.IPackageDataObserver; 70 import android.content.pm.IPackageManager; 71 import android.content.pm.InstrumentationInfo; 72 import android.content.pm.PackageInfo; 73 import android.content.pm.PackageManager; 74 import android.content.pm.PathPermission; 75 import android.content.pm.ProviderInfo; 76 import android.content.pm.ResolveInfo; 77 import android.content.pm.ServiceInfo; 78 import android.content.pm.PackageManager.NameNotFoundException; 79 import android.content.res.CompatibilityInfo; 80 import android.content.res.Configuration; 81 import android.graphics.Bitmap; 82 import android.net.Proxy; 83 import android.net.ProxyProperties; 84 import android.net.Uri; 85 import android.os.Binder; 86 import android.os.Build; 87 import android.os.Bundle; 88 import android.os.Debug; 89 import android.os.DropBoxManager; 90 import android.os.Environment; 91 import android.os.FileObserver; 92 import android.os.FileUtils; 93 import android.os.Handler; 94 import android.os.IBinder; 95 import android.os.IPermissionController; 96 import android.os.Looper; 97 import android.os.Message; 98 import android.os.Parcel; 99 import android.os.ParcelFileDescriptor; 100 import android.os.Process; 101 import android.os.RemoteCallbackList; 102 import android.os.RemoteException; 103 import android.os.ServiceManager; 104 import android.os.StrictMode; 105 import android.os.SystemClock; 106 import android.os.SystemProperties; 107 import android.provider.Settings; 108 import android.util.EventLog; 109 import android.util.Pair; 110 import android.util.Slog; 111 import android.util.Log; 112 import android.util.PrintWriterPrinter; 113 import android.util.SparseArray; 114 import android.util.TimeUtils; 115 import android.view.Gravity; 116 import android.view.LayoutInflater; 117 import android.view.View; 118 import android.view.WindowManager; 119 import android.view.WindowManagerPolicy; 120 121 import java.io.BufferedInputStream; 122 import java.io.BufferedOutputStream; 123 import java.io.BufferedReader; 124 import java.io.DataInputStream; 125 import java.io.DataOutputStream; 126 import java.io.File; 127 import java.io.FileDescriptor; 128 import java.io.FileInputStream; 129 import java.io.FileNotFoundException; 130 import java.io.FileOutputStream; 131 import java.io.IOException; 132 import java.io.InputStreamReader; 133 import java.io.PrintWriter; 134 import java.io.StringWriter; 135 import java.lang.IllegalStateException; 136 import java.lang.ref.WeakReference; 137 import java.util.ArrayList; 138 import java.util.Collections; 139 import java.util.Comparator; 140 import java.util.HashMap; 141 import java.util.HashSet; 142 import java.util.Iterator; 143 import java.util.List; 144 import java.util.Locale; 145 import java.util.Map; 146 import java.util.Set; 147 import java.util.concurrent.atomic.AtomicBoolean; 148 import java.util.concurrent.atomic.AtomicLong; 149 150 public final class ActivityManagerService extends ActivityManagerNative 151 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 152 static final String TAG = "ActivityManager"; 153 static final boolean DEBUG = false; 154 static final boolean localLOGV = DEBUG; 155 static final boolean DEBUG_SWITCH = localLOGV || false; 156 static final boolean DEBUG_TASKS = localLOGV || false; 157 static final boolean DEBUG_PAUSE = localLOGV || false; 158 static final boolean DEBUG_OOM_ADJ = localLOGV || false; 159 static final boolean DEBUG_TRANSITION = localLOGV || false; 160 static final boolean DEBUG_BROADCAST = localLOGV || false; 161 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false; 162 static final boolean DEBUG_SERVICE = localLOGV || false; 163 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false; 164 static final boolean DEBUG_VISBILITY = localLOGV || false; 165 static final boolean DEBUG_PROCESSES = localLOGV || false; 166 static final boolean DEBUG_PROVIDER = localLOGV || false; 167 static final boolean DEBUG_URI_PERMISSION = localLOGV || false; 168 static final boolean DEBUG_USER_LEAVING = localLOGV || false; 169 static final boolean DEBUG_RESULTS = localLOGV || false; 170 static final boolean DEBUG_BACKUP = localLOGV || false; 171 static final boolean DEBUG_CONFIGURATION = localLOGV || false; 172 static final boolean DEBUG_POWER = localLOGV || false; 173 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false; 174 static final boolean VALIDATE_TOKENS = false; 175 static final boolean SHOW_ACTIVITY_START_TIME = true; 176 177 // Control over CPU and battery monitoring. 178 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes. 179 static final boolean MONITOR_CPU_USAGE = true; 180 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds. 181 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample. 182 static final boolean MONITOR_THREAD_CPU_USAGE = false; 183 184 // The flags that are set for all calls we make to the package manager. 185 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 186 187 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 188 189 // Maximum number of recent tasks that we can remember. 190 static final int MAX_RECENT_TASKS = 20; 191 192 // Amount of time after a call to stopAppSwitches() during which we will 193 // prevent further untrusted switches from happening. 194 static final long APP_SWITCH_DELAY_TIME = 5*1000; 195 196 // How long we wait for a launched process to attach to the activity manager 197 // before we decide it's never going to come up for real. 198 static final int PROC_START_TIMEOUT = 10*1000; 199 200 // How long we wait for a launched process to attach to the activity manager 201 // before we decide it's never going to come up for real, when the process was 202 // started with a wrapper for instrumentation (such as Valgrind) because it 203 // could take much longer than usual. 204 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000; 205 206 // How long to wait after going idle before forcing apps to GC. 207 static final int GC_TIMEOUT = 5*1000; 208 209 // The minimum amount of time between successive GC requests for a process. 210 static final int GC_MIN_INTERVAL = 60*1000; 211 212 // The rate at which we check for apps using excessive power -- 15 mins. 213 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 214 215 // The minimum sample duration we will allow before deciding we have 216 // enough data on wake locks to start killing things. 217 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 218 219 // The minimum sample duration we will allow before deciding we have 220 // enough data on CPU usage to start killing things. 221 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 222 223 // How long we allow a receiver to run before giving up on it. 224 static final int BROADCAST_TIMEOUT = 10*1000; 225 226 // How long we wait for a service to finish executing. 227 static final int SERVICE_TIMEOUT = 20*1000; 228 229 // How long a service needs to be running until restarting its process 230 // is no longer considered to be a relaunch of the service. 231 static final int SERVICE_RESTART_DURATION = 5*1000; 232 233 // How long a service needs to be running until it will start back at 234 // SERVICE_RESTART_DURATION after being killed. 235 static final int SERVICE_RESET_RUN_DURATION = 60*1000; 236 237 // Multiplying factor to increase restart duration time by, for each time 238 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION. 239 static final int SERVICE_RESTART_DURATION_FACTOR = 4; 240 241 // The minimum amount of time between restarting services that we allow. 242 // That is, when multiple services are restarting, we won't allow each 243 // to restart less than this amount of time from the last one. 244 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000; 245 246 // Maximum amount of time for there to be no activity on a service before 247 // we consider it non-essential and allow its process to go on the 248 // LRU background list. 249 static final int MAX_SERVICE_INACTIVITY = 30*60*1000; 250 251 // How long we wait until we timeout on key dispatching. 252 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 253 254 // How long we wait until we timeout on key dispatching during instrumentation. 255 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 256 257 static final int MY_PID = Process.myPid(); 258 259 static final String[] EMPTY_STRING_ARRAY = new String[0]; 260 261 public ActivityStack mMainStack; 262 263 /** 264 * Description of a request to start a new activity, which has been held 265 * due to app switches being disabled. 266 */ 267 static class PendingActivityLaunch { 268 ActivityRecord r; 269 ActivityRecord sourceRecord; 270 Uri[] grantedUriPermissions; 271 int grantedMode; 272 boolean onlyIfNeeded; 273 } 274 275 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches 276 = new ArrayList<PendingActivityLaunch>(); 277 278 /** 279 * List of all active broadcasts that are to be executed immediately 280 * (without waiting for another broadcast to finish). Currently this only 281 * contains broadcasts to registered receivers, to avoid spinning up 282 * a bunch of processes to execute IntentReceiver components. 283 */ 284 final ArrayList<BroadcastRecord> mParallelBroadcasts 285 = new ArrayList<BroadcastRecord>(); 286 287 /** 288 * List of all active broadcasts that are to be executed one at a time. 289 * The object at the top of the list is the currently activity broadcasts; 290 * those after it are waiting for the top to finish.. 291 */ 292 final ArrayList<BroadcastRecord> mOrderedBroadcasts 293 = new ArrayList<BroadcastRecord>(); 294 295 /** 296 * Historical data of past broadcasts, for debugging. 297 */ 298 static final int MAX_BROADCAST_HISTORY = 25; 299 final BroadcastRecord[] mBroadcastHistory 300 = new BroadcastRecord[MAX_BROADCAST_HISTORY]; 301 302 /** 303 * Set when we current have a BROADCAST_INTENT_MSG in flight. 304 */ 305 boolean mBroadcastsScheduled = false; 306 307 /** 308 * Activity we have told the window manager to have key focus. 309 */ 310 ActivityRecord mFocusedActivity = null; 311 /** 312 * List of intents that were used to start the most recent tasks. 313 */ 314 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>(); 315 316 /** 317 * Process management. 318 */ 319 final ProcessList mProcessList = new ProcessList(); 320 321 /** 322 * All of the applications we currently have running organized by name. 323 * The keys are strings of the application package name (as 324 * returned by the package manager), and the keys are ApplicationRecord 325 * objects. 326 */ 327 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 328 329 /** 330 * The currently running heavy-weight process, if any. 331 */ 332 ProcessRecord mHeavyWeightProcess = null; 333 334 /** 335 * The last time that various processes have crashed. 336 */ 337 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 338 339 /** 340 * Set of applications that we consider to be bad, and will reject 341 * incoming broadcasts from (which the user has no control over). 342 * Processes are added to this set when they have crashed twice within 343 * a minimum amount of time; they are removed from it when they are 344 * later restarted (hopefully due to some user action). The value is the 345 * time it was added to the list. 346 */ 347 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>(); 348 349 /** 350 * All of the processes we currently have running organized by pid. 351 * The keys are the pid running the application. 352 * 353 * <p>NOTE: This object is protected by its own lock, NOT the global 354 * activity manager lock! 355 */ 356 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 357 358 /** 359 * All of the processes that have been forced to be foreground. The key 360 * is the pid of the caller who requested it (we hold a death 361 * link on it). 362 */ 363 abstract class ForegroundToken implements IBinder.DeathRecipient { 364 int pid; 365 IBinder token; 366 } 367 final SparseArray<ForegroundToken> mForegroundProcesses 368 = new SparseArray<ForegroundToken>(); 369 370 /** 371 * List of records for processes that someone had tried to start before the 372 * system was ready. We don't start them at that point, but ensure they 373 * are started by the time booting is complete. 374 */ 375 final ArrayList<ProcessRecord> mProcessesOnHold 376 = new ArrayList<ProcessRecord>(); 377 378 /** 379 * List of persistent applications that are in the process 380 * of being started. 381 */ 382 final ArrayList<ProcessRecord> mPersistentStartingProcesses 383 = new ArrayList<ProcessRecord>(); 384 385 /** 386 * Processes that are being forcibly torn down. 387 */ 388 final ArrayList<ProcessRecord> mRemovedProcesses 389 = new ArrayList<ProcessRecord>(); 390 391 /** 392 * List of running applications, sorted by recent usage. 393 * The first entry in the list is the least recently used. 394 * It contains ApplicationRecord objects. This list does NOT include 395 * any persistent application records (since we never want to exit them). 396 */ 397 final ArrayList<ProcessRecord> mLruProcesses 398 = new ArrayList<ProcessRecord>(); 399 400 /** 401 * List of processes that should gc as soon as things are idle. 402 */ 403 final ArrayList<ProcessRecord> mProcessesToGc 404 = new ArrayList<ProcessRecord>(); 405 406 /** 407 * This is the process holding what we currently consider to be 408 * the "home" activity. 409 */ 410 ProcessRecord mHomeProcess; 411 412 /** 413 * This is the process holding the activity the user last visited that 414 * is in a different process from the one they are currently in. 415 */ 416 ProcessRecord mPreviousProcess; 417 418 /** 419 * The time at which the previous process was last visible. 420 */ 421 long mPreviousProcessVisibleTime; 422 423 /** 424 * Packages that the user has asked to have run in screen size 425 * compatibility mode instead of filling the screen. 426 */ 427 final CompatModePackages mCompatModePackages; 428 429 /** 430 * Set of PendingResultRecord objects that are currently active. 431 */ 432 final HashSet mPendingResultRecords = new HashSet(); 433 434 /** 435 * Set of IntentSenderRecord objects that are currently active. 436 */ 437 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 438 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 439 440 /** 441 * Fingerprints (hashCode()) of stack traces that we've 442 * already logged DropBox entries for. Guarded by itself. If 443 * something (rogue user app) forces this over 444 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 445 */ 446 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 447 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 448 449 /** 450 * Strict Mode background batched logging state. 451 * 452 * The string buffer is guarded by itself, and its lock is also 453 * used to determine if another batched write is already 454 * in-flight. 455 */ 456 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 457 458 /** 459 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler. 460 */ 461 private boolean mPendingBroadcastTimeoutMessage; 462 463 /** 464 * Intent broadcast that we have tried to start, but are 465 * waiting for its application's process to be created. We only 466 * need one (instead of a list) because we always process broadcasts 467 * one at a time, so no others can be started while waiting for this 468 * one. 469 */ 470 BroadcastRecord mPendingBroadcast = null; 471 472 /** 473 * The receiver index that is pending, to restart the broadcast if needed. 474 */ 475 int mPendingBroadcastRecvIndex; 476 477 /** 478 * Keeps track of all IIntentReceivers that have been registered for 479 * broadcasts. Hash keys are the receiver IBinder, hash value is 480 * a ReceiverList. 481 */ 482 final HashMap mRegisteredReceivers = new HashMap(); 483 484 /** 485 * Resolver for broadcast intents to registered receivers. 486 * Holds BroadcastFilter (subclass of IntentFilter). 487 */ 488 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 489 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 490 @Override 491 protected boolean allowFilterResult( 492 BroadcastFilter filter, List<BroadcastFilter> dest) { 493 IBinder target = filter.receiverList.receiver.asBinder(); 494 for (int i=dest.size()-1; i>=0; i--) { 495 if (dest.get(i).receiverList.receiver.asBinder() == target) { 496 return false; 497 } 498 } 499 return true; 500 } 501 502 @Override 503 protected String packageForFilter(BroadcastFilter filter) { 504 return filter.packageName; 505 } 506 }; 507 508 /** 509 * State of all active sticky broadcasts. Keys are the action of the 510 * sticky Intent, values are an ArrayList of all broadcasted intents with 511 * that action (which should usually be one). 512 */ 513 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts = 514 new HashMap<String, ArrayList<Intent>>(); 515 516 /** 517 * All currently running services. 518 */ 519 final HashMap<ComponentName, ServiceRecord> mServices = 520 new HashMap<ComponentName, ServiceRecord>(); 521 522 /** 523 * All currently running services indexed by the Intent used to start them. 524 */ 525 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = 526 new HashMap<Intent.FilterComparison, ServiceRecord>(); 527 528 /** 529 * All currently bound service connections. Keys are the IBinder of 530 * the client's IServiceConnection. 531 */ 532 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections 533 = new HashMap<IBinder, ArrayList<ConnectionRecord>>(); 534 535 /** 536 * List of services that we have been asked to start, 537 * but haven't yet been able to. It is used to hold start requests 538 * while waiting for their corresponding application thread to get 539 * going. 540 */ 541 final ArrayList<ServiceRecord> mPendingServices 542 = new ArrayList<ServiceRecord>(); 543 544 /** 545 * List of services that are scheduled to restart following a crash. 546 */ 547 final ArrayList<ServiceRecord> mRestartingServices 548 = new ArrayList<ServiceRecord>(); 549 550 /** 551 * List of services that are in the process of being stopped. 552 */ 553 final ArrayList<ServiceRecord> mStoppingServices 554 = new ArrayList<ServiceRecord>(); 555 556 /** 557 * Backup/restore process management 558 */ 559 String mBackupAppName = null; 560 BackupRecord mBackupTarget = null; 561 562 /** 563 * List of PendingThumbnailsRecord objects of clients who are still 564 * waiting to receive all of the thumbnails for a task. 565 */ 566 final ArrayList mPendingThumbnails = new ArrayList(); 567 568 /** 569 * List of HistoryRecord objects that have been finished and must 570 * still report back to a pending thumbnail receiver. 571 */ 572 final ArrayList mCancelledThumbnails = new ArrayList(); 573 574 /** 575 * All of the currently running global content providers. Keys are a 576 * string containing the provider name and values are a 577 * ContentProviderRecord object containing the data about it. Note 578 * that a single provider may be published under multiple names, so 579 * there may be multiple entries here for a single one in mProvidersByClass. 580 */ 581 final HashMap<String, ContentProviderRecord> mProvidersByName 582 = new HashMap<String, ContentProviderRecord>(); 583 584 /** 585 * All of the currently running global content providers. Keys are a 586 * string containing the provider's implementation class and values are a 587 * ContentProviderRecord object containing the data about it. 588 */ 589 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass 590 = new HashMap<ComponentName, ContentProviderRecord>(); 591 592 /** 593 * List of content providers who have clients waiting for them. The 594 * application is currently being launched and the provider will be 595 * removed from this list once it is published. 596 */ 597 final ArrayList<ContentProviderRecord> mLaunchingProviders 598 = new ArrayList<ContentProviderRecord>(); 599 600 /** 601 * Global set of specific Uri permissions that have been granted. 602 */ 603 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions 604 = new SparseArray<HashMap<Uri, UriPermission>>(); 605 606 CoreSettingsObserver mCoreSettingsObserver; 607 608 /** 609 * Thread-local storage used to carry caller permissions over through 610 * indirect content-provider access. 611 * @see #ActivityManagerService.openContentUri() 612 */ 613 private class Identity { 614 public int pid; 615 public int uid; 616 617 Identity(int _pid, int _uid) { 618 pid = _pid; 619 uid = _uid; 620 } 621 } 622 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 623 624 /** 625 * All information we have collected about the runtime performance of 626 * any user id that can impact battery performance. 627 */ 628 final BatteryStatsService mBatteryStatsService; 629 630 /** 631 * information about component usage 632 */ 633 final UsageStatsService mUsageStatsService; 634 635 /** 636 * Current configuration information. HistoryRecord objects are given 637 * a reference to this object to indicate which configuration they are 638 * currently running in, so this object must be kept immutable. 639 */ 640 Configuration mConfiguration = new Configuration(); 641 642 /** 643 * Current sequencing integer of the configuration, for skipping old 644 * configurations. 645 */ 646 int mConfigurationSeq = 0; 647 648 /** 649 * Hardware-reported OpenGLES version. 650 */ 651 final int GL_ES_VERSION; 652 653 /** 654 * List of initialization arguments to pass to all processes when binding applications to them. 655 * For example, references to the commonly used services. 656 */ 657 HashMap<String, IBinder> mAppBindArgs; 658 659 /** 660 * Temporary to avoid allocations. Protected by main lock. 661 */ 662 final StringBuilder mStringBuilder = new StringBuilder(256); 663 664 /** 665 * Used to control how we initialize the service. 666 */ 667 boolean mStartRunning = false; 668 ComponentName mTopComponent; 669 String mTopAction; 670 String mTopData; 671 boolean mProcessesReady = false; 672 boolean mSystemReady = false; 673 boolean mBooting = false; 674 boolean mWaitingUpdate = false; 675 boolean mDidUpdate = false; 676 boolean mOnBattery = false; 677 boolean mLaunchWarningShown = false; 678 679 Context mContext; 680 681 int mFactoryTest; 682 683 boolean mCheckedForSetup; 684 685 /** 686 * The time at which we will allow normal application switches again, 687 * after a call to {@link #stopAppSwitches()}. 688 */ 689 long mAppSwitchesAllowedTime; 690 691 /** 692 * This is set to true after the first switch after mAppSwitchesAllowedTime 693 * is set; any switches after that will clear the time. 694 */ 695 boolean mDidAppSwitch; 696 697 /** 698 * Last time (in realtime) at which we checked for power usage. 699 */ 700 long mLastPowerCheckRealtime; 701 702 /** 703 * Last time (in uptime) at which we checked for power usage. 704 */ 705 long mLastPowerCheckUptime; 706 707 /** 708 * Set while we are wanting to sleep, to prevent any 709 * activities from being started/resumed. 710 */ 711 boolean mSleeping = false; 712 713 /** 714 * Set if we are shutting down the system, similar to sleeping. 715 */ 716 boolean mShuttingDown = false; 717 718 /** 719 * Task identifier that activities are currently being started 720 * in. Incremented each time a new task is created. 721 * todo: Replace this with a TokenSpace class that generates non-repeating 722 * integers that won't wrap. 723 */ 724 int mCurTask = 1; 725 726 /** 727 * Current sequence id for oom_adj computation traversal. 728 */ 729 int mAdjSeq = 0; 730 731 /** 732 * Current sequence id for process LRU updating. 733 */ 734 int mLruSeq = 0; 735 736 /** 737 * Keep track of the number of service processes we last found, to 738 * determine on the next iteration which should be B services. 739 */ 740 int mNumServiceProcs = 0; 741 int mNewNumServiceProcs = 0; 742 743 /** 744 * System monitoring: number of processes that died since the last 745 * N procs were started. 746 */ 747 int[] mProcDeaths = new int[20]; 748 749 /** 750 * This is set if we had to do a delayed dexopt of an app before launching 751 * it, to increasing the ANR timeouts in that case. 752 */ 753 boolean mDidDexOpt; 754 755 String mDebugApp = null; 756 boolean mWaitForDebugger = false; 757 boolean mDebugTransient = false; 758 String mOrigDebugApp = null; 759 boolean mOrigWaitForDebugger = false; 760 boolean mAlwaysFinishActivities = false; 761 IActivityController mController = null; 762 String mProfileApp = null; 763 ProcessRecord mProfileProc = null; 764 String mProfileFile; 765 ParcelFileDescriptor mProfileFd; 766 int mProfileType = 0; 767 boolean mAutoStopProfiler = false; 768 769 final RemoteCallbackList<IActivityWatcher> mWatchers 770 = new RemoteCallbackList<IActivityWatcher>(); 771 772 final RemoteCallbackList<IProcessObserver> mProcessObservers 773 = new RemoteCallbackList<IProcessObserver>(); 774 775 /** 776 * Callback of last caller to {@link #requestPss}. 777 */ 778 Runnable mRequestPssCallback; 779 780 /** 781 * Remaining processes for which we are waiting results from the last 782 * call to {@link #requestPss}. 783 */ 784 final ArrayList<ProcessRecord> mRequestPssList 785 = new ArrayList<ProcessRecord>(); 786 787 /** 788 * Runtime statistics collection thread. This object's lock is used to 789 * protect all related state. 790 */ 791 final Thread mProcessStatsThread; 792 793 /** 794 * Used to collect process stats when showing not responding dialog. 795 * Protected by mProcessStatsThread. 796 */ 797 final ProcessStats mProcessStats = new ProcessStats( 798 MONITOR_THREAD_CPU_USAGE); 799 final AtomicLong mLastCpuTime = new AtomicLong(0); 800 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true); 801 802 long mLastWriteTime = 0; 803 804 /** 805 * Set to true after the system has finished booting. 806 */ 807 boolean mBooted = false; 808 809 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS; 810 int mProcessLimitOverride = -1; 811 812 WindowManagerService mWindowManager; 813 814 static ActivityManagerService mSelf; 815 static ActivityThread mSystemThread; 816 817 private final class AppDeathRecipient implements IBinder.DeathRecipient { 818 final ProcessRecord mApp; 819 final int mPid; 820 final IApplicationThread mAppThread; 821 822 AppDeathRecipient(ProcessRecord app, int pid, 823 IApplicationThread thread) { 824 if (localLOGV) Slog.v( 825 TAG, "New death recipient " + this 826 + " for thread " + thread.asBinder()); 827 mApp = app; 828 mPid = pid; 829 mAppThread = thread; 830 } 831 832 public void binderDied() { 833 if (localLOGV) Slog.v( 834 TAG, "Death received in " + this 835 + " for thread " + mAppThread.asBinder()); 836 synchronized(ActivityManagerService.this) { 837 appDiedLocked(mApp, mPid, mAppThread); 838 } 839 } 840 } 841 842 static final int SHOW_ERROR_MSG = 1; 843 static final int SHOW_NOT_RESPONDING_MSG = 2; 844 static final int SHOW_FACTORY_ERROR_MSG = 3; 845 static final int UPDATE_CONFIGURATION_MSG = 4; 846 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 847 static final int WAIT_FOR_DEBUGGER_MSG = 6; 848 static final int BROADCAST_INTENT_MSG = 7; 849 static final int BROADCAST_TIMEOUT_MSG = 8; 850 static final int SERVICE_TIMEOUT_MSG = 12; 851 static final int UPDATE_TIME_ZONE = 13; 852 static final int SHOW_UID_ERROR_MSG = 14; 853 static final int IM_FEELING_LUCKY_MSG = 15; 854 static final int PROC_START_TIMEOUT_MSG = 20; 855 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 856 static final int KILL_APPLICATION_MSG = 22; 857 static final int FINALIZE_PENDING_INTENT_MSG = 23; 858 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 859 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 860 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 861 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 862 static final int CLEAR_DNS_CACHE = 28; 863 static final int UPDATE_HTTP_PROXY = 29; 864 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 865 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31; 866 static final int DISPATCH_PROCESS_DIED = 32; 867 static final int REPORT_MEM_USAGE = 33; 868 869 AlertDialog mUidAlert; 870 CompatModeDialog mCompatModeDialog; 871 long mLastMemUsageReportTime = 0; 872 873 final Handler mHandler = new Handler() { 874 //public Handler() { 875 // if (localLOGV) Slog.v(TAG, "Handler started!"); 876 //} 877 878 public void handleMessage(Message msg) { 879 switch (msg.what) { 880 case SHOW_ERROR_MSG: { 881 HashMap data = (HashMap) msg.obj; 882 synchronized (ActivityManagerService.this) { 883 ProcessRecord proc = (ProcessRecord)data.get("app"); 884 if (proc != null && proc.crashDialog != null) { 885 Slog.e(TAG, "App already has crash dialog: " + proc); 886 return; 887 } 888 AppErrorResult res = (AppErrorResult) data.get("result"); 889 if (!mSleeping && !mShuttingDown) { 890 Dialog d = new AppErrorDialog(mContext, res, proc); 891 d.show(); 892 proc.crashDialog = d; 893 } else { 894 // The device is asleep, so just pretend that the user 895 // saw a crash dialog and hit "force quit". 896 res.set(0); 897 } 898 } 899 900 ensureBootCompleted(); 901 } break; 902 case SHOW_NOT_RESPONDING_MSG: { 903 synchronized (ActivityManagerService.this) { 904 HashMap data = (HashMap) msg.obj; 905 ProcessRecord proc = (ProcessRecord)data.get("app"); 906 if (proc != null && proc.anrDialog != null) { 907 Slog.e(TAG, "App already has anr dialog: " + proc); 908 return; 909 } 910 911 Intent intent = new Intent("android.intent.action.ANR"); 912 if (!mProcessesReady) { 913 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 914 } 915 broadcastIntentLocked(null, null, intent, 916 null, null, 0, null, null, null, 917 false, false, MY_PID, Process.SYSTEM_UID); 918 919 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 920 mContext, proc, (ActivityRecord)data.get("activity")); 921 d.show(); 922 proc.anrDialog = d; 923 } 924 925 ensureBootCompleted(); 926 } break; 927 case SHOW_STRICT_MODE_VIOLATION_MSG: { 928 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 929 synchronized (ActivityManagerService.this) { 930 ProcessRecord proc = (ProcessRecord) data.get("app"); 931 if (proc == null) { 932 Slog.e(TAG, "App not found when showing strict mode dialog."); 933 break; 934 } 935 if (proc.crashDialog != null) { 936 Slog.e(TAG, "App already has strict mode dialog: " + proc); 937 return; 938 } 939 AppErrorResult res = (AppErrorResult) data.get("result"); 940 if (!mSleeping && !mShuttingDown) { 941 Dialog d = new StrictModeViolationDialog(mContext, res, proc); 942 d.show(); 943 proc.crashDialog = d; 944 } else { 945 // The device is asleep, so just pretend that the user 946 // saw a crash dialog and hit "force quit". 947 res.set(0); 948 } 949 } 950 ensureBootCompleted(); 951 } break; 952 case SHOW_FACTORY_ERROR_MSG: { 953 Dialog d = new FactoryErrorDialog( 954 mContext, msg.getData().getCharSequence("msg")); 955 d.show(); 956 ensureBootCompleted(); 957 } break; 958 case UPDATE_CONFIGURATION_MSG: { 959 final ContentResolver resolver = mContext.getContentResolver(); 960 Settings.System.putConfiguration(resolver, (Configuration)msg.obj); 961 } break; 962 case GC_BACKGROUND_PROCESSES_MSG: { 963 synchronized (ActivityManagerService.this) { 964 performAppGcsIfAppropriateLocked(); 965 } 966 } break; 967 case WAIT_FOR_DEBUGGER_MSG: { 968 synchronized (ActivityManagerService.this) { 969 ProcessRecord app = (ProcessRecord)msg.obj; 970 if (msg.arg1 != 0) { 971 if (!app.waitedForDebugger) { 972 Dialog d = new AppWaitingForDebuggerDialog( 973 ActivityManagerService.this, 974 mContext, app); 975 app.waitDialog = d; 976 app.waitedForDebugger = true; 977 d.show(); 978 } 979 } else { 980 if (app.waitDialog != null) { 981 app.waitDialog.dismiss(); 982 app.waitDialog = null; 983 } 984 } 985 } 986 } break; 987 case BROADCAST_INTENT_MSG: { 988 if (DEBUG_BROADCAST) Slog.v( 989 TAG, "Received BROADCAST_INTENT_MSG"); 990 processNextBroadcast(true); 991 } break; 992 case BROADCAST_TIMEOUT_MSG: { 993 synchronized (ActivityManagerService.this) { 994 broadcastTimeoutLocked(true); 995 } 996 } break; 997 case SERVICE_TIMEOUT_MSG: { 998 if (mDidDexOpt) { 999 mDidDexOpt = false; 1000 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1001 nmsg.obj = msg.obj; 1002 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT); 1003 return; 1004 } 1005 serviceTimeout((ProcessRecord)msg.obj); 1006 } break; 1007 case UPDATE_TIME_ZONE: { 1008 synchronized (ActivityManagerService.this) { 1009 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1010 ProcessRecord r = mLruProcesses.get(i); 1011 if (r.thread != null) { 1012 try { 1013 r.thread.updateTimeZone(); 1014 } catch (RemoteException ex) { 1015 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1016 } 1017 } 1018 } 1019 } 1020 } break; 1021 case CLEAR_DNS_CACHE: { 1022 synchronized (ActivityManagerService.this) { 1023 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1024 ProcessRecord r = mLruProcesses.get(i); 1025 if (r.thread != null) { 1026 try { 1027 r.thread.clearDnsCache(); 1028 } catch (RemoteException ex) { 1029 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1030 } 1031 } 1032 } 1033 } 1034 } break; 1035 case UPDATE_HTTP_PROXY: { 1036 ProxyProperties proxy = (ProxyProperties)msg.obj; 1037 String host = ""; 1038 String port = ""; 1039 String exclList = ""; 1040 if (proxy != null) { 1041 host = proxy.getHost(); 1042 port = Integer.toString(proxy.getPort()); 1043 exclList = proxy.getExclusionList(); 1044 } 1045 synchronized (ActivityManagerService.this) { 1046 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1047 ProcessRecord r = mLruProcesses.get(i); 1048 if (r.thread != null) { 1049 try { 1050 r.thread.setHttpProxy(host, port, exclList); 1051 } catch (RemoteException ex) { 1052 Slog.w(TAG, "Failed to update http proxy for: " + 1053 r.info.processName); 1054 } 1055 } 1056 } 1057 } 1058 } break; 1059 case SHOW_UID_ERROR_MSG: { 1060 // XXX This is a temporary dialog, no need to localize. 1061 AlertDialog d = new BaseErrorDialog(mContext); 1062 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1063 d.setCancelable(false); 1064 d.setTitle("System UIDs Inconsistent"); 1065 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable."); 1066 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky", 1067 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG)); 1068 mUidAlert = d; 1069 d.show(); 1070 } break; 1071 case IM_FEELING_LUCKY_MSG: { 1072 if (mUidAlert != null) { 1073 mUidAlert.dismiss(); 1074 mUidAlert = null; 1075 } 1076 } break; 1077 case PROC_START_TIMEOUT_MSG: { 1078 if (mDidDexOpt) { 1079 mDidDexOpt = false; 1080 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1081 nmsg.obj = msg.obj; 1082 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1083 return; 1084 } 1085 ProcessRecord app = (ProcessRecord)msg.obj; 1086 synchronized (ActivityManagerService.this) { 1087 processStartTimedOutLocked(app); 1088 } 1089 } break; 1090 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1091 synchronized (ActivityManagerService.this) { 1092 doPendingActivityLaunchesLocked(true); 1093 } 1094 } break; 1095 case KILL_APPLICATION_MSG: { 1096 synchronized (ActivityManagerService.this) { 1097 int uid = msg.arg1; 1098 boolean restart = (msg.arg2 == 1); 1099 String pkg = (String) msg.obj; 1100 forceStopPackageLocked(pkg, uid, restart, false, true, false); 1101 } 1102 } break; 1103 case FINALIZE_PENDING_INTENT_MSG: { 1104 ((PendingIntentRecord)msg.obj).completeFinalize(); 1105 } break; 1106 case POST_HEAVY_NOTIFICATION_MSG: { 1107 INotificationManager inm = NotificationManager.getService(); 1108 if (inm == null) { 1109 return; 1110 } 1111 1112 ActivityRecord root = (ActivityRecord)msg.obj; 1113 ProcessRecord process = root.app; 1114 if (process == null) { 1115 return; 1116 } 1117 1118 try { 1119 Context context = mContext.createPackageContext(process.info.packageName, 0); 1120 String text = mContext.getString(R.string.heavy_weight_notification, 1121 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1122 Notification notification = new Notification(); 1123 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon; 1124 notification.when = 0; 1125 notification.flags = Notification.FLAG_ONGOING_EVENT; 1126 notification.tickerText = text; 1127 notification.defaults = 0; // please be quiet 1128 notification.sound = null; 1129 notification.vibrate = null; 1130 notification.setLatestEventInfo(context, text, 1131 mContext.getText(R.string.heavy_weight_notification_detail), 1132 PendingIntent.getActivity(mContext, 0, root.intent, 1133 PendingIntent.FLAG_CANCEL_CURRENT)); 1134 1135 try { 1136 int[] outId = new int[1]; 1137 inm.enqueueNotification("android", R.string.heavy_weight_notification, 1138 notification, outId); 1139 } catch (RuntimeException e) { 1140 Slog.w(ActivityManagerService.TAG, 1141 "Error showing notification for heavy-weight app", e); 1142 } catch (RemoteException e) { 1143 } 1144 } catch (NameNotFoundException e) { 1145 Slog.w(TAG, "Unable to create context for heavy notification", e); 1146 } 1147 } break; 1148 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1149 INotificationManager inm = NotificationManager.getService(); 1150 if (inm == null) { 1151 return; 1152 } 1153 try { 1154 inm.cancelNotification("android", 1155 R.string.heavy_weight_notification); 1156 } catch (RuntimeException e) { 1157 Slog.w(ActivityManagerService.TAG, 1158 "Error canceling notification for service", e); 1159 } catch (RemoteException e) { 1160 } 1161 } break; 1162 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1163 synchronized (ActivityManagerService.this) { 1164 checkExcessivePowerUsageLocked(true); 1165 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1166 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1167 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1168 } 1169 } break; 1170 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1171 synchronized (ActivityManagerService.this) { 1172 ActivityRecord ar = (ActivityRecord)msg.obj; 1173 if (mCompatModeDialog != null) { 1174 if (mCompatModeDialog.mAppInfo.packageName.equals( 1175 ar.info.applicationInfo.packageName)) { 1176 return; 1177 } 1178 mCompatModeDialog.dismiss(); 1179 mCompatModeDialog = null; 1180 } 1181 if (ar != null && false) { 1182 if (mCompatModePackages.getPackageAskCompatModeLocked( 1183 ar.packageName)) { 1184 int mode = mCompatModePackages.computeCompatModeLocked( 1185 ar.info.applicationInfo); 1186 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1187 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1188 mCompatModeDialog = new CompatModeDialog( 1189 ActivityManagerService.this, mContext, 1190 ar.info.applicationInfo); 1191 mCompatModeDialog.show(); 1192 } 1193 } 1194 } 1195 } 1196 break; 1197 } 1198 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: { 1199 final int pid = msg.arg1; 1200 final int uid = msg.arg2; 1201 final boolean foregroundActivities = (Boolean) msg.obj; 1202 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities); 1203 break; 1204 } 1205 case DISPATCH_PROCESS_DIED: { 1206 final int pid = msg.arg1; 1207 final int uid = msg.arg2; 1208 dispatchProcessDied(pid, uid); 1209 break; 1210 } 1211 case REPORT_MEM_USAGE: { 1212 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 1213 if (!isDebuggable) { 1214 return; 1215 } 1216 synchronized (ActivityManagerService.this) { 1217 long now = SystemClock.uptimeMillis(); 1218 if (now < (mLastMemUsageReportTime+5*60*1000)) { 1219 // Don't report more than every 5 minutes to somewhat 1220 // avoid spamming. 1221 return; 1222 } 1223 mLastMemUsageReportTime = now; 1224 } 1225 Thread thread = new Thread() { 1226 @Override public void run() { 1227 StringBuilder dropBuilder = new StringBuilder(1024); 1228 StringBuilder logBuilder = new StringBuilder(1024); 1229 StringWriter oomSw = new StringWriter(); 1230 PrintWriter oomPw = new PrintWriter(oomSw); 1231 StringWriter catSw = new StringWriter(); 1232 PrintWriter catPw = new PrintWriter(catSw); 1233 String[] emptyArgs = new String[] { }; 1234 StringBuilder tag = new StringBuilder(128); 1235 StringBuilder stack = new StringBuilder(128); 1236 tag.append("Low on memory -- "); 1237 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw, 1238 tag, stack); 1239 dropBuilder.append(stack); 1240 dropBuilder.append('\n'); 1241 dropBuilder.append('\n'); 1242 String oomString = oomSw.toString(); 1243 dropBuilder.append(oomString); 1244 dropBuilder.append('\n'); 1245 logBuilder.append(oomString); 1246 try { 1247 java.lang.Process proc = Runtime.getRuntime().exec(new String[] { 1248 "procrank", }); 1249 final InputStreamReader converter = new InputStreamReader( 1250 proc.getInputStream()); 1251 BufferedReader in = new BufferedReader(converter); 1252 String line; 1253 while (true) { 1254 line = in.readLine(); 1255 if (line == null) { 1256 break; 1257 } 1258 if (line.length() > 0) { 1259 logBuilder.append(line); 1260 logBuilder.append('\n'); 1261 } 1262 dropBuilder.append(line); 1263 dropBuilder.append('\n'); 1264 } 1265 converter.close(); 1266 } catch (IOException e) { 1267 } 1268 synchronized (ActivityManagerService.this) { 1269 catPw.println(); 1270 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 1271 catPw.println(); 1272 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null); 1273 catPw.println(); 1274 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 1275 } 1276 dropBuilder.append(catSw.toString()); 1277 addErrorToDropBox("lowmem", null, "system_server", null, 1278 null, tag.toString(), dropBuilder.toString(), null, null); 1279 Slog.i(TAG, logBuilder.toString()); 1280 synchronized (ActivityManagerService.this) { 1281 long now = SystemClock.uptimeMillis(); 1282 if (mLastMemUsageReportTime < now) { 1283 mLastMemUsageReportTime = now; 1284 } 1285 } 1286 } 1287 }; 1288 thread.start(); 1289 break; 1290 } 1291 } 1292 } 1293 }; 1294 1295 public static void setSystemProcess() { 1296 try { 1297 ActivityManagerService m = mSelf; 1298 1299 ServiceManager.addService("activity", m); 1300 ServiceManager.addService("meminfo", new MemBinder(m)); 1301 ServiceManager.addService("gfxinfo", new GraphicsBinder(m)); 1302 if (MONITOR_CPU_USAGE) { 1303 ServiceManager.addService("cpuinfo", new CpuBinder(m)); 1304 } 1305 ServiceManager.addService("permission", new PermissionController(m)); 1306 1307 ApplicationInfo info = 1308 mSelf.mContext.getPackageManager().getApplicationInfo( 1309 "android", STOCK_PM_FLAGS); 1310 mSystemThread.installSystemApplicationInfo(info); 1311 1312 synchronized (mSelf) { 1313 ProcessRecord app = mSelf.newProcessRecordLocked( 1314 mSystemThread.getApplicationThread(), info, 1315 info.processName); 1316 app.persistent = true; 1317 app.pid = MY_PID; 1318 app.maxAdj = ProcessList.SYSTEM_ADJ; 1319 mSelf.mProcessNames.put(app.processName, app.info.uid, app); 1320 synchronized (mSelf.mPidsSelfLocked) { 1321 mSelf.mPidsSelfLocked.put(app.pid, app); 1322 } 1323 mSelf.updateLruProcessLocked(app, true, true); 1324 } 1325 } catch (PackageManager.NameNotFoundException e) { 1326 throw new RuntimeException( 1327 "Unable to find android system package", e); 1328 } 1329 } 1330 1331 public void setWindowManager(WindowManagerService wm) { 1332 mWindowManager = wm; 1333 } 1334 1335 public static final Context main(int factoryTest) { 1336 AThread thr = new AThread(); 1337 thr.start(); 1338 1339 synchronized (thr) { 1340 while (thr.mService == null) { 1341 try { 1342 thr.wait(); 1343 } catch (InterruptedException e) { 1344 } 1345 } 1346 } 1347 1348 ActivityManagerService m = thr.mService; 1349 mSelf = m; 1350 ActivityThread at = ActivityThread.systemMain(); 1351 mSystemThread = at; 1352 Context context = at.getSystemContext(); 1353 context.setTheme(android.R.style.Theme_Holo); 1354 m.mContext = context; 1355 m.mFactoryTest = factoryTest; 1356 m.mMainStack = new ActivityStack(m, context, true); 1357 1358 m.mBatteryStatsService.publish(context); 1359 m.mUsageStatsService.publish(context); 1360 1361 synchronized (thr) { 1362 thr.mReady = true; 1363 thr.notifyAll(); 1364 } 1365 1366 m.startRunning(null, null, null, null); 1367 1368 return context; 1369 } 1370 1371 public static ActivityManagerService self() { 1372 return mSelf; 1373 } 1374 1375 static class AThread extends Thread { 1376 ActivityManagerService mService; 1377 boolean mReady = false; 1378 1379 public AThread() { 1380 super("ActivityManager"); 1381 } 1382 1383 public void run() { 1384 Looper.prepare(); 1385 1386 android.os.Process.setThreadPriority( 1387 android.os.Process.THREAD_PRIORITY_FOREGROUND); 1388 android.os.Process.setCanSelfBackground(false); 1389 1390 ActivityManagerService m = new ActivityManagerService(); 1391 1392 synchronized (this) { 1393 mService = m; 1394 notifyAll(); 1395 } 1396 1397 synchronized (this) { 1398 while (!mReady) { 1399 try { 1400 wait(); 1401 } catch (InterruptedException e) { 1402 } 1403 } 1404 } 1405 1406 // For debug builds, log event loop stalls to dropbox for analysis. 1407 if (StrictMode.conditionallyEnableDebugLogging()) { 1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper"); 1409 } 1410 1411 Looper.loop(); 1412 } 1413 } 1414 1415 static class MemBinder extends Binder { 1416 ActivityManagerService mActivityManagerService; 1417 MemBinder(ActivityManagerService activityManagerService) { 1418 mActivityManagerService = activityManagerService; 1419 } 1420 1421 @Override 1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1424 != PackageManager.PERMISSION_GRANTED) { 1425 pw.println("Permission Denial: can't dump meminfo from from pid=" 1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1427 + " without permission " + android.Manifest.permission.DUMP); 1428 return; 1429 } 1430 1431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, 1432 false, null, null, null); 1433 } 1434 } 1435 1436 static class GraphicsBinder extends Binder { 1437 ActivityManagerService mActivityManagerService; 1438 GraphicsBinder(ActivityManagerService activityManagerService) { 1439 mActivityManagerService = activityManagerService; 1440 } 1441 1442 @Override 1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1445 != PackageManager.PERMISSION_GRANTED) { 1446 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1448 + " without permission " + android.Manifest.permission.DUMP); 1449 return; 1450 } 1451 1452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 1453 } 1454 } 1455 1456 static class CpuBinder extends Binder { 1457 ActivityManagerService mActivityManagerService; 1458 CpuBinder(ActivityManagerService activityManagerService) { 1459 mActivityManagerService = activityManagerService; 1460 } 1461 1462 @Override 1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1465 != PackageManager.PERMISSION_GRANTED) { 1466 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1468 + " without permission " + android.Manifest.permission.DUMP); 1469 return; 1470 } 1471 1472 synchronized (mActivityManagerService.mProcessStatsThread) { 1473 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad()); 1474 pw.print(mActivityManagerService.mProcessStats.printCurrentState( 1475 SystemClock.uptimeMillis())); 1476 } 1477 } 1478 } 1479 1480 private ActivityManagerService() { 1481 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 1482 1483 File dataDir = Environment.getDataDirectory(); 1484 File systemDir = new File(dataDir, "system"); 1485 systemDir.mkdirs(); 1486 mBatteryStatsService = new BatteryStatsService(new File( 1487 systemDir, "batterystats.bin").toString()); 1488 mBatteryStatsService.getActiveStatistics().readLocked(); 1489 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1490 mOnBattery = DEBUG_POWER ? true 1491 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 1492 mBatteryStatsService.getActiveStatistics().setCallback(this); 1493 1494 mUsageStatsService = new UsageStatsService(new File( 1495 systemDir, "usagestats").toString()); 1496 1497 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 1498 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 1499 1500 mConfiguration.setToDefaults(); 1501 mConfiguration.locale = Locale.getDefault(); 1502 mConfigurationSeq = mConfiguration.seq = 1; 1503 mProcessStats.init(); 1504 1505 mCompatModePackages = new CompatModePackages(this, systemDir); 1506 1507 // Add ourself to the Watchdog monitors. 1508 Watchdog.getInstance().addMonitor(this); 1509 1510 mProcessStatsThread = new Thread("ProcessStats") { 1511 public void run() { 1512 while (true) { 1513 try { 1514 try { 1515 synchronized(this) { 1516 final long now = SystemClock.uptimeMillis(); 1517 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 1518 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 1519 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 1520 // + ", write delay=" + nextWriteDelay); 1521 if (nextWriteDelay < nextCpuDelay) { 1522 nextCpuDelay = nextWriteDelay; 1523 } 1524 if (nextCpuDelay > 0) { 1525 mProcessStatsMutexFree.set(true); 1526 this.wait(nextCpuDelay); 1527 } 1528 } 1529 } catch (InterruptedException e) { 1530 } 1531 updateCpuStatsNow(); 1532 } catch (Exception e) { 1533 Slog.e(TAG, "Unexpected exception collecting process stats", e); 1534 } 1535 } 1536 } 1537 }; 1538 mProcessStatsThread.start(); 1539 } 1540 1541 @Override 1542 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1543 throws RemoteException { 1544 try { 1545 return super.onTransact(code, data, reply, flags); 1546 } catch (RuntimeException e) { 1547 // The activity manager only throws security exceptions, so let's 1548 // log all others. 1549 if (!(e instanceof SecurityException)) { 1550 Slog.e(TAG, "Activity Manager Crash", e); 1551 } 1552 throw e; 1553 } 1554 } 1555 1556 void updateCpuStats() { 1557 final long now = SystemClock.uptimeMillis(); 1558 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 1559 return; 1560 } 1561 if (mProcessStatsMutexFree.compareAndSet(true, false)) { 1562 synchronized (mProcessStatsThread) { 1563 mProcessStatsThread.notify(); 1564 } 1565 } 1566 } 1567 1568 void updateCpuStatsNow() { 1569 synchronized (mProcessStatsThread) { 1570 mProcessStatsMutexFree.set(false); 1571 final long now = SystemClock.uptimeMillis(); 1572 boolean haveNewCpuStats = false; 1573 1574 if (MONITOR_CPU_USAGE && 1575 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 1576 mLastCpuTime.set(now); 1577 haveNewCpuStats = true; 1578 mProcessStats.update(); 1579 //Slog.i(TAG, mProcessStats.printCurrentState()); 1580 //Slog.i(TAG, "Total CPU usage: " 1581 // + mProcessStats.getTotalCpuPercent() + "%"); 1582 1583 // Slog the cpu usage if the property is set. 1584 if ("true".equals(SystemProperties.get("events.cpu"))) { 1585 int user = mProcessStats.getLastUserTime(); 1586 int system = mProcessStats.getLastSystemTime(); 1587 int iowait = mProcessStats.getLastIoWaitTime(); 1588 int irq = mProcessStats.getLastIrqTime(); 1589 int softIrq = mProcessStats.getLastSoftIrqTime(); 1590 int idle = mProcessStats.getLastIdleTime(); 1591 1592 int total = user + system + iowait + irq + softIrq + idle; 1593 if (total == 0) total = 1; 1594 1595 EventLog.writeEvent(EventLogTags.CPU, 1596 ((user+system+iowait+irq+softIrq) * 100) / total, 1597 (user * 100) / total, 1598 (system * 100) / total, 1599 (iowait * 100) / total, 1600 (irq * 100) / total, 1601 (softIrq * 100) / total); 1602 } 1603 } 1604 1605 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes(); 1606 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 1607 synchronized(bstats) { 1608 synchronized(mPidsSelfLocked) { 1609 if (haveNewCpuStats) { 1610 if (mOnBattery) { 1611 int perc = bstats.startAddingCpuLocked(); 1612 int totalUTime = 0; 1613 int totalSTime = 0; 1614 final int N = mProcessStats.countStats(); 1615 for (int i=0; i<N; i++) { 1616 ProcessStats.Stats st = mProcessStats.getStats(i); 1617 if (!st.working) { 1618 continue; 1619 } 1620 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 1621 int otherUTime = (st.rel_utime*perc)/100; 1622 int otherSTime = (st.rel_stime*perc)/100; 1623 totalUTime += otherUTime; 1624 totalSTime += otherSTime; 1625 if (pr != null) { 1626 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats; 1627 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1628 st.rel_stime-otherSTime); 1629 ps.addSpeedStepTimes(cpuSpeedTimes); 1630 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10; 1631 } else { 1632 BatteryStatsImpl.Uid.Proc ps = 1633 bstats.getProcessStatsLocked(st.name, st.pid); 1634 if (ps != null) { 1635 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1636 st.rel_stime-otherSTime); 1637 ps.addSpeedStepTimes(cpuSpeedTimes); 1638 } 1639 } 1640 } 1641 bstats.finishAddingCpuLocked(perc, totalUTime, 1642 totalSTime, cpuSpeedTimes); 1643 } 1644 } 1645 } 1646 1647 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 1648 mLastWriteTime = now; 1649 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1650 } 1651 } 1652 } 1653 } 1654 1655 @Override 1656 public void batteryNeedsCpuUpdate() { 1657 updateCpuStatsNow(); 1658 } 1659 1660 @Override 1661 public void batteryPowerChanged(boolean onBattery) { 1662 // When plugging in, update the CPU stats first before changing 1663 // the plug state. 1664 updateCpuStatsNow(); 1665 synchronized (this) { 1666 synchronized(mPidsSelfLocked) { 1667 mOnBattery = DEBUG_POWER ? true : onBattery; 1668 } 1669 } 1670 } 1671 1672 /** 1673 * Initialize the application bind args. These are passed to each 1674 * process when the bindApplication() IPC is sent to the process. They're 1675 * lazily setup to make sure the services are running when they're asked for. 1676 */ 1677 private HashMap<String, IBinder> getCommonServicesLocked() { 1678 if (mAppBindArgs == null) { 1679 mAppBindArgs = new HashMap<String, IBinder>(); 1680 1681 // Setup the application init args 1682 mAppBindArgs.put("package", ServiceManager.getService("package")); 1683 mAppBindArgs.put("window", ServiceManager.getService("window")); 1684 mAppBindArgs.put(Context.ALARM_SERVICE, 1685 ServiceManager.getService(Context.ALARM_SERVICE)); 1686 } 1687 return mAppBindArgs; 1688 } 1689 1690 final void setFocusedActivityLocked(ActivityRecord r) { 1691 if (mFocusedActivity != r) { 1692 mFocusedActivity = r; 1693 if (r != null) { 1694 mWindowManager.setFocusedApp(r.appToken, true); 1695 } 1696 } 1697 } 1698 1699 private final void updateLruProcessInternalLocked(ProcessRecord app, 1700 boolean oomAdj, boolean updateActivityTime, int bestPos) { 1701 // put it on the LRU to keep track of when it should be exited. 1702 int lrui = mLruProcesses.indexOf(app); 1703 if (lrui >= 0) mLruProcesses.remove(lrui); 1704 1705 int i = mLruProcesses.size()-1; 1706 int skipTop = 0; 1707 1708 app.lruSeq = mLruSeq; 1709 1710 // compute the new weight for this process. 1711 if (updateActivityTime) { 1712 app.lastActivityTime = SystemClock.uptimeMillis(); 1713 } 1714 if (app.activities.size() > 0) { 1715 // If this process has activities, we more strongly want to keep 1716 // it around. 1717 app.lruWeight = app.lastActivityTime; 1718 } else if (app.pubProviders.size() > 0) { 1719 // If this process contains content providers, we want to keep 1720 // it a little more strongly. 1721 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET; 1722 // Also don't let it kick out the first few "real" hidden processes. 1723 skipTop = ProcessList.MIN_HIDDEN_APPS; 1724 } else { 1725 // If this process doesn't have activities, we less strongly 1726 // want to keep it around, and generally want to avoid getting 1727 // in front of any very recently used activities. 1728 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET; 1729 // Also don't let it kick out the first few "real" hidden processes. 1730 skipTop = ProcessList.MIN_HIDDEN_APPS; 1731 } 1732 1733 while (i >= 0) { 1734 ProcessRecord p = mLruProcesses.get(i); 1735 // If this app shouldn't be in front of the first N background 1736 // apps, then skip over that many that are currently hidden. 1737 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 1738 skipTop--; 1739 } 1740 if (p.lruWeight <= app.lruWeight || i < bestPos) { 1741 mLruProcesses.add(i+1, app); 1742 break; 1743 } 1744 i--; 1745 } 1746 if (i < 0) { 1747 mLruProcesses.add(0, app); 1748 } 1749 1750 // If the app is currently using a content provider or service, 1751 // bump those processes as well. 1752 if (app.connections.size() > 0) { 1753 for (ConnectionRecord cr : app.connections) { 1754 if (cr.binding != null && cr.binding.service != null 1755 && cr.binding.service.app != null 1756 && cr.binding.service.app.lruSeq != mLruSeq) { 1757 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj, 1758 updateActivityTime, i+1); 1759 } 1760 } 1761 } 1762 if (app.conProviders.size() > 0) { 1763 for (ContentProviderRecord cpr : app.conProviders.keySet()) { 1764 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) { 1765 updateLruProcessInternalLocked(cpr.proc, oomAdj, 1766 updateActivityTime, i+1); 1767 } 1768 } 1769 } 1770 1771 //Slog.i(TAG, "Putting proc to front: " + app.processName); 1772 if (oomAdj) { 1773 updateOomAdjLocked(); 1774 } 1775 } 1776 1777 final void updateLruProcessLocked(ProcessRecord app, 1778 boolean oomAdj, boolean updateActivityTime) { 1779 mLruSeq++; 1780 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0); 1781 } 1782 1783 final ProcessRecord getProcessRecordLocked( 1784 String processName, int uid) { 1785 if (uid == Process.SYSTEM_UID) { 1786 // The system gets to run in any process. If there are multiple 1787 // processes with the same uid, just pick the first (this 1788 // should never happen). 1789 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get( 1790 processName); 1791 return procs != null ? procs.valueAt(0) : null; 1792 } 1793 ProcessRecord proc = mProcessNames.get(processName, uid); 1794 return proc; 1795 } 1796 1797 void ensurePackageDexOpt(String packageName) { 1798 IPackageManager pm = AppGlobals.getPackageManager(); 1799 try { 1800 if (pm.performDexOpt(packageName)) { 1801 mDidDexOpt = true; 1802 } 1803 } catch (RemoteException e) { 1804 } 1805 } 1806 1807 boolean isNextTransitionForward() { 1808 int transit = mWindowManager.getPendingAppTransition(); 1809 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN 1810 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN 1811 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT; 1812 } 1813 1814 final ProcessRecord startProcessLocked(String processName, 1815 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 1816 String hostingType, ComponentName hostingName, boolean allowWhileBooting) { 1817 ProcessRecord app = getProcessRecordLocked(processName, info.uid); 1818 // We don't have to do anything more if: 1819 // (1) There is an existing application record; and 1820 // (2) The caller doesn't think it is dead, OR there is no thread 1821 // object attached to it so we know it couldn't have crashed; and 1822 // (3) There is a pid assigned to it, so it is either starting or 1823 // already running. 1824 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName 1825 + " app=" + app + " knownToBeDead=" + knownToBeDead 1826 + " thread=" + (app != null ? app.thread : null) 1827 + " pid=" + (app != null ? app.pid : -1)); 1828 if (app != null && app.pid > 0) { 1829 if (!knownToBeDead || app.thread == null) { 1830 // We already have the app running, or are waiting for it to 1831 // come up (we have a pid but not yet its thread), so keep it. 1832 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app); 1833 // If this is a new package in the process, add the package to the list 1834 app.addPackage(info.packageName); 1835 return app; 1836 } else { 1837 // An application record is attached to a previous process, 1838 // clean it up now. 1839 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app); 1840 handleAppDiedLocked(app, true, true); 1841 } 1842 } 1843 1844 String hostingNameStr = hostingName != null 1845 ? hostingName.flattenToShortString() : null; 1846 1847 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) { 1848 // If we are in the background, then check to see if this process 1849 // is bad. If so, we will just silently fail. 1850 if (mBadProcesses.get(info.processName, info.uid) != null) { 1851 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 1852 + "/" + info.processName); 1853 return null; 1854 } 1855 } else { 1856 // When the user is explicitly starting a process, then clear its 1857 // crash count so that we won't make it bad until they see at 1858 // least one crash dialog again, and make the process good again 1859 // if it had been bad. 1860 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 1861 + "/" + info.processName); 1862 mProcessCrashTimes.remove(info.processName, info.uid); 1863 if (mBadProcesses.get(info.processName, info.uid) != null) { 1864 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid, 1865 info.processName); 1866 mBadProcesses.remove(info.processName, info.uid); 1867 if (app != null) { 1868 app.bad = false; 1869 } 1870 } 1871 } 1872 1873 if (app == null) { 1874 app = newProcessRecordLocked(null, info, processName); 1875 mProcessNames.put(processName, info.uid, app); 1876 } else { 1877 // If this is a new package in the process, add the package to the list 1878 app.addPackage(info.packageName); 1879 } 1880 1881 // If the system is not ready yet, then hold off on starting this 1882 // process until it is. 1883 if (!mProcessesReady 1884 && !isAllowedWhileBooting(info) 1885 && !allowWhileBooting) { 1886 if (!mProcessesOnHold.contains(app)) { 1887 mProcessesOnHold.add(app); 1888 } 1889 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app); 1890 return app; 1891 } 1892 1893 startProcessLocked(app, hostingType, hostingNameStr); 1894 return (app.pid != 0) ? app : null; 1895 } 1896 1897 boolean isAllowedWhileBooting(ApplicationInfo ai) { 1898 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 1899 } 1900 1901 private final void startProcessLocked(ProcessRecord app, 1902 String hostingType, String hostingNameStr) { 1903 if (app.pid > 0 && app.pid != MY_PID) { 1904 synchronized (mPidsSelfLocked) { 1905 mPidsSelfLocked.remove(app.pid); 1906 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 1907 } 1908 app.pid = 0; 1909 } 1910 1911 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 1912 "startProcessLocked removing on hold: " + app); 1913 mProcessesOnHold.remove(app); 1914 1915 updateCpuStats(); 1916 1917 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1); 1918 mProcDeaths[0] = 0; 1919 1920 try { 1921 int uid = app.info.uid; 1922 int[] gids = null; 1923 try { 1924 gids = mContext.getPackageManager().getPackageGids( 1925 app.info.packageName); 1926 } catch (PackageManager.NameNotFoundException e) { 1927 Slog.w(TAG, "Unable to retrieve gids", e); 1928 } 1929 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) { 1930 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 1931 && mTopComponent != null 1932 && app.processName.equals(mTopComponent.getPackageName())) { 1933 uid = 0; 1934 } 1935 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL 1936 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 1937 uid = 0; 1938 } 1939 } 1940 int debugFlags = 0; 1941 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 1942 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 1943 // Also turn on CheckJNI for debuggable apps. It's quite 1944 // awkward to turn on otherwise. 1945 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 1946 } 1947 // Run the app in safe mode if its manifest requests so or the 1948 // system is booted in safe mode. 1949 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 1950 Zygote.systemInSafeMode == true) { 1951 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 1952 } 1953 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 1954 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 1955 } 1956 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 1957 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 1958 } 1959 if ("1".equals(SystemProperties.get("debug.assert"))) { 1960 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 1961 } 1962 1963 // Start the process. It will either succeed and return a result containing 1964 // the PID of the new process, or else throw a RuntimeException. 1965 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread", 1966 app.processName, uid, uid, gids, debugFlags, 1967 app.info.targetSdkVersion, null); 1968 1969 BatteryStatsImpl bs = app.batteryStats.getBatteryStats(); 1970 synchronized (bs) { 1971 if (bs.isOnBattery()) { 1972 app.batteryStats.incStartsLocked(); 1973 } 1974 } 1975 1976 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid, 1977 app.processName, hostingType, 1978 hostingNameStr != null ? hostingNameStr : ""); 1979 1980 if (app.persistent) { 1981 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 1982 } 1983 1984 StringBuilder buf = mStringBuilder; 1985 buf.setLength(0); 1986 buf.append("Start proc "); 1987 buf.append(app.processName); 1988 buf.append(" for "); 1989 buf.append(hostingType); 1990 if (hostingNameStr != null) { 1991 buf.append(" "); 1992 buf.append(hostingNameStr); 1993 } 1994 buf.append(": pid="); 1995 buf.append(startResult.pid); 1996 buf.append(" uid="); 1997 buf.append(uid); 1998 buf.append(" gids={"); 1999 if (gids != null) { 2000 for (int gi=0; gi<gids.length; gi++) { 2001 if (gi != 0) buf.append(", "); 2002 buf.append(gids[gi]); 2003 2004 } 2005 } 2006 buf.append("}"); 2007 Slog.i(TAG, buf.toString()); 2008 app.pid = startResult.pid; 2009 app.usingWrapper = startResult.usingWrapper; 2010 app.removed = false; 2011 synchronized (mPidsSelfLocked) { 2012 this.mPidsSelfLocked.put(startResult.pid, app); 2013 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 2014 msg.obj = app; 2015 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 2016 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 2017 } 2018 } catch (RuntimeException e) { 2019 // XXX do better error recovery. 2020 app.pid = 0; 2021 Slog.e(TAG, "Failure starting process " + app.processName, e); 2022 } 2023 } 2024 2025 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) { 2026 if (resumed) { 2027 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity); 2028 } else { 2029 mUsageStatsService.notePauseComponent(resumedComponent.realActivity); 2030 } 2031 } 2032 2033 boolean startHomeActivityLocked() { 2034 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 2035 && mTopAction == null) { 2036 // We are running in factory test mode, but unable to find 2037 // the factory test app, so just sit around displaying the 2038 // error message and don't try to start anything. 2039 return false; 2040 } 2041 Intent intent = new Intent( 2042 mTopAction, 2043 mTopData != null ? Uri.parse(mTopData) : null); 2044 intent.setComponent(mTopComponent); 2045 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { 2046 intent.addCategory(Intent.CATEGORY_HOME); 2047 } 2048 ActivityInfo aInfo = 2049 intent.resolveActivityInfo(mContext.getPackageManager(), 2050 STOCK_PM_FLAGS); 2051 if (aInfo != null) { 2052 intent.setComponent(new ComponentName( 2053 aInfo.applicationInfo.packageName, aInfo.name)); 2054 // Don't do this if the home app is currently being 2055 // instrumented. 2056 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 2057 aInfo.applicationInfo.uid); 2058 if (app == null || app.instrumentationClass == null) { 2059 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 2060 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo, 2061 null, null, 0, 0, 0, false, false, null); 2062 } 2063 } 2064 2065 2066 return true; 2067 } 2068 2069 /** 2070 * Starts the "new version setup screen" if appropriate. 2071 */ 2072 void startSetupActivityLocked() { 2073 // Only do this once per boot. 2074 if (mCheckedForSetup) { 2075 return; 2076 } 2077 2078 // We will show this screen if the current one is a different 2079 // version than the last one shown, and we are not running in 2080 // low-level factory test mode. 2081 final ContentResolver resolver = mContext.getContentResolver(); 2082 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL && 2083 Settings.Secure.getInt(resolver, 2084 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) { 2085 mCheckedForSetup = true; 2086 2087 // See if we should be showing the platform update setup UI. 2088 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 2089 List<ResolveInfo> ris = mSelf.mContext.getPackageManager() 2090 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 2091 2092 // We don't allow third party apps to replace this. 2093 ResolveInfo ri = null; 2094 for (int i=0; ris != null && i<ris.size(); i++) { 2095 if ((ris.get(i).activityInfo.applicationInfo.flags 2096 & ApplicationInfo.FLAG_SYSTEM) != 0) { 2097 ri = ris.get(i); 2098 break; 2099 } 2100 } 2101 2102 if (ri != null) { 2103 String vers = ri.activityInfo.metaData != null 2104 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 2105 : null; 2106 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 2107 vers = ri.activityInfo.applicationInfo.metaData.getString( 2108 Intent.METADATA_SETUP_VERSION); 2109 } 2110 String lastVers = Settings.Secure.getString( 2111 resolver, Settings.Secure.LAST_SETUP_SHOWN); 2112 if (vers != null && !vers.equals(lastVers)) { 2113 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2114 intent.setComponent(new ComponentName( 2115 ri.activityInfo.packageName, ri.activityInfo.name)); 2116 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo, 2117 null, null, 0, 0, 0, false, false, null); 2118 } 2119 } 2120 } 2121 } 2122 2123 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 2124 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 2125 } 2126 2127 public int getFrontActivityScreenCompatMode() { 2128 synchronized (this) { 2129 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 2130 } 2131 } 2132 2133 public void setFrontActivityScreenCompatMode(int mode) { 2134 synchronized (this) { 2135 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 2136 } 2137 } 2138 2139 public int getPackageScreenCompatMode(String packageName) { 2140 synchronized (this) { 2141 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 2142 } 2143 } 2144 2145 public void setPackageScreenCompatMode(String packageName, int mode) { 2146 synchronized (this) { 2147 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 2148 } 2149 } 2150 2151 public boolean getPackageAskScreenCompat(String packageName) { 2152 synchronized (this) { 2153 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 2154 } 2155 } 2156 2157 public void setPackageAskScreenCompat(String packageName, boolean ask) { 2158 synchronized (this) { 2159 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 2160 } 2161 } 2162 2163 void reportResumedActivityLocked(ActivityRecord r) { 2164 //Slog.i(TAG, "**** REPORT RESUME: " + r); 2165 2166 final int identHash = System.identityHashCode(r); 2167 updateUsageStats(r, true); 2168 2169 int i = mWatchers.beginBroadcast(); 2170 while (i > 0) { 2171 i--; 2172 IActivityWatcher w = mWatchers.getBroadcastItem(i); 2173 if (w != null) { 2174 try { 2175 w.activityResuming(identHash); 2176 } catch (RemoteException e) { 2177 } 2178 } 2179 } 2180 mWatchers.finishBroadcast(); 2181 } 2182 2183 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) { 2184 int i = mProcessObservers.beginBroadcast(); 2185 while (i > 0) { 2186 i--; 2187 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2188 if (observer != null) { 2189 try { 2190 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities); 2191 } catch (RemoteException e) { 2192 } 2193 } 2194 } 2195 mProcessObservers.finishBroadcast(); 2196 } 2197 2198 private void dispatchProcessDied(int pid, int uid) { 2199 int i = mProcessObservers.beginBroadcast(); 2200 while (i > 0) { 2201 i--; 2202 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2203 if (observer != null) { 2204 try { 2205 observer.onProcessDied(pid, uid); 2206 } catch (RemoteException e) { 2207 } 2208 } 2209 } 2210 mProcessObservers.finishBroadcast(); 2211 } 2212 2213 final void doPendingActivityLaunchesLocked(boolean doResume) { 2214 final int N = mPendingActivityLaunches.size(); 2215 if (N <= 0) { 2216 return; 2217 } 2218 for (int i=0; i<N; i++) { 2219 PendingActivityLaunch pal = mPendingActivityLaunches.get(i); 2220 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord, 2221 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded, 2222 doResume && i == (N-1)); 2223 } 2224 mPendingActivityLaunches.clear(); 2225 } 2226 2227 public final int startActivity(IApplicationThread caller, 2228 Intent intent, String resolvedType, Uri[] grantedUriPermissions, 2229 int grantedMode, IBinder resultTo, 2230 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug, 2231 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) { 2232 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType, 2233 grantedUriPermissions, grantedMode, resultTo, resultWho, 2234 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler, 2235 null, null); 2236 } 2237 2238 public final WaitResult startActivityAndWait(IApplicationThread caller, 2239 Intent intent, String resolvedType, Uri[] grantedUriPermissions, 2240 int grantedMode, IBinder resultTo, 2241 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug, 2242 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) { 2243 WaitResult res = new WaitResult(); 2244 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType, 2245 grantedUriPermissions, grantedMode, resultTo, resultWho, 2246 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler, 2247 res, null); 2248 return res; 2249 } 2250 2251 public final int startActivityWithConfig(IApplicationThread caller, 2252 Intent intent, String resolvedType, Uri[] grantedUriPermissions, 2253 int grantedMode, IBinder resultTo, 2254 String resultWho, int requestCode, boolean onlyIfNeeded, 2255 boolean debug, Configuration config) { 2256 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType, 2257 grantedUriPermissions, grantedMode, resultTo, resultWho, 2258 requestCode, onlyIfNeeded, debug, null, null, false, null, config); 2259 } 2260 2261 public int startActivityIntentSender(IApplicationThread caller, 2262 IntentSender intent, Intent fillInIntent, String resolvedType, 2263 IBinder resultTo, String resultWho, int requestCode, 2264 int flagsMask, int flagsValues) { 2265 // Refuse possible leaked file descriptors 2266 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 2267 throw new IllegalArgumentException("File descriptors passed in Intent"); 2268 } 2269 2270 IIntentSender sender = intent.getTarget(); 2271 if (!(sender instanceof PendingIntentRecord)) { 2272 throw new IllegalArgumentException("Bad PendingIntent object"); 2273 } 2274 2275 PendingIntentRecord pir = (PendingIntentRecord)sender; 2276 2277 synchronized (this) { 2278 // If this is coming from the currently resumed activity, it is 2279 // effectively saying that app switches are allowed at this point. 2280 if (mMainStack.mResumedActivity != null 2281 && mMainStack.mResumedActivity.info.applicationInfo.uid == 2282 Binder.getCallingUid()) { 2283 mAppSwitchesAllowedTime = 0; 2284 } 2285 } 2286 2287 return pir.sendInner(0, fillInIntent, resolvedType, null, 2288 null, resultTo, resultWho, requestCode, flagsMask, flagsValues); 2289 } 2290 2291 public boolean startNextMatchingActivity(IBinder callingActivity, 2292 Intent intent) { 2293 // Refuse possible leaked file descriptors 2294 if (intent != null && intent.hasFileDescriptors() == true) { 2295 throw new IllegalArgumentException("File descriptors passed in Intent"); 2296 } 2297 2298 synchronized (this) { 2299 ActivityRecord r = mMainStack.isInStackLocked(callingActivity); 2300 if (r == null) { 2301 return false; 2302 } 2303 if (r.app == null || r.app.thread == null) { 2304 // The caller is not running... d'oh! 2305 return false; 2306 } 2307 intent = new Intent(intent); 2308 // The caller is not allowed to change the data. 2309 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 2310 // And we are resetting to find the next component... 2311 intent.setComponent(null); 2312 2313 ActivityInfo aInfo = null; 2314 try { 2315 List<ResolveInfo> resolves = 2316 AppGlobals.getPackageManager().queryIntentActivities( 2317 intent, r.resolvedType, 2318 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS); 2319 2320 // Look for the original activity in the list... 2321 final int N = resolves != null ? resolves.size() : 0; 2322 for (int i=0; i<N; i++) { 2323 ResolveInfo rInfo = resolves.get(i); 2324 if (rInfo.activityInfo.packageName.equals(r.packageName) 2325 && rInfo.activityInfo.name.equals(r.info.name)) { 2326 // We found the current one... the next matching is 2327 // after it. 2328 i++; 2329 if (i<N) { 2330 aInfo = resolves.get(i).activityInfo; 2331 } 2332 break; 2333 } 2334 } 2335 } catch (RemoteException e) { 2336 } 2337 2338 if (aInfo == null) { 2339 // Nobody who is next! 2340 return false; 2341 } 2342 2343 intent.setComponent(new ComponentName( 2344 aInfo.applicationInfo.packageName, aInfo.name)); 2345 intent.setFlags(intent.getFlags()&~( 2346 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 2347 Intent.FLAG_ACTIVITY_CLEAR_TOP| 2348 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 2349 Intent.FLAG_ACTIVITY_NEW_TASK)); 2350 2351 // Okay now we need to start the new activity, replacing the 2352 // currently running activity. This is a little tricky because 2353 // we want to start the new one as if the current one is finished, 2354 // but not finish the current one first so that there is no flicker. 2355 // And thus... 2356 final boolean wasFinishing = r.finishing; 2357 r.finishing = true; 2358 2359 // Propagate reply information over to the new activity. 2360 final ActivityRecord resultTo = r.resultTo; 2361 final String resultWho = r.resultWho; 2362 final int requestCode = r.requestCode; 2363 r.resultTo = null; 2364 if (resultTo != null) { 2365 resultTo.removeResultsLocked(r, resultWho, requestCode); 2366 } 2367 2368 final long origId = Binder.clearCallingIdentity(); 2369 // XXX we are not dealing with propagating grantedUriPermissions... 2370 // those are not yet exposed to user code, so there is no need. 2371 int res = mMainStack.startActivityLocked(r.app.thread, intent, 2372 r.resolvedType, null, 0, aInfo, 2373 resultTo != null ? resultTo.appToken : null, resultWho, 2374 requestCode, -1, r.launchedFromUid, false, false, null); 2375 Binder.restoreCallingIdentity(origId); 2376 2377 r.finishing = wasFinishing; 2378 if (res != START_SUCCESS) { 2379 return false; 2380 } 2381 return true; 2382 } 2383 } 2384 2385 public final int startActivityInPackage(int uid, 2386 Intent intent, String resolvedType, IBinder resultTo, 2387 String resultWho, int requestCode, boolean onlyIfNeeded) { 2388 2389 // This is so super not safe, that only the system (or okay root) 2390 // can do it. 2391 final int callingUid = Binder.getCallingUid(); 2392 if (callingUid != 0 && callingUid != Process.myUid()) { 2393 throw new SecurityException( 2394 "startActivityInPackage only available to the system"); 2395 } 2396 2397 return mMainStack.startActivityMayWait(null, uid, intent, resolvedType, 2398 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false, 2399 null, null, false, null, null); 2400 } 2401 2402 public final int startActivities(IApplicationThread caller, 2403 Intent[] intents, String[] resolvedTypes, IBinder resultTo) { 2404 return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo); 2405 } 2406 2407 public final int startActivitiesInPackage(int uid, 2408 Intent[] intents, String[] resolvedTypes, IBinder resultTo) { 2409 2410 // This is so super not safe, that only the system (or okay root) 2411 // can do it. 2412 final int callingUid = Binder.getCallingUid(); 2413 if (callingUid != 0 && callingUid != Process.myUid()) { 2414 throw new SecurityException( 2415 "startActivityInPackage only available to the system"); 2416 } 2417 2418 return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo); 2419 } 2420 2421 final void addRecentTaskLocked(TaskRecord task) { 2422 int N = mRecentTasks.size(); 2423 // Quick case: check if the top-most recent task is the same. 2424 if (N > 0 && mRecentTasks.get(0) == task) { 2425 return; 2426 } 2427 // Remove any existing entries that are the same kind of task. 2428 for (int i=0; i<N; i++) { 2429 TaskRecord tr = mRecentTasks.get(i); 2430 if ((task.affinity != null && task.affinity.equals(tr.affinity)) 2431 || (task.intent != null && task.intent.filterEquals(tr.intent))) { 2432 mRecentTasks.remove(i); 2433 i--; 2434 N--; 2435 if (task.intent == null) { 2436 // If the new recent task we are adding is not fully 2437 // specified, then replace it with the existing recent task. 2438 task = tr; 2439 } 2440 } 2441 } 2442 if (N >= MAX_RECENT_TASKS) { 2443 mRecentTasks.remove(N-1); 2444 } 2445 mRecentTasks.add(0, task); 2446 } 2447 2448 public void setRequestedOrientation(IBinder token, 2449 int requestedOrientation) { 2450 synchronized (this) { 2451 ActivityRecord r = mMainStack.isInStackLocked(token); 2452 if (r == null) { 2453 return; 2454 } 2455 final long origId = Binder.clearCallingIdentity(); 2456 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 2457 Configuration config = mWindowManager.updateOrientationFromAppTokens( 2458 mConfiguration, 2459 r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 2460 if (config != null) { 2461 r.frozenBeforeDestroy = true; 2462 if (!updateConfigurationLocked(config, r, false, false)) { 2463 mMainStack.resumeTopActivityLocked(null); 2464 } 2465 } 2466 Binder.restoreCallingIdentity(origId); 2467 } 2468 } 2469 2470 public int getRequestedOrientation(IBinder token) { 2471 synchronized (this) { 2472 ActivityRecord r = mMainStack.isInStackLocked(token); 2473 if (r == null) { 2474 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 2475 } 2476 return mWindowManager.getAppOrientation(r.appToken); 2477 } 2478 } 2479 2480 /** 2481 * This is the internal entry point for handling Activity.finish(). 2482 * 2483 * @param token The Binder token referencing the Activity we want to finish. 2484 * @param resultCode Result code, if any, from this Activity. 2485 * @param resultData Result data (Intent), if any, from this Activity. 2486 * 2487 * @return Returns true if the activity successfully finished, or false if it is still running. 2488 */ 2489 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) { 2490 // Refuse possible leaked file descriptors 2491 if (resultData != null && resultData.hasFileDescriptors() == true) { 2492 throw new IllegalArgumentException("File descriptors passed in Intent"); 2493 } 2494 2495 synchronized(this) { 2496 if (mController != null) { 2497 // Find the first activity that is not finishing. 2498 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0); 2499 if (next != null) { 2500 // ask watcher if this is allowed 2501 boolean resumeOK = true; 2502 try { 2503 resumeOK = mController.activityResuming(next.packageName); 2504 } catch (RemoteException e) { 2505 mController = null; 2506 } 2507 2508 if (!resumeOK) { 2509 return false; 2510 } 2511 } 2512 } 2513 final long origId = Binder.clearCallingIdentity(); 2514 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode, 2515 resultData, "app-request"); 2516 Binder.restoreCallingIdentity(origId); 2517 return res; 2518 } 2519 } 2520 2521 public final void finishHeavyWeightApp() { 2522 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2523 != PackageManager.PERMISSION_GRANTED) { 2524 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 2525 + Binder.getCallingPid() 2526 + ", uid=" + Binder.getCallingUid() 2527 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2528 Slog.w(TAG, msg); 2529 throw new SecurityException(msg); 2530 } 2531 2532 synchronized(this) { 2533 if (mHeavyWeightProcess == null) { 2534 return; 2535 } 2536 2537 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>( 2538 mHeavyWeightProcess.activities); 2539 for (int i=0; i<activities.size(); i++) { 2540 ActivityRecord r = activities.get(i); 2541 if (!r.finishing) { 2542 int index = mMainStack.indexOfTokenLocked(r.appToken); 2543 if (index >= 0) { 2544 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED, 2545 null, "finish-heavy"); 2546 } 2547 } 2548 } 2549 2550 mHeavyWeightProcess = null; 2551 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG); 2552 } 2553 } 2554 2555 public void crashApplication(int uid, int initialPid, String packageName, 2556 String message) { 2557 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2558 != PackageManager.PERMISSION_GRANTED) { 2559 String msg = "Permission Denial: crashApplication() from pid=" 2560 + Binder.getCallingPid() 2561 + ", uid=" + Binder.getCallingUid() 2562 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2563 Slog.w(TAG, msg); 2564 throw new SecurityException(msg); 2565 } 2566 2567 synchronized(this) { 2568 ProcessRecord proc = null; 2569 2570 // Figure out which process to kill. We don't trust that initialPid 2571 // still has any relation to current pids, so must scan through the 2572 // list. 2573 synchronized (mPidsSelfLocked) { 2574 for (int i=0; i<mPidsSelfLocked.size(); i++) { 2575 ProcessRecord p = mPidsSelfLocked.valueAt(i); 2576 if (p.info.uid != uid) { 2577 continue; 2578 } 2579 if (p.pid == initialPid) { 2580 proc = p; 2581 break; 2582 } 2583 for (String str : p.pkgList) { 2584 if (str.equals(packageName)) { 2585 proc = p; 2586 } 2587 } 2588 } 2589 } 2590 2591 if (proc == null) { 2592 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 2593 + " initialPid=" + initialPid 2594 + " packageName=" + packageName); 2595 return; 2596 } 2597 2598 if (proc.thread != null) { 2599 if (proc.pid == Process.myPid()) { 2600 Log.w(TAG, "crashApplication: trying to crash self!"); 2601 return; 2602 } 2603 long ident = Binder.clearCallingIdentity(); 2604 try { 2605 proc.thread.scheduleCrash(message); 2606 } catch (RemoteException e) { 2607 } 2608 Binder.restoreCallingIdentity(ident); 2609 } 2610 } 2611 } 2612 2613 public final void finishSubActivity(IBinder token, String resultWho, 2614 int requestCode) { 2615 synchronized(this) { 2616 ActivityRecord self = mMainStack.isInStackLocked(token); 2617 if (self == null) { 2618 return; 2619 } 2620 2621 final long origId = Binder.clearCallingIdentity(); 2622 2623 int i; 2624 for (i=mMainStack.mHistory.size()-1; i>=0; i--) { 2625 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 2626 if (r.resultTo == self && r.requestCode == requestCode) { 2627 if ((r.resultWho == null && resultWho == null) || 2628 (r.resultWho != null && r.resultWho.equals(resultWho))) { 2629 mMainStack.finishActivityLocked(r, i, 2630 Activity.RESULT_CANCELED, null, "request-sub"); 2631 } 2632 } 2633 } 2634 2635 Binder.restoreCallingIdentity(origId); 2636 } 2637 } 2638 2639 public boolean willActivityBeVisible(IBinder token) { 2640 synchronized(this) { 2641 int i; 2642 for (i=mMainStack.mHistory.size()-1; i>=0; i--) { 2643 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 2644 if (r.appToken == token) { 2645 return true; 2646 } 2647 if (r.fullscreen && !r.finishing) { 2648 return false; 2649 } 2650 } 2651 return true; 2652 } 2653 } 2654 2655 public void overridePendingTransition(IBinder token, String packageName, 2656 int enterAnim, int exitAnim) { 2657 synchronized(this) { 2658 ActivityRecord self = mMainStack.isInStackLocked(token); 2659 if (self == null) { 2660 return; 2661 } 2662 2663 final long origId = Binder.clearCallingIdentity(); 2664 2665 if (self.state == ActivityState.RESUMED 2666 || self.state == ActivityState.PAUSING) { 2667 mWindowManager.overridePendingAppTransition(packageName, 2668 enterAnim, exitAnim); 2669 } 2670 2671 Binder.restoreCallingIdentity(origId); 2672 } 2673 } 2674 2675 /** 2676 * Main function for removing an existing process from the activity manager 2677 * as a result of that process going away. Clears out all connections 2678 * to the process. 2679 */ 2680 private final void handleAppDiedLocked(ProcessRecord app, 2681 boolean restarting, boolean allowRestart) { 2682 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 2683 if (!restarting) { 2684 mLruProcesses.remove(app); 2685 } 2686 2687 if (mProfileProc == app) { 2688 clearProfilerLocked(); 2689 } 2690 2691 // Just in case... 2692 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) { 2693 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity); 2694 mMainStack.mPausingActivity = null; 2695 } 2696 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) { 2697 mMainStack.mLastPausedActivity = null; 2698 } 2699 2700 // Remove this application's activities from active lists. 2701 mMainStack.removeHistoryRecordsForAppLocked(app); 2702 2703 boolean atTop = true; 2704 boolean hasVisibleActivities = false; 2705 2706 // Clean out the history list. 2707 int i = mMainStack.mHistory.size(); 2708 if (localLOGV) Slog.v( 2709 TAG, "Removing app " + app + " from history with " + i + " entries"); 2710 while (i > 0) { 2711 i--; 2712 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 2713 if (localLOGV) Slog.v( 2714 TAG, "Record #" + i + " " + r + ": app=" + r.app); 2715 if (r.app == app) { 2716 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) { 2717 if (ActivityStack.DEBUG_ADD_REMOVE) { 2718 RuntimeException here = new RuntimeException("here"); 2719 here.fillInStackTrace(); 2720 Slog.i(TAG, "Removing activity " + r + " from stack at " + i 2721 + ": haveState=" + r.haveState 2722 + " stateNotNeeded=" + r.stateNotNeeded 2723 + " finishing=" + r.finishing 2724 + " state=" + r.state, here); 2725 } 2726 if (!r.finishing) { 2727 Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); 2728 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 2729 System.identityHashCode(r), 2730 r.task.taskId, r.shortComponentName, 2731 "proc died without state saved"); 2732 } 2733 r.makeFinishing(); 2734 mMainStack.mHistory.remove(i); 2735 r.takeFromHistory(); 2736 mWindowManager.removeAppToken(r.appToken); 2737 if (VALIDATE_TOKENS) { 2738 mMainStack.validateAppTokensLocked(); 2739 } 2740 r.removeUriPermissionsLocked(); 2741 2742 } else { 2743 // We have the current state for this activity, so 2744 // it can be restarted later when needed. 2745 if (localLOGV) Slog.v( 2746 TAG, "Keeping entry, setting app to null"); 2747 if (r.visible) { 2748 hasVisibleActivities = true; 2749 } 2750 r.app = null; 2751 r.nowVisible = false; 2752 if (!r.haveState) { 2753 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG, 2754 "App died, clearing saved state of " + r); 2755 r.icicle = null; 2756 } 2757 } 2758 2759 r.stack.cleanUpActivityLocked(r, true, true); 2760 } 2761 atTop = false; 2762 } 2763 2764 app.activities.clear(); 2765 2766 if (app.instrumentationClass != null) { 2767 Slog.w(TAG, "Crash of app " + app.processName 2768 + " running instrumentation " + app.instrumentationClass); 2769 Bundle info = new Bundle(); 2770 info.putString("shortMsg", "Process crashed."); 2771 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 2772 } 2773 2774 if (!restarting) { 2775 if (!mMainStack.resumeTopActivityLocked(null)) { 2776 // If there was nothing to resume, and we are not already 2777 // restarting this process, but there is a visible activity that 2778 // is hosted by the process... then make sure all visible 2779 // activities are running, taking care of restarting this 2780 // process. 2781 if (hasVisibleActivities) { 2782 mMainStack.ensureActivitiesVisibleLocked(null, 0); 2783 } 2784 } 2785 } 2786 } 2787 2788 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 2789 IBinder threadBinder = thread.asBinder(); 2790 2791 // Find the application record. 2792 for (int i=mLruProcesses.size()-1; i>=0; i--) { 2793 ProcessRecord rec = mLruProcesses.get(i); 2794 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 2795 return i; 2796 } 2797 } 2798 return -1; 2799 } 2800 2801 final ProcessRecord getRecordForAppLocked( 2802 IApplicationThread thread) { 2803 if (thread == null) { 2804 return null; 2805 } 2806 2807 int appIndex = getLRURecordIndexForAppLocked(thread); 2808 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 2809 } 2810 2811 final void appDiedLocked(ProcessRecord app, int pid, 2812 IApplicationThread thread) { 2813 2814 mProcDeaths[0]++; 2815 2816 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 2817 synchronized (stats) { 2818 stats.noteProcessDiedLocked(app.info.uid, pid); 2819 } 2820 2821 // Clean up already done if the process has been re-started. 2822 if (app.pid == pid && app.thread != null && 2823 app.thread.asBinder() == thread.asBinder()) { 2824 if (!app.killedBackground) { 2825 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 2826 + ") has died."); 2827 } 2828 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName); 2829 if (localLOGV) Slog.v( 2830 TAG, "Dying app: " + app + ", pid: " + pid 2831 + ", thread: " + thread.asBinder()); 2832 boolean doLowMem = app.instrumentationClass == null; 2833 handleAppDiedLocked(app, false, true); 2834 2835 if (doLowMem) { 2836 // If there are no longer any background processes running, 2837 // and the app that died was not running instrumentation, 2838 // then tell everyone we are now low on memory. 2839 boolean haveBg = false; 2840 for (int i=mLruProcesses.size()-1; i>=0; i--) { 2841 ProcessRecord rec = mLruProcesses.get(i); 2842 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 2843 haveBg = true; 2844 break; 2845 } 2846 } 2847 2848 if (!haveBg) { 2849 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 2850 long now = SystemClock.uptimeMillis(); 2851 for (int i=mLruProcesses.size()-1; i>=0; i--) { 2852 ProcessRecord rec = mLruProcesses.get(i); 2853 if (rec != app && rec.thread != null && 2854 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 2855 // The low memory report is overriding any current 2856 // state for a GC request. Make sure to do 2857 // heavy/important/visible/foreground processes first. 2858 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 2859 rec.lastRequestedGc = 0; 2860 } else { 2861 rec.lastRequestedGc = rec.lastLowMemory; 2862 } 2863 rec.reportLowMemory = true; 2864 rec.lastLowMemory = now; 2865 mProcessesToGc.remove(rec); 2866 addProcessToGcListLocked(rec); 2867 } 2868 } 2869 mHandler.sendEmptyMessage(REPORT_MEM_USAGE); 2870 scheduleAppGcsLocked(); 2871 } 2872 } 2873 } else if (app.pid != pid) { 2874 // A new process has already been started. 2875 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 2876 + ") has died and restarted (pid " + app.pid + ")."); 2877 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName); 2878 } else if (DEBUG_PROCESSES) { 2879 Slog.d(TAG, "Received spurious death notification for thread " 2880 + thread.asBinder()); 2881 } 2882 } 2883 2884 /** 2885 * If a stack trace dump file is configured, dump process stack traces. 2886 * @param clearTraces causes the dump file to be erased prior to the new 2887 * traces being written, if true; when false, the new traces will be 2888 * appended to any existing file content. 2889 * @param firstPids of dalvik VM processes to dump stack traces for first 2890 * @param lastPids of dalvik VM processes to dump stack traces for last 2891 * @return file containing stack traces, or null if no dump file is configured 2892 */ 2893 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 2894 ProcessStats processStats, SparseArray<Boolean> lastPids) { 2895 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 2896 if (tracesPath == null || tracesPath.length() == 0) { 2897 return null; 2898 } 2899 2900 File tracesFile = new File(tracesPath); 2901 try { 2902 File tracesDir = tracesFile.getParentFile(); 2903 if (!tracesDir.exists()) tracesFile.mkdirs(); 2904 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 2905 2906 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 2907 tracesFile.createNewFile(); 2908 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 2909 } catch (IOException e) { 2910 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 2911 return null; 2912 } 2913 2914 // Use a FileObserver to detect when traces finish writing. 2915 // The order of traces is considered important to maintain for legibility. 2916 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 2917 public synchronized void onEvent(int event, String path) { notify(); } 2918 }; 2919 2920 try { 2921 observer.startWatching(); 2922 2923 // First collect all of the stacks of the most important pids. 2924 try { 2925 int num = firstPids.size(); 2926 for (int i = 0; i < num; i++) { 2927 synchronized (observer) { 2928 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 2929 observer.wait(200); // Wait for write-close, give up after 200msec 2930 } 2931 } 2932 } catch (InterruptedException e) { 2933 Log.wtf(TAG, e); 2934 } 2935 2936 // Next measure CPU usage. 2937 if (processStats != null) { 2938 processStats.init(); 2939 System.gc(); 2940 processStats.update(); 2941 try { 2942 synchronized (processStats) { 2943 processStats.wait(500); // measure over 1/2 second. 2944 } 2945 } catch (InterruptedException e) { 2946 } 2947 processStats.update(); 2948 2949 // We'll take the stack crawls of just the top apps using CPU. 2950 final int N = processStats.countWorkingStats(); 2951 int numProcs = 0; 2952 for (int i=0; i<N && numProcs<5; i++) { 2953 ProcessStats.Stats stats = processStats.getWorkingStats(i); 2954 if (lastPids.indexOfKey(stats.pid) >= 0) { 2955 numProcs++; 2956 try { 2957 synchronized (observer) { 2958 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 2959 observer.wait(200); // Wait for write-close, give up after 200msec 2960 } 2961 } catch (InterruptedException e) { 2962 Log.wtf(TAG, e); 2963 } 2964 2965 } 2966 } 2967 } 2968 2969 return tracesFile; 2970 2971 } finally { 2972 observer.stopWatching(); 2973 } 2974 } 2975 2976 private final class AppNotResponding implements Runnable { 2977 private final ProcessRecord mApp; 2978 private final String mAnnotation; 2979 2980 public AppNotResponding(ProcessRecord app, String annotation) { 2981 mApp = app; 2982 mAnnotation = annotation; 2983 } 2984 2985 @Override 2986 public void run() { 2987 appNotResponding(mApp, null, null, mAnnotation); 2988 } 2989 } 2990 2991 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 2992 ActivityRecord parent, final String annotation) { 2993 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 2994 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 2995 2996 if (mController != null) { 2997 try { 2998 // 0 == continue, -1 = kill process immediately 2999 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 3000 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3001 } catch (RemoteException e) { 3002 mController = null; 3003 } 3004 } 3005 3006 long anrTime = SystemClock.uptimeMillis(); 3007 if (MONITOR_CPU_USAGE) { 3008 updateCpuStatsNow(); 3009 } 3010 3011 synchronized (this) { 3012 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 3013 if (mShuttingDown) { 3014 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 3015 return; 3016 } else if (app.notResponding) { 3017 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 3018 return; 3019 } else if (app.crashing) { 3020 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 3021 return; 3022 } 3023 3024 // In case we come through here for the same app before completing 3025 // this one, mark as anring now so we will bail out. 3026 app.notResponding = true; 3027 3028 // Log the ANR to the event log. 3029 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags, 3030 annotation); 3031 3032 // Dump thread traces as quickly as we can, starting with "interesting" processes. 3033 firstPids.add(app.pid); 3034 3035 int parentPid = app.pid; 3036 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 3037 if (parentPid != app.pid) firstPids.add(parentPid); 3038 3039 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 3040 3041 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3042 ProcessRecord r = mLruProcesses.get(i); 3043 if (r != null && r.thread != null) { 3044 int pid = r.pid; 3045 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 3046 if (r.persistent) { 3047 firstPids.add(pid); 3048 } else { 3049 lastPids.put(pid, Boolean.TRUE); 3050 } 3051 } 3052 } 3053 } 3054 } 3055 3056 // Log the ANR to the main log. 3057 StringBuilder info = mStringBuilder; 3058 info.setLength(0); 3059 info.append("ANR in ").append(app.processName); 3060 if (activity != null && activity.shortComponentName != null) { 3061 info.append(" (").append(activity.shortComponentName).append(")"); 3062 } 3063 info.append("\n"); 3064 if (annotation != null) { 3065 info.append("Reason: ").append(annotation).append("\n"); 3066 } 3067 if (parent != null && parent != activity) { 3068 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 3069 } 3070 3071 final ProcessStats processStats = new ProcessStats(true); 3072 3073 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids); 3074 3075 String cpuInfo = null; 3076 if (MONITOR_CPU_USAGE) { 3077 updateCpuStatsNow(); 3078 synchronized (mProcessStatsThread) { 3079 cpuInfo = mProcessStats.printCurrentState(anrTime); 3080 } 3081 info.append(processStats.printCurrentLoad()); 3082 info.append(cpuInfo); 3083 } 3084 3085 info.append(processStats.printCurrentState(anrTime)); 3086 3087 Slog.e(TAG, info.toString()); 3088 if (tracesFile == null) { 3089 // There is no trace file, so dump (only) the alleged culprit's threads to the log 3090 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 3091 } 3092 3093 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 3094 cpuInfo, tracesFile, null); 3095 3096 if (mController != null) { 3097 try { 3098 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 3099 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 3100 if (res != 0) { 3101 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3102 return; 3103 } 3104 } catch (RemoteException e) { 3105 mController = null; 3106 } 3107 } 3108 3109 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 3110 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 3111 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 3112 3113 synchronized (this) { 3114 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 3115 Slog.w(TAG, "Killing " + app + ": background ANR"); 3116 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid, 3117 app.processName, app.setAdj, "background ANR"); 3118 Process.killProcessQuiet(app.pid); 3119 return; 3120 } 3121 3122 // Set the app's notResponding state, and look up the errorReportReceiver 3123 makeAppNotRespondingLocked(app, 3124 activity != null ? activity.shortComponentName : null, 3125 annotation != null ? "ANR " + annotation : "ANR", 3126 info.toString()); 3127 3128 // Bring up the infamous App Not Responding dialog 3129 Message msg = Message.obtain(); 3130 HashMap map = new HashMap(); 3131 msg.what = SHOW_NOT_RESPONDING_MSG; 3132 msg.obj = map; 3133 map.put("app", app); 3134 if (activity != null) { 3135 map.put("activity", activity); 3136 } 3137 3138 mHandler.sendMessage(msg); 3139 } 3140 } 3141 3142 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 3143 if (!mLaunchWarningShown) { 3144 mLaunchWarningShown = true; 3145 mHandler.post(new Runnable() { 3146 @Override 3147 public void run() { 3148 synchronized (ActivityManagerService.this) { 3149 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 3150 d.show(); 3151 mHandler.postDelayed(new Runnable() { 3152 @Override 3153 public void run() { 3154 synchronized (ActivityManagerService.this) { 3155 d.dismiss(); 3156 mLaunchWarningShown = false; 3157 } 3158 } 3159 }, 4000); 3160 } 3161 } 3162 }); 3163 } 3164 } 3165 3166 public boolean clearApplicationUserData(final String packageName, 3167 final IPackageDataObserver observer) { 3168 int uid = Binder.getCallingUid(); 3169 int pid = Binder.getCallingPid(); 3170 long callingId = Binder.clearCallingIdentity(); 3171 try { 3172 IPackageManager pm = AppGlobals.getPackageManager(); 3173 int pkgUid = -1; 3174 synchronized(this) { 3175 try { 3176 pkgUid = pm.getPackageUid(packageName); 3177 } catch (RemoteException e) { 3178 } 3179 if (pkgUid == -1) { 3180 Slog.w(TAG, "Invalid packageName:" + packageName); 3181 return false; 3182 } 3183 if (uid == pkgUid || checkComponentPermission( 3184 android.Manifest.permission.CLEAR_APP_USER_DATA, 3185 pid, uid, -1, true) 3186 == PackageManager.PERMISSION_GRANTED) { 3187 forceStopPackageLocked(packageName, pkgUid); 3188 } else { 3189 throw new SecurityException(pid+" does not have permission:"+ 3190 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" + 3191 "for process:"+packageName); 3192 } 3193 } 3194 3195 try { 3196 //clear application user data 3197 pm.clearApplicationUserData(packageName, observer); 3198 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 3199 Uri.fromParts("package", packageName, null)); 3200 intent.putExtra(Intent.EXTRA_UID, pkgUid); 3201 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 3202 null, null, 0, null, null, null, false, false); 3203 } catch (RemoteException e) { 3204 } 3205 } finally { 3206 Binder.restoreCallingIdentity(callingId); 3207 } 3208 return true; 3209 } 3210 3211 public void killBackgroundProcesses(final String packageName) { 3212 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3213 != PackageManager.PERMISSION_GRANTED && 3214 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3215 != PackageManager.PERMISSION_GRANTED) { 3216 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3217 + Binder.getCallingPid() 3218 + ", uid=" + Binder.getCallingUid() 3219 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3220 Slog.w(TAG, msg); 3221 throw new SecurityException(msg); 3222 } 3223 3224 long callingId = Binder.clearCallingIdentity(); 3225 try { 3226 IPackageManager pm = AppGlobals.getPackageManager(); 3227 int pkgUid = -1; 3228 synchronized(this) { 3229 try { 3230 pkgUid = pm.getPackageUid(packageName); 3231 } catch (RemoteException e) { 3232 } 3233 if (pkgUid == -1) { 3234 Slog.w(TAG, "Invalid packageName: " + packageName); 3235 return; 3236 } 3237 killPackageProcessesLocked(packageName, pkgUid, 3238 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 3239 } 3240 } finally { 3241 Binder.restoreCallingIdentity(callingId); 3242 } 3243 } 3244 3245 public void killAllBackgroundProcesses() { 3246 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3247 != PackageManager.PERMISSION_GRANTED) { 3248 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3249 + Binder.getCallingPid() 3250 + ", uid=" + Binder.getCallingUid() 3251 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3252 Slog.w(TAG, msg); 3253 throw new SecurityException(msg); 3254 } 3255 3256 long callingId = Binder.clearCallingIdentity(); 3257 try { 3258 synchronized(this) { 3259 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3260 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3261 final int NA = apps.size(); 3262 for (int ia=0; ia<NA; ia++) { 3263 ProcessRecord app = apps.valueAt(ia); 3264 if (app.persistent) { 3265 // we don't kill persistent processes 3266 continue; 3267 } 3268 if (app.removed) { 3269 procs.add(app); 3270 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 3271 app.removed = true; 3272 procs.add(app); 3273 } 3274 } 3275 } 3276 3277 int N = procs.size(); 3278 for (int i=0; i<N; i++) { 3279 removeProcessLocked(procs.get(i), false, true, "kill all background"); 3280 } 3281 } 3282 } finally { 3283 Binder.restoreCallingIdentity(callingId); 3284 } 3285 } 3286 3287 public void forceStopPackage(final String packageName) { 3288 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3289 != PackageManager.PERMISSION_GRANTED) { 3290 String msg = "Permission Denial: forceStopPackage() from pid=" 3291 + Binder.getCallingPid() 3292 + ", uid=" + Binder.getCallingUid() 3293 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3294 Slog.w(TAG, msg); 3295 throw new SecurityException(msg); 3296 } 3297 3298 long callingId = Binder.clearCallingIdentity(); 3299 try { 3300 IPackageManager pm = AppGlobals.getPackageManager(); 3301 int pkgUid = -1; 3302 synchronized(this) { 3303 try { 3304 pkgUid = pm.getPackageUid(packageName); 3305 } catch (RemoteException e) { 3306 } 3307 if (pkgUid == -1) { 3308 Slog.w(TAG, "Invalid packageName: " + packageName); 3309 return; 3310 } 3311 forceStopPackageLocked(packageName, pkgUid); 3312 try { 3313 pm.setPackageStoppedState(packageName, true); 3314 } catch (RemoteException e) { 3315 } catch (IllegalArgumentException e) { 3316 Slog.w(TAG, "Failed trying to unstop package " 3317 + packageName + ": " + e); 3318 } 3319 } 3320 } finally { 3321 Binder.restoreCallingIdentity(callingId); 3322 } 3323 } 3324 3325 /* 3326 * The pkg name and uid have to be specified. 3327 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int) 3328 */ 3329 public void killApplicationWithUid(String pkg, int uid) { 3330 if (pkg == null) { 3331 return; 3332 } 3333 // Make sure the uid is valid. 3334 if (uid < 0) { 3335 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg); 3336 return; 3337 } 3338 int callerUid = Binder.getCallingUid(); 3339 // Only the system server can kill an application 3340 if (callerUid == Process.SYSTEM_UID) { 3341 // Post an aysnc message to kill the application 3342 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 3343 msg.arg1 = uid; 3344 msg.arg2 = 0; 3345 msg.obj = pkg; 3346 mHandler.sendMessage(msg); 3347 } else { 3348 throw new SecurityException(callerUid + " cannot kill pkg: " + 3349 pkg); 3350 } 3351 } 3352 3353 public void closeSystemDialogs(String reason) { 3354 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 3355 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3356 if (reason != null) { 3357 intent.putExtra("reason", reason); 3358 } 3359 3360 final int uid = Binder.getCallingUid(); 3361 final long origId = Binder.clearCallingIdentity(); 3362 synchronized (this) { 3363 int i = mWatchers.beginBroadcast(); 3364 while (i > 0) { 3365 i--; 3366 IActivityWatcher w = mWatchers.getBroadcastItem(i); 3367 if (w != null) { 3368 try { 3369 w.closingSystemDialogs(reason); 3370 } catch (RemoteException e) { 3371 } 3372 } 3373 } 3374 mWatchers.finishBroadcast(); 3375 3376 mWindowManager.closeSystemDialogs(reason); 3377 3378 for (i=mMainStack.mHistory.size()-1; i>=0; i--) { 3379 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3380 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3381 r.stack.finishActivityLocked(r, i, 3382 Activity.RESULT_CANCELED, null, "close-sys"); 3383 } 3384 } 3385 3386 broadcastIntentLocked(null, null, intent, null, 3387 null, 0, null, null, null, false, false, -1, uid); 3388 } 3389 Binder.restoreCallingIdentity(origId); 3390 } 3391 3392 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) 3393 throws RemoteException { 3394 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 3395 for (int i=pids.length-1; i>=0; i--) { 3396 infos[i] = new Debug.MemoryInfo(); 3397 Debug.getMemoryInfo(pids[i], infos[i]); 3398 } 3399 return infos; 3400 } 3401 3402 public long[] getProcessPss(int[] pids) throws RemoteException { 3403 long[] pss = new long[pids.length]; 3404 for (int i=pids.length-1; i>=0; i--) { 3405 pss[i] = Debug.getPss(pids[i]); 3406 } 3407 return pss; 3408 } 3409 3410 public void killApplicationProcess(String processName, int uid) { 3411 if (processName == null) { 3412 return; 3413 } 3414 3415 int callerUid = Binder.getCallingUid(); 3416 // Only the system server can kill an application 3417 if (callerUid == Process.SYSTEM_UID) { 3418 synchronized (this) { 3419 ProcessRecord app = getProcessRecordLocked(processName, uid); 3420 if (app != null && app.thread != null) { 3421 try { 3422 app.thread.scheduleSuicide(); 3423 } catch (RemoteException e) { 3424 // If the other end already died, then our work here is done. 3425 } 3426 } else { 3427 Slog.w(TAG, "Process/uid not found attempting kill of " 3428 + processName + " / " + uid); 3429 } 3430 } 3431 } else { 3432 throw new SecurityException(callerUid + " cannot kill app process: " + 3433 processName); 3434 } 3435 } 3436 3437 private void forceStopPackageLocked(final String packageName, int uid) { 3438 forceStopPackageLocked(packageName, uid, false, false, true, false); 3439 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 3440 Uri.fromParts("package", packageName, null)); 3441 if (!mProcessesReady) { 3442 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3443 } 3444 intent.putExtra(Intent.EXTRA_UID, uid); 3445 broadcastIntentLocked(null, null, intent, 3446 null, null, 0, null, null, null, 3447 false, false, MY_PID, Process.SYSTEM_UID); 3448 } 3449 3450 private final boolean killPackageProcessesLocked(String packageName, int uid, 3451 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit, 3452 boolean evenPersistent, String reason) { 3453 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3454 3455 // Remove all processes this package may have touched: all with the 3456 // same UID (except for the system or root user), and all whose name 3457 // matches the package name. 3458 final String procNamePrefix = packageName + ":"; 3459 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3460 final int NA = apps.size(); 3461 for (int ia=0; ia<NA; ia++) { 3462 ProcessRecord app = apps.valueAt(ia); 3463 if (app.persistent && !evenPersistent) { 3464 // we don't kill persistent processes 3465 continue; 3466 } 3467 if (app.removed) { 3468 if (doit) { 3469 procs.add(app); 3470 } 3471 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid) 3472 || app.processName.equals(packageName) 3473 || app.processName.startsWith(procNamePrefix)) { 3474 if (app.setAdj >= minOomAdj) { 3475 if (!doit) { 3476 return true; 3477 } 3478 app.removed = true; 3479 procs.add(app); 3480 } 3481 } 3482 } 3483 } 3484 3485 int N = procs.size(); 3486 for (int i=0; i<N; i++) { 3487 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 3488 } 3489 return N > 0; 3490 } 3491 3492 private final boolean forceStopPackageLocked(String name, int uid, 3493 boolean callerWillRestart, boolean purgeCache, boolean doit, 3494 boolean evenPersistent) { 3495 int i; 3496 int N; 3497 3498 if (uid < 0) { 3499 try { 3500 uid = AppGlobals.getPackageManager().getPackageUid(name); 3501 } catch (RemoteException e) { 3502 } 3503 } 3504 3505 if (doit) { 3506 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid); 3507 3508 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator(); 3509 while (badApps.hasNext()) { 3510 SparseArray<Long> ba = badApps.next(); 3511 if (ba.get(uid) != null) { 3512 badApps.remove(); 3513 } 3514 } 3515 } 3516 3517 boolean didSomething = killPackageProcessesLocked(name, uid, -100, 3518 callerWillRestart, false, doit, evenPersistent, "force stop"); 3519 3520 TaskRecord lastTask = null; 3521 for (i=0; i<mMainStack.mHistory.size(); i++) { 3522 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3523 final boolean samePackage = r.packageName.equals(name); 3524 if ((samePackage || r.task == lastTask) 3525 && (r.app == null || evenPersistent || !r.app.persistent)) { 3526 if (!doit) { 3527 if (r.finishing) { 3528 // If this activity is just finishing, then it is not 3529 // interesting as far as something to stop. 3530 continue; 3531 } 3532 return true; 3533 } 3534 didSomething = true; 3535 Slog.i(TAG, " Force finishing activity " + r); 3536 if (samePackage) { 3537 if (r.app != null) { 3538 r.app.removed = true; 3539 } 3540 r.app = null; 3541 } 3542 lastTask = r.task; 3543 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, 3544 null, "force-stop")) { 3545 i--; 3546 } 3547 } 3548 } 3549 3550 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>(); 3551 for (ServiceRecord service : mServices.values()) { 3552 if (service.packageName.equals(name) 3553 && (service.app == null || evenPersistent || !service.app.persistent)) { 3554 if (!doit) { 3555 return true; 3556 } 3557 didSomething = true; 3558 Slog.i(TAG, " Force stopping service " + service); 3559 if (service.app != null) { 3560 service.app.removed = true; 3561 } 3562 service.app = null; 3563 services.add(service); 3564 } 3565 } 3566 3567 N = services.size(); 3568 for (i=0; i<N; i++) { 3569 bringDownServiceLocked(services.get(i), true); 3570 } 3571 3572 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>(); 3573 for (ContentProviderRecord provider : mProvidersByClass.values()) { 3574 if (provider.info.packageName.equals(name) 3575 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) { 3576 if (!doit) { 3577 return true; 3578 } 3579 didSomething = true; 3580 providers.add(provider); 3581 } 3582 } 3583 3584 N = providers.size(); 3585 for (i=0; i<N; i++) { 3586 removeDyingProviderLocked(null, providers.get(i)); 3587 } 3588 3589 if (doit) { 3590 if (purgeCache) { 3591 AttributeCache ac = AttributeCache.instance(); 3592 if (ac != null) { 3593 ac.removePackage(name); 3594 } 3595 } 3596 if (mBooted) { 3597 mMainStack.resumeTopActivityLocked(null); 3598 mMainStack.scheduleIdleLocked(); 3599 } 3600 } 3601 3602 return didSomething; 3603 } 3604 3605 private final boolean removeProcessLocked(ProcessRecord app, 3606 boolean callerWillRestart, boolean allowRestart, String reason) { 3607 final String name = app.processName; 3608 final int uid = app.info.uid; 3609 if (DEBUG_PROCESSES) Slog.d( 3610 TAG, "Force removing proc " + app.toShortString() + " (" + name 3611 + "/" + uid + ")"); 3612 3613 mProcessNames.remove(name, uid); 3614 if (mHeavyWeightProcess == app) { 3615 mHeavyWeightProcess = null; 3616 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG); 3617 } 3618 boolean needRestart = false; 3619 if (app.pid > 0 && app.pid != MY_PID) { 3620 int pid = app.pid; 3621 synchronized (mPidsSelfLocked) { 3622 mPidsSelfLocked.remove(pid); 3623 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 3624 } 3625 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason); 3626 handleAppDiedLocked(app, true, allowRestart); 3627 mLruProcesses.remove(app); 3628 Process.killProcessQuiet(pid); 3629 3630 if (app.persistent) { 3631 if (!callerWillRestart) { 3632 addAppLocked(app.info); 3633 } else { 3634 needRestart = true; 3635 } 3636 } 3637 } else { 3638 mRemovedProcesses.add(app); 3639 } 3640 3641 return needRestart; 3642 } 3643 3644 private final void processStartTimedOutLocked(ProcessRecord app) { 3645 final int pid = app.pid; 3646 boolean gone = false; 3647 synchronized (mPidsSelfLocked) { 3648 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 3649 if (knownApp != null && knownApp.thread == null) { 3650 mPidsSelfLocked.remove(pid); 3651 gone = true; 3652 } 3653 } 3654 3655 if (gone) { 3656 Slog.w(TAG, "Process " + app + " failed to attach"); 3657 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid, 3658 app.processName); 3659 mProcessNames.remove(app.processName, app.info.uid); 3660 if (mHeavyWeightProcess == app) { 3661 mHeavyWeightProcess = null; 3662 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG); 3663 } 3664 // Take care of any launching providers waiting for this process. 3665 checkAppInLaunchingProvidersLocked(app, true); 3666 // Take care of any services that are waiting for the process. 3667 for (int i=0; i<mPendingServices.size(); i++) { 3668 ServiceRecord sr = mPendingServices.get(i); 3669 if (app.info.uid == sr.appInfo.uid 3670 && app.processName.equals(sr.processName)) { 3671 Slog.w(TAG, "Forcing bringing down service: " + sr); 3672 mPendingServices.remove(i); 3673 i--; 3674 bringDownServiceLocked(sr, true); 3675 } 3676 } 3677 EventLog.writeEvent(EventLogTags.AM_KILL, pid, 3678 app.processName, app.setAdj, "start timeout"); 3679 Process.killProcessQuiet(pid); 3680 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 3681 Slog.w(TAG, "Unattached app died before backup, skipping"); 3682 try { 3683 IBackupManager bm = IBackupManager.Stub.asInterface( 3684 ServiceManager.getService(Context.BACKUP_SERVICE)); 3685 bm.agentDisconnected(app.info.packageName); 3686 } catch (RemoteException e) { 3687 // Can't happen; the backup manager is local 3688 } 3689 } 3690 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) { 3691 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 3692 mPendingBroadcast.state = BroadcastRecord.IDLE; 3693 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex; 3694 mPendingBroadcast = null; 3695 scheduleBroadcastsLocked(); 3696 } 3697 } else { 3698 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 3699 } 3700 } 3701 3702 private final boolean attachApplicationLocked(IApplicationThread thread, 3703 int pid) { 3704 3705 // Find the application record that is being attached... either via 3706 // the pid if we are running in multiple processes, or just pull the 3707 // next app record if we are emulating process with anonymous threads. 3708 ProcessRecord app; 3709 if (pid != MY_PID && pid >= 0) { 3710 synchronized (mPidsSelfLocked) { 3711 app = mPidsSelfLocked.get(pid); 3712 } 3713 } else { 3714 app = null; 3715 } 3716 3717 if (app == null) { 3718 Slog.w(TAG, "No pending application record for pid " + pid 3719 + " (IApplicationThread " + thread + "); dropping process"); 3720 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 3721 if (pid > 0 && pid != MY_PID) { 3722 Process.killProcessQuiet(pid); 3723 } else { 3724 try { 3725 thread.scheduleExit(); 3726 } catch (Exception e) { 3727 // Ignore exceptions. 3728 } 3729 } 3730 return false; 3731 } 3732 3733 // If this application record is still attached to a previous 3734 // process, clean it up now. 3735 if (app.thread != null) { 3736 handleAppDiedLocked(app, true, true); 3737 } 3738 3739 // Tell the process all about itself. 3740 3741 if (localLOGV) Slog.v( 3742 TAG, "Binding process pid " + pid + " to record " + app); 3743 3744 String processName = app.processName; 3745 try { 3746 AppDeathRecipient adr = new AppDeathRecipient( 3747 app, pid, thread); 3748 thread.asBinder().linkToDeath(adr, 0); 3749 app.deathRecipient = adr; 3750 } catch (RemoteException e) { 3751 app.resetPackageList(); 3752 startProcessLocked(app, "link fail", processName); 3753 return false; 3754 } 3755 3756 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName); 3757 3758 app.thread = thread; 3759 app.curAdj = app.setAdj = -100; 3760 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 3761 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 3762 app.forcingToForeground = null; 3763 app.foregroundServices = false; 3764 app.hasShownUi = false; 3765 app.debugging = false; 3766 3767 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 3768 3769 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 3770 List providers = normalMode ? generateApplicationProvidersLocked(app) : null; 3771 3772 if (!normalMode) { 3773 Slog.i(TAG, "Launching preboot mode app: " + app); 3774 } 3775 3776 if (localLOGV) Slog.v( 3777 TAG, "New app record " + app 3778 + " thread=" + thread.asBinder() + " pid=" + pid); 3779 try { 3780 int testMode = IApplicationThread.DEBUG_OFF; 3781 if (mDebugApp != null && mDebugApp.equals(processName)) { 3782 testMode = mWaitForDebugger 3783 ? IApplicationThread.DEBUG_WAIT 3784 : IApplicationThread.DEBUG_ON; 3785 app.debugging = true; 3786 if (mDebugTransient) { 3787 mDebugApp = mOrigDebugApp; 3788 mWaitForDebugger = mOrigWaitForDebugger; 3789 } 3790 } 3791 String profileFile = app.instrumentationProfileFile; 3792 ParcelFileDescriptor profileFd = null; 3793 boolean profileAutoStop = false; 3794 if (mProfileApp != null && mProfileApp.equals(processName)) { 3795 mProfileProc = app; 3796 profileFile = mProfileFile; 3797 profileFd = mProfileFd; 3798 profileAutoStop = mAutoStopProfiler; 3799 } 3800 3801 // If the app is being launched for restore or full backup, set it up specially 3802 boolean isRestrictedBackupMode = false; 3803 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 3804 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 3805 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 3806 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 3807 } 3808 3809 ensurePackageDexOpt(app.instrumentationInfo != null 3810 ? app.instrumentationInfo.packageName 3811 : app.info.packageName); 3812 if (app.instrumentationClass != null) { 3813 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 3814 } 3815 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc " 3816 + processName + " with config " + mConfiguration); 3817 ApplicationInfo appInfo = app.instrumentationInfo != null 3818 ? app.instrumentationInfo : app.info; 3819 app.compat = compatibilityInfoForPackageLocked(appInfo); 3820 if (profileFd != null) { 3821 profileFd = profileFd.dup(); 3822 } 3823 thread.bindApplication(processName, appInfo, providers, 3824 app.instrumentationClass, profileFile, profileFd, profileAutoStop, 3825 app.instrumentationArguments, app.instrumentationWatcher, testMode, 3826 isRestrictedBackupMode || !normalMode, app.persistent, 3827 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), 3828 mCoreSettingsObserver.getCoreSettingsLocked()); 3829 updateLruProcessLocked(app, false, true); 3830 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 3831 } catch (Exception e) { 3832 // todo: Yikes! What should we do? For now we will try to 3833 // start another process, but that could easily get us in 3834 // an infinite loop of restarting processes... 3835 Slog.w(TAG, "Exception thrown during bind!", e); 3836 3837 app.resetPackageList(); 3838 app.unlinkDeathRecipient(); 3839 startProcessLocked(app, "bind fail", processName); 3840 return false; 3841 } 3842 3843 // Remove this record from the list of starting applications. 3844 mPersistentStartingProcesses.remove(app); 3845 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 3846 "Attach application locked removing on hold: " + app); 3847 mProcessesOnHold.remove(app); 3848 3849 boolean badApp = false; 3850 boolean didSomething = false; 3851 3852 // See if the top visible activity is waiting to run in this process... 3853 ActivityRecord hr = mMainStack.topRunningActivityLocked(null); 3854 if (hr != null && normalMode) { 3855 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid 3856 && processName.equals(hr.processName)) { 3857 try { 3858 if (mMainStack.realStartActivityLocked(hr, app, true, true)) { 3859 didSomething = true; 3860 } 3861 } catch (Exception e) { 3862 Slog.w(TAG, "Exception in new application when starting activity " 3863 + hr.intent.getComponent().flattenToShortString(), e); 3864 badApp = true; 3865 } 3866 } else { 3867 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0); 3868 } 3869 } 3870 3871 // Find any services that should be running in this process... 3872 if (!badApp && mPendingServices.size() > 0) { 3873 ServiceRecord sr = null; 3874 try { 3875 for (int i=0; i<mPendingServices.size(); i++) { 3876 sr = mPendingServices.get(i); 3877 if (app.info.uid != sr.appInfo.uid 3878 || !processName.equals(sr.processName)) { 3879 continue; 3880 } 3881 3882 mPendingServices.remove(i); 3883 i--; 3884 realStartServiceLocked(sr, app); 3885 didSomething = true; 3886 } 3887 } catch (Exception e) { 3888 Slog.w(TAG, "Exception in new application when starting service " 3889 + sr.shortName, e); 3890 badApp = true; 3891 } 3892 } 3893 3894 // Check if the next broadcast receiver is in this process... 3895 BroadcastRecord br = mPendingBroadcast; 3896 if (!badApp && br != null && br.curApp == app) { 3897 try { 3898 mPendingBroadcast = null; 3899 processCurBroadcastLocked(br, app); 3900 didSomething = true; 3901 } catch (Exception e) { 3902 Slog.w(TAG, "Exception in new application when starting receiver " 3903 + br.curComponent.flattenToShortString(), e); 3904 badApp = true; 3905 logBroadcastReceiverDiscardLocked(br); 3906 finishReceiverLocked(br.receiver, br.resultCode, br.resultData, 3907 br.resultExtras, br.resultAbort, true); 3908 scheduleBroadcastsLocked(); 3909 // We need to reset the state if we fails to start the receiver. 3910 br.state = BroadcastRecord.IDLE; 3911 } 3912 } 3913 3914 // Check whether the next backup agent is in this process... 3915 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) { 3916 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app); 3917 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 3918 try { 3919 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 3920 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 3921 mBackupTarget.backupMode); 3922 } catch (Exception e) { 3923 Slog.w(TAG, "Exception scheduling backup agent creation: "); 3924 e.printStackTrace(); 3925 } 3926 } 3927 3928 if (badApp) { 3929 // todo: Also need to kill application to deal with all 3930 // kinds of exceptions. 3931 handleAppDiedLocked(app, false, true); 3932 return false; 3933 } 3934 3935 if (!didSomething) { 3936 updateOomAdjLocked(); 3937 } 3938 3939 return true; 3940 } 3941 3942 public final void attachApplication(IApplicationThread thread) { 3943 synchronized (this) { 3944 int callingPid = Binder.getCallingPid(); 3945 final long origId = Binder.clearCallingIdentity(); 3946 attachApplicationLocked(thread, callingPid); 3947 Binder.restoreCallingIdentity(origId); 3948 } 3949 } 3950 3951 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 3952 final long origId = Binder.clearCallingIdentity(); 3953 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config); 3954 if (stopProfiling) { 3955 synchronized (this) { 3956 if (mProfileProc == r.app) { 3957 if (mProfileFd != null) { 3958 try { 3959 mProfileFd.close(); 3960 } catch (IOException e) { 3961 } 3962 clearProfilerLocked(); 3963 } 3964 } 3965 } 3966 } 3967 Binder.restoreCallingIdentity(origId); 3968 } 3969 3970 void enableScreenAfterBoot() { 3971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 3972 SystemClock.uptimeMillis()); 3973 mWindowManager.enableScreenAfterBoot(); 3974 } 3975 3976 public void showBootMessage(final CharSequence msg, final boolean always) { 3977 mWindowManager.showBootMessage(msg, always); 3978 } 3979 3980 public void dismissKeyguardOnNextActivity() { 3981 synchronized (this) { 3982 mMainStack.dismissKeyguardOnNextActivityLocked(); 3983 } 3984 } 3985 3986 final void finishBooting() { 3987 IntentFilter pkgFilter = new IntentFilter(); 3988 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 3989 pkgFilter.addDataScheme("package"); 3990 mContext.registerReceiver(new BroadcastReceiver() { 3991 @Override 3992