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 static android.content.pm.PackageManager.PERMISSION_GRANTED; 20 21 import android.app.AppOpsManager; 22 import android.appwidget.AppWidgetManager; 23 import com.android.internal.R; 24 import com.android.internal.os.BatteryStatsImpl; 25 import com.android.internal.os.ProcessStats; 26 import com.android.server.AppOpsService; 27 import com.android.server.AttributeCache; 28 import com.android.server.IntentResolver; 29 import com.android.server.ProcessMap; 30 import com.android.server.SystemServer; 31 import com.android.server.Watchdog; 32 import com.android.server.am.ActivityStack.ActivityState; 33 import com.android.server.firewall.IntentFirewall; 34 import com.android.server.pm.UserManagerService; 35 import com.android.server.wm.AppTransition; 36 import com.android.server.wm.WindowManagerService; 37 38 import dalvik.system.Zygote; 39 40 import android.app.Activity; 41 import android.app.ActivityManager; 42 import android.app.ActivityManagerNative; 43 import android.app.ActivityOptions; 44 import android.app.ActivityThread; 45 import android.app.AlertDialog; 46 import android.app.AppGlobals; 47 import android.app.ApplicationErrorReport; 48 import android.app.Dialog; 49 import android.app.IActivityController; 50 import android.app.IApplicationThread; 51 import android.app.IInstrumentationWatcher; 52 import android.app.INotificationManager; 53 import android.app.IProcessObserver; 54 import android.app.IServiceConnection; 55 import android.app.IStopUserCallback; 56 import android.app.IThumbnailReceiver; 57 import android.app.IUiAutomationConnection; 58 import android.app.IUserSwitchObserver; 59 import android.app.Instrumentation; 60 import android.app.Notification; 61 import android.app.NotificationManager; 62 import android.app.PendingIntent; 63 import android.app.backup.IBackupManager; 64 import android.content.ActivityNotFoundException; 65 import android.content.BroadcastReceiver; 66 import android.content.ClipData; 67 import android.content.ComponentCallbacks2; 68 import android.content.ComponentName; 69 import android.content.ContentProvider; 70 import android.content.ContentResolver; 71 import android.content.Context; 72 import android.content.DialogInterface; 73 import android.content.IContentProvider; 74 import android.content.IIntentReceiver; 75 import android.content.IIntentSender; 76 import android.content.Intent; 77 import android.content.IntentFilter; 78 import android.content.IntentSender; 79 import android.content.pm.ActivityInfo; 80 import android.content.pm.ApplicationInfo; 81 import android.content.pm.ConfigurationInfo; 82 import android.content.pm.IPackageDataObserver; 83 import android.content.pm.IPackageManager; 84 import android.content.pm.InstrumentationInfo; 85 import android.content.pm.PackageInfo; 86 import android.content.pm.PackageManager; 87 import android.content.pm.UserInfo; 88 import android.content.pm.PackageManager.NameNotFoundException; 89 import android.content.pm.PathPermission; 90 import android.content.pm.ProviderInfo; 91 import android.content.pm.ResolveInfo; 92 import android.content.pm.ServiceInfo; 93 import android.content.res.CompatibilityInfo; 94 import android.content.res.Configuration; 95 import android.graphics.Bitmap; 96 import android.net.Proxy; 97 import android.net.ProxyProperties; 98 import android.net.Uri; 99 import android.os.Binder; 100 import android.os.Build; 101 import android.os.Bundle; 102 import android.os.Debug; 103 import android.os.DropBoxManager; 104 import android.os.Environment; 105 import android.os.FileObserver; 106 import android.os.FileUtils; 107 import android.os.Handler; 108 import android.os.IBinder; 109 import android.os.IPermissionController; 110 import android.os.IRemoteCallback; 111 import android.os.IUserManager; 112 import android.os.Looper; 113 import android.os.Message; 114 import android.os.Parcel; 115 import android.os.ParcelFileDescriptor; 116 import android.os.Process; 117 import android.os.RemoteCallbackList; 118 import android.os.RemoteException; 119 import android.os.SELinux; 120 import android.os.ServiceManager; 121 import android.os.StrictMode; 122 import android.os.SystemClock; 123 import android.os.SystemProperties; 124 import android.os.UpdateLock; 125 import android.os.UserHandle; 126 import android.provider.Settings; 127 import android.text.format.Time; 128 import android.util.EventLog; 129 import android.util.Log; 130 import android.util.Pair; 131 import android.util.PrintWriterPrinter; 132 import android.util.Slog; 133 import android.util.SparseArray; 134 import android.util.TimeUtils; 135 import android.view.Gravity; 136 import android.view.LayoutInflater; 137 import android.view.View; 138 import android.view.WindowManager; 139 140 import java.io.BufferedInputStream; 141 import java.io.BufferedOutputStream; 142 import java.io.BufferedReader; 143 import java.io.DataInputStream; 144 import java.io.DataOutputStream; 145 import java.io.File; 146 import java.io.FileDescriptor; 147 import java.io.FileInputStream; 148 import java.io.FileNotFoundException; 149 import java.io.FileOutputStream; 150 import java.io.IOException; 151 import java.io.InputStreamReader; 152 import java.io.PrintWriter; 153 import java.io.StringWriter; 154 import java.lang.ref.WeakReference; 155 import java.util.ArrayList; 156 import java.util.Arrays; 157 import java.util.Collections; 158 import java.util.Comparator; 159 import java.util.HashMap; 160 import java.util.HashSet; 161 import java.util.Iterator; 162 import java.util.List; 163 import java.util.Locale; 164 import java.util.Map; 165 import java.util.Set; 166 import java.util.concurrent.atomic.AtomicBoolean; 167 import java.util.concurrent.atomic.AtomicLong; 168 169 public final class ActivityManagerService extends ActivityManagerNative 170 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 171 private static final String USER_DATA_DIR = "/data/user/"; 172 static final String TAG = "ActivityManager"; 173 static final String TAG_MU = "ActivityManagerServiceMU"; 174 static final boolean DEBUG = false; 175 static final boolean localLOGV = DEBUG; 176 static final boolean DEBUG_SWITCH = localLOGV || false; 177 static final boolean DEBUG_TASKS = localLOGV || false; 178 static final boolean DEBUG_THUMBNAILS = localLOGV || false; 179 static final boolean DEBUG_PAUSE = localLOGV || false; 180 static final boolean DEBUG_OOM_ADJ = localLOGV || false; 181 static final boolean DEBUG_TRANSITION = localLOGV || false; 182 static final boolean DEBUG_BROADCAST = localLOGV || false; 183 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false; 184 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false; 185 static final boolean DEBUG_SERVICE = localLOGV || false; 186 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false; 187 static final boolean DEBUG_VISBILITY = localLOGV || false; 188 static final boolean DEBUG_PROCESSES = localLOGV || false; 189 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false; 190 static final boolean DEBUG_CLEANUP = localLOGV || false; 191 static final boolean DEBUG_PROVIDER = localLOGV || false; 192 static final boolean DEBUG_URI_PERMISSION = localLOGV || false; 193 static final boolean DEBUG_USER_LEAVING = localLOGV || false; 194 static final boolean DEBUG_RESULTS = localLOGV || false; 195 static final boolean DEBUG_BACKUP = localLOGV || false; 196 static final boolean DEBUG_CONFIGURATION = localLOGV || false; 197 static final boolean DEBUG_POWER = localLOGV || false; 198 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false; 199 static final boolean DEBUG_MU = localLOGV || false; 200 static final boolean DEBUG_IMMERSIVE = localLOGV || false; 201 static final boolean VALIDATE_TOKENS = false; 202 static final boolean SHOW_ACTIVITY_START_TIME = true; 203 204 // Control over CPU and battery monitoring. 205 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes. 206 static final boolean MONITOR_CPU_USAGE = true; 207 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds. 208 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample. 209 static final boolean MONITOR_THREAD_CPU_USAGE = false; 210 211 // The flags that are set for all calls we make to the package manager. 212 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 213 214 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 215 216 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 217 218 // Maximum number of recent tasks that we can remember. 219 static final int MAX_RECENT_TASKS = 20; 220 221 // Amount of time after a call to stopAppSwitches() during which we will 222 // prevent further untrusted switches from happening. 223 static final long APP_SWITCH_DELAY_TIME = 5*1000; 224 225 // How long we wait for a launched process to attach to the activity manager 226 // before we decide it's never going to come up for real. 227 static final int PROC_START_TIMEOUT = 10*1000; 228 229 // How long we wait for a launched process to attach to the activity manager 230 // before we decide it's never going to come up for real, when the process was 231 // started with a wrapper for instrumentation (such as Valgrind) because it 232 // could take much longer than usual. 233 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000; 234 235 // How long to wait after going idle before forcing apps to GC. 236 static final int GC_TIMEOUT = 5*1000; 237 238 // The minimum amount of time between successive GC requests for a process. 239 static final int GC_MIN_INTERVAL = 60*1000; 240 241 // The rate at which we check for apps using excessive power -- 15 mins. 242 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 243 244 // The minimum sample duration we will allow before deciding we have 245 // enough data on wake locks to start killing things. 246 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 247 248 // The minimum sample duration we will allow before deciding we have 249 // enough data on CPU usage to start killing things. 250 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 251 252 // How long we allow a receiver to run before giving up on it. 253 static final int BROADCAST_FG_TIMEOUT = 10*1000; 254 static final int BROADCAST_BG_TIMEOUT = 60*1000; 255 256 // How long we wait until we timeout on key dispatching. 257 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 258 259 // How long we wait until we timeout on key dispatching during instrumentation. 260 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 261 262 // Amount of time we wait for observers to handle a user switch before 263 // giving up on them and unfreezing the screen. 264 static final int USER_SWITCH_TIMEOUT = 2*1000; 265 266 // Maximum number of users we allow to be running at a time. 267 static final int MAX_RUNNING_USERS = 3; 268 269 // How long to wait in getTopActivityExtras for the activity to respond with the result. 270 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000; 271 272 static final int MY_PID = Process.myPid(); 273 274 static final String[] EMPTY_STRING_ARRAY = new String[0]; 275 276 public ActivityStack mMainStack; 277 278 public IntentFirewall mIntentFirewall; 279 280 private final boolean mHeadless; 281 282 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 283 // default actuion automatically. Important for devices without direct input 284 // devices. 285 private boolean mShowDialogs = true; 286 287 /** 288 * Description of a request to start a new activity, which has been held 289 * due to app switches being disabled. 290 */ 291 static class PendingActivityLaunch { 292 ActivityRecord r; 293 ActivityRecord sourceRecord; 294 int startFlags; 295 } 296 297 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches 298 = new ArrayList<PendingActivityLaunch>(); 299 300 301 BroadcastQueue mFgBroadcastQueue; 302 BroadcastQueue mBgBroadcastQueue; 303 // Convenient for easy iteration over the queues. Foreground is first 304 // so that dispatch of foreground broadcasts gets precedence. 305 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 306 307 BroadcastQueue broadcastQueueForIntent(Intent intent) { 308 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 309 if (DEBUG_BACKGROUND_BROADCAST) { 310 Slog.i(TAG, "Broadcast intent " + intent + " on " 311 + (isFg ? "foreground" : "background") 312 + " queue"); 313 } 314 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 315 } 316 317 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) { 318 for (BroadcastQueue queue : mBroadcastQueues) { 319 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver); 320 if (r != null) { 321 return r; 322 } 323 } 324 return null; 325 } 326 327 /** 328 * Activity we have told the window manager to have key focus. 329 */ 330 ActivityRecord mFocusedActivity = null; 331 332 /** 333 * List of intents that were used to start the most recent tasks. 334 */ 335 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>(); 336 337 public class PendingActivityExtras extends Binder implements Runnable { 338 public final ActivityRecord activity; 339 public boolean haveResult = false; 340 public Bundle result = null; 341 public PendingActivityExtras(ActivityRecord _activity) { 342 activity = _activity; 343 } 344 @Override 345 public void run() { 346 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity); 347 synchronized (this) { 348 haveResult = true; 349 notifyAll(); 350 } 351 } 352 } 353 354 final ArrayList<PendingActivityExtras> mPendingActivityExtras 355 = new ArrayList<PendingActivityExtras>(); 356 357 /** 358 * Process management. 359 */ 360 final ProcessList mProcessList = new ProcessList(); 361 362 /** 363 * All of the applications we currently have running organized by name. 364 * The keys are strings of the application package name (as 365 * returned by the package manager), and the keys are ApplicationRecord 366 * objects. 367 */ 368 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 369 370 /** 371 * The currently running isolated processes. 372 */ 373 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 374 375 /** 376 * Counter for assigning isolated process uids, to avoid frequently reusing the 377 * same ones. 378 */ 379 int mNextIsolatedProcessUid = 0; 380 381 /** 382 * The currently running heavy-weight process, if any. 383 */ 384 ProcessRecord mHeavyWeightProcess = null; 385 386 /** 387 * The last time that various processes have crashed. 388 */ 389 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 390 391 /** 392 * Set of applications that we consider to be bad, and will reject 393 * incoming broadcasts from (which the user has no control over). 394 * Processes are added to this set when they have crashed twice within 395 * a minimum amount of time; they are removed from it when they are 396 * later restarted (hopefully due to some user action). The value is the 397 * time it was added to the list. 398 */ 399 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>(); 400 401 /** 402 * All of the processes we currently have running organized by pid. 403 * The keys are the pid running the application. 404 * 405 * <p>NOTE: This object is protected by its own lock, NOT the global 406 * activity manager lock! 407 */ 408 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 409 410 /** 411 * All of the processes that have been forced to be foreground. The key 412 * is the pid of the caller who requested it (we hold a death 413 * link on it). 414 */ 415 abstract class ForegroundToken implements IBinder.DeathRecipient { 416 int pid; 417 IBinder token; 418 } 419 final SparseArray<ForegroundToken> mForegroundProcesses 420 = new SparseArray<ForegroundToken>(); 421 422 /** 423 * List of records for processes that someone had tried to start before the 424 * system was ready. We don't start them at that point, but ensure they 425 * are started by the time booting is complete. 426 */ 427 final ArrayList<ProcessRecord> mProcessesOnHold 428 = new ArrayList<ProcessRecord>(); 429 430 /** 431 * List of persistent applications that are in the process 432 * of being started. 433 */ 434 final ArrayList<ProcessRecord> mPersistentStartingProcesses 435 = new ArrayList<ProcessRecord>(); 436 437 /** 438 * Processes that are being forcibly torn down. 439 */ 440 final ArrayList<ProcessRecord> mRemovedProcesses 441 = new ArrayList<ProcessRecord>(); 442 443 /** 444 * List of running applications, sorted by recent usage. 445 * The first entry in the list is the least recently used. 446 * It contains ApplicationRecord objects. This list does NOT include 447 * any persistent application records (since we never want to exit them). 448 */ 449 final ArrayList<ProcessRecord> mLruProcesses 450 = new ArrayList<ProcessRecord>(); 451 452 /** 453 * List of processes that should gc as soon as things are idle. 454 */ 455 final ArrayList<ProcessRecord> mProcessesToGc 456 = new ArrayList<ProcessRecord>(); 457 458 /** 459 * This is the process holding what we currently consider to be 460 * the "home" activity. 461 */ 462 ProcessRecord mHomeProcess; 463 464 /** 465 * This is the process holding the activity the user last visited that 466 * is in a different process from the one they are currently in. 467 */ 468 ProcessRecord mPreviousProcess; 469 470 /** 471 * The time at which the previous process was last visible. 472 */ 473 long mPreviousProcessVisibleTime; 474 475 /** 476 * Which uses have been started, so are allowed to run code. 477 */ 478 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>(); 479 480 /** 481 * LRU list of history of current users. Most recently current is at the end. 482 */ 483 final ArrayList<Integer> mUserLru = new ArrayList<Integer>(); 484 485 /** 486 * Constant array of the users that are currently started. 487 */ 488 int[] mStartedUserArray = new int[] { 0 }; 489 490 /** 491 * Registered observers of the user switching mechanics. 492 */ 493 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 494 = new RemoteCallbackList<IUserSwitchObserver>(); 495 496 /** 497 * Currently active user switch. 498 */ 499 Object mCurUserSwitchCallback; 500 501 /** 502 * Packages that the user has asked to have run in screen size 503 * compatibility mode instead of filling the screen. 504 */ 505 final CompatModePackages mCompatModePackages; 506 507 /** 508 * Set of PendingResultRecord objects that are currently active. 509 */ 510 final HashSet mPendingResultRecords = new HashSet(); 511 512 /** 513 * Set of IntentSenderRecord objects that are currently active. 514 */ 515 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 516 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 517 518 /** 519 * Fingerprints (hashCode()) of stack traces that we've 520 * already logged DropBox entries for. Guarded by itself. If 521 * something (rogue user app) forces this over 522 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 523 */ 524 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 525 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 526 527 /** 528 * Strict Mode background batched logging state. 529 * 530 * The string buffer is guarded by itself, and its lock is also 531 * used to determine if another batched write is already 532 * in-flight. 533 */ 534 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 535 536 /** 537 * Keeps track of all IIntentReceivers that have been registered for 538 * broadcasts. Hash keys are the receiver IBinder, hash value is 539 * a ReceiverList. 540 */ 541 final HashMap mRegisteredReceivers = new HashMap(); 542 543 /** 544 * Resolver for broadcast intents to registered receivers. 545 * Holds BroadcastFilter (subclass of IntentFilter). 546 */ 547 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 548 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 549 @Override 550 protected boolean allowFilterResult( 551 BroadcastFilter filter, List<BroadcastFilter> dest) { 552 IBinder target = filter.receiverList.receiver.asBinder(); 553 for (int i=dest.size()-1; i>=0; i--) { 554 if (dest.get(i).receiverList.receiver.asBinder() == target) { 555 return false; 556 } 557 } 558 return true; 559 } 560 561 @Override 562 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 563 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 564 || userId == filter.owningUserId) { 565 return super.newResult(filter, match, userId); 566 } 567 return null; 568 } 569 570 @Override 571 protected BroadcastFilter[] newArray(int size) { 572 return new BroadcastFilter[size]; 573 } 574 575 @Override 576 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 577 return packageName.equals(filter.packageName); 578 } 579 }; 580 581 /** 582 * State of all active sticky broadcasts per user. Keys are the action of the 583 * sticky Intent, values are an ArrayList of all broadcasted intents with 584 * that action (which should usually be one). The SparseArray is keyed 585 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 586 * for stickies that are sent to all users. 587 */ 588 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts = 589 new SparseArray<HashMap<String, ArrayList<Intent>>>(); 590 591 final ActiveServices mServices; 592 593 /** 594 * Backup/restore process management 595 */ 596 String mBackupAppName = null; 597 BackupRecord mBackupTarget = null; 598 599 /** 600 * List of PendingThumbnailsRecord objects of clients who are still 601 * waiting to receive all of the thumbnails for a task. 602 */ 603 final ArrayList mPendingThumbnails = new ArrayList(); 604 605 /** 606 * List of HistoryRecord objects that have been finished and must 607 * still report back to a pending thumbnail receiver. 608 */ 609 final ArrayList mCancelledThumbnails = new ArrayList(); 610 611 final ProviderMap mProviderMap; 612 613 /** 614 * List of content providers who have clients waiting for them. The 615 * application is currently being launched and the provider will be 616 * removed from this list once it is published. 617 */ 618 final ArrayList<ContentProviderRecord> mLaunchingProviders 619 = new ArrayList<ContentProviderRecord>(); 620 621 /** 622 * Global set of specific Uri permissions that have been granted. 623 */ 624 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions 625 = new SparseArray<HashMap<Uri, UriPermission>>(); 626 627 CoreSettingsObserver mCoreSettingsObserver; 628 629 /** 630 * Thread-local storage used to carry caller permissions over through 631 * indirect content-provider access. 632 */ 633 private class Identity { 634 public int pid; 635 public int uid; 636 637 Identity(int _pid, int _uid) { 638 pid = _pid; 639 uid = _uid; 640 } 641 } 642 643 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 644 645 /** 646 * All information we have collected about the runtime performance of 647 * any user id that can impact battery performance. 648 */ 649 final BatteryStatsService mBatteryStatsService; 650 651 /** 652 * Information about component usage 653 */ 654 final UsageStatsService mUsageStatsService; 655 656 /** 657 * Information about and control over application operations 658 */ 659 final AppOpsService mAppOpsService; 660 661 /** 662 * Current configuration information. HistoryRecord objects are given 663 * a reference to this object to indicate which configuration they are 664 * currently running in, so this object must be kept immutable. 665 */ 666 Configuration mConfiguration = new Configuration(); 667 668 /** 669 * Current sequencing integer of the configuration, for skipping old 670 * configurations. 671 */ 672 int mConfigurationSeq = 0; 673 674 /** 675 * Hardware-reported OpenGLES version. 676 */ 677 final int GL_ES_VERSION; 678 679 /** 680 * List of initialization arguments to pass to all processes when binding applications to them. 681 * For example, references to the commonly used services. 682 */ 683 HashMap<String, IBinder> mAppBindArgs; 684 685 /** 686 * Temporary to avoid allocations. Protected by main lock. 687 */ 688 final StringBuilder mStringBuilder = new StringBuilder(256); 689 690 /** 691 * Used to control how we initialize the service. 692 */ 693 boolean mStartRunning = false; 694 ComponentName mTopComponent; 695 String mTopAction; 696 String mTopData; 697 boolean mProcessesReady = false; 698 boolean mSystemReady = false; 699 boolean mBooting = false; 700 boolean mWaitingUpdate = false; 701 boolean mDidUpdate = false; 702 boolean mOnBattery = false; 703 boolean mLaunchWarningShown = false; 704 705 Context mContext; 706 707 int mFactoryTest; 708 709 boolean mCheckedForSetup; 710 711 /** 712 * The time at which we will allow normal application switches again, 713 * after a call to {@link #stopAppSwitches()}. 714 */ 715 long mAppSwitchesAllowedTime; 716 717 /** 718 * This is set to true after the first switch after mAppSwitchesAllowedTime 719 * is set; any switches after that will clear the time. 720 */ 721 boolean mDidAppSwitch; 722 723 /** 724 * Last time (in realtime) at which we checked for power usage. 725 */ 726 long mLastPowerCheckRealtime; 727 728 /** 729 * Last time (in uptime) at which we checked for power usage. 730 */ 731 long mLastPowerCheckUptime; 732 733 /** 734 * Set while we are wanting to sleep, to prevent any 735 * activities from being started/resumed. 736 */ 737 boolean mSleeping = false; 738 739 /** 740 * State of external calls telling us if the device is asleep. 741 */ 742 boolean mWentToSleep = false; 743 744 /** 745 * State of external call telling us if the lock screen is shown. 746 */ 747 boolean mLockScreenShown = false; 748 749 /** 750 * Set if we are shutting down the system, similar to sleeping. 751 */ 752 boolean mShuttingDown = false; 753 754 /** 755 * Task identifier that activities are currently being started 756 * in. Incremented each time a new task is created. 757 * todo: Replace this with a TokenSpace class that generates non-repeating 758 * integers that won't wrap. 759 */ 760 int mCurTask = 1; 761 762 /** 763 * Current sequence id for oom_adj computation traversal. 764 */ 765 int mAdjSeq = 0; 766 767 /** 768 * Current sequence id for process LRU updating. 769 */ 770 int mLruSeq = 0; 771 772 /** 773 * Keep track of the non-hidden/empty process we last found, to help 774 * determine how to distribute hidden/empty processes next time. 775 */ 776 int mNumNonHiddenProcs = 0; 777 778 /** 779 * Keep track of the number of hidden procs, to balance oom adj 780 * distribution between those and empty procs. 781 */ 782 int mNumHiddenProcs = 0; 783 784 /** 785 * Keep track of the number of service processes we last found, to 786 * determine on the next iteration which should be B services. 787 */ 788 int mNumServiceProcs = 0; 789 int mNewNumServiceProcs = 0; 790 791 /** 792 * System monitoring: number of processes that died since the last 793 * N procs were started. 794 */ 795 int[] mProcDeaths = new int[20]; 796 797 /** 798 * This is set if we had to do a delayed dexopt of an app before launching 799 * it, to increasing the ANR timeouts in that case. 800 */ 801 boolean mDidDexOpt; 802 803 String mDebugApp = null; 804 boolean mWaitForDebugger = false; 805 boolean mDebugTransient = false; 806 String mOrigDebugApp = null; 807 boolean mOrigWaitForDebugger = false; 808 boolean mAlwaysFinishActivities = false; 809 IActivityController mController = null; 810 String mProfileApp = null; 811 ProcessRecord mProfileProc = null; 812 String mProfileFile; 813 ParcelFileDescriptor mProfileFd; 814 int mProfileType = 0; 815 boolean mAutoStopProfiler = false; 816 String mOpenGlTraceApp = null; 817 818 static class ProcessChangeItem { 819 static final int CHANGE_ACTIVITIES = 1<<0; 820 static final int CHANGE_IMPORTANCE= 1<<1; 821 int changes; 822 int uid; 823 int pid; 824 int importance; 825 boolean foregroundActivities; 826 } 827 828 final RemoteCallbackList<IProcessObserver> mProcessObservers 829 = new RemoteCallbackList<IProcessObserver>(); 830 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 831 832 final ArrayList<ProcessChangeItem> mPendingProcessChanges 833 = new ArrayList<ProcessChangeItem>(); 834 final ArrayList<ProcessChangeItem> mAvailProcessChanges 835 = new ArrayList<ProcessChangeItem>(); 836 837 /** 838 * Runtime statistics collection thread. This object's lock is used to 839 * protect all related state. 840 */ 841 final Thread mProcessStatsThread; 842 843 /** 844 * Used to collect process stats when showing not responding dialog. 845 * Protected by mProcessStatsThread. 846 */ 847 final ProcessStats mProcessStats = new ProcessStats( 848 MONITOR_THREAD_CPU_USAGE); 849 final AtomicLong mLastCpuTime = new AtomicLong(0); 850 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true); 851 852 long mLastWriteTime = 0; 853 854 /** 855 * Used to retain an update lock when the foreground activity is in 856 * immersive mode. 857 */ 858 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 859 860 /** 861 * Set to true after the system has finished booting. 862 */ 863 boolean mBooted = false; 864 865 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS; 866 int mProcessLimitOverride = -1; 867 868 WindowManagerService mWindowManager; 869 870 static ActivityManagerService mSelf; 871 static ActivityThread mSystemThread; 872 873 private int mCurrentUserId = 0; 874 private int[] mCurrentUserArray = new int[] { 0 }; 875 private UserManagerService mUserManager; 876 877 private final class AppDeathRecipient implements IBinder.DeathRecipient { 878 final ProcessRecord mApp; 879 final int mPid; 880 final IApplicationThread mAppThread; 881 882 AppDeathRecipient(ProcessRecord app, int pid, 883 IApplicationThread thread) { 884 if (localLOGV) Slog.v( 885 TAG, "New death recipient " + this 886 + " for thread " + thread.asBinder()); 887 mApp = app; 888 mPid = pid; 889 mAppThread = thread; 890 } 891 892 public void binderDied() { 893 if (localLOGV) Slog.v( 894 TAG, "Death received in " + this 895 + " for thread " + mAppThread.asBinder()); 896 synchronized(ActivityManagerService.this) { 897 appDiedLocked(mApp, mPid, mAppThread); 898 } 899 } 900 } 901 902 static final int SHOW_ERROR_MSG = 1; 903 static final int SHOW_NOT_RESPONDING_MSG = 2; 904 static final int SHOW_FACTORY_ERROR_MSG = 3; 905 static final int UPDATE_CONFIGURATION_MSG = 4; 906 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 907 static final int WAIT_FOR_DEBUGGER_MSG = 6; 908 static final int SERVICE_TIMEOUT_MSG = 12; 909 static final int UPDATE_TIME_ZONE = 13; 910 static final int SHOW_UID_ERROR_MSG = 14; 911 static final int IM_FEELING_LUCKY_MSG = 15; 912 static final int PROC_START_TIMEOUT_MSG = 20; 913 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 914 static final int KILL_APPLICATION_MSG = 22; 915 static final int FINALIZE_PENDING_INTENT_MSG = 23; 916 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 917 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 918 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 919 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 920 static final int CLEAR_DNS_CACHE = 28; 921 static final int UPDATE_HTTP_PROXY = 29; 922 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 923 static final int DISPATCH_PROCESSES_CHANGED = 31; 924 static final int DISPATCH_PROCESS_DIED = 32; 925 static final int REPORT_MEM_USAGE = 33; 926 static final int REPORT_USER_SWITCH_MSG = 34; 927 static final int CONTINUE_USER_SWITCH_MSG = 35; 928 static final int USER_SWITCH_TIMEOUT_MSG = 36; 929 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 930 931 static final int FIRST_ACTIVITY_STACK_MSG = 100; 932 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 933 static final int FIRST_COMPAT_MODE_MSG = 300; 934 935 AlertDialog mUidAlert; 936 CompatModeDialog mCompatModeDialog; 937 long mLastMemUsageReportTime = 0; 938 939 /** 940 * Flag whether the current user is a "monkey", i.e. whether 941 * the UI is driven by a UI automation tool. 942 */ 943 private boolean mUserIsMonkey; 944 945 final Handler mHandler = new Handler() { 946 //public Handler() { 947 // if (localLOGV) Slog.v(TAG, "Handler started!"); 948 //} 949 950 public void handleMessage(Message msg) { 951 switch (msg.what) { 952 case SHOW_ERROR_MSG: { 953 HashMap data = (HashMap) msg.obj; 954 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 955 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 956 synchronized (ActivityManagerService.this) { 957 ProcessRecord proc = (ProcessRecord)data.get("app"); 958 AppErrorResult res = (AppErrorResult) data.get("result"); 959 if (proc != null && proc.crashDialog != null) { 960 Slog.e(TAG, "App already has crash dialog: " + proc); 961 if (res != null) { 962 res.set(0); 963 } 964 return; 965 } 966 if (!showBackground && UserHandle.getAppId(proc.uid) 967 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId 968 && proc.pid != MY_PID) { 969 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 970 if (res != null) { 971 res.set(0); 972 } 973 return; 974 } 975 if (mShowDialogs && !mSleeping && !mShuttingDown) { 976 Dialog d = new AppErrorDialog(mContext, 977 ActivityManagerService.this, res, proc); 978 d.show(); 979 proc.crashDialog = d; 980 } else { 981 // The device is asleep, so just pretend that the user 982 // saw a crash dialog and hit "force quit". 983 if (res != null) { 984 res.set(0); 985 } 986 } 987 } 988 989 ensureBootCompleted(); 990 } break; 991 case SHOW_NOT_RESPONDING_MSG: { 992 synchronized (ActivityManagerService.this) { 993 HashMap data = (HashMap) msg.obj; 994 ProcessRecord proc = (ProcessRecord)data.get("app"); 995 if (proc != null && proc.anrDialog != null) { 996 Slog.e(TAG, "App already has anr dialog: " + proc); 997 return; 998 } 999 1000 Intent intent = new Intent("android.intent.action.ANR"); 1001 if (!mProcessesReady) { 1002 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1003 | Intent.FLAG_RECEIVER_FOREGROUND); 1004 } 1005 broadcastIntentLocked(null, null, intent, 1006 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1007 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 1008 1009 if (mShowDialogs) { 1010 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 1011 mContext, proc, (ActivityRecord)data.get("activity"), 1012 msg.arg1 != 0); 1013 d.show(); 1014 proc.anrDialog = d; 1015 } else { 1016 // Just kill the app if there is no dialog to be shown. 1017 killAppAtUsersRequest(proc, null); 1018 } 1019 } 1020 1021 ensureBootCompleted(); 1022 } break; 1023 case SHOW_STRICT_MODE_VIOLATION_MSG: { 1024 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1025 synchronized (ActivityManagerService.this) { 1026 ProcessRecord proc = (ProcessRecord) data.get("app"); 1027 if (proc == null) { 1028 Slog.e(TAG, "App not found when showing strict mode dialog."); 1029 break; 1030 } 1031 if (proc.crashDialog != null) { 1032 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1033 return; 1034 } 1035 AppErrorResult res = (AppErrorResult) data.get("result"); 1036 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1037 Dialog d = new StrictModeViolationDialog(mContext, 1038 ActivityManagerService.this, res, proc); 1039 d.show(); 1040 proc.crashDialog = d; 1041 } else { 1042 // The device is asleep, so just pretend that the user 1043 // saw a crash dialog and hit "force quit". 1044 res.set(0); 1045 } 1046 } 1047 ensureBootCompleted(); 1048 } break; 1049 case SHOW_FACTORY_ERROR_MSG: { 1050 Dialog d = new FactoryErrorDialog( 1051 mContext, msg.getData().getCharSequence("msg")); 1052 d.show(); 1053 ensureBootCompleted(); 1054 } break; 1055 case UPDATE_CONFIGURATION_MSG: { 1056 final ContentResolver resolver = mContext.getContentResolver(); 1057 Settings.System.putConfiguration(resolver, (Configuration)msg.obj); 1058 } break; 1059 case GC_BACKGROUND_PROCESSES_MSG: { 1060 synchronized (ActivityManagerService.this) { 1061 performAppGcsIfAppropriateLocked(); 1062 } 1063 } break; 1064 case WAIT_FOR_DEBUGGER_MSG: { 1065 synchronized (ActivityManagerService.this) { 1066 ProcessRecord app = (ProcessRecord)msg.obj; 1067 if (msg.arg1 != 0) { 1068 if (!app.waitedForDebugger) { 1069 Dialog d = new AppWaitingForDebuggerDialog( 1070 ActivityManagerService.this, 1071 mContext, app); 1072 app.waitDialog = d; 1073 app.waitedForDebugger = true; 1074 d.show(); 1075 } 1076 } else { 1077 if (app.waitDialog != null) { 1078 app.waitDialog.dismiss(); 1079 app.waitDialog = null; 1080 } 1081 } 1082 } 1083 } break; 1084 case SERVICE_TIMEOUT_MSG: { 1085 if (mDidDexOpt) { 1086 mDidDexOpt = false; 1087 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1088 nmsg.obj = msg.obj; 1089 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1090 return; 1091 } 1092 mServices.serviceTimeout((ProcessRecord)msg.obj); 1093 } break; 1094 case UPDATE_TIME_ZONE: { 1095 synchronized (ActivityManagerService.this) { 1096 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1097 ProcessRecord r = mLruProcesses.get(i); 1098 if (r.thread != null) { 1099 try { 1100 r.thread.updateTimeZone(); 1101 } catch (RemoteException ex) { 1102 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1103 } 1104 } 1105 } 1106 } 1107 } break; 1108 case CLEAR_DNS_CACHE: { 1109 synchronized (ActivityManagerService.this) { 1110 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1111 ProcessRecord r = mLruProcesses.get(i); 1112 if (r.thread != null) { 1113 try { 1114 r.thread.clearDnsCache(); 1115 } catch (RemoteException ex) { 1116 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1117 } 1118 } 1119 } 1120 } 1121 } break; 1122 case UPDATE_HTTP_PROXY: { 1123 ProxyProperties proxy = (ProxyProperties)msg.obj; 1124 String host = ""; 1125 String port = ""; 1126 String exclList = ""; 1127 if (proxy != null) { 1128 host = proxy.getHost(); 1129 port = Integer.toString(proxy.getPort()); 1130 exclList = proxy.getExclusionList(); 1131 } 1132 synchronized (ActivityManagerService.this) { 1133 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1134 ProcessRecord r = mLruProcesses.get(i); 1135 if (r.thread != null) { 1136 try { 1137 r.thread.setHttpProxy(host, port, exclList); 1138 } catch (RemoteException ex) { 1139 Slog.w(TAG, "Failed to update http proxy for: " + 1140 r.info.processName); 1141 } 1142 } 1143 } 1144 } 1145 } break; 1146 case SHOW_UID_ERROR_MSG: { 1147 String title = "System UIDs Inconsistent"; 1148 String text = "UIDs on the system are inconsistent, you need to wipe your" 1149 + " data partition or your device will be unstable."; 1150 Log.e(TAG, title + ": " + text); 1151 if (mShowDialogs) { 1152 // XXX This is a temporary dialog, no need to localize. 1153 AlertDialog d = new BaseErrorDialog(mContext); 1154 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1155 d.setCancelable(false); 1156 d.setTitle(title); 1157 d.setMessage(text); 1158 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky", 1159 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG)); 1160 mUidAlert = d; 1161 d.show(); 1162 } 1163 } break; 1164 case IM_FEELING_LUCKY_MSG: { 1165 if (mUidAlert != null) { 1166 mUidAlert.dismiss(); 1167 mUidAlert = null; 1168 } 1169 } break; 1170 case PROC_START_TIMEOUT_MSG: { 1171 if (mDidDexOpt) { 1172 mDidDexOpt = false; 1173 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1174 nmsg.obj = msg.obj; 1175 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1176 return; 1177 } 1178 ProcessRecord app = (ProcessRecord)msg.obj; 1179 synchronized (ActivityManagerService.this) { 1180 processStartTimedOutLocked(app); 1181 } 1182 } break; 1183 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1184 synchronized (ActivityManagerService.this) { 1185 doPendingActivityLaunchesLocked(true); 1186 } 1187 } break; 1188 case KILL_APPLICATION_MSG: { 1189 synchronized (ActivityManagerService.this) { 1190 int appid = msg.arg1; 1191 boolean restart = (msg.arg2 == 1); 1192 String pkg = (String) msg.obj; 1193 forceStopPackageLocked(pkg, appid, restart, false, true, false, 1194 UserHandle.USER_ALL); 1195 } 1196 } break; 1197 case FINALIZE_PENDING_INTENT_MSG: { 1198 ((PendingIntentRecord)msg.obj).completeFinalize(); 1199 } break; 1200 case POST_HEAVY_NOTIFICATION_MSG: { 1201 INotificationManager inm = NotificationManager.getService(); 1202 if (inm == null) { 1203 return; 1204 } 1205 1206 ActivityRecord root = (ActivityRecord)msg.obj; 1207 ProcessRecord process = root.app; 1208 if (process == null) { 1209 return; 1210 } 1211 1212 try { 1213 Context context = mContext.createPackageContext(process.info.packageName, 0); 1214 String text = mContext.getString(R.string.heavy_weight_notification, 1215 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1216 Notification notification = new Notification(); 1217 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon; 1218 notification.when = 0; 1219 notification.flags = Notification.FLAG_ONGOING_EVENT; 1220 notification.tickerText = text; 1221 notification.defaults = 0; // please be quiet 1222 notification.sound = null; 1223 notification.vibrate = null; 1224 notification.setLatestEventInfo(context, text, 1225 mContext.getText(R.string.heavy_weight_notification_detail), 1226 PendingIntent.getActivityAsUser(mContext, 0, root.intent, 1227 PendingIntent.FLAG_CANCEL_CURRENT, null, 1228 new UserHandle(root.userId))); 1229 1230 try { 1231 int[] outId = new int[1]; 1232 inm.enqueueNotificationWithTag("android", "android", null, 1233 R.string.heavy_weight_notification, 1234 notification, outId, root.userId); 1235 } catch (RuntimeException e) { 1236 Slog.w(ActivityManagerService.TAG, 1237 "Error showing notification for heavy-weight app", e); 1238 } catch (RemoteException e) { 1239 } 1240 } catch (NameNotFoundException e) { 1241 Slog.w(TAG, "Unable to create context for heavy notification", e); 1242 } 1243 } break; 1244 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1245 INotificationManager inm = NotificationManager.getService(); 1246 if (inm == null) { 1247 return; 1248 } 1249 try { 1250 inm.cancelNotificationWithTag("android", null, 1251 R.string.heavy_weight_notification, msg.arg1); 1252 } catch (RuntimeException e) { 1253 Slog.w(ActivityManagerService.TAG, 1254 "Error canceling notification for service", e); 1255 } catch (RemoteException e) { 1256 } 1257 } break; 1258 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1259 synchronized (ActivityManagerService.this) { 1260 checkExcessivePowerUsageLocked(true); 1261 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1262 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1263 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1264 } 1265 } break; 1266 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1267 synchronized (ActivityManagerService.this) { 1268 ActivityRecord ar = (ActivityRecord)msg.obj; 1269 if (mCompatModeDialog != null) { 1270 if (mCompatModeDialog.mAppInfo.packageName.equals( 1271 ar.info.applicationInfo.packageName)) { 1272 return; 1273 } 1274 mCompatModeDialog.dismiss(); 1275 mCompatModeDialog = null; 1276 } 1277 if (ar != null && false) { 1278 if (mCompatModePackages.getPackageAskCompatModeLocked( 1279 ar.packageName)) { 1280 int mode = mCompatModePackages.computeCompatModeLocked( 1281 ar.info.applicationInfo); 1282 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1283 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1284 mCompatModeDialog = new CompatModeDialog( 1285 ActivityManagerService.this, mContext, 1286 ar.info.applicationInfo); 1287 mCompatModeDialog.show(); 1288 } 1289 } 1290 } 1291 } 1292 break; 1293 } 1294 case DISPATCH_PROCESSES_CHANGED: { 1295 dispatchProcessesChanged(); 1296 break; 1297 } 1298 case DISPATCH_PROCESS_DIED: { 1299 final int pid = msg.arg1; 1300 final int uid = msg.arg2; 1301 dispatchProcessDied(pid, uid); 1302 break; 1303 } 1304 case REPORT_MEM_USAGE: { 1305 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 1306 if (!isDebuggable) { 1307 return; 1308 } 1309 synchronized (ActivityManagerService.this) { 1310 long now = SystemClock.uptimeMillis(); 1311 if (now < (mLastMemUsageReportTime+5*60*1000)) { 1312 // Don't report more than every 5 minutes to somewhat 1313 // avoid spamming. 1314 return; 1315 } 1316 mLastMemUsageReportTime = now; 1317 } 1318 Thread thread = new Thread() { 1319 @Override public void run() { 1320 StringBuilder dropBuilder = new StringBuilder(1024); 1321 StringBuilder logBuilder = new StringBuilder(1024); 1322 StringWriter oomSw = new StringWriter(); 1323 PrintWriter oomPw = new PrintWriter(oomSw); 1324 StringWriter catSw = new StringWriter(); 1325 PrintWriter catPw = new PrintWriter(catSw); 1326 String[] emptyArgs = new String[] { }; 1327 StringBuilder tag = new StringBuilder(128); 1328 StringBuilder stack = new StringBuilder(128); 1329 tag.append("Low on memory -- "); 1330 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw, 1331 tag, stack); 1332 dropBuilder.append(stack); 1333 dropBuilder.append('\n'); 1334 dropBuilder.append('\n'); 1335 String oomString = oomSw.toString(); 1336 dropBuilder.append(oomString); 1337 dropBuilder.append('\n'); 1338 logBuilder.append(oomString); 1339 try { 1340 java.lang.Process proc = Runtime.getRuntime().exec(new String[] { 1341 "procrank", }); 1342 final InputStreamReader converter = new InputStreamReader( 1343 proc.getInputStream()); 1344 BufferedReader in = new BufferedReader(converter); 1345 String line; 1346 while (true) { 1347 line = in.readLine(); 1348 if (line == null) { 1349 break; 1350 } 1351 if (line.length() > 0) { 1352 logBuilder.append(line); 1353 logBuilder.append('\n'); 1354 } 1355 dropBuilder.append(line); 1356 dropBuilder.append('\n'); 1357 } 1358 converter.close(); 1359 } catch (IOException e) { 1360 } 1361 synchronized (ActivityManagerService.this) { 1362 catPw.println(); 1363 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 1364 catPw.println(); 1365 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0, 1366 false, false, null); 1367 catPw.println(); 1368 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 1369 } 1370 dropBuilder.append(catSw.toString()); 1371 addErrorToDropBox("lowmem", null, "system_server", null, 1372 null, tag.toString(), dropBuilder.toString(), null, null); 1373 Slog.i(TAG, logBuilder.toString()); 1374 synchronized (ActivityManagerService.this) { 1375 long now = SystemClock.uptimeMillis(); 1376 if (mLastMemUsageReportTime < now) { 1377 mLastMemUsageReportTime = now; 1378 } 1379 } 1380 } 1381 }; 1382 thread.start(); 1383 break; 1384 } 1385 case REPORT_USER_SWITCH_MSG: { 1386 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1387 break; 1388 } 1389 case CONTINUE_USER_SWITCH_MSG: { 1390 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1391 break; 1392 } 1393 case USER_SWITCH_TIMEOUT_MSG: { 1394 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1395 break; 1396 } 1397 case IMMERSIVE_MODE_LOCK_MSG: { 1398 final boolean nextState = (msg.arg1 != 0); 1399 if (mUpdateLock.isHeld() != nextState) { 1400 if (DEBUG_IMMERSIVE) { 1401 final ActivityRecord r = (ActivityRecord) msg.obj; 1402 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r); 1403 } 1404 if (nextState) { 1405 mUpdateLock.acquire(); 1406 } else { 1407 mUpdateLock.release(); 1408 } 1409 } 1410 break; 1411 } 1412 } 1413 } 1414 }; 1415 1416 public static void setSystemProcess() { 1417 try { 1418 ActivityManagerService m = mSelf; 1419 1420 ServiceManager.addService("activity", m, true); 1421 ServiceManager.addService("meminfo", new MemBinder(m)); 1422 ServiceManager.addService("gfxinfo", new GraphicsBinder(m)); 1423 ServiceManager.addService("dbinfo", new DbBinder(m)); 1424 if (MONITOR_CPU_USAGE) { 1425 ServiceManager.addService("cpuinfo", new CpuBinder(m)); 1426 } 1427 ServiceManager.addService("permission", new PermissionController(m)); 1428 1429 ApplicationInfo info = 1430 mSelf.mContext.getPackageManager().getApplicationInfo( 1431 "android", STOCK_PM_FLAGS); 1432 mSystemThread.installSystemApplicationInfo(info); 1433 1434 synchronized (mSelf) { 1435 ProcessRecord app = mSelf.newProcessRecordLocked( 1436 mSystemThread.getApplicationThread(), info, 1437 info.processName, false); 1438 app.persistent = true; 1439 app.pid = MY_PID; 1440 app.maxAdj = ProcessList.SYSTEM_ADJ; 1441 mSelf.mProcessNames.put(app.processName, app.uid, app); 1442 synchronized (mSelf.mPidsSelfLocked) { 1443 mSelf.mPidsSelfLocked.put(app.pid, app); 1444 } 1445 mSelf.updateLruProcessLocked(app, true); 1446 } 1447 } catch (PackageManager.NameNotFoundException e) { 1448 throw new RuntimeException( 1449 "Unable to find android system package", e); 1450 } 1451 } 1452 1453 public void setWindowManager(WindowManagerService wm) { 1454 mWindowManager = wm; 1455 } 1456 1457 public void startObservingNativeCrashes() { 1458 final NativeCrashListener ncl = new NativeCrashListener(); 1459 ncl.start(); 1460 } 1461 1462 public static final Context main(int factoryTest) { 1463 AThread thr = new AThread(); 1464 thr.start(); 1465 1466 synchronized (thr) { 1467 while (thr.mService == null) { 1468 try { 1469 thr.wait(); 1470 } catch (InterruptedException e) { 1471 } 1472 } 1473 } 1474 1475 ActivityManagerService m = thr.mService; 1476 mSelf = m; 1477 ActivityThread at = ActivityThread.systemMain(); 1478 mSystemThread = at; 1479 Context context = at.getSystemContext(); 1480 context.setTheme(android.R.style.Theme_Holo); 1481 m.mContext = context; 1482 m.mFactoryTest = factoryTest; 1483 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper); 1484 m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface()); 1485 1486 m.mBatteryStatsService.publish(context); 1487 m.mUsageStatsService.publish(context); 1488 m.mAppOpsService.publish(context); 1489 1490 synchronized (thr) { 1491 thr.mReady = true; 1492 thr.notifyAll(); 1493 } 1494 1495 m.startRunning(null, null, null, null); 1496 1497 return context; 1498 } 1499 1500 public static ActivityManagerService self() { 1501 return mSelf; 1502 } 1503 1504 static class AThread extends Thread { 1505 ActivityManagerService mService; 1506 Looper mLooper; 1507 boolean mReady = false; 1508 1509 public AThread() { 1510 super("ActivityManager"); 1511 } 1512 1513 public void run() { 1514 Looper.prepare(); 1515 1516 android.os.Process.setThreadPriority( 1517 android.os.Process.THREAD_PRIORITY_FOREGROUND); 1518 android.os.Process.setCanSelfBackground(false); 1519 1520 ActivityManagerService m = new ActivityManagerService(); 1521 1522 synchronized (this) { 1523 mService = m; 1524 mLooper = Looper.myLooper(); 1525 notifyAll(); 1526 } 1527 1528 synchronized (this) { 1529 while (!mReady) { 1530 try { 1531 wait(); 1532 } catch (InterruptedException e) { 1533 } 1534 } 1535 } 1536 1537 // For debug builds, log event loop stalls to dropbox for analysis. 1538 if (StrictMode.conditionallyEnableDebugLogging()) { 1539 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper"); 1540 } 1541 1542 Looper.loop(); 1543 } 1544 } 1545 1546 static class MemBinder extends Binder { 1547 ActivityManagerService mActivityManagerService; 1548 MemBinder(ActivityManagerService activityManagerService) { 1549 mActivityManagerService = activityManagerService; 1550 } 1551 1552 @Override 1553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1554 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1555 != PackageManager.PERMISSION_GRANTED) { 1556 pw.println("Permission Denial: can't dump meminfo from from pid=" 1557 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1558 + " without permission " + android.Manifest.permission.DUMP); 1559 return; 1560 } 1561 1562 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, 1563 false, null, null, null); 1564 } 1565 } 1566 1567 static class GraphicsBinder extends Binder { 1568 ActivityManagerService mActivityManagerService; 1569 GraphicsBinder(ActivityManagerService activityManagerService) { 1570 mActivityManagerService = activityManagerService; 1571 } 1572 1573 @Override 1574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1575 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1576 != PackageManager.PERMISSION_GRANTED) { 1577 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 1578 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1579 + " without permission " + android.Manifest.permission.DUMP); 1580 return; 1581 } 1582 1583 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 1584 } 1585 } 1586 1587 static class DbBinder extends Binder { 1588 ActivityManagerService mActivityManagerService; 1589 DbBinder(ActivityManagerService activityManagerService) { 1590 mActivityManagerService = activityManagerService; 1591 } 1592 1593 @Override 1594 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1595 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1596 != PackageManager.PERMISSION_GRANTED) { 1597 pw.println("Permission Denial: can't dump dbinfo from from pid=" 1598 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1599 + " without permission " + android.Manifest.permission.DUMP); 1600 return; 1601 } 1602 1603 mActivityManagerService.dumpDbInfo(fd, pw, args); 1604 } 1605 } 1606 1607 static class CpuBinder extends Binder { 1608 ActivityManagerService mActivityManagerService; 1609 CpuBinder(ActivityManagerService activityManagerService) { 1610 mActivityManagerService = activityManagerService; 1611 } 1612 1613 @Override 1614 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1615 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1616 != PackageManager.PERMISSION_GRANTED) { 1617 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 1618 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1619 + " without permission " + android.Manifest.permission.DUMP); 1620 return; 1621 } 1622 1623 synchronized (mActivityManagerService.mProcessStatsThread) { 1624 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad()); 1625 pw.print(mActivityManagerService.mProcessStats.printCurrentState( 1626 SystemClock.uptimeMillis())); 1627 } 1628 } 1629 } 1630 1631 private ActivityManagerService() { 1632 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 1633 1634 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT); 1635 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT); 1636 mBroadcastQueues[0] = mFgBroadcastQueue; 1637 mBroadcastQueues[1] = mBgBroadcastQueue; 1638 1639 mServices = new ActiveServices(this); 1640 mProviderMap = new ProviderMap(this); 1641 1642 File dataDir = Environment.getDataDirectory(); 1643 File systemDir = new File(dataDir, "system"); 1644 systemDir.mkdirs(); 1645 mBatteryStatsService = new BatteryStatsService(new File( 1646 systemDir, "batterystats.bin").toString()); 1647 mBatteryStatsService.getActiveStatistics().readLocked(); 1648 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1649 mOnBattery = DEBUG_POWER ? true 1650 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 1651 mBatteryStatsService.getActiveStatistics().setCallback(this); 1652 1653 mUsageStatsService = new UsageStatsService(new File( 1654 systemDir, "usagestats").toString()); 1655 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml")); 1656 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0")); 1657 1658 // User 0 is the first and only user that runs at boot. 1659 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true)); 1660 mUserLru.add(Integer.valueOf(0)); 1661 updateStartedUserArrayLocked(); 1662 1663 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 1664 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 1665 1666 mConfiguration.setToDefaults(); 1667 mConfiguration.setLocale(Locale.getDefault()); 1668 1669 mConfigurationSeq = mConfiguration.seq = 1; 1670 mProcessStats.init(); 1671 1672 mCompatModePackages = new CompatModePackages(this, systemDir); 1673 1674 // Add ourself to the Watchdog monitors. 1675 Watchdog.getInstance().addMonitor(this); 1676 1677 mProcessStatsThread = new Thread("ProcessStats") { 1678 public void run() { 1679 while (true) { 1680 try { 1681 try { 1682 synchronized(this) { 1683 final long now = SystemClock.uptimeMillis(); 1684 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 1685 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 1686 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 1687 // + ", write delay=" + nextWriteDelay); 1688 if (nextWriteDelay < nextCpuDelay) { 1689 nextCpuDelay = nextWriteDelay; 1690 } 1691 if (nextCpuDelay > 0) { 1692 mProcessStatsMutexFree.set(true); 1693 this.wait(nextCpuDelay); 1694 } 1695 } 1696 } catch (InterruptedException e) { 1697 } 1698 updateCpuStatsNow(); 1699 } catch (Exception e) { 1700 Slog.e(TAG, "Unexpected exception collecting process stats", e); 1701 } 1702 } 1703 } 1704 }; 1705 mProcessStatsThread.start(); 1706 } 1707 1708 @Override 1709 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1710 throws RemoteException { 1711 if (code == SYSPROPS_TRANSACTION) { 1712 // We need to tell all apps about the system property change. 1713 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 1714 synchronized(this) { 1715 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 1716 final int NA = apps.size(); 1717 for (int ia=0; ia<NA; ia++) { 1718 ProcessRecord app = apps.valueAt(ia); 1719 if (app.thread != null) { 1720 procs.add(app.thread.asBinder()); 1721 } 1722 } 1723 } 1724 } 1725 1726 int N = procs.size(); 1727 for (int i=0; i<N; i++) { 1728 Parcel data2 = Parcel.obtain(); 1729 try { 1730 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0); 1731 } catch (RemoteException e) { 1732 } 1733 data2.recycle(); 1734 } 1735 } 1736 try { 1737 return super.onTransact(code, data, reply, flags); 1738 } catch (RuntimeException e) { 1739 // The activity manager only throws security exceptions, so let's 1740 // log all others. 1741 if (!(e instanceof SecurityException)) { 1742 Slog.e(TAG, "Activity Manager Crash", e); 1743 } 1744 throw e; 1745 } 1746 } 1747 1748 void updateCpuStats() { 1749 final long now = SystemClock.uptimeMillis(); 1750 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 1751 return; 1752 } 1753 if (mProcessStatsMutexFree.compareAndSet(true, false)) { 1754 synchronized (mProcessStatsThread) { 1755 mProcessStatsThread.notify(); 1756 } 1757 } 1758 } 1759 1760 void updateCpuStatsNow() { 1761 synchronized (mProcessStatsThread) { 1762 mProcessStatsMutexFree.set(false); 1763 final long now = SystemClock.uptimeMillis(); 1764 boolean haveNewCpuStats = false; 1765 1766 if (MONITOR_CPU_USAGE && 1767 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 1768 mLastCpuTime.set(now); 1769 haveNewCpuStats = true; 1770 mProcessStats.update(); 1771 //Slog.i(TAG, mProcessStats.printCurrentState()); 1772 //Slog.i(TAG, "Total CPU usage: " 1773 // + mProcessStats.getTotalCpuPercent() + "%"); 1774 1775 // Slog the cpu usage if the property is set. 1776 if ("true".equals(SystemProperties.get("events.cpu"))) { 1777 int user = mProcessStats.getLastUserTime(); 1778 int system = mProcessStats.getLastSystemTime(); 1779 int iowait = mProcessStats.getLastIoWaitTime(); 1780 int irq = mProcessStats.getLastIrqTime(); 1781 int softIrq = mProcessStats.getLastSoftIrqTime(); 1782 int idle = mProcessStats.getLastIdleTime(); 1783 1784 int total = user + system + iowait + irq + softIrq + idle; 1785 if (total == 0) total = 1; 1786 1787 EventLog.writeEvent(EventLogTags.CPU, 1788 ((user+system+iowait+irq+softIrq) * 100) / total, 1789 (user * 100) / total, 1790 (system * 100) / total, 1791 (iowait * 100) / total, 1792 (irq * 100) / total, 1793 (softIrq * 100) / total); 1794 } 1795 } 1796 1797 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes(); 1798 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 1799 synchronized(bstats) { 1800 synchronized(mPidsSelfLocked) { 1801 if (haveNewCpuStats) { 1802 if (mOnBattery) { 1803 int perc = bstats.startAddingCpuLocked(); 1804 int totalUTime = 0; 1805 int totalSTime = 0; 1806 final int N = mProcessStats.countStats(); 1807 for (int i=0; i<N; i++) { 1808 ProcessStats.Stats st = mProcessStats.getStats(i); 1809 if (!st.working) { 1810 continue; 1811 } 1812 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 1813 int otherUTime = (st.rel_utime*perc)/100; 1814 int otherSTime = (st.rel_stime*perc)/100; 1815 totalUTime += otherUTime; 1816 totalSTime += otherSTime; 1817 if (pr != null) { 1818 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats; 1819 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1820 st.rel_stime-otherSTime); 1821 ps.addSpeedStepTimes(cpuSpeedTimes); 1822 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10; 1823 } else { 1824 BatteryStatsImpl.Uid.Proc ps = 1825 bstats.getProcessStatsLocked(st.name, st.pid); 1826 if (ps != null) { 1827 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1828 st.rel_stime-otherSTime); 1829 ps.addSpeedStepTimes(cpuSpeedTimes); 1830 } 1831 } 1832 } 1833 bstats.finishAddingCpuLocked(perc, totalUTime, 1834 totalSTime, cpuSpeedTimes); 1835 } 1836 } 1837 } 1838 1839 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 1840 mLastWriteTime = now; 1841 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1842 } 1843 } 1844 } 1845 } 1846 1847 @Override 1848 public void batteryNeedsCpuUpdate() { 1849 updateCpuStatsNow(); 1850 } 1851 1852 @Override 1853 public void batteryPowerChanged(boolean onBattery) { 1854 // When plugging in, update the CPU stats first before changing 1855 // the plug state. 1856 updateCpuStatsNow(); 1857 synchronized (this) { 1858 synchronized(mPidsSelfLocked) { 1859 mOnBattery = DEBUG_POWER ? true : onBattery; 1860 } 1861 } 1862 } 1863 1864 /** 1865 * Initialize the application bind args. These are passed to each 1866 * process when the bindApplication() IPC is sent to the process. They're 1867 * lazily setup to make sure the services are running when they're asked for. 1868 */ 1869 private HashMap<String, IBinder> getCommonServicesLocked() { 1870 if (mAppBindArgs == null) { 1871 mAppBindArgs = new HashMap<String, IBinder>(); 1872 1873 // Setup the application init args 1874 mAppBindArgs.put("package", ServiceManager.getService("package")); 1875 mAppBindArgs.put("window", ServiceManager.getService("window")); 1876 mAppBindArgs.put(Context.ALARM_SERVICE, 1877 ServiceManager.getService(Context.ALARM_SERVICE)); 1878 } 1879 return mAppBindArgs; 1880 } 1881 1882 final void setFocusedActivityLocked(ActivityRecord r) { 1883 if (mFocusedActivity != r) { 1884 mFocusedActivity = r; 1885 if (r != null) { 1886 mWindowManager.setFocusedApp(r.appToken, true); 1887 } 1888 applyUpdateLockStateLocked(r); 1889 } 1890 } 1891 1892 final void applyUpdateLockStateLocked(ActivityRecord r) { 1893 // Modifications to the UpdateLock state are done on our handler, outside 1894 // the activity manager's locks. The new state is determined based on the 1895 // state *now* of the relevant activity record. The object is passed to 1896 // the handler solely for logging detail, not to be consulted/modified. 1897 final boolean nextState = r != null && r.immersive; 1898 mHandler.sendMessage( 1899 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 1900 } 1901 1902 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) { 1903 // put it on the LRU to keep track of when it should be exited. 1904 int lrui = mLruProcesses.indexOf(app); 1905 if (lrui >= 0) mLruProcesses.remove(lrui); 1906 1907 int i = mLruProcesses.size()-1; 1908 int skipTop = 0; 1909 1910 app.lruSeq = mLruSeq; 1911 1912 // compute the new weight for this process. 1913 app.lastActivityTime = SystemClock.uptimeMillis(); 1914 if (app.activities.size() > 0) { 1915 // If this process has activities, we more strongly want to keep 1916 // it around. 1917 app.lruWeight = app.lastActivityTime; 1918 } else if (app.pubProviders.size() > 0) { 1919 // If this process contains content providers, we want to keep 1920 // it a little more strongly. 1921 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET; 1922 // Also don't let it kick out the first few "real" hidden processes. 1923 skipTop = ProcessList.MIN_HIDDEN_APPS; 1924 } else { 1925 // If this process doesn't have activities, we less strongly 1926 // want to keep it around, and generally want to avoid getting 1927 // in front of any very recently used activities. 1928 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET; 1929 // Also don't let it kick out the first few "real" hidden processes. 1930 skipTop = ProcessList.MIN_HIDDEN_APPS; 1931 } 1932 1933 while (i >= 0) { 1934 ProcessRecord p = mLruProcesses.get(i); 1935 // If this app shouldn't be in front of the first N background 1936 // apps, then skip over that many that are currently hidden. 1937 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 1938 skipTop--; 1939 } 1940 if (p.lruWeight <= app.lruWeight || i < bestPos) { 1941 mLruProcesses.add(i+1, app); 1942 break; 1943 } 1944 i--; 1945 } 1946 if (i < 0) { 1947 mLruProcesses.add(0, app); 1948 } 1949 1950 // If the app is currently using a content provider or service, 1951 // bump those processes as well. 1952 if (app.connections.size() > 0) { 1953 for (ConnectionRecord cr : app.connections) { 1954 if (cr.binding != null && cr.binding.service != null 1955 && cr.binding.service.app != null 1956 && cr.binding.service.app.lruSeq != mLruSeq) { 1957 updateLruProcessInternalLocked(cr.binding.service.app, i+1); 1958 } 1959 } 1960 } 1961 for (int j=app.conProviders.size()-1; j>=0; j--) { 1962 ContentProviderRecord cpr = app.conProviders.get(j).provider; 1963 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) { 1964 updateLruProcessInternalLocked(cpr.proc, i+1); 1965 } 1966 } 1967 } 1968 1969 final void updateLruProcessLocked(ProcessRecord app, 1970 boolean oomAdj) { 1971 mLruSeq++; 1972 updateLruProcessInternalLocked(app, 0); 1973 1974 //Slog.i(TAG, "Putting proc to front: " + app.processName); 1975 if (oomAdj) { 1976 updateOomAdjLocked(); 1977 } 1978 } 1979 1980 final ProcessRecord getProcessRecordLocked( 1981 String processName, int uid) { 1982 if (uid == Process.SYSTEM_UID) { 1983 // The system gets to run in any process. If there are multiple 1984 // processes with the same uid, just pick the first (this 1985 // should never happen). 1986 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get( 1987 processName); 1988 if (procs == null) return null; 1989 final int N = procs.size(); 1990 for (int i = 0; i < N; i++) { 1991 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i); 1992 } 1993 } 1994 ProcessRecord proc = mProcessNames.get(processName, uid); 1995 return proc; 1996 } 1997 1998 void ensurePackageDexOpt(String packageName) { 1999 IPackageManager pm = AppGlobals.getPackageManager(); 2000 try { 2001 if (pm.performDexOpt(packageName)) { 2002 mDidDexOpt = true; 2003 } 2004 } catch (RemoteException e) { 2005 } 2006 } 2007 2008 boolean isNextTransitionForward() { 2009 int transit = mWindowManager.getPendingAppTransition(); 2010 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN 2011 || transit == AppTransition.TRANSIT_TASK_OPEN 2012 || transit == AppTransition.TRANSIT_TASK_TO_FRONT; 2013 } 2014 2015 final ProcessRecord startProcessLocked(String processName, 2016 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2017 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 2018 boolean isolated) { 2019 ProcessRecord app; 2020 if (!isolated) { 2021 app = getProcessRecordLocked(processName, info.uid); 2022 } else { 2023 // If this is an isolated process, it can't re-use an existing process. 2024 app = null; 2025 } 2026 // We don't have to do anything more if: 2027 // (1) There is an existing application record; and 2028 // (2) The caller doesn't think it is dead, OR there is no thread 2029 // object attached to it so we know it couldn't have crashed; and 2030 // (3) There is a pid assigned to it, so it is either starting or 2031 // already running. 2032 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName 2033 + " app=" + app + " knownToBeDead=" + knownToBeDead 2034 + " thread=" + (app != null ? app.thread : null) 2035 + " pid=" + (app != null ? app.pid : -1)); 2036 if (app != null && app.pid > 0) { 2037 if (!knownToBeDead || app.thread == null) { 2038 // We already have the app running, or are waiting for it to 2039 // come up (we have a pid but not yet its thread), so keep it. 2040 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app); 2041 // If this is a new package in the process, add the package to the list 2042 app.addPackage(info.packageName); 2043 return app; 2044 } else { 2045 // An application record is attached to a previous process, 2046 // clean it up now. 2047 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app); 2048 handleAppDiedLocked(app, true, true); 2049 } 2050 } 2051 2052 String hostingNameStr = hostingName != null 2053 ? hostingName.flattenToShortString() : null; 2054 2055 if (!isolated) { 2056 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) { 2057 // If we are in the background, then check to see if this process 2058 // is bad. If so, we will just silently fail. 2059 if (mBadProcesses.get(info.processName, info.uid) != null) { 2060 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 2061 + "/" + info.processName); 2062 return null; 2063 } 2064 } else { 2065 // When the user is explicitly starting a process, then clear its 2066 // crash count so that we won't make it bad until they see at 2067 // least one crash dialog again, and make the process good again 2068 // if it had been bad. 2069 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 2070 + "/" + info.processName); 2071 mProcessCrashTimes.remove(info.processName, info.uid); 2072 if (mBadProcesses.get(info.processName, info.uid) != null) { 2073 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 2074 UserHandle.getUserId(info.uid), info.uid, 2075 info.processName); 2076 mBadProcesses.remove(info.processName, info.uid); 2077 if (app != null) { 2078 app.bad = false; 2079 } 2080 } 2081 } 2082 } 2083 2084 if (app == null) { 2085 app = newProcessRecordLocked(null, info, processName, isolated); 2086 if (app == null) { 2087 Slog.w(TAG, "Failed making new process record for " 2088 + processName + "/" + info.uid + " isolated=" + isolated); 2089 return null; 2090 } 2091 mProcessNames.put(processName, app.uid, app); 2092 if (isolated) { 2093 mIsolatedProcesses.put(app.uid, app); 2094 } 2095 } else { 2096 // If this is a new package in the process, add the package to the list 2097 app.addPackage(info.packageName); 2098 } 2099 2100 // If the system is not ready yet, then hold off on starting this 2101 // process until it is. 2102 if (!mProcessesReady 2103 && !isAllowedWhileBooting(info) 2104 && !allowWhileBooting) { 2105 if (!mProcessesOnHold.contains(app)) { 2106 mProcessesOnHold.add(app); 2107 } 2108 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app); 2109 return app; 2110 } 2111 2112 startProcessLocked(app, hostingType, hostingNameStr); 2113 return (app.pid != 0) ? app : null; 2114 } 2115 2116 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2117 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2118 } 2119 2120 private final void startProcessLocked(ProcessRecord app, 2121 String hostingType, String hostingNameStr) { 2122 if (app.pid > 0 && app.pid != MY_PID) { 2123 synchronized (mPidsSelfLocked) { 2124 mPidsSelfLocked.remove(app.pid); 2125 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 2126 } 2127 app.setPid(0); 2128 } 2129 2130 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 2131 "startProcessLocked removing on hold: " + app); 2132 mProcessesOnHold.remove(app); 2133 2134 updateCpuStats(); 2135 2136 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1); 2137 mProcDeaths[0] = 0; 2138 2139 try { 2140 int uid = app.uid; 2141 2142 int[] gids = null; 2143 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 2144 if (!app.isolated) { 2145 int[] permGids = null; 2146 try { 2147 final PackageManager pm = mContext.getPackageManager(); 2148 permGids = pm.getPackageGids(app.info.packageName); 2149 2150 if (Environment.isExternalStorageEmulated()) { 2151 if (pm.checkPermission( 2152 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE, 2153 app.info.packageName) == PERMISSION_GRANTED) { 2154 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL; 2155 } else { 2156 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER; 2157 } 2158 } 2159 } catch (PackageManager.NameNotFoundException e) { 2160 Slog.w(TAG, "Unable to retrieve gids", e); 2161 } 2162 2163 /* 2164 * Add shared application GID so applications can share some 2165 * resources like shared libraries 2166 */ 2167 if (permGids == null) { 2168 gids = new int[1]; 2169 } else { 2170 gids = new int[permGids.length + 1]; 2171 System.arraycopy(permGids, 0, gids, 1, permGids.length); 2172 } 2173 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 2174 } 2175 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) { 2176 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 2177 && mTopComponent != null 2178 && app.processName.equals(mTopComponent.getPackageName())) { 2179 uid = 0; 2180 } 2181 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL 2182 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 2183 uid = 0; 2184 } 2185 } 2186 int debugFlags = 0; 2187 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 2188 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 2189 // Also turn on CheckJNI for debuggable apps. It's quite 2190 // awkward to turn on otherwise. 2191 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 2192 } 2193 // Run the app in safe mode if its manifest requests so or the 2194 // system is booted in safe mode. 2195 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 2196 Zygote.systemInSafeMode == true) { 2197 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 2198 } 2199 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 2200 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 2201 } 2202 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 2203 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 2204 } 2205 if ("1".equals(SystemProperties.get("debug.assert"))) { 2206 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 2207 } 2208 2209 // Start the process. It will either succeed and return a result containing 2210 // the PID of the new process, or else throw a RuntimeException. 2211 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread", 2212 app.processName, uid, uid, gids, debugFlags, mountExternal, 2213 app.info.targetSdkVersion, app.info.seinfo, null); 2214 2215 BatteryStatsImpl bs = app.batteryStats.getBatteryStats(); 2216 synchronized (bs) { 2217 if (bs.isOnBattery()) { 2218 app.batteryStats.incStartsLocked(); 2219 } 2220 } 2221 2222 EventLog.writeEvent(EventLogTags.AM_PROC_START, 2223 UserHandle.getUserId(uid), startResult.pid, uid, 2224 app.processName, hostingType, 2225 hostingNameStr != null ? hostingNameStr : ""); 2226 2227 if (app.persistent) { 2228 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 2229 } 2230 2231 StringBuilder buf = mStringBuilder; 2232 buf.setLength(0); 2233 buf.append("Start proc "); 2234 buf.append(app.processName); 2235 buf.append(" for "); 2236 buf.append(hostingType); 2237 if (hostingNameStr != null) { 2238 buf.append(" "); 2239 buf.append(hostingNameStr); 2240 } 2241 buf.append(": pid="); 2242 buf.append(startResult.pid); 2243 buf.append(" uid="); 2244 buf.append(uid); 2245 buf.append(" gids={"); 2246 if (gids != null) { 2247 for (int gi=0; gi<gids.length; gi++) { 2248 if (gi != 0) buf.append(", "); 2249 buf.append(gids[gi]); 2250 2251 } 2252 } 2253 buf.append("}"); 2254 Slog.i(TAG, buf.toString()); 2255 app.setPid(startResult.pid); 2256 app.usingWrapper = startResult.usingWrapper; 2257 app.removed = false; 2258 synchronized (mPidsSelfLocked) { 2259 this.mPidsSelfLocked.put(startResult.pid, app); 2260 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 2261 msg.obj = app; 2262 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 2263 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 2264 } 2265 } catch (RuntimeException e) { 2266 // XXX do better error recovery. 2267 app.setPid(0); 2268 Slog.e(TAG, "Failure starting process " + app.processName, e); 2269 } 2270 } 2271 2272 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) { 2273 if (resumed) { 2274 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity); 2275 } else { 2276 mUsageStatsService.notePauseComponent(resumedComponent.realActivity); 2277 } 2278 } 2279 2280 boolean startHomeActivityLocked(int userId) { 2281 if (mHeadless) { 2282 // Added because none of the other calls to ensureBootCompleted seem to fire 2283 // when running headless. 2284 ensureBootCompleted(); 2285 return false; 2286 } 2287 2288 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 2289 && mTopAction == null) { 2290 // We are running in factory test mode, but unable to find 2291 // the factory test app, so just sit around displaying the 2292 // error message and don't try to start anything. 2293 return false; 2294 } 2295 Intent intent = new Intent( 2296 mTopAction, 2297 mTopData != null ? Uri.parse(mTopData) : null); 2298 intent.setComponent(mTopComponent); 2299 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { 2300 intent.addCategory(Intent.CATEGORY_HOME); 2301 } 2302 ActivityInfo aInfo = 2303 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 2304 if (aInfo != null) { 2305 intent.setComponent(new ComponentName( 2306 aInfo.applicationInfo.packageName, aInfo.name)); 2307 // Don't do this if the home app is currently being 2308 // instrumented. 2309 aInfo = new ActivityInfo(aInfo); 2310 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 2311 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 2312 aInfo.applicationInfo.uid); 2313 if (app == null || app.instrumentationClass == null) { 2314 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 2315 mMainStack.startActivityLocked(null, intent, null, aInfo, 2316 null, null, 0, 0, 0, null, 0, null, false, null); 2317 } 2318 } 2319 2320 return true; 2321 } 2322 2323 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 2324 ActivityInfo ai = null; 2325 ComponentName comp = intent.getComponent(); 2326 try { 2327 if (comp != null) { 2328 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 2329 } else { 2330 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 2331 intent, 2332 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 2333 flags, userId); 2334 2335 if (info != null) { 2336 ai = info.activityInfo; 2337 } 2338 } 2339 } catch (RemoteException e) { 2340 // ignore 2341 } 2342 2343 return ai; 2344 } 2345 2346 /** 2347 * Starts the "new version setup screen" if appropriate. 2348 */ 2349 void startSetupActivityLocked() { 2350 // Only do this once per boot. 2351 if (mCheckedForSetup) { 2352 return; 2353 } 2354 2355 // We will show this screen if the current one is a different 2356 // version than the last one shown, and we are not running in 2357 // low-level factory test mode. 2358 final ContentResolver resolver = mContext.getContentResolver(); 2359 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL && 2360 Settings.Global.getInt(resolver, 2361 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 2362 mCheckedForSetup = true; 2363 2364 // See if we should be showing the platform update setup UI. 2365 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 2366 List<ResolveInfo> ris = mSelf.mContext.getPackageManager() 2367 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 2368 2369 // We don't allow third party apps to replace this. 2370 ResolveInfo ri = null; 2371 for (int i=0; ris != null && i<ris.size(); i++) { 2372 if ((ris.get(i).activityInfo.applicationInfo.flags 2373 & ApplicationInfo.FLAG_SYSTEM) != 0) { 2374 ri = ris.get(i); 2375 break; 2376 } 2377 } 2378 2379 if (ri != null) { 2380 String vers = ri.activityInfo.metaData != null 2381 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 2382 : null; 2383 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 2384 vers = ri.activityInfo.applicationInfo.metaData.getString( 2385 Intent.METADATA_SETUP_VERSION); 2386 } 2387 String lastVers = Settings.Secure.getString( 2388 resolver, Settings.Secure.LAST_SETUP_SHOWN); 2389 if (vers != null && !vers.equals(lastVers)) { 2390 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2391 intent.setComponent(new ComponentName( 2392 ri.activityInfo.packageName, ri.activityInfo.name)); 2393 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo, 2394 null, null, 0, 0, 0, null, 0, null, false, null); 2395 } 2396 } 2397 } 2398 } 2399 2400 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 2401 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 2402 } 2403 2404 void enforceNotIsolatedCaller(String caller) { 2405 if (UserHandle.isIsolated(Binder.getCallingUid())) { 2406 throw new SecurityException("Isolated process not allowed to call " + caller); 2407 } 2408 } 2409 2410 public int getFrontActivityScreenCompatMode() { 2411 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 2412 synchronized (this) { 2413 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 2414 } 2415 } 2416 2417 public void setFrontActivityScreenCompatMode(int mode) { 2418 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2419 "setFrontActivityScreenCompatMode"); 2420 synchronized (this) { 2421 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 2422 } 2423 } 2424 2425 public int getPackageScreenCompatMode(String packageName) { 2426 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 2427 synchronized (this) { 2428 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 2429 } 2430 } 2431 2432 public void setPackageScreenCompatMode(String packageName, int mode) { 2433 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2434 "setPackageScreenCompatMode"); 2435 synchronized (this) { 2436 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 2437 } 2438 } 2439 2440 public boolean getPackageAskScreenCompat(String packageName) { 2441 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 2442 synchronized (this) { 2443 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 2444 } 2445 } 2446 2447 public void setPackageAskScreenCompat(String packageName, boolean ask) { 2448 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2449 "setPackageAskScreenCompat"); 2450 synchronized (this) { 2451 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 2452 } 2453 } 2454 2455 void reportResumedActivityLocked(ActivityRecord r) { 2456 //Slog.i(TAG, "**** REPORT RESUME: " + r); 2457 updateUsageStats(r, true); 2458 } 2459 2460 private void dispatchProcessesChanged() { 2461 int N; 2462 synchronized (this) { 2463 N = mPendingProcessChanges.size(); 2464 if (mActiveProcessChanges.length < N) { 2465 mActiveProcessChanges = new ProcessChangeItem[N]; 2466 } 2467 mPendingProcessChanges.toArray(mActiveProcessChanges); 2468 mAvailProcessChanges.addAll(mPendingProcessChanges); 2469 mPendingProcessChanges.clear(); 2470 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes"); 2471 } 2472 int i = mProcessObservers.beginBroadcast(); 2473 while (i > 0) { 2474 i--; 2475 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2476 if (observer != null) { 2477 try { 2478 for (int j=0; j<N; j++) { 2479 ProcessChangeItem item = mActiveProcessChanges[j]; 2480 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 2481 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid=" 2482 + item.pid + " uid=" + item.uid + ": " 2483 + item.foregroundActivities); 2484 observer.onForegroundActivitiesChanged(item.pid, item.uid, 2485 item.foregroundActivities); 2486 } 2487 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) { 2488 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid=" 2489 + item.pid + " uid=" + item.uid + ": " + item.importance); 2490 observer.onImportanceChanged(item.pid, item.uid, 2491 item.importance); 2492 } 2493 } 2494 } catch (RemoteException e) { 2495 } 2496 } 2497 } 2498 mProcessObservers.finishBroadcast(); 2499 } 2500 2501 private void dispatchProcessDied(int pid, int uid) { 2502 int i = mProcessObservers.beginBroadcast(); 2503 while (i > 0) { 2504 i--; 2505 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2506 if (observer != null) { 2507 try { 2508 observer.onProcessDied(pid, uid); 2509 } catch (RemoteException e) { 2510 } 2511 } 2512 } 2513 mProcessObservers.finishBroadcast(); 2514 } 2515 2516 final void doPendingActivityLaunchesLocked(boolean doResume) { 2517 final int N = mPendingActivityLaunches.size(); 2518 if (N <= 0) { 2519 return; 2520 } 2521 for (int i=0; i<N; i++) { 2522 PendingActivityLaunch pal = mPendingActivityLaunches.get(i); 2523 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord, 2524 pal.startFlags, doResume && i == (N-1), null); 2525 } 2526 mPendingActivityLaunches.clear(); 2527 } 2528 2529 public final int startActivity(IApplicationThread caller, String callingPackage, 2530 Intent intent, String resolvedType, IBinder resultTo, 2531 String resultWho, int requestCode, int startFlags, 2532 String profileFile, ParcelFileDescriptor profileFd, Bundle options) { 2533 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 2534 resultWho, requestCode, 2535 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId()); 2536 } 2537 2538 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 2539 Intent intent, String resolvedType, IBinder resultTo, 2540 String resultWho, int requestCode, int startFlags, 2541 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) { 2542 enforceNotIsolatedCaller("startActivity"); 2543 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2544 false, true, "startActivity", null); 2545 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2546 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 2547 null, null, options, userId); 2548 } 2549 2550 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 2551 Intent intent, String resolvedType, IBinder resultTo, 2552 String resultWho, int requestCode, int startFlags, String profileFile, 2553 ParcelFileDescriptor profileFd, Bundle options, int userId) { 2554 enforceNotIsolatedCaller("startActivityAndWait"); 2555 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2556 false, true, "startActivityAndWait", null); 2557 WaitResult res = new WaitResult(); 2558 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2559 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 2560 res, null, options, UserHandle.getCallingUserId()); 2561 return res; 2562 } 2563 2564 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 2565 Intent intent, String resolvedType, IBinder resultTo, 2566 String resultWho, int requestCode, int startFlags, Configuration config, 2567 Bundle options, int userId) { 2568 enforceNotIsolatedCaller("startActivityWithConfig"); 2569 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2570 false, true, "startActivityWithConfig", null); 2571 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2572 resultTo, resultWho, requestCode, startFlags, 2573 null, null, null, config, options, userId); 2574 return ret; 2575 } 2576 2577 public int startActivityIntentSender(IApplicationThread caller, 2578 IntentSender intent, Intent fillInIntent, String resolvedType, 2579 IBinder resultTo, String resultWho, int requestCode, 2580 int flagsMask, int flagsValues, Bundle options) { 2581 enforceNotIsolatedCaller("startActivityIntentSender"); 2582 // Refuse possible leaked file descriptors 2583 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 2584 throw new IllegalArgumentException("File descriptors passed in Intent"); 2585 } 2586 2587 IIntentSender sender = intent.getTarget(); 2588 if (!(sender instanceof PendingIntentRecord)) { 2589 throw new IllegalArgumentException("Bad PendingIntent object"); 2590 } 2591 2592 PendingIntentRecord pir = (PendingIntentRecord)sender; 2593 2594 synchronized (this) { 2595 // If this is coming from the currently resumed activity, it is 2596 // effectively saying that app switches are allowed at this point. 2597 if (mMainStack.mResumedActivity != null 2598 && mMainStack.mResumedActivity.info.applicationInfo.uid == 2599 Binder.getCallingUid()) { 2600 mAppSwitchesAllowedTime = 0; 2601 } 2602 } 2603 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null, 2604 resultTo, resultWho, requestCode, flagsMask, flagsValues, options); 2605 return ret; 2606 } 2607 2608 public boolean startNextMatchingActivity(IBinder callingActivity, 2609 Intent intent, Bundle options) { 2610 // Refuse possible leaked file descriptors 2611 if (intent != null && intent.hasFileDescriptors() == true) { 2612 throw new IllegalArgumentException("File descriptors passed in Intent"); 2613 } 2614 2615 synchronized (this) { 2616 ActivityRecord r = mMainStack.isInStackLocked(callingActivity); 2617 if (r == null) { 2618 ActivityOptions.abort(options); 2619 return false; 2620 } 2621 if (r.app == null || r.app.thread == null) { 2622 // The caller is not running... d'oh! 2623 ActivityOptions.abort(options); 2624 return false; 2625 } 2626 intent = new Intent(intent); 2627 // The caller is not allowed to change the data. 2628 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 2629 // And we are resetting to find the next component... 2630 intent.setComponent(null); 2631 2632 ActivityInfo aInfo = null; 2633 try { 2634 List<ResolveInfo> resolves = 2635 AppGlobals.getPackageManager().queryIntentActivities( 2636 intent, r.resolvedType, 2637 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 2638 UserHandle.getCallingUserId()); 2639 2640 // Look for the original activity in the list... 2641 final int N = resolves != null ? resolves.size() : 0; 2642 for (int i=0; i<N; i++) { 2643 ResolveInfo rInfo = resolves.get(i); 2644 if (rInfo.activityInfo.packageName.equals(r.packageName) 2645 && rInfo.activityInfo.name.equals(r.info.name)) { 2646 // We found the current one... the next matching is 2647 // after it. 2648 i++; 2649 if (i<N) { 2650 aInfo = resolves.get(i).activityInfo; 2651 } 2652 break; 2653 } 2654 } 2655 } catch (RemoteException e) { 2656 } 2657 2658 if (aInfo == null) { 2659 // Nobody who is next! 2660 ActivityOptions.abort(options); 2661 return false; 2662 } 2663 2664 intent.setComponent(new ComponentName( 2665 aInfo.applicationInfo.packageName, aInfo.name)); 2666 intent.setFlags(intent.getFlags()&~( 2667 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 2668 Intent.FLAG_ACTIVITY_CLEAR_TOP| 2669 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 2670 Intent.FLAG_ACTIVITY_NEW_TASK)); 2671 2672 // Okay now we need to start the new activity, replacing the 2673 // currently running activity. This is a little tricky because 2674 // we want to start the new one as if the current one is finished, 2675 // but not finish the current one first so that there is no flicker. 2676 // And thus... 2677 final boolean wasFinishing = r.finishing; 2678 r.finishing = true; 2679 2680 // Propagate reply information over to the new activity. 2681 final ActivityRecord resultTo = r.resultTo; 2682 final String resultWho = r.resultWho; 2683 final int requestCode = r.requestCode; 2684 r.resultTo = null; 2685 if (resultTo != null) { 2686 resultTo.removeResultsLocked(r, resultWho, requestCode); 2687 } 2688 2689 final long origId = Binder.clearCallingIdentity(); 2690 int res = mMainStack.startActivityLocked(r.app.thread, intent, 2691 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null, 2692 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0, 2693 options, false, null); 2694 Binder.restoreCallingIdentity(origId); 2695 2696 r.finishing = wasFinishing; 2697 if (res != ActivityManager.START_SUCCESS) { 2698 return false; 2699 } 2700 return true; 2701 } 2702 } 2703 2704 final int startActivityInPackage(int uid, String callingPackage, 2705 Intent intent, String resolvedType, IBinder resultTo, 2706 String resultWho, int requestCode, int startFlags, Bundle options, int userId) { 2707 2708 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2709 false, true, "startActivityInPackage", null); 2710 2711 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType, 2712 resultTo, resultWho, requestCode, startFlags, 2713 null, null, null, null, options, userId); 2714 return ret; 2715 } 2716 2717 public final int startActivities(IApplicationThread caller, String callingPackage, 2718 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, 2719 int userId) { 2720 enforceNotIsolatedCaller("startActivities"); 2721 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2722 false, true, "startActivity", null); 2723 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents, 2724 resolvedTypes, resultTo, options, userId); 2725 return ret; 2726 } 2727 2728 final int startActivitiesInPackage(int uid, String callingPackage, 2729 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 2730 Bundle options, int userId) { 2731 2732 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2733 false, true, "startActivityInPackage", null); 2734 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes, 2735 resultTo, options, userId); 2736 return ret; 2737 } 2738 2739 final void addRecentTaskLocked(TaskRecord task) { 2740 int N = mRecentTasks.size(); 2741 // Quick case: check if the top-most recent task is the same. 2742 if (N > 0 && mRecentTasks.get(0) == task) { 2743 return; 2744 } 2745 // Remove any existing entries that are the same kind of task. 2746 for (int i=0; i<N; i++) { 2747 TaskRecord tr = mRecentTasks.get(i); 2748 if (task.userId == tr.userId 2749 && ((task.affinity != null && task.affinity.equals(tr.affinity)) 2750 || (task.intent != null && task.intent.filterEquals(tr.intent)))) { 2751 mRecentTasks.remove(i); 2752 i--; 2753 N--; 2754 if (task.intent == null) { 2755 // If the new recent task we are adding is not fully 2756 // specified, then replace it with the existing recent task. 2757 task = tr; 2758 } 2759 } 2760 } 2761 if (N >= MAX_RECENT_TASKS) { 2762 mRecentTasks.remove(N-1); 2763 } 2764 mRecentTasks.add(0, task); 2765 } 2766 2767 public void setRequestedOrientation(IBinder token, 2768 int requestedOrientation) { 2769 synchronized (this) { 2770 ActivityRecord r = mMainStack.isInStackLocked(token); 2771 if (r == null) { 2772 return; 2773 } 2774 final long origId = Binder.clearCallingIdentity(); 2775 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 2776 Configuration config = mWindowManager.updateOrientationFromAppTokens( 2777 mConfiguration, 2778 r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 2779 if (config != null) { 2780 r.frozenBeforeDestroy = true; 2781 if (!updateConfigurationLocked(config, r, false, false)) { 2782 mMainStack.resumeTopActivityLocked(null); 2783 } 2784 } 2785 Binder.restoreCallingIdentity(origId); 2786 } 2787 } 2788 2789 public int getRequestedOrientation(IBinder token) { 2790 synchronized (this) { 2791 ActivityRecord r = mMainStack.isInStackLocked(token); 2792 if (r == null) { 2793 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 2794 } 2795 return mWindowManager.getAppOrientation(r.appToken); 2796 } 2797 } 2798 2799 /** 2800 * This is the internal entry point for handling Activity.finish(). 2801 * 2802 * @param token The Binder token referencing the Activity we want to finish. 2803 * @param resultCode Result code, if any, from this Activity. 2804 * @param resultData Result data (Intent), if any, from this Activity. 2805 * 2806 * @return Returns true if the activity successfully finished, or false if it is still running. 2807 */ 2808 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) { 2809 // Refuse possible leaked file descriptors 2810 if (resultData != null && resultData.hasFileDescriptors() == true) { 2811 throw new IllegalArgumentException("File descriptors passed in Intent"); 2812 } 2813 2814 synchronized(this) { 2815 if (mController != null) { 2816 // Find the first activity that is not finishing. 2817 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0); 2818 if (next != null) { 2819 // ask watcher if this is allowed 2820 boolean resumeOK = true; 2821 try { 2822 resumeOK = mController.activityResuming(next.packageName); 2823 } catch (RemoteException e) { 2824 mController = null; 2825 Watchdog.getInstance().setActivityController(null); 2826 } 2827 2828 if (!resumeOK) { 2829 return false; 2830 } 2831 } 2832 } 2833 final long origId = Binder.clearCallingIdentity(); 2834 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode, 2835 resultData, "app-request", true); 2836 Binder.restoreCallingIdentity(origId); 2837 return res; 2838 } 2839 } 2840 2841 public final void finishHeavyWeightApp() { 2842 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2843 != PackageManager.PERMISSION_GRANTED) { 2844 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 2845 + Binder.getCallingPid() 2846 + ", uid=" + Binder.getCallingUid() 2847 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2848 Slog.w(TAG, msg); 2849 throw new SecurityException(msg); 2850 } 2851 2852 synchronized(this) { 2853 if (mHeavyWeightProcess == null) { 2854 return; 2855 } 2856 2857 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>( 2858 mHeavyWeightProcess.activities); 2859 for (int i=0; i<activities.size(); i++) { 2860 ActivityRecord r = activities.get(i); 2861 if (!r.finishing) { 2862 int index = mMainStack.indexOfTokenLocked(r.appToken); 2863 if (index >= 0) { 2864 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED, 2865 null, "finish-heavy", true); 2866 } 2867 } 2868 } 2869 2870 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 2871 mHeavyWeightProcess.userId, 0)); 2872 mHeavyWeightProcess = null; 2873 } 2874 } 2875 2876 public void crashApplication(int uid, int initialPid, String packageName, 2877 String message) { 2878 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2879 != PackageManager.PERMISSION_GRANTED) { 2880 String msg = "Permission Denial: crashApplication() from pid=" 2881 + Binder.getCallingPid() 2882 + ", uid=" + Binder.getCallingUid() 2883 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2884 Slog.w(TAG, msg); 2885 throw new SecurityException(msg); 2886 } 2887 2888 synchronized(this) { 2889 ProcessRecord proc = null; 2890 2891 // Figure out which process to kill. We don't trust that initialPid 2892 // still has any relation to current pids, so must scan through the 2893 // list. 2894 synchronized (mPidsSelfLocked) { 2895 for (int i=0; i<mPidsSelfLocked.size(); i++) { 2896 ProcessRecord p = mPidsSelfLocked.valueAt(i); 2897 if (p.uid != uid) { 2898 continue; 2899 } 2900 if (p.pid == initialPid) { 2901 proc = p; 2902 break; 2903 } 2904 for (String str : p.pkgList) { 2905 if (str.equals(packageName)) { 2906 proc = p; 2907 } 2908 } 2909 } 2910 } 2911 2912 if (proc == null) { 2913 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 2914 + " initialPid=" + initialPid 2915 + " packageName=" + packageName); 2916 return; 2917 } 2918 2919 if (proc.thread != null) { 2920 if (proc.pid == Process.myPid()) { 2921 Log.w(TAG, "crashApplication: trying to crash self!"); 2922 return; 2923 } 2924 long ident = Binder.clearCallingIdentity(); 2925 try { 2926 proc.thread.scheduleCrash(message); 2927 } catch (RemoteException e) { 2928 } 2929 Binder.restoreCallingIdentity(ident); 2930 } 2931 } 2932 } 2933 2934 public final void finishSubActivity(IBinder token, String resultWho, 2935 int requestCode) { 2936 synchronized(this) { 2937 final long origId = Binder.clearCallingIdentity(); 2938 mMainStack.finishSubActivityLocked(token, resultWho, requestCode); 2939 Binder.restoreCallingIdentity(origId); 2940 } 2941 } 2942 2943 public boolean finishActivityAffinity(IBinder token) { 2944 synchronized(this) { 2945 final long origId = Binder.clearCallingIdentity(); 2946 boolean res = mMainStack.finishActivityAffinityLocked(token); 2947 Binder.restoreCallingIdentity(origId); 2948 return res; 2949 } 2950 } 2951 2952 public boolean willActivityBeVisible(IBinder token) { 2953 synchronized(this) { 2954 int i; 2955 for (i=mMainStack.mHistory.size()-1; i>=0; i--) { 2956 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 2957 if (r.appToken == token) { 2958 return true; 2959 } 2960 if (r.fullscreen && !r.finishing) { 2961 return false; 2962 } 2963 } 2964 return true; 2965 } 2966 } 2967 2968 public void overridePendingTransition(IBinder token, String packageName, 2969 int enterAnim, int exitAnim) { 2970 synchronized(this) { 2971 ActivityRecord self = mMainStack.isInStackLocked(token); 2972 if (self == null) { 2973 return; 2974 } 2975 2976 final long origId = Binder.clearCallingIdentity(); 2977 2978 if (self.state == ActivityState.RESUMED 2979 || self.state == ActivityState.PAUSING) { 2980 mWindowManager.overridePendingAppTransition(packageName, 2981 enterAnim, exitAnim, null); 2982 } 2983 2984 Binder.restoreCallingIdentity(origId); 2985 } 2986 } 2987 2988 /** 2989 * Main function for removing an existing process from the activity manager 2990 * as a result of that process going away. Clears out all connections 2991 * to the process. 2992 */ 2993 private final void handleAppDiedLocked(ProcessRecord app, 2994 boolean restarting, boolean allowRestart) { 2995 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 2996 if (!restarting) { 2997 mLruProcesses.remove(app); 2998 } 2999 3000 if (mProfileProc == app) { 3001 clearProfilerLocked(); 3002 } 3003 3004 // Just in case... 3005 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) { 3006 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG, 3007 "App died while pausing: " + mMainStack.mPausingActivity); 3008 mMainStack.mPausingActivity = null; 3009 } 3010 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) { 3011 mMainStack.mLastPausedActivity = null; 3012 } 3013 3014 // Remove this application's activities from active lists. 3015 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app); 3016 3017 app.activities.clear(); 3018 3019 if (app.instrumentationClass != null) { 3020 Slog.w(TAG, "Crash of app " + app.processName 3021 + " running instrumentation " + app.instrumentationClass); 3022 Bundle info = new Bundle(); 3023 info.putString("shortMsg", "Process crashed."); 3024 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3025 } 3026 3027 if (!restarting) { 3028 if (!mMainStack.resumeTopActivityLocked(null)) { 3029 // If there was nothing to resume, and we are not already 3030 // restarting this process, but there is a visible activity that 3031 // is hosted by the process... then make sure all visible 3032 // activities are running, taking care of restarting this 3033 // process. 3034 if (hasVisibleActivities) { 3035 mMainStack.ensureActivitiesVisibleLocked(null, 0); 3036 } 3037 } 3038 } 3039 } 3040 3041 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 3042 IBinder threadBinder = thread.asBinder(); 3043 // Find the application record. 3044 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3045 ProcessRecord rec = mLruProcesses.get(i); 3046 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 3047 return i; 3048 } 3049 } 3050 return -1; 3051 } 3052 3053 final ProcessRecord getRecordForAppLocked( 3054 IApplicationThread thread) { 3055 if (thread == null) { 3056 return null; 3057 } 3058 3059 int appIndex = getLRURecordIndexForAppLocked(thread); 3060 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 3061 } 3062 3063 final void appDiedLocked(ProcessRecord app, int pid, 3064 IApplicationThread thread) { 3065 3066 mProcDeaths[0]++; 3067 3068 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3069 synchronized (stats) { 3070 stats.noteProcessDiedLocked(app.info.uid, pid); 3071 } 3072 3073 // Clean up already done if the process has been re-started. 3074 if (app.pid == pid && app.thread != null && 3075 app.thread.asBinder() == thread.asBinder()) { 3076 if (!app.killedBackground) { 3077 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 3078 + ") has died."); 3079 } 3080 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 3081 if (DEBUG_CLEANUP) Slog.v( 3082 TAG, "Dying app: " + app + ", pid: " + pid 3083 + ", thread: " + thread.asBinder()); 3084 boolean doLowMem = app.instrumentationClass == null; 3085 handleAppDiedLocked(app, false, true); 3086 3087 if (doLowMem) { 3088 // If there are no longer any background processes running, 3089 // and the app that died was not running instrumentation, 3090 // then tell everyone we are now low on memory. 3091 boolean haveBg = false; 3092 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3093 ProcessRecord rec = mLruProcesses.get(i); 3094 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 3095 haveBg = true; 3096 break; 3097 } 3098 } 3099 3100 if (!haveBg) { 3101 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 3102 long now = SystemClock.uptimeMillis(); 3103 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3104 ProcessRecord rec = mLruProcesses.get(i); 3105 if (rec != app && rec.thread != null && 3106 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 3107 // The low memory report is overriding any current 3108 // state for a GC request. Make sure to do 3109 // heavy/important/visible/foreground processes first. 3110 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 3111 rec.lastRequestedGc = 0; 3112 } else { 3113 rec.lastRequestedGc = rec.lastLowMemory; 3114 } 3115 rec.reportLowMemory = true; 3116 rec.lastLowMemory = now; 3117 mProcessesToGc.remove(rec); 3118 addProcessToGcListLocked(rec); 3119 } 3120 } 3121 mHandler.sendEmptyMessage(REPORT_MEM_USAGE); 3122 scheduleAppGcsLocked(); 3123 } 3124 } 3125 } else if (app.pid != pid) { 3126 // A new process has already been started. 3127 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 3128 + ") has died and restarted (pid " + app.pid + ")."); 3129 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 3130 } else if (DEBUG_PROCESSES) { 3131 Slog.d(TAG, "Received spurious death notification for thread " 3132 + thread.asBinder()); 3133 } 3134 } 3135 3136 /** 3137 * If a stack trace dump file is configured, dump process stack traces. 3138 * @param clearTraces causes the dump file to be erased prior to the new 3139 * traces being written, if true; when false, the new traces will be 3140 * appended to any existing file content. 3141 * @param firstPids of dalvik VM processes to dump stack traces for first 3142 * @param lastPids of dalvik VM processes to dump stack traces for last 3143 * @param nativeProcs optional list of native process names to dump stack crawls 3144 * @return file containing stack traces, or null if no dump file is configured 3145 */ 3146 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 3147 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) { 3148 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 3149 if (tracesPath == null || tracesPath.length() == 0) { 3150 return null; 3151 } 3152 3153 File tracesFile = new File(tracesPath); 3154 try { 3155 File tracesDir = tracesFile.getParentFile(); 3156 if (!tracesDir.exists()) { 3157 tracesFile.mkdirs(); 3158 if (!SELinux.restorecon(tracesDir)) { 3159 return null; 3160 } 3161 } 3162 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 3163 3164 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 3165 tracesFile.createNewFile(); 3166 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 3167 } catch (IOException e) { 3168 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 3169 return null; 3170 } 3171 3172 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs); 3173 return tracesFile; 3174 } 3175 3176 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 3177 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) { 3178 // Use a FileObserver to detect when traces finish writing. 3179 // The order of traces is considered important to maintain for legibility. 3180 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 3181 public synchronized void onEvent(int event, String path) { notify(); } 3182 }; 3183 3184 try { 3185 observer.startWatching(); 3186 3187 // First collect all of the stacks of the most important pids. 3188 if (firstPids != null) { 3189 try { 3190 int num = firstPids.size(); 3191 for (int i = 0; i < num; i++) { 3192 synchronized (observer) { 3193 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 3194 observer.wait(200); // Wait for write-close, give up after 200msec 3195 } 3196 } 3197 } catch (InterruptedException e) { 3198 Log.wtf(TAG, e); 3199 } 3200 } 3201 3202 // Next measure CPU usage. 3203 if (processStats != null) { 3204 processStats.init(); 3205 System.gc(); 3206 processStats.update(); 3207 try { 3208 synchronized (processStats) { 3209 processStats.wait(500); // measure over 1/2 second. 3210 } 3211 } catch (InterruptedException e) { 3212 } 3213 processStats.update(); 3214 3215 // We'll take the stack crawls of just the top apps using CPU. 3216 final int N = processStats.countWorkingStats(); 3217 int numProcs = 0; 3218 for (int i=0; i<N && numProcs<5; i++) { 3219 ProcessStats.Stats stats = processStats.getWorkingStats(i); 3220 if (lastPids.indexOfKey(stats.pid) >= 0) { 3221 numProcs++; 3222 try { 3223 synchronized (observer) { 3224 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 3225 observer.wait(200); // Wait for write-close, give up after 200msec 3226 } 3227 } catch (InterruptedException e) { 3228 Log.wtf(TAG, e); 3229 } 3230 3231 } 3232 } 3233 } 3234 3235 } finally { 3236 observer.stopWatching(); 3237 } 3238 3239 if (nativeProcs != null) { 3240 int[] pids = Process.getPidsForCommands(nativeProcs); 3241 if (pids != null) { 3242 for (int pid : pids) { 3243 Debug.dumpNativeBacktraceToFile(pid, tracesPath); 3244 } 3245 } 3246 } 3247 } 3248 3249 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 3250 if (true || IS_USER_BUILD) { 3251 return; 3252 } 3253 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 3254 if (tracesPath == null || tracesPath.length() == 0) { 3255 return; 3256 } 3257 3258 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 3259 StrictMode.allowThreadDiskWrites(); 3260 try { 3261 final File tracesFile = new File(tracesPath); 3262 final File tracesDir = tracesFile.getParentFile(); 3263 final File tracesTmp = new File(tracesDir, "__tmp__"); 3264 try { 3265 if (!tracesDir.exists()) { 3266 tracesFile.mkdirs(); 3267 if (!SELinux.restorecon(tracesDir.getPath())) { 3268 return; 3269 } 3270 } 3271 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 3272 3273 if (tracesFile.exists()) { 3274 tracesTmp.delete(); 3275 tracesFile.renameTo(tracesTmp); 3276 } 3277 StringBuilder sb = new StringBuilder(); 3278 Time tobj = new Time(); 3279 tobj.set(System.currentTimeMillis()); 3280 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 3281 sb.append(": "); 3282 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 3283 sb.append(" since "); 3284 sb.append(msg); 3285 FileOutputStream fos = new FileOutputStream(tracesFile); 3286 fos.write(sb.toString().getBytes()); 3287 if (app == null) { 3288 fos.write("\n*** No application process!".getBytes()); 3289 } 3290 fos.close(); 3291 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 3292 } catch (IOException e) { 3293 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 3294 return; 3295 } 3296 3297 if (app != null) { 3298 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 3299 firstPids.add(app.pid); 3300 dumpStackTraces(tracesPath, firstPids, null, null, null); 3301 } 3302 3303 File lastTracesFile = null; 3304 File curTracesFile = null; 3305 for (int i=9; i>=0; i--) { 3306 String name = String.format("slow%02d.txt", i); 3307 curTracesFile = new File(tracesDir, name); 3308 if (curTracesFile.exists()) { 3309 if (lastTracesFile != null) { 3310 curTracesFile.renameTo(lastTracesFile); 3311 } else { 3312 curTracesFile.delete(); 3313 } 3314 } 3315 lastTracesFile = curTracesFile; 3316 } 3317 tracesFile.renameTo(curTracesFile); 3318 if (tracesTmp.exists()) { 3319 tracesTmp.renameTo(tracesFile); 3320 } 3321 } finally { 3322 StrictMode.setThreadPolicy(oldPolicy); 3323 } 3324 } 3325 3326 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 3327 ActivityRecord parent, boolean aboveSystem, final String annotation) { 3328 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 3329 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 3330 3331 if (mController != null) { 3332 try { 3333 // 0 == continue, -1 = kill process immediately 3334 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 3335 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3336 } catch (RemoteException e) { 3337 mController = null; 3338 Watchdog.getInstance().setActivityController(null); 3339 } 3340 } 3341 3342 long anrTime = SystemClock.uptimeMillis(); 3343 if (MONITOR_CPU_USAGE) { 3344 updateCpuStatsNow(); 3345 } 3346 3347 synchronized (this) { 3348 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 3349 if (mShuttingDown) { 3350 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 3351 return; 3352 } else if (app.notResponding) { 3353 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 3354 return; 3355 } else if (app.crashing) { 3356 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 3357 return; 3358 } 3359 3360 // In case we come through here for the same app before completing 3361 // this one, mark as anring now so we will bail out. 3362 app.notResponding = true; 3363 3364 // Log the ANR to the event log. 3365 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 3366 app.processName, app.info.flags, annotation); 3367 3368 // Dump thread traces as quickly as we can, starting with "interesting" processes. 3369 firstPids.add(app.pid); 3370 3371 int parentPid = app.pid; 3372 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 3373 if (parentPid != app.pid) firstPids.add(parentPid); 3374 3375 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 3376 3377 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3378 ProcessRecord r = mLruProcesses.get(i); 3379 if (r != null && r.thread != null) { 3380 int pid = r.pid; 3381 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 3382 if (r.persistent) { 3383 firstPids.add(pid); 3384 } else { 3385 lastPids.put(pid, Boolean.TRUE); 3386 } 3387 } 3388 } 3389 } 3390 } 3391 3392 // Log the ANR to the main log. 3393 StringBuilder info = new StringBuilder(); 3394 info.setLength(0); 3395 info.append("ANR in ").append(app.processName); 3396 if (activity != null && activity.shortComponentName != null) { 3397 info.append(" (").append(activity.shortComponentName).append(")"); 3398 } 3399 info.append("\n"); 3400 if (annotation != null) { 3401 info.append("Reason: ").append(annotation).append("\n"); 3402 } 3403 if (parent != null && parent != activity) { 3404 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 3405 } 3406 3407 final ProcessStats processStats = new ProcessStats(true); 3408 3409 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null); 3410 3411 String cpuInfo = null; 3412 if (MONITOR_CPU_USAGE) { 3413 updateCpuStatsNow(); 3414 synchronized (mProcessStatsThread) { 3415 cpuInfo = mProcessStats.printCurrentState(anrTime); 3416 } 3417 info.append(processStats.printCurrentLoad()); 3418 info.append(cpuInfo); 3419 } 3420 3421 info.append(processStats.printCurrentState(anrTime)); 3422 3423 Slog.e(TAG, info.toString()); 3424 if (tracesFile == null) { 3425 // There is no trace file, so dump (only) the alleged culprit's threads to the log 3426 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 3427 } 3428 3429 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 3430 cpuInfo, tracesFile, null); 3431 3432 if (mController != null) { 3433 try { 3434 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 3435 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 3436 if (res != 0) { 3437 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3438 return; 3439 } 3440 } catch (RemoteException e) { 3441 mController = null; 3442 Watchdog.getInstance().setActivityController(null); 3443 } 3444 } 3445 3446 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 3447 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 3448 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 3449 3450 synchronized (this) { 3451 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 3452 Slog.w(TAG, "Killing " + app + ": background ANR"); 3453 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid, 3454 app.processName, app.setAdj, "background ANR"); 3455 Process.killProcessQuiet(app.pid); 3456 return; 3457 } 3458 3459 // Set the app's notResponding state, and look up the errorReportReceiver 3460 makeAppNotRespondingLocked(app, 3461 activity != null ? activity.shortComponentName : null, 3462 annotation != null ? "ANR " + annotation : "ANR", 3463 info.toString()); 3464 3465 // Bring up the infamous App Not Responding dialog 3466 Message msg = Message.obtain(); 3467 HashMap map = new HashMap(); 3468 msg.what = SHOW_NOT_RESPONDING_MSG; 3469 msg.obj = map; 3470 msg.arg1 = aboveSystem ? 1 : 0; 3471 map.put("app", app); 3472 if (activity != null) { 3473 map.put("activity", activity); 3474 } 3475 3476 mHandler.sendMessage(msg); 3477 } 3478 } 3479 3480 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 3481 if (!mLaunchWarningShown) { 3482 mLaunchWarningShown = true; 3483 mHandler.post(new Runnable() { 3484 @Override 3485 public void run() { 3486 synchronized (ActivityManagerService.this) { 3487 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 3488 d.show(); 3489 mHandler.postDelayed(new Runnable() { 3490 @Override 3491 public void run() { 3492 synchronized (ActivityManagerService.this) { 3493 d.dismiss(); 3494 mLaunchWarningShown = false; 3495 } 3496 } 3497 }, 4000); 3498 } 3499 } 3500 }); 3501 } 3502 } 3503 3504 public boolean clearApplicationUserData(final String packageName, 3505 final IPackageDataObserver observer, int userId) { 3506 enforceNotIsolatedCaller("clearApplicationUserData"); 3507 int uid = Binder.getCallingUid(); 3508 int pid = Binder.getCallingPid(); 3509 userId = handleIncomingUser(pid, uid, 3510 userId, false, true, "clearApplicationUserData", null); 3511 long callingId = Binder.clearCallingIdentity(); 3512 try { 3513 IPackageManager pm = AppGlobals.getPackageManager(); 3514 int pkgUid = -1; 3515 synchronized(this) { 3516 try { 3517 pkgUid = pm.getPackageUid(packageName, userId); 3518 } catch (RemoteException e) { 3519 } 3520 if (pkgUid == -1) { 3521 Slog.w(TAG, "Invalid packageName: " + packageName); 3522 if (observer != null) { 3523 try { 3524 observer.onRemoveCompleted(packageName, false); 3525 } catch (RemoteException e) { 3526 Slog.i(TAG, "Observer no longer exists."); 3527 } 3528 } 3529 return false; 3530 } 3531 if (uid == pkgUid || checkComponentPermission( 3532 android.Manifest.permission.CLEAR_APP_USER_DATA, 3533 pid, uid, -1, true) 3534 == PackageManager.PERMISSION_GRANTED) { 3535 forceStopPackageLocked(packageName, pkgUid); 3536 } else { 3537 throw new SecurityException(pid+" does not have permission:"+ 3538 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" + 3539 "for process:"+packageName); 3540 } 3541 } 3542 3543 try { 3544 //clear application user data 3545 pm.clearApplicationUserData(packageName, observer, userId); 3546 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 3547 Uri.fromParts("package", packageName, null)); 3548 intent.putExtra(Intent.EXTRA_UID, pkgUid); 3549 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 3550 null, null, 0, null, null, null, false, false, userId); 3551 } catch (RemoteException e) { 3552 } 3553 } finally { 3554 Binder.restoreCallingIdentity(callingId); 3555 } 3556 return true; 3557 } 3558 3559 public void killBackgroundProcesses(final String packageName, int userId) { 3560 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3561 != PackageManager.PERMISSION_GRANTED && 3562 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3563 != PackageManager.PERMISSION_GRANTED) { 3564 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3565 + Binder.getCallingPid() 3566 + ", uid=" + Binder.getCallingUid() 3567 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3568 Slog.w(TAG, msg); 3569 throw new SecurityException(msg); 3570 } 3571 3572 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 3573 userId, true, true, "killBackgroundProcesses", null); 3574 long callingId = Binder.clearCallingIdentity(); 3575 try { 3576 IPackageManager pm = AppGlobals.getPackageManager(); 3577 synchronized(this) { 3578 int appId = -1; 3579 try { 3580 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0)); 3581 } catch (RemoteException e) { 3582 } 3583 if (appId == -1) { 3584 Slog.w(TAG, "Invalid packageName: " + packageName); 3585 return; 3586 } 3587 killPackageProcessesLocked(packageName, appId, userId, 3588 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 3589 } 3590 } finally { 3591 Binder.restoreCallingIdentity(callingId); 3592 } 3593 } 3594 3595 public void killAllBackgroundProcesses() { 3596 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3597 != PackageManager.PERMISSION_GRANTED) { 3598 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3599 + Binder.getCallingPid() 3600 + ", uid=" + Binder.getCallingUid() 3601 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3602 Slog.w(TAG, msg); 3603 throw new SecurityException(msg); 3604 } 3605 3606 long callingId = Binder.clearCallingIdentity(); 3607 try { 3608 synchronized(this) { 3609 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3610 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3611 final int NA = apps.size(); 3612 for (int ia=0; ia<NA; ia++) { 3613 ProcessRecord app = apps.valueAt(ia); 3614 if (app.persistent) { 3615 // we don't kill persistent processes 3616 continue; 3617 } 3618 if (app.removed) { 3619 procs.add(app); 3620 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 3621 app.removed = true; 3622 procs.add(app); 3623 } 3624 } 3625 } 3626 3627 int N = procs.size(); 3628 for (int i=0; i<N; i++) { 3629 removeProcessLocked(procs.get(i), false, true, "kill all background"); 3630 } 3631 } 3632 } finally { 3633 Binder.restoreCallingIdentity(callingId); 3634 } 3635 } 3636 3637 public void forceStopPackage(final String packageName, int userId) { 3638 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3639 != PackageManager.PERMISSION_GRANTED) { 3640 String msg = "Permission Denial: forceStopPackage() from pid=" 3641 + Binder.getCallingPid() 3642 + ", uid=" + Binder.getCallingUid() 3643 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3644 Slog.w(TAG, msg); 3645 throw new SecurityException(msg); 3646 } 3647 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 3648 userId, true, true, "forceStopPackage", null); 3649 long callingId = Binder.clearCallingIdentity(); 3650 try { 3651 IPackageManager pm = AppGlobals.getPackageManager(); 3652 synchronized(this) { 3653 int[] users = userId == UserHandle.USER_ALL 3654 ? getUsersLocked() : new int[] { userId }; 3655 for (int user : users) { 3656 int pkgUid = -1; 3657 try { 3658 pkgUid = pm.getPackageUid(packageName, user); 3659 } catch (RemoteException e) { 3660 } 3661 if (pkgUid == -1) { 3662 Slog.w(TAG, "Invalid packageName: " + packageName); 3663 continue; 3664 } 3665 try { 3666 pm.setPackageStoppedState(packageName, true, user); 3667 } catch (RemoteException e) { 3668 } catch (IllegalArgumentException e) { 3669 Slog.w(TAG, "Failed trying to unstop package " 3670 + packageName + ": " + e); 3671 } 3672 if (isUserRunningLocked(user, false)) { 3673 forceStopPackageLocked(packageName, pkgUid); 3674 } 3675 } 3676 } 3677 } finally { 3678 Binder.restoreCallingIdentity(callingId); 3679 } 3680 } 3681 3682 /* 3683 * The pkg name and app id have to be specified. 3684 */ 3685 public void killApplicationWithAppId(String pkg, int appid) { 3686 if (pkg == null) { 3687 return; 3688 } 3689 // Make sure the uid is valid. 3690 if (appid < 0) { 3691 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 3692 return; 3693 } 3694 int callerUid = Binder.getCallingUid(); 3695 // Only the system server can kill an application 3696 if (callerUid == Process.SYSTEM_UID) { 3697 // Post an aysnc message to kill the application 3698 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 3699 msg.arg1 = appid; 3700 msg.arg2 = 0; 3701 msg.obj = pkg; 3702 mHandler.sendMessage(msg); 3703 } else { 3704 throw new SecurityException(callerUid + " cannot kill pkg: " + 3705 pkg); 3706 } 3707 } 3708 3709 public void closeSystemDialogs(String reason) { 3710 enforceNotIsolatedCaller("closeSystemDialogs"); 3711 3712 final int pid = Binder.getCallingPid(); 3713 final int uid = Binder.getCallingUid(); 3714 final long origId = Binder.clearCallingIdentity(); 3715 try { 3716 synchronized (this) { 3717 // Only allow this from foreground processes, so that background 3718 // applications can't abuse it to prevent system UI from being shown. 3719 if (uid >= Process.FIRST_APPLICATION_UID) { 3720 ProcessRecord proc; 3721 synchronized (mPidsSelfLocked) { 3722 proc = mPidsSelfLocked.get(pid); 3723 } 3724 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 3725 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 3726 + " from background process " + proc); 3727 return; 3728 } 3729 } 3730 closeSystemDialogsLocked(reason); 3731 } 3732 } finally { 3733 Binder.restoreCallingIdentity(origId); 3734 } 3735 } 3736 3737 void closeSystemDialogsLocked(String reason) { 3738 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 3739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3740 | Intent.FLAG_RECEIVER_FOREGROUND); 3741 if (reason != null) { 3742 intent.putExtra("reason", reason); 3743 } 3744 mWindowManager.closeSystemDialogs(reason); 3745 3746 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) { 3747 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3748 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3749 r.stack.finishActivityLocked(r, i, 3750 Activity.RESULT_CANCELED, null, "close-sys", true); 3751 } 3752 } 3753 3754 broadcastIntentLocked(null, null, intent, null, 3755 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1, 3756 Process.SYSTEM_UID, UserHandle.USER_ALL); 3757 } 3758 3759 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) 3760 throws RemoteException { 3761 enforceNotIsolatedCaller("getProcessMemoryInfo"); 3762 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 3763 for (int i=pids.length-1; i>=0; i--) { 3764 infos[i] = new Debug.MemoryInfo(); 3765 Debug.getMemoryInfo(pids[i], infos[i]); 3766 } 3767 return infos; 3768 } 3769 3770 public long[] getProcessPss(int[] pids) throws RemoteException { 3771 enforceNotIsolatedCaller("getProcessPss"); 3772 long[] pss = new long[pids.length]; 3773 for (int i=pids.length-1; i>=0; i--) { 3774 pss[i] = Debug.getPss(pids[i]); 3775 } 3776 return pss; 3777 } 3778 3779 public void killApplicationProcess(String processName, int uid) { 3780 if (processName == null) { 3781 return; 3782 } 3783 3784 int callerUid = Binder.getCallingUid(); 3785 // Only the system server can kill an application 3786 if (callerUid == Process.SYSTEM_UID) { 3787 synchronized (this) { 3788 ProcessRecord app = getProcessRecordLocked(processName, uid); 3789 if (app != null && app.thread != null) { 3790 try { 3791 app.thread.scheduleSuicide(); 3792 } catch (RemoteException e) { 3793 // If the other end already died, then our work here is done. 3794 } 3795 } else { 3796 Slog.w(TAG, "Process/uid not found attempting kill of " 3797 + processName + " / " + uid); 3798 } 3799 } 3800 } else { 3801 throw new SecurityException(callerUid + " cannot kill app process: " + 3802 processName); 3803 } 3804 } 3805 3806 private void forceStopPackageLocked(final String packageName, int uid) { 3807 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 3808 false, true, false, UserHandle.getUserId(uid)); 3809 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 3810 Uri.fromParts("package", packageName, null)); 3811 if (!mProcessesReady) { 3812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3813 | Intent.FLAG_RECEIVER_FOREGROUND); 3814 } 3815 intent.putExtra(Intent.EXTRA_UID, uid); 3816 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 3817 broadcastIntentLocked(null, null, intent, 3818 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 3819 false, false, 3820 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); 3821 } 3822 3823 private void forceStopUserLocked(int userId) { 3824 forceStopPackageLocked(null, -1, false, false, true, false, userId); 3825 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 3826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3827 | Intent.FLAG_RECEIVER_FOREGROUND); 3828 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 3829 broadcastIntentLocked(null, null, intent, 3830 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 3831 false, false, 3832 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 3833 } 3834 3835 private final boolean killPackageProcessesLocked(String packageName, int appId, 3836 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 3837 boolean doit, boolean evenPersistent, String reason) { 3838 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3839 3840 // Remove all processes this package may have touched: all with the 3841 // same UID (except for the system or root user), and all whose name 3842 // matches the package name. 3843 final String procNamePrefix = packageName != null ? (packageName + ":") : null; 3844 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3845 final int NA = apps.size(); 3846 for (int ia=0; ia<NA; ia++) { 3847 ProcessRecord app = apps.valueAt(ia); 3848 if (app.persistent && !evenPersistent) { 3849 // we don't kill persistent processes 3850 continue; 3851 } 3852 if (app.removed) { 3853 if (doit) { 3854 procs.add(app); 3855 } 3856 continue; 3857 } 3858 3859 // Skip process if it doesn't meet our oom adj requirement. 3860 if (app.setAdj < minOomAdj) { 3861 continue; 3862 } 3863 3864 // If no package is specified, we call all processes under the 3865 // give user id. 3866 if (packageName == null) { 3867 if (app.userId != userId) { 3868 continue; 3869 } 3870 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 3871 continue; 3872 } 3873 // Package has been specified, we want to hit all processes 3874 // that match it. We need to qualify this by the processes 3875 // that are running under the specified app and user ID. 3876 } else { 3877 if (UserHandle.getAppId(app.uid) != appId) { 3878 continue; 3879 } 3880 if (userId != UserHandle.USER_ALL && app.userId != userId) { 3881 continue; 3882 } 3883 if (!app.pkgList.contains(packageName)) { 3884 continue; 3885 } 3886 } 3887 3888 // Process has passed all conditions, kill it! 3889 if (!doit) { 3890 return true; 3891 } 3892 app.removed = true; 3893 procs.add(app); 3894 } 3895 } 3896 3897 int N = procs.size(); 3898 for (int i=0; i<N; i++) { 3899 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 3900 } 3901 return N > 0; 3902 } 3903 3904 private final boolean forceStopPackageLocked(String name, int appId, 3905 boolean callerWillRestart, boolean purgeCache, boolean doit, 3906 boolean evenPersistent, int userId) { 3907 int i; 3908 int N; 3909 3910 if (userId == UserHandle.USER_ALL && name == null) { 3911 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 3912 } 3913 3914 if (appId < 0 && name != null) { 3915 try { 3916 appId = UserHandle.getAppId( 3917 AppGlobals.getPackageManager().getPackageUid(name, 0)); 3918 } catch (RemoteException e) { 3919 } 3920 } 3921 3922 if (doit) { 3923 if (name != null) { 3924 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId 3925 + " user=" + userId); 3926 } else { 3927 Slog.i(TAG, "Force stopping user " + userId); 3928 } 3929 3930 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator(); 3931 while (badApps.hasNext()) { 3932 SparseArray<Long> ba = badApps.next(); 3933 for (i=ba.size()-1; i>=0; i--) { 3934 boolean remove = false; 3935 final int entUid = ba.keyAt(i); 3936 if (name != null) { 3937 if (userId == UserHandle.USER_ALL) { 3938 if (UserHandle.getAppId(entUid) == appId) { 3939 remove = true; 3940 } 3941 } else { 3942 if (entUid == UserHandle.getUid(userId, appId)) { 3943 remove = true; 3944 } 3945 } 3946 } else if (UserHandle.getUserId(entUid) == userId) { 3947 remove = true; 3948 } 3949 if (remove) { 3950 ba.removeAt(i); 3951 } 3952 } 3953 if (ba.size() == 0) { 3954 badApps.remove(); 3955 } 3956 } 3957 } 3958 3959 boolean didSomething = killPackageProcessesLocked(name, appId, userId, 3960 -100, callerWillRestart, true, doit, evenPersistent, 3961 name == null ? ("force stop user " + userId) : ("force stop " + name)); 3962 3963 TaskRecord lastTask = null; 3964 for (i=0; i<mMainStack.mHistory.size(); i++) { 3965 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3966 final boolean samePackage = r.packageName.equals(name) 3967 || (name == null && r.userId == userId); 3968 if ((userId == UserHandle.USER_ALL || r.userId == userId) 3969 && (samePackage || r.task == lastTask) 3970 && (r.app == null || evenPersistent || !r.app.persistent)) { 3971 if (!doit) { 3972 if (r.finishing) { 3973 // If this activity is just finishing, then it is not 3974 // interesting as far as something to stop. 3975 continue; 3976 } 3977 return true; 3978 } 3979 didSomething = true; 3980 Slog.i(TAG, " Force finishing activity " + r); 3981 if (samePackage) { 3982 if (r.app != null) { 3983 r.app.removed = true; 3984 } 3985 r.app = null; 3986 } 3987 lastTask = r.task; 3988 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, 3989 null, "force-stop", true)) { 3990 i--; 3991 } 3992 } 3993 } 3994 3995 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) { 3996 if (!doit) { 3997 return true; 3998 } 3999 didSomething = true; 4000 } 4001 4002 if (name == null) { 4003 // Remove all sticky broadcasts from this user. 4004 mStickyBroadcasts.remove(userId); 4005 } 4006 4007 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>(); 4008 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent, 4009 userId, providers)) { 4010 if (!doit) { 4011 return true; 4012 } 4013 didSomething = true; 4014 } 4015 N = providers.size(); 4016 for (i=0; i<N; i++) { 4017 removeDyingProviderLocked(null, providers.get(i), true); 4018 } 4019 4020 if (name == null) { 4021 // Remove pending intents. For now we only do this when force 4022 // stopping users, because we have some problems when doing this 4023 // for packages -- app widgets are not currently cleaned up for 4024 // such packages, so they can be left with bad pending intents. 4025 if (mIntentSenderRecords.size() > 0) { 4026 Iterator<WeakReference<PendingIntentRecord>> it 4027 = mIntentSenderRecords.values().iterator(); 4028 while (it.hasNext()) { 4029 WeakReference<PendingIntentRecord> wpir = it.next(); 4030 if (wpir == null) { 4031 it.remove(); 4032 continue; 4033 } 4034 PendingIntentRecord pir = wpir.get(); 4035 if (pir == null) { 4036 it.remove(); 4037 continue; 4038 } 4039 if (name == null) { 4040 // Stopping user, remove all objects for the user. 4041 if (pir.key.userId != userId) { 4042 // Not the same user, skip it. 4043 continue; 4044 } 4045 } else { 4046 if (UserHandle.getAppId(pir.uid) != appId) { 4047 // Different app id, skip it. 4048 continue; 4049 } 4050 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 4051 // Different user, skip it. 4052 continue; 4053 } 4054 if (!pir.key.packageName.equals(name)) { 4055 // Different package, skip it. 4056 continue; 4057 } 4058 } 4059 if (!doit) { 4060 return true; 4061 } 4062 didSomething = true; 4063 it.remove(); 4064 pir.canceled = true; 4065 if (pir.key.activity != null) { 4066 pir.key.activity.pendingResults.remove(pir.ref); 4067 } 4068 } 4069 } 4070 } 4071 4072 if (doit) { 4073 if (purgeCache && name != null) { 4074 AttributeCache ac = AttributeCache.instance(); 4075 if (ac != null) { 4076 ac.removePackage(name); 4077 } 4078 } 4079 if (mBooted) { 4080 mMainStack.resumeTopActivityLocked(null); 4081 mMainStack.scheduleIdleLocked(); 4082 } 4083 } 4084 4085 return didSomething; 4086 } 4087 4088 private final boolean removeProcessLocked(ProcessRecord app, 4089 boolean callerWillRestart, boolean allowRestart, String reason) { 4090 final String name = app.processName; 4091 final int uid = app.uid; 4092 if (DEBUG_PROCESSES) Slog.d( 4093 TAG, "Force removing proc " + app.toShortString() + " (" + name 4094 + "/" + uid + ")"); 4095 4096 mProcessNames.remove(name, uid); 4097 mIsolatedProcesses.remove(app.uid); 4098 if (mHeavyWeightProcess == app) { 4099 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4100 mHeavyWeightProcess.userId, 0)); 4101 mHeavyWeightProcess = null; 4102 } 4103 boolean needRestart = false; 4104 if (app.pid > 0 && app.pid != MY_PID) { 4105 int pid = app.pid; 4106 synchronized (mPidsSelfLocked) { 4107 mPidsSelfLocked.remove(pid); 4108 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4109 } 4110 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason); 4111 handleAppDiedLocked(app, true, allowRestart); 4112 mLruProcesses.remove(app); 4113 Process.killProcessQuiet(pid); 4114 4115 if (app.persistent && !app.isolated) { 4116 if (!callerWillRestart) { 4117 addAppLocked(app.info, false); 4118 } else { 4119 needRestart = true; 4120 } 4121 } 4122 } else { 4123 mRemovedProcesses.add(app); 4124 } 4125 4126 return needRestart; 4127 } 4128 4129 private final void processStartTimedOutLocked(ProcessRecord app) { 4130 final int pid = app.pid; 4131 boolean gone = false; 4132 synchronized (mPidsSelfLocked) { 4133 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 4134 if (knownApp != null && knownApp.thread == null) { 4135 mPidsSelfLocked.remove(pid); 4136 gone = true; 4137 } 4138 } 4139 4140 if (gone) { 4141 Slog.w(TAG, "Process " + app + " failed to attach"); 4142 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 4143 pid, app.uid, app.processName); 4144 mProcessNames.remove(app.processName, app.uid); 4145 mIsolatedProcesses.remove(app.uid); 4146 if (mHeavyWeightProcess == app) { 4147 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4148 mHeavyWeightProcess.userId, 0)); 4149 mHeavyWeightProcess = null; 4150 } 4151 // Take care of any launching providers waiting for this process. 4152 checkAppInLaunchingProvidersLocked(app, true); 4153 // Take care of any services that are waiting for the process. 4154 mServices.processStartTimedOutLocked(app); 4155 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid, 4156 app.processName, app.setAdj, "start timeout"); 4157 Process.killProcessQuiet(pid); 4158 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 4159 Slog.w(TAG, "Unattached app died before backup, skipping"); 4160 try { 4161 IBackupManager bm = IBackupManager.Stub.asInterface( 4162 ServiceManager.getService(Context.BACKUP_SERVICE)); 4163 bm.agentDisconnected(app.info.packageName); 4164 } catch (RemoteException e) { 4165 // Can't happen; the backup manager is local 4166 } 4167 } 4168 if (isPendingBroadcastProcessLocked(pid)) { 4169 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 4170 skipPendingBroadcastLocked(pid); 4171 } 4172 } else { 4173 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4174 } 4175 } 4176 4177 private final boolean attachApplicationLocked(IApplicationThread thread, 4178 int pid) { 4179 4180 // Find the application record that is being attached... either via 4181 // the pid if we are running in multiple processes, or just pull the 4182 // next app record if we are emulating process with anonymous threads. 4183 ProcessRecord app; 4184 if (pid != MY_PID && pid >= 0) { 4185 synchronized (mPidsSelfLocked) { 4186 app = mPidsSelfLocked.get(pid); 4187 } 4188 } else { 4189 app = null; 4190 } 4191 4192 if (app == null) { 4193 Slog.w(TAG, "No pending application record for pid " + pid 4194 + " (IApplicationThread " + thread + "); dropping process"); 4195 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 4196 if (pid > 0 && pid != MY_PID) { 4197 Process.killProcessQuiet(pid); 4198 } else { 4199 try { 4200 thread.scheduleExit(); 4201 } catch (Exception e) { 4202 // Ignore exceptions. 4203 } 4204 } 4205 return false; 4206 } 4207 4208 // If this application record is still attached to a previous 4209 // process, clean it up now. 4210 if (app.thread != null) { 4211 handleAppDiedLocked(app, true, true); 4212 } 4213 4214 // Tell the process all about itself. 4215 4216 if (localLOGV) Slog.v( 4217 TAG, "Binding process pid " + pid + " to record " + app); 4218 4219 String processName = app.processName; 4220 try { 4221 AppDeathRecipient adr = new AppDeathRecipient( 4222 app, pid, thread); 4223 thread.asBinder().linkToDeath(adr, 0); 4224 app.deathRecipient = adr; 4225 } catch (RemoteException e) { 4226 app.resetPackageList(); 4227 startProcessLocked(app, "link fail", processName); 4228 return false; 4229 } 4230 4231 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 4232 4233 app.thread = thread; 4234 app.curAdj = app.setAdj = -100; 4235 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 4236 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 4237 app.forcingToForeground = null; 4238 app.foregroundServices = false; 4239 app.hasShownUi = false; 4240 app.debugging = false; 4241 4242 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4243 4244 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4245 List providers = normalMode ? generateApplicationProvidersLocked(app) : null; 4246 4247 if (!normalMode) { 4248 Slog.i(TAG, "Launching preboot mode app: " + app); 4249 } 4250 4251 if (localLOGV) Slog.v( 4252 TAG, "New app record " + app 4253 + " thread=" + thread.asBinder() + " pid=" + pid); 4254 try { 4255 int testMode = IApplicationThread.DEBUG_OFF; 4256 if (mDebugApp != null && mDebugApp.equals(processName)) { 4257 testMode = mWaitForDebugger 4258 ? IApplicationThread.DEBUG_WAIT 4259 : IApplicationThread.DEBUG_ON; 4260 app.debugging = true; 4261 if (mDebugTransient) { 4262 mDebugApp = mOrigDebugApp; 4263 mWaitForDebugger = mOrigWaitForDebugger; 4264 } 4265 } 4266 String profileFile = app.instrumentationProfileFile; 4267 ParcelFileDescriptor profileFd = null; 4268 boolean profileAutoStop = false; 4269 if (mProfileApp != null && mProfileApp.equals(processName)) { 4270 mProfileProc = app; 4271 profileFile = mProfileFile; 4272 profileFd = mProfileFd; 4273 profileAutoStop = mAutoStopProfiler; 4274 } 4275 boolean enableOpenGlTrace = false; 4276 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) { 4277 enableOpenGlTrace = true; 4278 mOpenGlTraceApp = null; 4279 } 4280 4281 // If the app is being launched for restore or full backup, set it up specially 4282 boolean isRestrictedBackupMode = false; 4283 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 4284 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 4285 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 4286 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 4287 } 4288 4289 ensurePackageDexOpt(app.instrumentationInfo != null 4290 ? app.instrumentationInfo.packageName 4291 : app.info.packageName); 4292 if (app.instrumentationClass != null) { 4293 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 4294 } 4295 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc " 4296 + processName + " with config " + mConfiguration); 4297 ApplicationInfo appInfo = app.instrumentationInfo != null 4298 ? app.instrumentationInfo : app.info; 4299 app.compat = compatibilityInfoForPackageLocked(appInfo); 4300 if (profileFd != null) { 4301 profileFd = profileFd.dup(); 4302 } 4303 thread.bindApplication(processName, appInfo, providers, 4304 app.instrumentationClass, profileFile, profileFd, profileAutoStop, 4305 app.instrumentationArguments, app.instrumentationWatcher, 4306 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, 4307 isRestrictedBackupMode || !normalMode, app.persistent, 4308 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), 4309 mCoreSettingsObserver.getCoreSettingsLocked()); 4310 updateLruProcessLocked(app, false); 4311 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 4312 } catch (Exception e) { 4313 // todo: Yikes! What should we do? For now we will try to 4314 // start another process, but that could easily get us in 4315 // an infinite loop of restarting processes... 4316 Slog.w(TAG, "Exception thrown during bind!", e); 4317 4318 app.resetPackageList(); 4319 app.unlinkDeathRecipient(); 4320 startProcessLocked(app, "bind fail", processName); 4321 return false; 4322 } 4323 4324 // Remove this record from the list of starting applications. 4325 mPersistentStartingProcesses.remove(app); 4326 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 4327 "Attach application locked removing on hold: " + app); 4328 mProcessesOnHold.remove(app); 4329 4330 boolean badApp = false; 4331 boolean didSomething = false; 4332 4333 // See if the top visible activity is waiting to run in this process... 4334 ActivityRecord hr = mMainStack.topRunningActivityLocked(null); 4335 if (hr != null && normalMode) { 4336 if (hr.app == null && app.uid == hr.info.applicationInfo.uid 4337 && processName.equals(hr.processName)) { 4338 try { 4339 if (mHeadless) { 4340 Slog.e(TAG, "Starting activities not supported on headless device: " + hr); 4341 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) { 4342 didSomething = true; 4343 } 4344 } catch (Exception e) { 4345 Slog.w(TAG, "Exception in new application when starting activity " 4346 + hr.intent.getComponent().flattenToShortString(), e); 4347 badApp = true; 4348 } 4349 } else { 4350 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0); 4351 } 4352 } 4353 4354 // Find any services that should be running in this process... 4355 if (!badApp) { 4356 try { 4357 didSomething |= mServices.attachApplicationLocked(app, processName); 4358 } catch (Exception e) { 4359 badApp = true; 4360 } 4361 } 4362 4363 // Check if a next-broadcast receiver is in this process... 4364 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 4365 try { 4366 didSomething = sendPendingBroadcastsLocked(app); 4367 } catch (Exception e) { 4368 // If the app died trying to launch the receiver we declare it 'bad' 4369 badApp = true; 4370 } 4371 } 4372 4373 // Check whether the next backup agent is in this process... 4374 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) { 4375 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app); 4376 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 4377 try { 4378 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 4379 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 4380 mBackupTarget.backupMode); 4381 } catch (Exception e) { 4382 Slog.w(TAG, "Exception scheduling backup agent creation: "); 4383 e.printStackTrace(); 4384 } 4385 } 4386 4387 if (badApp) { 4388 // todo: Also need to kill application to deal with all 4389 // kinds of exceptions. 4390 handleAppDiedLocked(app, false, true); 4391 return false; 4392 } 4393 4394 if (!didSomething) { 4395 updateOomAdjLocked(); 4396 } 4397 4398 return true; 4399 } 4400 4401 public final void attachApplication(IApplicationThread thread) { 4402 synchronized (this) { 4403 int callingPid = Binder.getCallingPid(); 4404 final long origId = Binder.clearCallingIdentity(); 4405 attachApplicationLocked(thread, callingPid); 4406 Binder.restoreCallingIdentity(origId); 4407 } 4408 } 4409 4410 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 4411 final long origId = Binder.clearCallingIdentity(); 4412 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config); 4413 if (stopProfiling) { 4414 synchronized (this) { 4415 if (mProfileProc == r.app) { 4416 if (mProfileFd != null) { 4417 try { 4418 mProfileFd.close(); 4419 } catch (IOException e) { 4420 } 4421 clearProfilerLocked(); 4422 } 4423 } 4424 } 4425 } 4426 Binder.restoreCallingIdentity(origId); 4427 } 4428 4429 void enableScreenAfterBoot() { 4430 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 4431 SystemClock.uptimeMillis()); 4432 mWindowManager.enableScreenAfterBoot(); 4433 4434 synchronized (this) { 4435 updateEventDispatchingLocked(); 4436 } 4437 } 4438 4439 public void showBootMessage(final CharSequence msg, final boolean always) { 4440 enforceNotIsolatedCaller("showBootMessage"); 4441 mWindowManager.showBootMessage(msg, always); 4442 } 4443 4444 public void dismissKeyguardOnNextActivity() { 4445 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity"); 4446 final long token = Binder.clearCallingIdentity(); 4447 try { 4448 synchronized (this) { 4449 if (mLockScreenShown) { 4450 mLockScreenShown = false; 4451 comeOutOfSleepIfNeededLocked(); 4452 } 4453 mMainStack.dismissKeyguardOnNextActivityLocked(); 4454 } 4455 } finally { 4456 Binder.restoreCallingIdentity(token); 4457 } 4458 } 4459 4460 final void finishBooting() { 4461 IntentFilter pkgFilter = new IntentFilter(); 4462 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 4463 pkgFilter.addDataScheme("package"); 4464 mContext.registerReceiver(new BroadcastReceiver() { 4465 @Override 4466 public void onReceive(Context context, Intent intent) { 4467 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 4468 if (pkgs != null) { 4469 for (String pkg : pkgs) { 4470 synchronized (ActivityManagerService.this) { 4471 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) { 4472 setResultCode(Activity.RESULT_OK); 4473 return; 4474 } 4475 } 4476 } 4477 } 4478 } 4479 }, pkgFilter); 4480 4481 synchronized (this) { 4482 // Ensure that any processes we had put on hold are now started 4483 // up. 4484 final int NP = mProcessesOnHold.size(); 4485 if (NP > 0) { 4486 ArrayList<ProcessRecord> procs = 4487 new ArrayList<ProcessRecord>(mProcessesOnHold); 4488 for (int ip=0; ip<NP; ip++) { 4489 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: " 4490 + procs.get(ip)); 4491 startProcessLocked(procs.get(ip), "on-hold", null); 4492 } 4493 } 4494 4495 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { 4496 // Start looking for apps that are abusing wake locks. 4497 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 4498 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 4499 // Tell anyone interested that we are done booting! 4500 SystemProperties.set("sys.boot_completed", "1"); 4501 SystemProperties.set("dev.bootcomplete", "1"); 4502 for (int i=0; i<mStartedUsers.size(); i++) { 4503 UserStartedState uss = mStartedUsers.valueAt(i); 4504 if (uss.mState == UserStartedState.STATE_BOOTING) { 4505 uss.mState = UserStartedState.STATE_RUNNING; 4506 final int userId = mStartedUsers.keyAt(i); 4507 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 4508 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 4509 broadcastIntentLocked(null, null, intent, 4510 null, null, 0, null, null, 4511 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, 4512 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID, 4513 userId); 4514 } 4515 } 4516 } 4517 } 4518 } 4519 4520 final void ensureBootCompleted() { 4521 boolean booting; 4522 boolean enableScreen; 4523 synchronized (this) { 4524 booting = mBooting; 4525 mBooting = false; 4526 enableScreen = !mBooted; 4527 mBooted = true; 4528 } 4529 4530 if (booting) { 4531 finishBooting(); 4532 } 4533 4534 if (enableScreen) { 4535 enableScreenAfterBoot(); 4536 } 4537 } 4538 4539 public final void activityResumed(IBinder token) { 4540 final long origId = Binder.clearCallingIdentity(); 4541 mMainStack.activityResumed(token); 4542 Binder.restoreCallingIdentity(origId); 4543 } 4544 4545 public final void activityPaused(IBinder token) { 4546 final long origId = Binder.clearCallingIdentity(); 4547 mMainStack.activityPaused(token, false); 4548 Binder.restoreCallingIdentity(origId); 4549 } 4550 4551 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail, 4552 CharSequence description) { 4553 if (localLOGV) Slog.v( 4554 TAG, "Activity stopped: token=" + token); 4555 4556 // Refuse possible leaked file descriptors 4557 if (icicle != null && icicle.hasFileDescriptors()) { 4558 throw new IllegalArgumentException("File descriptors passed in Bundle"); 4559 } 4560 4561 ActivityRecord r = null; 4562 4563 final long origId = Binder.clearCallingIdentity(); 4564 4565 synchronized (this) { 4566 r = mMainStack.isInStackLocked(token); 4567 if (r != null) { 4568 r.stack.activityStoppedLocked(r, icicle, thumbnail, description); 4569 } 4570 } 4571 4572 if (r != null) { 4573 sendPendingThumbnail(r, null, null, null, false); 4574 } 4575 4576 trimApplications(); 4577 4578 Binder.restoreCallingIdentity(origId); 4579 } 4580 4581 public final void activityDestroyed(IBinder token) { 4582 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token); 4583 mMainStack.activityDestroyed(token); 4584 } 4585 4586 public String getCallingPackage(IBinder token) { 4587 synchronized (this) { 4588 ActivityRecord r = getCallingRecordLocked(token); 4589 return r != null ? r.info.packageName : null; 4590 } 4591 } 4592 4593 public ComponentName getCallingActivity(IBinder token) { 4594 synchronized (this) { 4595 ActivityRecord r = getCallingRecordLocked(token); 4596 return r != null ? r.intent.getComponent() : null; 4597 } 4598 } 4599 4600 private ActivityRecord getCallingRecordLocked(IBinder token) { 4601 ActivityRecord r = mMainStack.isInStackLocked(token); 4602 if (r == null) { 4603 return null; 4604 } 4605 return r.resultTo; 4606 } 4607 4608 public ComponentName getActivityClassForToken(IBinder token) { 4609 synchronized(this) { 4610 ActivityRecord r = mMainStack.isInStackLocked(token); 4611 if (r == null) { 4612 return null; 4613 } 4614 return r.intent.getComponent(); 4615 } 4616 } 4617 4618 public String getPackageForToken(IBinder token) { 4619 synchronized(this) { 4620 ActivityRecord r = mMainStack.isInStackLocked(token); 4621 if (r == null) { 4622 return null; 4623 } 4624 return r.packageName; 4625 } 4626 } 4627 4628 public IIntentSender getIntentSender(int type, 4629 String packageName, IBinder token, String resultWho, 4630 int requestCode, Intent[] intents, String[] resolvedTypes, 4631 int flags, Bundle options, int userId) { 4632 enforceNotIsolatedCaller("getIntentSender"); 4633 // Refuse possible leaked file descriptors 4634 if (intents != null) { 4635 if (intents.length < 1) { 4636 throw new IllegalArgumentException("Intents array length must be >= 1"); 4637 } 4638 for (int i=0; i<intents.length; i++) { 4639 Intent intent = intents[i]; 4640 if (intent != null) { 4641 if (intent.hasFileDescriptors()) { 4642 throw new IllegalArgumentException("File descriptors passed in Intent"); 4643 } 4644 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 4645 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 4646 throw new IllegalArgumentException( 4647 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 4648 } 4649 intents[i] = new Intent(intent); 4650 } 4651 } 4652 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 4653 throw new IllegalArgumentException( 4654 "Intent array length does not match resolvedTypes length"); 4655 } 4656 } 4657 if (options != null) { 4658 if (options.hasFileDescriptors()) { 4659 throw new IllegalArgumentException("File descriptors passed in options"); 4660 } 4661 } 4662 4663 synchronized(this) { 4664 int callingUid = Binder.getCallingUid(); 4665 int origUserId = userId; 4666 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 4667 type == ActivityManager.INTENT_SENDER_BROADCAST, false, 4668 "getIntentSender", null); 4669 if (origUserId == UserHandle.USER_CURRENT) { 4670 // We don't want to evaluate this until the pending intent is 4671 // actually executed. However, we do want to always do the 4672 // security checking for it above. 4673 userId = UserHandle.USER_CURRENT; 4674 } 4675 try { 4676 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 4677 int uid = AppGlobals.getPackageManager() 4678 .getPackageUid(packageName, UserHandle.getUserId(callingUid)); 4679 if (!UserHandle.isSameApp(callingUid, uid)) { 4680 String msg = "Permission Denial: getIntentSender() from pid=" 4681 + Binder.getCallingPid() 4682 + ", uid=" + Binder.getCallingUid() 4683 + ", (need uid=" + uid + ")" 4684 + " is not allowed to send as package " + packageName; 4685 Slog.w(TAG, msg); 4686 throw new SecurityException(msg); 4687 } 4688 } 4689 4690 return getIntentSenderLocked(type, packageName, callingUid, userId, 4691 token, resultWho, requestCode, intents, resolvedTypes, flags, options); 4692 4693 } catch (RemoteException e) { 4694 throw new SecurityException(e); 4695 } 4696 } 4697 } 4698 4699 IIntentSender getIntentSenderLocked(int type, String packageName, 4700 int callingUid, int userId, IBinder token, String resultWho, 4701 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 4702 Bundle options) { 4703 if (DEBUG_MU) 4704 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 4705 ActivityRecord activity = null; 4706 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 4707 activity = mMainStack.isInStackLocked(token); 4708 if (activity == null) { 4709 return null; 4710 } 4711 if (activity.finishing) { 4712 return null; 4713 } 4714 } 4715 4716 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 4717 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 4718 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 4719 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 4720 |PendingIntent.FLAG_UPDATE_CURRENT); 4721 4722 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 4723 type, packageName, activity, resultWho, 4724 requestCode, intents, resolvedTypes, flags, options, userId); 4725 WeakReference<PendingIntentRecord> ref; 4726 ref = mIntentSenderRecords.get(key); 4727 PendingIntentRecord rec = ref != null ? ref.get() : null; 4728 if (rec != null) { 4729 if (!cancelCurrent) { 4730 if (updateCurrent) { 4731 if (rec.key.requestIntent != null) { 4732 rec.key.requestIntent.replaceExtras(intents != null ? 4733 intents[intents.length - 1] : null); 4734 } 4735 if (intents != null) { 4736 intents[intents.length-1] = rec.key.requestIntent; 4737 rec.key.allIntents = intents; 4738 rec.key.allResolvedTypes = resolvedTypes; 4739 } else { 4740 rec.key.allIntents = null; 4741 rec.key.allResolvedTypes = null; 4742 } 4743 } 4744 return rec; 4745 } 4746 rec.canceled = true; 4747 mIntentSenderRecords.remove(key); 4748 } 4749 if (noCreate) { 4750 return rec; 4751 } 4752 rec = new PendingIntentRecord(this, key, callingUid); 4753 mIntentSenderRecords.put(key, rec.ref); 4754 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 4755 if (activity.pendingResults == null) { 4756 activity.pendingResults 4757 = new HashSet<WeakReference<PendingIntentRecord>>(); 4758 } 4759 activity.pendingResults.add(rec.ref); 4760 } 4761 return rec; 4762 } 4763 4764 public void cancelIntentSender(IIntentSender sender) { 4765 if (!(sender instanceof PendingIntentRecord)) { 4766 return; 4767 } 4768 synchronized(this) { 4769 PendingIntentRecord rec = (PendingIntentRecord)sender; 4770 try { 4771 int uid = AppGlobals.getPackageManager() 4772 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId()); 4773 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 4774 String msg = "Permission Denial: cancelIntentSender() from pid=" 4775 + Binder.getCallingPid() 4776 + ", uid=" + Binder.getCallingUid() 4777 + " is not allowed to cancel packges " 4778 + rec.key.packageName; 4779 Slog.w(TAG, msg); 4780 throw new SecurityException(msg); 4781 } 4782 } catch (RemoteException e) { 4783 throw new SecurityException(e); 4784 } 4785 cancelIntentSenderLocked(rec, true); 4786 } 4787 } 4788 4789 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 4790 rec.canceled = true; 4791 mIntentSenderRecords.remove(rec.key); 4792 if (cleanActivity && rec.key.activity != null) { 4793 rec.key.activity.pendingResults.remove(rec.ref); 4794 } 4795 } 4796 4797 public String getPackageForIntentSender(IIntentSender pendingResult) { 4798 if (!(pendingResult instanceof PendingIntentRecord)) { 4799 return null; 4800 } 4801 try { 4802 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4803 return res.key.packageName; 4804 } catch (ClassCastException e) { 4805 } 4806 return null; 4807 } 4808 4809 public int getUidForIntentSender(IIntentSender sender) { 4810 if (sender instanceof PendingIntentRecord) { 4811 try { 4812 PendingIntentRecord res = (PendingIntentRecord)sender; 4813 return res.uid; 4814 } catch (ClassCastException e) { 4815 } 4816 } 4817 return -1; 4818 } 4819 4820 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 4821 if (!(pendingResult instanceof PendingIntentRecord)) { 4822 return false; 4823 } 4824 try { 4825 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4826 if (res.key.allIntents == null) { 4827 return false; 4828 } 4829 for (int i=0; i<res.key.allIntents.length; i++) { 4830 Intent intent = res.key.allIntents[i]; 4831 if (intent.getPackage() != null && intent.getComponent() != null) { 4832 return false; 4833 } 4834 } 4835 return true; 4836 } catch (ClassCastException e) { 4837 } 4838 return false; 4839 } 4840 4841 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 4842 if (!(pendingResult instanceof PendingIntentRecord)) { 4843 return false; 4844 } 4845 try { 4846 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4847 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 4848 return true; 4849 } 4850 return false; 4851 } catch (ClassCastException e) { 4852 } 4853 return false; 4854 } 4855 4856 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 4857 if (!(pendingResult instanceof PendingIntentRecord)) { 4858 return null; 4859 } 4860 try { 4861 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4862 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 4863 } catch (ClassCastException e) { 4864 } 4865 return null; 4866 } 4867 4868 public void setProcessLimit(int max) { 4869 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4870 "setProcessLimit()"); 4871 synchronized (this) { 4872 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max; 4873 mProcessLimitOverride = max; 4874 } 4875 trimApplications(); 4876 } 4877 4878 public int getProcessLimit() { 4879 synchronized (this) { 4880 return mProcessLimitOverride; 4881 } 4882 } 4883 4884 void foregroundTokenDied(ForegroundToken token) { 4885 synchronized (ActivityManagerService.this) { 4886 synchronized (mPidsSelfLocked) { 4887 ForegroundToken cur 4888 = mForegroundProcesses.get(token.pid); 4889 if (cur != token) { 4890 return; 4891 } 4892 mForegroundProcesses.remove(token.pid); 4893 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 4894 if (pr == null) { 4895 return; 4896 } 4897 pr.forcingToForeground = null; 4898 pr.foregroundServices = false; 4899 } 4900 updateOomAdjLocked(); 4901 } 4902 } 4903 4904 public void setProcessForeground(IBinder token, int pid, boolean isForeground) { 4905 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4906 "setProcessForeground()"); 4907 synchronized(this) { 4908 boolean changed = false; 4909 4910 synchronized (mPidsSelfLocked) { 4911 ProcessRecord pr = mPidsSelfLocked.get(pid); 4912 if (pr == null && isForeground) { 4913 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 4914 return; 4915 } 4916 ForegroundToken oldToken = mForegroundProcesses.get(pid); 4917 if (oldToken != null) { 4918 oldToken.token.unlinkToDeath(oldToken, 0); 4919 mForegroundProcesses.remove(pid); 4920 if (pr != null) { 4921 pr.forcingToForeground = null; 4922 } 4923 changed = true; 4924 } 4925 if (isForeground && token != null) { 4926 ForegroundToken newToken = new ForegroundToken() { 4927 public void binderDied() { 4928 foregroundTokenDied(this); 4929 } 4930 }; 4931 newToken.pid = pid; 4932 newToken.token = token; 4933 try { 4934 token.linkToDeath(newToken, 0); 4935 mForegroundProcesses.put(pid, newToken); 4936 pr.forcingToForeground = token; 4937 changed = true; 4938 } catch (RemoteException e) { 4939 // If the process died while doing this, we will later 4940 // do the cleanup with the process death link. 4941 } 4942 } 4943 } 4944 4945 if (changed) { 4946 updateOomAdjLocked(); 4947 } 4948 } 4949 } 4950 4951 // ========================================================= 4952 // PERMISSIONS 4953 // ========================================================= 4954 4955 static class PermissionController extends IPermissionController.Stub { 4956 ActivityManagerService mActivityManagerService; 4957 PermissionController(ActivityManagerService activityManagerService) { 4958 mActivityManagerService = activityManagerService; 4959 } 4960 4961 public boolean checkPermission(String permission, int pid, int uid) { 4962 return mActivityManagerService.checkPermission(permission, pid, 4963 uid) == PackageManager.PERMISSION_GRANTED; 4964 } 4965 } 4966 4967 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 4968 public int checkComponentPermission(String permission, int pid, int uid, 4969 int owningUid, boolean exported) { 4970 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 4971 owningUid, exported); 4972 } 4973 4974 public Object getAMSLock() { 4975 return ActivityManagerService.this; 4976 } 4977 } 4978 4979 /** 4980 * This can be called with or without the global lock held. 4981 */ 4982 int checkComponentPermission(String permission, int pid, int uid, 4983 int owningUid, boolean exported) { 4984 // We might be performing an operation on behalf of an indirect binder 4985 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 4986 // client identity accordingly before proceeding. 4987 Identity tlsIdentity = sCallerIdentity.get(); 4988 if (tlsIdentity != null) { 4989 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 4990 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 4991 uid = tlsIdentity.uid; 4992 pid = tlsIdentity.pid; 4993 } 4994 4995 if (pid == MY_PID) { 4996 return PackageManager.PERMISSION_GRANTED; 4997 } 4998 4999 return ActivityManager.checkComponentPermission(permission, uid, 5000 owningUid, exported); 5001 } 5002 5003 /** 5004 * As the only public entry point for permissions checking, this method 5005 * can enforce the semantic that requesting a check on a null global 5006 * permission is automatically denied. (Internally a null permission 5007 * string is used when calling {@link #checkComponentPermission} in cases 5008 * when only uid-based security is needed.) 5009 * 5010 * This can be called with or without the global lock held. 5011 */ 5012 public int checkPermission(String permission, int pid, int uid) { 5013 if (permission == null) { 5014 return PackageManager.PERMISSION_DENIED; 5015 } 5016 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true); 5017 } 5018 5019 /** 5020 * Binder IPC calls go through the public entry point. 5021 * This can be called with or without the global lock held. 5022 */ 5023 int checkCallingPermission(String permission) { 5024 return checkPermission(permission, 5025 Binder.getCallingPid(), 5026 UserHandle.getAppId(Binder.getCallingUid())); 5027 } 5028 5029 /** 5030 * This can be called with or without the global lock held. 5031 */ 5032 void enforceCallingPermission(String permission, String func) { 5033 if (checkCallingPermission(permission) 5034 == PackageManager.PERMISSION_GRANTED) { 5035 return; 5036 } 5037 5038 String msg = "Permission Denial: " + func + " from pid=" 5039 + Binder.getCallingPid() 5040 + ", uid=" + Binder.getCallingUid() 5041 + " requires " + permission; 5042 Slog.w(TAG, msg); 5043 throw new SecurityException(msg); 5044 } 5045 5046 /** 5047 * Determine if UID is holding permissions required to access {@link Uri} in 5048 * the given {@link ProviderInfo}. Final permission checking is always done 5049 * in {@link ContentProvider}. 5050 */ 5051 private final boolean checkHoldingPermissionsLocked( 5052 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) { 5053 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5054 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid); 5055 5056 if (pi.applicationInfo.uid == uid) { 5057 return true; 5058 } else if (!pi.exported) { 5059 return false; 5060 } 5061 5062 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 5063 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 5064 try { 5065 // check if target holds top-level <provider> permissions 5066 if (!readMet && pi.readPermission != null 5067 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 5068 readMet = true; 5069 } 5070 if (!writeMet && pi.writePermission != null 5071 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 5072 writeMet = true; 5073 } 5074 5075 // track if unprotected read/write is allowed; any denied 5076 // <path-permission> below removes this ability 5077 boolean allowDefaultRead = pi.readPermission == null; 5078 boolean allowDefaultWrite = pi.writePermission == null; 5079 5080 // check if target holds any <path-permission> that match uri 5081 final PathPermission[] pps = pi.pathPermissions; 5082 if (pps != null) { 5083 final String path = uri.getPath(); 5084 int i = pps.length; 5085 while (i > 0 && (!readMet || !writeMet)) { 5086 i--; 5087 PathPermission pp = pps[i]; 5088 if (pp.match(path)) { 5089 if (!readMet) { 5090 final String pprperm = pp.getReadPermission(); 5091 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for " 5092 + pprperm + " for " + pp.getPath() 5093 + ": match=" + pp.match(path) 5094 + " check=" + pm.checkUidPermission(pprperm, uid)); 5095 if (pprperm != null) { 5096 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) { 5097 readMet = true; 5098 } else { 5099 allowDefaultRead = false; 5100 } 5101 } 5102 } 5103 if (!writeMet) { 5104 final String ppwperm = pp.getWritePermission(); 5105 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm " 5106 + ppwperm + " for " + pp.getPath() 5107 + ": match=" + pp.match(path) 5108 + " check=" + pm.checkUidPermission(ppwperm, uid)); 5109 if (ppwperm != null) { 5110 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) { 5111 writeMet = true; 5112 } else { 5113 allowDefaultWrite = false; 5114 } 5115 } 5116 } 5117 } 5118 } 5119 } 5120 5121 // grant unprotected <provider> read/write, if not blocked by 5122 // <path-permission> above 5123 if (allowDefaultRead) readMet = true; 5124 if (allowDefaultWrite) writeMet = true; 5125 5126 } catch (RemoteException e) { 5127 return false; 5128 } 5129 5130 return readMet && writeMet; 5131 } 5132 5133 private final boolean checkUriPermissionLocked(Uri uri, int uid, 5134 int modeFlags) { 5135 // Root gets to do everything. 5136 if (uid == 0) { 5137 return true; 5138 } 5139 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid); 5140 if (perms == null) return false; 5141 UriPermission perm = perms.get(uri); 5142 if (perm == null) return false; 5143 return (modeFlags&perm.modeFlags) == modeFlags; 5144 } 5145 5146 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 5147 enforceNotIsolatedCaller("checkUriPermission"); 5148 5149 // Another redirected-binder-call permissions check as in 5150 // {@link checkComponentPermission}. 5151 Identity tlsIdentity = sCallerIdentity.get(); 5152 if (tlsIdentity != null) { 5153 uid = tlsIdentity.uid; 5154 pid = tlsIdentity.pid; 5155 } 5156 5157 // Our own process gets to do everything. 5158 if (pid == MY_PID) { 5159 return PackageManager.PERMISSION_GRANTED; 5160 } 5161 synchronized(this) { 5162 return checkUriPermissionLocked(uri, uid, modeFlags) 5163 ? PackageManager.PERMISSION_GRANTED 5164 : PackageManager.PERMISSION_DENIED; 5165 } 5166 } 5167 5168 /** 5169 * Check if the targetPkg can be granted permission to access uri by 5170 * the callingUid using the given modeFlags. Throws a security exception 5171 * if callingUid is not allowed to do this. Returns the uid of the target 5172 * if the URI permission grant should be performed; returns -1 if it is not 5173 * needed (for example targetPkg already has permission to access the URI). 5174 * If you already know the uid of the target, you can supply it in 5175 * lastTargetUid else set that to -1. 5176 */ 5177 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, 5178 Uri uri, int modeFlags, int lastTargetUid) { 5179 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION 5180 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 5181 if (modeFlags == 0) { 5182 return -1; 5183 } 5184 5185 if (targetPkg != null) { 5186 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5187 "Checking grant " + targetPkg + " permission to " + uri); 5188 } 5189 5190 final IPackageManager pm = AppGlobals.getPackageManager(); 5191 5192 // If this is not a content: uri, we can't do anything with it. 5193 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { 5194 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5195 "Can't grant URI permission for non-content URI: " + uri); 5196 return -1; 5197 } 5198 5199 String name = uri.getAuthority(); 5200 ProviderInfo pi = null; 5201 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, 5202 UserHandle.getUserId(callingUid)); 5203 if (cpr != null) { 5204 pi = cpr.info; 5205 } else { 5206 try { 5207 pi = pm.resolveContentProvider(name, 5208 PackageManager.GET_URI_PERMISSION_PATTERNS, 5209 UserHandle.getUserId(callingUid)); 5210 } catch (RemoteException ex) { 5211 } 5212 } 5213 if (pi == null) { 5214 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString()); 5215 return -1; 5216 } 5217 5218 int targetUid = lastTargetUid; 5219 if (targetUid < 0 && targetPkg != null) { 5220 try { 5221 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid)); 5222 if (targetUid < 0) { 5223 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5224 "Can't grant URI permission no uid for: " + targetPkg); 5225 return -1; 5226 } 5227 } catch (RemoteException ex) { 5228 return -1; 5229 } 5230 } 5231 5232 if (targetUid >= 0) { 5233 // First... does the target actually need this permission?