ActivityManagerService.java revision a0e0c0dfadf54ea7ba0eb1cfc5225c9887d3150a
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 17package com.android.server.am; 18 19import static android.Manifest.permission.INTERACT_ACROSS_USERS; 20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 21import static android.Manifest.permission.START_TASKS_FROM_RECENTS; 22import static android.content.pm.PackageManager.PERMISSION_GRANTED; 23import static com.android.internal.util.XmlUtils.readBooleanAttribute; 24import static com.android.internal.util.XmlUtils.readIntAttribute; 25import static com.android.internal.util.XmlUtils.readLongAttribute; 26import static com.android.internal.util.XmlUtils.writeBooleanAttribute; 27import static com.android.internal.util.XmlUtils.writeIntAttribute; 28import static com.android.internal.util.XmlUtils.writeLongAttribute; 29import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST; 30import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 31import static org.xmlpull.v1.XmlPullParser.START_TAG; 32import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID; 33 34import android.Manifest; 35import android.app.AppOpsManager; 36import android.app.ApplicationThreadNative; 37import android.app.IActivityContainer; 38import android.app.IActivityContainerCallback; 39import android.app.IAppTask; 40import android.app.ProfilerInfo; 41import android.app.admin.DevicePolicyManager; 42import android.app.usage.UsageEvents; 43import android.app.usage.UsageStatsManagerInternal; 44import android.appwidget.AppWidgetManager; 45import android.content.res.Resources; 46import android.graphics.Bitmap; 47import android.graphics.Point; 48import android.graphics.Rect; 49import android.os.BatteryStats; 50import android.os.PersistableBundle; 51import android.service.voice.IVoiceInteractionSession; 52import android.util.ArrayMap; 53import android.util.ArraySet; 54import android.util.SparseIntArray; 55 56import com.android.internal.R; 57import com.android.internal.annotations.GuardedBy; 58import com.android.internal.app.IAppOpsService; 59import com.android.internal.app.IVoiceInteractor; 60import com.android.internal.app.ProcessMap; 61import com.android.internal.app.ProcessStats; 62import com.android.internal.content.PackageMonitor; 63import com.android.internal.os.BackgroundThread; 64import com.android.internal.os.BatteryStatsImpl; 65import com.android.internal.os.ProcessCpuTracker; 66import com.android.internal.os.TransferPipe; 67import com.android.internal.os.Zygote; 68import com.android.internal.util.FastPrintWriter; 69import com.android.internal.util.FastXmlSerializer; 70import com.android.internal.util.MemInfoReader; 71import com.android.internal.util.Preconditions; 72import com.android.server.AppOpsService; 73import com.android.server.AttributeCache; 74import com.android.server.IntentResolver; 75import com.android.server.LocalServices; 76import com.android.server.ServiceThread; 77import com.android.server.SystemService; 78import com.android.server.SystemServiceManager; 79import com.android.server.Watchdog; 80import com.android.server.am.ActivityStack.ActivityState; 81import com.android.server.firewall.IntentFirewall; 82import com.android.server.pm.UserManagerService; 83import com.android.server.wm.AppTransition; 84import com.android.server.wm.WindowManagerService; 85import com.google.android.collect.Lists; 86import com.google.android.collect.Maps; 87 88import libcore.io.IoUtils; 89 90import org.xmlpull.v1.XmlPullParser; 91import org.xmlpull.v1.XmlPullParserException; 92import org.xmlpull.v1.XmlSerializer; 93 94import android.app.Activity; 95import android.app.ActivityManager; 96import android.app.ActivityManager.RunningTaskInfo; 97import android.app.ActivityManager.StackInfo; 98import android.app.ActivityManagerInternal; 99import android.app.ActivityManagerNative; 100import android.app.ActivityOptions; 101import android.app.ActivityThread; 102import android.app.AlertDialog; 103import android.app.AppGlobals; 104import android.app.ApplicationErrorReport; 105import android.app.Dialog; 106import android.app.IActivityController; 107import android.app.IApplicationThread; 108import android.app.IInstrumentationWatcher; 109import android.app.INotificationManager; 110import android.app.IProcessObserver; 111import android.app.IServiceConnection; 112import android.app.IStopUserCallback; 113import android.app.IUiAutomationConnection; 114import android.app.IUserSwitchObserver; 115import android.app.Instrumentation; 116import android.app.Notification; 117import android.app.NotificationManager; 118import android.app.PendingIntent; 119import android.app.backup.IBackupManager; 120import android.content.ActivityNotFoundException; 121import android.content.BroadcastReceiver; 122import android.content.ClipData; 123import android.content.ComponentCallbacks2; 124import android.content.ComponentName; 125import android.content.ContentProvider; 126import android.content.ContentResolver; 127import android.content.Context; 128import android.content.DialogInterface; 129import android.content.IContentProvider; 130import android.content.IIntentReceiver; 131import android.content.IIntentSender; 132import android.content.Intent; 133import android.content.IntentFilter; 134import android.content.IntentSender; 135import android.content.pm.ActivityInfo; 136import android.content.pm.ApplicationInfo; 137import android.content.pm.ConfigurationInfo; 138import android.content.pm.IPackageDataObserver; 139import android.content.pm.IPackageManager; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageManager; 143import android.content.pm.ParceledListSlice; 144import android.content.pm.UserInfo; 145import android.content.pm.PackageManager.NameNotFoundException; 146import android.content.pm.PathPermission; 147import android.content.pm.ProviderInfo; 148import android.content.pm.ResolveInfo; 149import android.content.pm.ServiceInfo; 150import android.content.res.CompatibilityInfo; 151import android.content.res.Configuration; 152import android.net.Proxy; 153import android.net.ProxyInfo; 154import android.net.Uri; 155import android.os.Binder; 156import android.os.Build; 157import android.os.Bundle; 158import android.os.Debug; 159import android.os.DropBoxManager; 160import android.os.Environment; 161import android.os.FactoryTest; 162import android.os.FileObserver; 163import android.os.FileUtils; 164import android.os.Handler; 165import android.os.IBinder; 166import android.os.IPermissionController; 167import android.os.IRemoteCallback; 168import android.os.IUserManager; 169import android.os.Looper; 170import android.os.Message; 171import android.os.Parcel; 172import android.os.ParcelFileDescriptor; 173import android.os.Process; 174import android.os.RemoteCallbackList; 175import android.os.RemoteException; 176import android.os.SELinux; 177import android.os.ServiceManager; 178import android.os.StrictMode; 179import android.os.SystemClock; 180import android.os.SystemProperties; 181import android.os.UpdateLock; 182import android.os.UserHandle; 183import android.os.UserManager; 184import android.provider.Settings; 185import android.text.format.DateUtils; 186import android.text.format.Time; 187import android.util.AtomicFile; 188import android.util.EventLog; 189import android.util.Log; 190import android.util.Pair; 191import android.util.PrintWriterPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.TimeUtils; 195import android.util.Xml; 196import android.view.Gravity; 197import android.view.LayoutInflater; 198import android.view.View; 199import android.view.WindowManager; 200import dalvik.system.VMRuntime; 201 202import java.io.BufferedInputStream; 203import java.io.BufferedOutputStream; 204import java.io.DataInputStream; 205import java.io.DataOutputStream; 206import java.io.File; 207import java.io.FileDescriptor; 208import java.io.FileInputStream; 209import java.io.FileNotFoundException; 210import java.io.FileOutputStream; 211import java.io.IOException; 212import java.io.InputStreamReader; 213import java.io.PrintWriter; 214import java.io.StringWriter; 215import java.lang.ref.WeakReference; 216import java.util.ArrayList; 217import java.util.Arrays; 218import java.util.Collections; 219import java.util.Comparator; 220import java.util.HashMap; 221import java.util.HashSet; 222import java.util.Iterator; 223import java.util.List; 224import java.util.Locale; 225import java.util.Map; 226import java.util.Set; 227import java.util.concurrent.atomic.AtomicBoolean; 228import java.util.concurrent.atomic.AtomicLong; 229 230public final class ActivityManagerService extends ActivityManagerNative 231 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 232 233 private static final String USER_DATA_DIR = "/data/user/"; 234 // File that stores last updated system version and called preboot receivers 235 static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat"; 236 237 static final String TAG = "ActivityManager"; 238 static final String TAG_MU = "ActivityManagerServiceMU"; 239 static final boolean DEBUG = false; 240 static final boolean localLOGV = DEBUG; 241 static final boolean DEBUG_BACKUP = localLOGV || false; 242 static final boolean DEBUG_BROADCAST = localLOGV || false; 243 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false; 244 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false; 245 static final boolean DEBUG_CLEANUP = localLOGV || false; 246 static final boolean DEBUG_CONFIGURATION = localLOGV || false; 247 static final boolean DEBUG_FOCUS = false; 248 static final boolean DEBUG_IMMERSIVE = localLOGV || false; 249 static final boolean DEBUG_MU = localLOGV || false; 250 static final boolean DEBUG_OOM_ADJ = localLOGV || false; 251 static final boolean DEBUG_LRU = localLOGV || false; 252 static final boolean DEBUG_PAUSE = localLOGV || false; 253 static final boolean DEBUG_POWER = localLOGV || false; 254 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false; 255 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false; 256 static final boolean DEBUG_PROCESSES = localLOGV || false; 257 static final boolean DEBUG_PROVIDER = localLOGV || false; 258 static final boolean DEBUG_RESULTS = localLOGV || false; 259 static final boolean DEBUG_SERVICE = localLOGV || false; 260 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false; 261 static final boolean DEBUG_STACK = localLOGV || false; 262 static final boolean DEBUG_SWITCH = localLOGV || false; 263 static final boolean DEBUG_TASKS = localLOGV || false; 264 static final boolean DEBUG_THUMBNAILS = localLOGV || false; 265 static final boolean DEBUG_TRANSITION = localLOGV || false; 266 static final boolean DEBUG_URI_PERMISSION = localLOGV || false; 267 static final boolean DEBUG_USER_LEAVING = localLOGV || false; 268 static final boolean DEBUG_VISBILITY = localLOGV || false; 269 static final boolean DEBUG_PSS = localLOGV || false; 270 static final boolean DEBUG_LOCKSCREEN = localLOGV || false; 271 static final boolean DEBUG_RECENTS = localLOGV || false; 272 static final boolean VALIDATE_TOKENS = false; 273 static final boolean SHOW_ACTIVITY_START_TIME = true; 274 275 // Control over CPU and battery monitoring. 276 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes. 277 static final boolean MONITOR_CPU_USAGE = true; 278 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds. 279 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample. 280 static final boolean MONITOR_THREAD_CPU_USAGE = false; 281 282 // The flags that are set for all calls we make to the package manager. 283 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 284 285 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 286 287 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 288 289 // Maximum number recent bitmaps to keep in memory. 290 static final int MAX_RECENT_BITMAPS = 5; 291 292 // Amount of time after a call to stopAppSwitches() during which we will 293 // prevent further untrusted switches from happening. 294 static final long APP_SWITCH_DELAY_TIME = 5*1000; 295 296 // How long we wait for a launched process to attach to the activity manager 297 // before we decide it's never going to come up for real. 298 static final int PROC_START_TIMEOUT = 10*1000; 299 300 // How long we wait for a launched process to attach to the activity manager 301 // before we decide it's never going to come up for real, when the process was 302 // started with a wrapper for instrumentation (such as Valgrind) because it 303 // could take much longer than usual. 304 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 305 306 // How long to wait after going idle before forcing apps to GC. 307 static final int GC_TIMEOUT = 5*1000; 308 309 // The minimum amount of time between successive GC requests for a process. 310 static final int GC_MIN_INTERVAL = 60*1000; 311 312 // The minimum amount of time between successive PSS requests for a process. 313 static final int FULL_PSS_MIN_INTERVAL = 10*60*1000; 314 315 // The minimum amount of time between successive PSS requests for a process 316 // when the request is due to the memory state being lowered. 317 static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000; 318 319 // The rate at which we check for apps using excessive power -- 15 mins. 320 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 321 322 // The minimum sample duration we will allow before deciding we have 323 // enough data on wake locks to start killing things. 324 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 325 326 // The minimum sample duration we will allow before deciding we have 327 // enough data on CPU usage to start killing things. 328 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 329 330 // How long we allow a receiver to run before giving up on it. 331 static final int BROADCAST_FG_TIMEOUT = 10*1000; 332 static final int BROADCAST_BG_TIMEOUT = 60*1000; 333 334 // How long we wait until we timeout on key dispatching. 335 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 336 337 // How long we wait until we timeout on key dispatching during instrumentation. 338 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 339 340 // Amount of time we wait for observers to handle a user switch before 341 // giving up on them and unfreezing the screen. 342 static final int USER_SWITCH_TIMEOUT = 2*1000; 343 344 // Maximum number of users we allow to be running at a time. 345 static final int MAX_RUNNING_USERS = 3; 346 347 // How long to wait in getAssistContextExtras for the activity and foreground services 348 // to respond with the result. 349 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500; 350 351 // Maximum number of persisted Uri grants a package is allowed 352 static final int MAX_PERSISTED_URI_GRANTS = 128; 353 354 static final int MY_PID = Process.myPid(); 355 356 static final String[] EMPTY_STRING_ARRAY = new String[0]; 357 358 // How many bytes to write into the dropbox log before truncating 359 static final int DROPBOX_MAX_SIZE = 256 * 1024; 360 361 // Access modes for handleIncomingUser. 362 static final int ALLOW_NON_FULL = 0; 363 static final int ALLOW_NON_FULL_IN_PROFILE = 1; 364 static final int ALLOW_FULL_ONLY = 2; 365 366 static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000; 367 368 /** All system services */ 369 SystemServiceManager mSystemServiceManager; 370 371 /** Run all ActivityStacks through this */ 372 ActivityStackSupervisor mStackSupervisor; 373 374 public IntentFirewall mIntentFirewall; 375 376 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 377 // default actuion automatically. Important for devices without direct input 378 // devices. 379 private boolean mShowDialogs = true; 380 381 BroadcastQueue mFgBroadcastQueue; 382 BroadcastQueue mBgBroadcastQueue; 383 // Convenient for easy iteration over the queues. Foreground is first 384 // so that dispatch of foreground broadcasts gets precedence. 385 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 386 387 BroadcastQueue broadcastQueueForIntent(Intent intent) { 388 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 389 if (DEBUG_BACKGROUND_BROADCAST) { 390 Slog.i(TAG, "Broadcast intent " + intent + " on " 391 + (isFg ? "foreground" : "background") 392 + " queue"); 393 } 394 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 395 } 396 397 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) { 398 for (BroadcastQueue queue : mBroadcastQueues) { 399 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver); 400 if (r != null) { 401 return r; 402 } 403 } 404 return null; 405 } 406 407 /** 408 * Activity we have told the window manager to have key focus. 409 */ 410 ActivityRecord mFocusedActivity = null; 411 412 /** 413 * List of intents that were used to start the most recent tasks. 414 */ 415 ArrayList<TaskRecord> mRecentTasks; 416 ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>(); 417 418 /** 419 * For addAppTask: cached of the last activity component that was added. 420 */ 421 ComponentName mLastAddedTaskComponent; 422 423 /** 424 * For addAppTask: cached of the last activity uid that was added. 425 */ 426 int mLastAddedTaskUid; 427 428 /** 429 * For addAppTask: cached of the last ActivityInfo that was added. 430 */ 431 ActivityInfo mLastAddedTaskActivity; 432 433 public class PendingAssistExtras extends Binder implements Runnable { 434 public final ActivityRecord activity; 435 public boolean haveResult = false; 436 public Bundle result = null; 437 public PendingAssistExtras(ActivityRecord _activity) { 438 activity = _activity; 439 } 440 @Override 441 public void run() { 442 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity); 443 synchronized (this) { 444 haveResult = true; 445 notifyAll(); 446 } 447 } 448 } 449 450 final ArrayList<PendingAssistExtras> mPendingAssistExtras 451 = new ArrayList<PendingAssistExtras>(); 452 453 /** 454 * Process management. 455 */ 456 final ProcessList mProcessList = new ProcessList(); 457 458 /** 459 * All of the applications we currently have running organized by name. 460 * The keys are strings of the application package name (as 461 * returned by the package manager), and the keys are ApplicationRecord 462 * objects. 463 */ 464 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 465 466 /** 467 * Tracking long-term execution of processes to look for abuse and other 468 * bad app behavior. 469 */ 470 final ProcessStatsService mProcessStats; 471 472 /** 473 * The currently running isolated processes. 474 */ 475 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 476 477 /** 478 * Counter for assigning isolated process uids, to avoid frequently reusing the 479 * same ones. 480 */ 481 int mNextIsolatedProcessUid = 0; 482 483 /** 484 * The currently running heavy-weight process, if any. 485 */ 486 ProcessRecord mHeavyWeightProcess = null; 487 488 /** 489 * The last time that various processes have crashed. 490 */ 491 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 492 493 /** 494 * Information about a process that is currently marked as bad. 495 */ 496 static final class BadProcessInfo { 497 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) { 498 this.time = time; 499 this.shortMsg = shortMsg; 500 this.longMsg = longMsg; 501 this.stack = stack; 502 } 503 504 final long time; 505 final String shortMsg; 506 final String longMsg; 507 final String stack; 508 } 509 510 /** 511 * Set of applications that we consider to be bad, and will reject 512 * incoming broadcasts from (which the user has no control over). 513 * Processes are added to this set when they have crashed twice within 514 * a minimum amount of time; they are removed from it when they are 515 * later restarted (hopefully due to some user action). The value is the 516 * time it was added to the list. 517 */ 518 final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>(); 519 520 /** 521 * All of the processes we currently have running organized by pid. 522 * The keys are the pid running the application. 523 * 524 * <p>NOTE: This object is protected by its own lock, NOT the global 525 * activity manager lock! 526 */ 527 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 528 529 /** 530 * All of the processes that have been forced to be foreground. The key 531 * is the pid of the caller who requested it (we hold a death 532 * link on it). 533 */ 534 abstract class ForegroundToken implements IBinder.DeathRecipient { 535 int pid; 536 IBinder token; 537 } 538 final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>(); 539 540 /** 541 * List of records for processes that someone had tried to start before the 542 * system was ready. We don't start them at that point, but ensure they 543 * are started by the time booting is complete. 544 */ 545 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 546 547 /** 548 * List of persistent applications that are in the process 549 * of being started. 550 */ 551 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 552 553 /** 554 * Processes that are being forcibly torn down. 555 */ 556 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 557 558 /** 559 * List of running applications, sorted by recent usage. 560 * The first entry in the list is the least recently used. 561 */ 562 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 563 564 /** 565 * Where in mLruProcesses that the processes hosting activities start. 566 */ 567 int mLruProcessActivityStart = 0; 568 569 /** 570 * Where in mLruProcesses that the processes hosting services start. 571 * This is after (lower index) than mLruProcessesActivityStart. 572 */ 573 int mLruProcessServiceStart = 0; 574 575 /** 576 * List of processes that should gc as soon as things are idle. 577 */ 578 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 579 580 /** 581 * Processes we want to collect PSS data from. 582 */ 583 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 584 585 /** 586 * Last time we requested PSS data of all processes. 587 */ 588 long mLastFullPssTime = SystemClock.uptimeMillis(); 589 590 /** 591 * If set, the next time we collect PSS data we should do a full collection 592 * with data from native processes and the kernel. 593 */ 594 boolean mFullPssPending = false; 595 596 /** 597 * This is the process holding what we currently consider to be 598 * the "home" activity. 599 */ 600 ProcessRecord mHomeProcess; 601 602 /** 603 * This is the process holding the activity the user last visited that 604 * is in a different process from the one they are currently in. 605 */ 606 ProcessRecord mPreviousProcess; 607 608 /** 609 * The time at which the previous process was last visible. 610 */ 611 long mPreviousProcessVisibleTime; 612 613 /** 614 * Which uses have been started, so are allowed to run code. 615 */ 616 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>(); 617 618 /** 619 * LRU list of history of current users. Most recently current is at the end. 620 */ 621 final ArrayList<Integer> mUserLru = new ArrayList<Integer>(); 622 623 /** 624 * Constant array of the users that are currently started. 625 */ 626 int[] mStartedUserArray = new int[] { 0 }; 627 628 /** 629 * Registered observers of the user switching mechanics. 630 */ 631 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 632 = new RemoteCallbackList<IUserSwitchObserver>(); 633 634 /** 635 * Currently active user switch. 636 */ 637 Object mCurUserSwitchCallback; 638 639 /** 640 * Packages that the user has asked to have run in screen size 641 * compatibility mode instead of filling the screen. 642 */ 643 final CompatModePackages mCompatModePackages; 644 645 /** 646 * Set of IntentSenderRecord objects that are currently active. 647 */ 648 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 649 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 650 651 /** 652 * Fingerprints (hashCode()) of stack traces that we've 653 * already logged DropBox entries for. Guarded by itself. If 654 * something (rogue user app) forces this over 655 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 656 */ 657 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 658 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 659 660 /** 661 * Strict Mode background batched logging state. 662 * 663 * The string buffer is guarded by itself, and its lock is also 664 * used to determine if another batched write is already 665 * in-flight. 666 */ 667 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 668 669 /** 670 * Keeps track of all IIntentReceivers that have been registered for 671 * broadcasts. Hash keys are the receiver IBinder, hash value is 672 * a ReceiverList. 673 */ 674 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = 675 new HashMap<IBinder, ReceiverList>(); 676 677 /** 678 * Resolver for broadcast intents to registered receivers. 679 * Holds BroadcastFilter (subclass of IntentFilter). 680 */ 681 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 682 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 683 @Override 684 protected boolean allowFilterResult( 685 BroadcastFilter filter, List<BroadcastFilter> dest) { 686 IBinder target = filter.receiverList.receiver.asBinder(); 687 for (int i=dest.size()-1; i>=0; i--) { 688 if (dest.get(i).receiverList.receiver.asBinder() == target) { 689 return false; 690 } 691 } 692 return true; 693 } 694 695 @Override 696 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 697 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 698 || userId == filter.owningUserId) { 699 return super.newResult(filter, match, userId); 700 } 701 return null; 702 } 703 704 @Override 705 protected BroadcastFilter[] newArray(int size) { 706 return new BroadcastFilter[size]; 707 } 708 709 @Override 710 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 711 return packageName.equals(filter.packageName); 712 } 713 }; 714 715 /** 716 * State of all active sticky broadcasts per user. Keys are the action of the 717 * sticky Intent, values are an ArrayList of all broadcasted intents with 718 * that action (which should usually be one). The SparseArray is keyed 719 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 720 * for stickies that are sent to all users. 721 */ 722 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 723 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 724 725 final ActiveServices mServices; 726 727 /** 728 * Backup/restore process management 729 */ 730 String mBackupAppName = null; 731 BackupRecord mBackupTarget = null; 732 733 final ProviderMap mProviderMap; 734 735 /** 736 * List of content providers who have clients waiting for them. The 737 * application is currently being launched and the provider will be 738 * removed from this list once it is published. 739 */ 740 final ArrayList<ContentProviderRecord> mLaunchingProviders 741 = new ArrayList<ContentProviderRecord>(); 742 743 /** 744 * File storing persisted {@link #mGrantedUriPermissions}. 745 */ 746 private final AtomicFile mGrantFile; 747 748 /** XML constants used in {@link #mGrantFile} */ 749 private static final String TAG_URI_GRANTS = "uri-grants"; 750 private static final String TAG_URI_GRANT = "uri-grant"; 751 private static final String ATTR_USER_HANDLE = "userHandle"; 752 private static final String ATTR_SOURCE_USER_ID = "sourceUserId"; 753 private static final String ATTR_TARGET_USER_ID = "targetUserId"; 754 private static final String ATTR_SOURCE_PKG = "sourcePkg"; 755 private static final String ATTR_TARGET_PKG = "targetPkg"; 756 private static final String ATTR_URI = "uri"; 757 private static final String ATTR_MODE_FLAGS = "modeFlags"; 758 private static final String ATTR_CREATED_TIME = "createdTime"; 759 private static final String ATTR_PREFIX = "prefix"; 760 761 /** 762 * Global set of specific {@link Uri} permissions that have been granted. 763 * This optimized lookup structure maps from {@link UriPermission#targetUid} 764 * to {@link UriPermission#uri} to {@link UriPermission}. 765 */ 766 @GuardedBy("this") 767 private final SparseArray<ArrayMap<GrantUri, UriPermission>> 768 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>(); 769 770 public static class GrantUri { 771 public final int sourceUserId; 772 public final Uri uri; 773 public boolean prefix; 774 775 public GrantUri(int sourceUserId, Uri uri, boolean prefix) { 776 this.sourceUserId = sourceUserId; 777 this.uri = uri; 778 this.prefix = prefix; 779 } 780 781 @Override 782 public int hashCode() { 783 return toString().hashCode(); 784 } 785 786 @Override 787 public boolean equals(Object o) { 788 if (o instanceof GrantUri) { 789 GrantUri other = (GrantUri) o; 790 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId) 791 && prefix == other.prefix; 792 } 793 return false; 794 } 795 796 @Override 797 public String toString() { 798 String result = Integer.toString(sourceUserId) + " @ " + uri.toString(); 799 if (prefix) result += " [prefix]"; 800 return result; 801 } 802 803 public String toSafeString() { 804 String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString(); 805 if (prefix) result += " [prefix]"; 806 return result; 807 } 808 809 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) { 810 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle), 811 ContentProvider.getUriWithoutUserId(uri), false); 812 } 813 } 814 815 CoreSettingsObserver mCoreSettingsObserver; 816 817 /** 818 * Thread-local storage used to carry caller permissions over through 819 * indirect content-provider access. 820 */ 821 private class Identity { 822 public int pid; 823 public int uid; 824 825 Identity(int _pid, int _uid) { 826 pid = _pid; 827 uid = _uid; 828 } 829 } 830 831 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 832 833 /** 834 * All information we have collected about the runtime performance of 835 * any user id that can impact battery performance. 836 */ 837 final BatteryStatsService mBatteryStatsService; 838 839 /** 840 * Information about component usage 841 */ 842 UsageStatsManagerInternal mUsageStatsService; 843 844 /** 845 * Information about and control over application operations 846 */ 847 final AppOpsService mAppOpsService; 848 849 /** 850 * Save recent tasks information across reboots. 851 */ 852 final TaskPersister mTaskPersister; 853 854 /** 855 * Current configuration information. HistoryRecord objects are given 856 * a reference to this object to indicate which configuration they are 857 * currently running in, so this object must be kept immutable. 858 */ 859 Configuration mConfiguration = new Configuration(); 860 861 /** 862 * Current sequencing integer of the configuration, for skipping old 863 * configurations. 864 */ 865 int mConfigurationSeq = 0; 866 867 /** 868 * Hardware-reported OpenGLES version. 869 */ 870 final int GL_ES_VERSION; 871 872 /** 873 * List of initialization arguments to pass to all processes when binding applications to them. 874 * For example, references to the commonly used services. 875 */ 876 HashMap<String, IBinder> mAppBindArgs; 877 878 /** 879 * Temporary to avoid allocations. Protected by main lock. 880 */ 881 final StringBuilder mStringBuilder = new StringBuilder(256); 882 883 /** 884 * Used to control how we initialize the service. 885 */ 886 ComponentName mTopComponent; 887 String mTopAction = Intent.ACTION_MAIN; 888 String mTopData; 889 boolean mProcessesReady = false; 890 boolean mSystemReady = false; 891 boolean mBooting = false; 892 boolean mCallFinishBooting = false; 893 boolean mBootAnimationComplete = false; 894 boolean mWaitingUpdate = false; 895 boolean mDidUpdate = false; 896 boolean mOnBattery = false; 897 boolean mLaunchWarningShown = false; 898 899 Context mContext; 900 901 int mFactoryTest; 902 903 boolean mCheckedForSetup; 904 905 /** 906 * The time at which we will allow normal application switches again, 907 * after a call to {@link #stopAppSwitches()}. 908 */ 909 long mAppSwitchesAllowedTime; 910 911 /** 912 * This is set to true after the first switch after mAppSwitchesAllowedTime 913 * is set; any switches after that will clear the time. 914 */ 915 boolean mDidAppSwitch; 916 917 /** 918 * Last time (in realtime) at which we checked for power usage. 919 */ 920 long mLastPowerCheckRealtime; 921 922 /** 923 * Last time (in uptime) at which we checked for power usage. 924 */ 925 long mLastPowerCheckUptime; 926 927 /** 928 * Set while we are wanting to sleep, to prevent any 929 * activities from being started/resumed. 930 */ 931 private boolean mSleeping = false; 932 933 /** 934 * Set while we are running a voice interaction. This overrides 935 * sleeping while it is active. 936 */ 937 private boolean mRunningVoice = false; 938 939 /** 940 * Set while the keyguard is waiting for an activity to draw. 941 * In this state, if we are sleeping, we allow Activities to launch 942 * so that they can draw before Keyguard dismisses itself. 943 */ 944 private boolean mKeyguardWaitingForDraw = false; 945 946 /** 947 * State of external calls telling us if the device is asleep. 948 */ 949 private boolean mWentToSleep = false; 950 951 /** 952 * State of external call telling us if the lock screen is shown. 953 */ 954 private boolean mLockScreenShown = false; 955 956 /** 957 * Set if we are shutting down the system, similar to sleeping. 958 */ 959 boolean mShuttingDown = false; 960 961 /** 962 * Current sequence id for oom_adj computation traversal. 963 */ 964 int mAdjSeq = 0; 965 966 /** 967 * Current sequence id for process LRU updating. 968 */ 969 int mLruSeq = 0; 970 971 /** 972 * Keep track of the non-cached/empty process we last found, to help 973 * determine how to distribute cached/empty processes next time. 974 */ 975 int mNumNonCachedProcs = 0; 976 977 /** 978 * Keep track of the number of cached hidden procs, to balance oom adj 979 * distribution between those and empty procs. 980 */ 981 int mNumCachedHiddenProcs = 0; 982 983 /** 984 * Keep track of the number of service processes we last found, to 985 * determine on the next iteration which should be B services. 986 */ 987 int mNumServiceProcs = 0; 988 int mNewNumAServiceProcs = 0; 989 int mNewNumServiceProcs = 0; 990 991 /** 992 * Allow the current computed overall memory level of the system to go down? 993 * This is set to false when we are killing processes for reasons other than 994 * memory management, so that the now smaller process list will not be taken as 995 * an indication that memory is tighter. 996 */ 997 boolean mAllowLowerMemLevel = false; 998 999 /** 1000 * The last computed memory level, for holding when we are in a state that 1001 * processes are going away for other reasons. 1002 */ 1003 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 1004 1005 /** 1006 * The last total number of process we have, to determine if changes actually look 1007 * like a shrinking number of process due to lower RAM. 1008 */ 1009 int mLastNumProcesses; 1010 1011 /** 1012 * The uptime of the last time we performed idle maintenance. 1013 */ 1014 long mLastIdleTime = SystemClock.uptimeMillis(); 1015 1016 /** 1017 * Total time spent with RAM that has been added in the past since the last idle time. 1018 */ 1019 long mLowRamTimeSinceLastIdle = 0; 1020 1021 /** 1022 * If RAM is currently low, when that horrible situation started. 1023 */ 1024 long mLowRamStartTime = 0; 1025 1026 /** 1027 * For reporting to battery stats the current top application. 1028 */ 1029 private String mCurResumedPackage = null; 1030 private int mCurResumedUid = -1; 1031 1032 /** 1033 * For reporting to battery stats the apps currently running foreground 1034 * service. The ProcessMap is package/uid tuples; each of these contain 1035 * an array of the currently foreground processes. 1036 */ 1037 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1038 = new ProcessMap<ArrayList<ProcessRecord>>(); 1039 1040 /** 1041 * This is set if we had to do a delayed dexopt of an app before launching 1042 * it, to increase the ANR timeouts in that case. 1043 */ 1044 boolean mDidDexOpt; 1045 1046 /** 1047 * Set if the systemServer made a call to enterSafeMode. 1048 */ 1049 boolean mSafeMode; 1050 1051 String mDebugApp = null; 1052 boolean mWaitForDebugger = false; 1053 boolean mDebugTransient = false; 1054 String mOrigDebugApp = null; 1055 boolean mOrigWaitForDebugger = false; 1056 boolean mAlwaysFinishActivities = false; 1057 IActivityController mController = null; 1058 String mProfileApp = null; 1059 ProcessRecord mProfileProc = null; 1060 String mProfileFile; 1061 ParcelFileDescriptor mProfileFd; 1062 int mSamplingInterval = 0; 1063 boolean mAutoStopProfiler = false; 1064 int mProfileType = 0; 1065 String mOpenGlTraceApp = null; 1066 1067 static class ProcessChangeItem { 1068 static final int CHANGE_ACTIVITIES = 1<<0; 1069 static final int CHANGE_PROCESS_STATE = 1<<1; 1070 int changes; 1071 int uid; 1072 int pid; 1073 int processState; 1074 boolean foregroundActivities; 1075 } 1076 1077 final RemoteCallbackList<IProcessObserver> mProcessObservers 1078 = new RemoteCallbackList<IProcessObserver>(); 1079 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 1080 1081 final ArrayList<ProcessChangeItem> mPendingProcessChanges 1082 = new ArrayList<ProcessChangeItem>(); 1083 final ArrayList<ProcessChangeItem> mAvailProcessChanges 1084 = new ArrayList<ProcessChangeItem>(); 1085 1086 /** 1087 * Runtime CPU use collection thread. This object's lock is used to 1088 * perform synchronization with the thread (notifying it to run). 1089 */ 1090 final Thread mProcessCpuThread; 1091 1092 /** 1093 * Used to collect per-process CPU use for ANRs, battery stats, etc. 1094 * Must acquire this object's lock when accessing it. 1095 * NOTE: this lock will be held while doing long operations (trawling 1096 * through all processes in /proc), so it should never be acquired by 1097 * any critical paths such as when holding the main activity manager lock. 1098 */ 1099 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 1100 MONITOR_THREAD_CPU_USAGE); 1101 final AtomicLong mLastCpuTime = new AtomicLong(0); 1102 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 1103 1104 long mLastWriteTime = 0; 1105 1106 /** 1107 * Used to retain an update lock when the foreground activity is in 1108 * immersive mode. 1109 */ 1110 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 1111 1112 /** 1113 * Set to true after the system has finished booting. 1114 */ 1115 boolean mBooted = false; 1116 1117 int mProcessLimit = ProcessList.MAX_CACHED_APPS; 1118 int mProcessLimitOverride = -1; 1119 1120 WindowManagerService mWindowManager; 1121 1122 final ActivityThread mSystemThread; 1123 1124 // Holds the current foreground user's id 1125 int mCurrentUserId = 0; 1126 // Holds the target user's id during a user switch 1127 int mTargetUserId = UserHandle.USER_NULL; 1128 // If there are multiple profiles for the current user, their ids are here 1129 // Currently only the primary user can have managed profiles 1130 int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack 1131 1132 /** 1133 * Mapping from each known user ID to the profile group ID it is associated with. 1134 */ 1135 SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray(); 1136 1137 private UserManagerService mUserManager; 1138 1139 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1140 final ProcessRecord mApp; 1141 final int mPid; 1142 final IApplicationThread mAppThread; 1143 1144 AppDeathRecipient(ProcessRecord app, int pid, 1145 IApplicationThread thread) { 1146 if (localLOGV) Slog.v( 1147 TAG, "New death recipient " + this 1148 + " for thread " + thread.asBinder()); 1149 mApp = app; 1150 mPid = pid; 1151 mAppThread = thread; 1152 } 1153 1154 @Override 1155 public void binderDied() { 1156 if (localLOGV) Slog.v( 1157 TAG, "Death received in " + this 1158 + " for thread " + mAppThread.asBinder()); 1159 synchronized(ActivityManagerService.this) { 1160 appDiedLocked(mApp, mPid, mAppThread); 1161 } 1162 } 1163 } 1164 1165 static final int SHOW_ERROR_MSG = 1; 1166 static final int SHOW_NOT_RESPONDING_MSG = 2; 1167 static final int SHOW_FACTORY_ERROR_MSG = 3; 1168 static final int UPDATE_CONFIGURATION_MSG = 4; 1169 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1170 static final int WAIT_FOR_DEBUGGER_MSG = 6; 1171 static final int SERVICE_TIMEOUT_MSG = 12; 1172 static final int UPDATE_TIME_ZONE = 13; 1173 static final int SHOW_UID_ERROR_MSG = 14; 1174 static final int IM_FEELING_LUCKY_MSG = 15; 1175 static final int PROC_START_TIMEOUT_MSG = 20; 1176 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 1177 static final int KILL_APPLICATION_MSG = 22; 1178 static final int FINALIZE_PENDING_INTENT_MSG = 23; 1179 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 1180 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 1181 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 1182 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 1183 static final int CLEAR_DNS_CACHE_MSG = 28; 1184 static final int UPDATE_HTTP_PROXY_MSG = 29; 1185 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 1186 static final int DISPATCH_PROCESSES_CHANGED = 31; 1187 static final int DISPATCH_PROCESS_DIED = 32; 1188 static final int REPORT_MEM_USAGE_MSG = 33; 1189 static final int REPORT_USER_SWITCH_MSG = 34; 1190 static final int CONTINUE_USER_SWITCH_MSG = 35; 1191 static final int USER_SWITCH_TIMEOUT_MSG = 36; 1192 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 1193 static final int PERSIST_URI_GRANTS_MSG = 38; 1194 static final int REQUEST_ALL_PSS_MSG = 39; 1195 static final int START_PROFILES_MSG = 40; 1196 static final int UPDATE_TIME = 41; 1197 static final int SYSTEM_USER_START_MSG = 42; 1198 static final int SYSTEM_USER_CURRENT_MSG = 43; 1199 static final int ENTER_ANIMATION_COMPLETE_MSG = 44; 1200 static final int ENABLE_SCREEN_AFTER_BOOT_MSG = 45; 1201 static final int START_USER_SWITCH_MSG = 46; 1202 1203 static final int FIRST_ACTIVITY_STACK_MSG = 100; 1204 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1205 static final int FIRST_COMPAT_MODE_MSG = 300; 1206 static final int FIRST_SUPERVISOR_STACK_MSG = 100; 1207 1208 AlertDialog mUidAlert; 1209 CompatModeDialog mCompatModeDialog; 1210 long mLastMemUsageReportTime = 0; 1211 1212 private LockToAppRequestDialog mLockToAppRequest; 1213 1214 /** 1215 * Flag whether the current user is a "monkey", i.e. whether 1216 * the UI is driven by a UI automation tool. 1217 */ 1218 private boolean mUserIsMonkey; 1219 1220 /** Flag whether the device has a Recents UI */ 1221 boolean mHasRecents; 1222 1223 /** The dimensions of the thumbnails in the Recents UI. */ 1224 int mThumbnailWidth; 1225 int mThumbnailHeight; 1226 1227 final ServiceThread mHandlerThread; 1228 final MainHandler mHandler; 1229 1230 final class MainHandler extends Handler { 1231 public MainHandler(Looper looper) { 1232 super(looper, null, true); 1233 } 1234 1235 @Override 1236 public void handleMessage(Message msg) { 1237 switch (msg.what) { 1238 case SHOW_ERROR_MSG: { 1239 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1240 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 1241 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 1242 synchronized (ActivityManagerService.this) { 1243 ProcessRecord proc = (ProcessRecord)data.get("app"); 1244 AppErrorResult res = (AppErrorResult) data.get("result"); 1245 if (proc != null && proc.crashDialog != null) { 1246 Slog.e(TAG, "App already has crash dialog: " + proc); 1247 if (res != null) { 1248 res.set(0); 1249 } 1250 return; 1251 } 1252 boolean isBackground = (UserHandle.getAppId(proc.uid) 1253 >= Process.FIRST_APPLICATION_UID 1254 && proc.pid != MY_PID); 1255 for (int userId : mCurrentProfileIds) { 1256 isBackground &= (proc.userId != userId); 1257 } 1258 if (isBackground && !showBackground) { 1259 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 1260 if (res != null) { 1261 res.set(0); 1262 } 1263 return; 1264 } 1265 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1266 Dialog d = new AppErrorDialog(mContext, 1267 ActivityManagerService.this, res, proc); 1268 d.show(); 1269 proc.crashDialog = d; 1270 } else { 1271 // The device is asleep, so just pretend that the user 1272 // saw a crash dialog and hit "force quit". 1273 if (res != null) { 1274 res.set(0); 1275 } 1276 } 1277 } 1278 1279 ensureBootCompleted(); 1280 } break; 1281 case SHOW_NOT_RESPONDING_MSG: { 1282 synchronized (ActivityManagerService.this) { 1283 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1284 ProcessRecord proc = (ProcessRecord)data.get("app"); 1285 if (proc != null && proc.anrDialog != null) { 1286 Slog.e(TAG, "App already has anr dialog: " + proc); 1287 return; 1288 } 1289 1290 Intent intent = new Intent("android.intent.action.ANR"); 1291 if (!mProcessesReady) { 1292 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1293 | Intent.FLAG_RECEIVER_FOREGROUND); 1294 } 1295 broadcastIntentLocked(null, null, intent, 1296 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1297 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 1298 1299 if (mShowDialogs) { 1300 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 1301 mContext, proc, (ActivityRecord)data.get("activity"), 1302 msg.arg1 != 0); 1303 d.show(); 1304 proc.anrDialog = d; 1305 } else { 1306 // Just kill the app if there is no dialog to be shown. 1307 killAppAtUsersRequest(proc, null); 1308 } 1309 } 1310 1311 ensureBootCompleted(); 1312 } break; 1313 case SHOW_STRICT_MODE_VIOLATION_MSG: { 1314 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1315 synchronized (ActivityManagerService.this) { 1316 ProcessRecord proc = (ProcessRecord) data.get("app"); 1317 if (proc == null) { 1318 Slog.e(TAG, "App not found when showing strict mode dialog."); 1319 break; 1320 } 1321 if (proc.crashDialog != null) { 1322 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1323 return; 1324 } 1325 AppErrorResult res = (AppErrorResult) data.get("result"); 1326 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1327 Dialog d = new StrictModeViolationDialog(mContext, 1328 ActivityManagerService.this, res, proc); 1329 d.show(); 1330 proc.crashDialog = d; 1331 } else { 1332 // The device is asleep, so just pretend that the user 1333 // saw a crash dialog and hit "force quit". 1334 res.set(0); 1335 } 1336 } 1337 ensureBootCompleted(); 1338 } break; 1339 case SHOW_FACTORY_ERROR_MSG: { 1340 Dialog d = new FactoryErrorDialog( 1341 mContext, msg.getData().getCharSequence("msg")); 1342 d.show(); 1343 ensureBootCompleted(); 1344 } break; 1345 case UPDATE_CONFIGURATION_MSG: { 1346 final ContentResolver resolver = mContext.getContentResolver(); 1347 Settings.System.putConfiguration(resolver, (Configuration)msg.obj); 1348 } break; 1349 case GC_BACKGROUND_PROCESSES_MSG: { 1350 synchronized (ActivityManagerService.this) { 1351 performAppGcsIfAppropriateLocked(); 1352 } 1353 } break; 1354 case WAIT_FOR_DEBUGGER_MSG: { 1355 synchronized (ActivityManagerService.this) { 1356 ProcessRecord app = (ProcessRecord)msg.obj; 1357 if (msg.arg1 != 0) { 1358 if (!app.waitedForDebugger) { 1359 Dialog d = new AppWaitingForDebuggerDialog( 1360 ActivityManagerService.this, 1361 mContext, app); 1362 app.waitDialog = d; 1363 app.waitedForDebugger = true; 1364 d.show(); 1365 } 1366 } else { 1367 if (app.waitDialog != null) { 1368 app.waitDialog.dismiss(); 1369 app.waitDialog = null; 1370 } 1371 } 1372 } 1373 } break; 1374 case SERVICE_TIMEOUT_MSG: { 1375 if (mDidDexOpt) { 1376 mDidDexOpt = false; 1377 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1378 nmsg.obj = msg.obj; 1379 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1380 return; 1381 } 1382 mServices.serviceTimeout((ProcessRecord)msg.obj); 1383 } break; 1384 case UPDATE_TIME_ZONE: { 1385 synchronized (ActivityManagerService.this) { 1386 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1387 ProcessRecord r = mLruProcesses.get(i); 1388 if (r.thread != null) { 1389 try { 1390 r.thread.updateTimeZone(); 1391 } catch (RemoteException ex) { 1392 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1393 } 1394 } 1395 } 1396 } 1397 } break; 1398 case CLEAR_DNS_CACHE_MSG: { 1399 synchronized (ActivityManagerService.this) { 1400 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1401 ProcessRecord r = mLruProcesses.get(i); 1402 if (r.thread != null) { 1403 try { 1404 r.thread.clearDnsCache(); 1405 } catch (RemoteException ex) { 1406 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1407 } 1408 } 1409 } 1410 } 1411 } break; 1412 case UPDATE_HTTP_PROXY_MSG: { 1413 ProxyInfo proxy = (ProxyInfo)msg.obj; 1414 String host = ""; 1415 String port = ""; 1416 String exclList = ""; 1417 Uri pacFileUrl = Uri.EMPTY; 1418 if (proxy != null) { 1419 host = proxy.getHost(); 1420 port = Integer.toString(proxy.getPort()); 1421 exclList = proxy.getExclusionListAsString(); 1422 pacFileUrl = proxy.getPacFileUrl(); 1423 } 1424 synchronized (ActivityManagerService.this) { 1425 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1426 ProcessRecord r = mLruProcesses.get(i); 1427 if (r.thread != null) { 1428 try { 1429 r.thread.setHttpProxy(host, port, exclList, pacFileUrl); 1430 } catch (RemoteException ex) { 1431 Slog.w(TAG, "Failed to update http proxy for: " + 1432 r.info.processName); 1433 } 1434 } 1435 } 1436 } 1437 } break; 1438 case SHOW_UID_ERROR_MSG: { 1439 String title = "System UIDs Inconsistent"; 1440 String text = "UIDs on the system are inconsistent, you need to wipe your" 1441 + " data partition or your device will be unstable."; 1442 Log.e(TAG, title + ": " + text); 1443 if (mShowDialogs) { 1444 // XXX This is a temporary dialog, no need to localize. 1445 AlertDialog d = new BaseErrorDialog(mContext); 1446 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1447 d.setCancelable(false); 1448 d.setTitle(title); 1449 d.setMessage(text); 1450 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky", 1451 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG)); 1452 mUidAlert = d; 1453 d.show(); 1454 } 1455 } break; 1456 case IM_FEELING_LUCKY_MSG: { 1457 if (mUidAlert != null) { 1458 mUidAlert.dismiss(); 1459 mUidAlert = null; 1460 } 1461 } break; 1462 case PROC_START_TIMEOUT_MSG: { 1463 if (mDidDexOpt) { 1464 mDidDexOpt = false; 1465 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1466 nmsg.obj = msg.obj; 1467 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1468 return; 1469 } 1470 ProcessRecord app = (ProcessRecord)msg.obj; 1471 synchronized (ActivityManagerService.this) { 1472 processStartTimedOutLocked(app); 1473 } 1474 } break; 1475 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1476 synchronized (ActivityManagerService.this) { 1477 mStackSupervisor.doPendingActivityLaunchesLocked(true); 1478 } 1479 } break; 1480 case KILL_APPLICATION_MSG: { 1481 synchronized (ActivityManagerService.this) { 1482 int appid = msg.arg1; 1483 boolean restart = (msg.arg2 == 1); 1484 Bundle bundle = (Bundle)msg.obj; 1485 String pkg = bundle.getString("pkg"); 1486 String reason = bundle.getString("reason"); 1487 forceStopPackageLocked(pkg, appid, restart, false, true, false, 1488 false, UserHandle.USER_ALL, reason); 1489 } 1490 } break; 1491 case FINALIZE_PENDING_INTENT_MSG: { 1492 ((PendingIntentRecord)msg.obj).completeFinalize(); 1493 } break; 1494 case POST_HEAVY_NOTIFICATION_MSG: { 1495 INotificationManager inm = NotificationManager.getService(); 1496 if (inm == null) { 1497 return; 1498 } 1499 1500 ActivityRecord root = (ActivityRecord)msg.obj; 1501 ProcessRecord process = root.app; 1502 if (process == null) { 1503 return; 1504 } 1505 1506 try { 1507 Context context = mContext.createPackageContext(process.info.packageName, 0); 1508 String text = mContext.getString(R.string.heavy_weight_notification, 1509 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1510 Notification notification = new Notification(); 1511 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon; 1512 notification.when = 0; 1513 notification.flags = Notification.FLAG_ONGOING_EVENT; 1514 notification.tickerText = text; 1515 notification.defaults = 0; // please be quiet 1516 notification.sound = null; 1517 notification.vibrate = null; 1518 notification.color = mContext.getResources().getColor( 1519 com.android.internal.R.color.system_notification_accent_color); 1520 notification.setLatestEventInfo(context, text, 1521 mContext.getText(R.string.heavy_weight_notification_detail), 1522 PendingIntent.getActivityAsUser(mContext, 0, root.intent, 1523 PendingIntent.FLAG_CANCEL_CURRENT, null, 1524 new UserHandle(root.userId))); 1525 1526 try { 1527 int[] outId = new int[1]; 1528 inm.enqueueNotificationWithTag("android", "android", null, 1529 R.string.heavy_weight_notification, 1530 notification, outId, root.userId); 1531 } catch (RuntimeException e) { 1532 Slog.w(ActivityManagerService.TAG, 1533 "Error showing notification for heavy-weight app", e); 1534 } catch (RemoteException e) { 1535 } 1536 } catch (NameNotFoundException e) { 1537 Slog.w(TAG, "Unable to create context for heavy notification", e); 1538 } 1539 } break; 1540 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1541 INotificationManager inm = NotificationManager.getService(); 1542 if (inm == null) { 1543 return; 1544 } 1545 try { 1546 inm.cancelNotificationWithTag("android", null, 1547 R.string.heavy_weight_notification, msg.arg1); 1548 } catch (RuntimeException e) { 1549 Slog.w(ActivityManagerService.TAG, 1550 "Error canceling notification for service", e); 1551 } catch (RemoteException e) { 1552 } 1553 } break; 1554 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1555 synchronized (ActivityManagerService.this) { 1556 checkExcessivePowerUsageLocked(true); 1557 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1558 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1559 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1560 } 1561 } break; 1562 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1563 synchronized (ActivityManagerService.this) { 1564 ActivityRecord ar = (ActivityRecord)msg.obj; 1565 if (mCompatModeDialog != null) { 1566 if (mCompatModeDialog.mAppInfo.packageName.equals( 1567 ar.info.applicationInfo.packageName)) { 1568 return; 1569 } 1570 mCompatModeDialog.dismiss(); 1571 mCompatModeDialog = null; 1572 } 1573 if (ar != null && false) { 1574 if (mCompatModePackages.getPackageAskCompatModeLocked( 1575 ar.packageName)) { 1576 int mode = mCompatModePackages.computeCompatModeLocked( 1577 ar.info.applicationInfo); 1578 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1579 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1580 mCompatModeDialog = new CompatModeDialog( 1581 ActivityManagerService.this, mContext, 1582 ar.info.applicationInfo); 1583 mCompatModeDialog.show(); 1584 } 1585 } 1586 } 1587 } 1588 break; 1589 } 1590 case DISPATCH_PROCESSES_CHANGED: { 1591 dispatchProcessesChanged(); 1592 break; 1593 } 1594 case DISPATCH_PROCESS_DIED: { 1595 final int pid = msg.arg1; 1596 final int uid = msg.arg2; 1597 dispatchProcessDied(pid, uid); 1598 break; 1599 } 1600 case REPORT_MEM_USAGE_MSG: { 1601 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 1602 Thread thread = new Thread() { 1603 @Override public void run() { 1604 final SparseArray<ProcessMemInfo> infoMap 1605 = new SparseArray<ProcessMemInfo>(memInfos.size()); 1606 for (int i=0, N=memInfos.size(); i<N; i++) { 1607 ProcessMemInfo mi = memInfos.get(i); 1608 infoMap.put(mi.pid, mi); 1609 } 1610 updateCpuStatsNow(); 1611 synchronized (mProcessCpuTracker) { 1612 final int N = mProcessCpuTracker.countStats(); 1613 for (int i=0; i<N; i++) { 1614 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 1615 if (st.vsize > 0) { 1616 long pss = Debug.getPss(st.pid, null); 1617 if (pss > 0) { 1618 if (infoMap.indexOfKey(st.pid) < 0) { 1619 ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid, 1620 ProcessList.NATIVE_ADJ, -1, "native", null); 1621 mi.pss = pss; 1622 memInfos.add(mi); 1623 } 1624 } 1625 } 1626 } 1627 } 1628 1629 long totalPss = 0; 1630 for (int i=0, N=memInfos.size(); i<N; i++) { 1631 ProcessMemInfo mi = memInfos.get(i); 1632 if (mi.pss == 0) { 1633 mi.pss = Debug.getPss(mi.pid, null); 1634 } 1635 totalPss += mi.pss; 1636 } 1637 Collections.sort(memInfos, new Comparator<ProcessMemInfo>() { 1638 @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) { 1639 if (lhs.oomAdj != rhs.oomAdj) { 1640 return lhs.oomAdj < rhs.oomAdj ? -1 : 1; 1641 } 1642 if (lhs.pss != rhs.pss) { 1643 return lhs.pss < rhs.pss ? 1 : -1; 1644 } 1645 return 0; 1646 } 1647 }); 1648 1649 StringBuilder tag = new StringBuilder(128); 1650 StringBuilder stack = new StringBuilder(128); 1651 tag.append("Low on memory -- "); 1652 appendMemBucket(tag, totalPss, "total", false); 1653 appendMemBucket(stack, totalPss, "total", true); 1654 1655 StringBuilder logBuilder = new StringBuilder(1024); 1656 logBuilder.append("Low on memory:\n"); 1657 1658 boolean firstLine = true; 1659 int lastOomAdj = Integer.MIN_VALUE; 1660 for (int i=0, N=memInfos.size(); i<N; i++) { 1661 ProcessMemInfo mi = memInfos.get(i); 1662 1663 if (mi.oomAdj != ProcessList.NATIVE_ADJ 1664 && (mi.oomAdj < ProcessList.SERVICE_ADJ 1665 || mi.oomAdj == ProcessList.HOME_APP_ADJ 1666 || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) { 1667 if (lastOomAdj != mi.oomAdj) { 1668 lastOomAdj = mi.oomAdj; 1669 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 1670 tag.append(" / "); 1671 } 1672 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) { 1673 if (firstLine) { 1674 stack.append(":"); 1675 firstLine = false; 1676 } 1677 stack.append("\n\t at "); 1678 } else { 1679 stack.append("$"); 1680 } 1681 } else { 1682 tag.append(" "); 1683 stack.append("$"); 1684 } 1685 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 1686 appendMemBucket(tag, mi.pss, mi.name, false); 1687 } 1688 appendMemBucket(stack, mi.pss, mi.name, true); 1689 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ 1690 && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) { 1691 stack.append("("); 1692 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) { 1693 if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) { 1694 stack.append(DUMP_MEM_OOM_LABEL[k]); 1695 stack.append(":"); 1696 stack.append(DUMP_MEM_OOM_ADJ[k]); 1697 } 1698 } 1699 stack.append(")"); 1700 } 1701 } 1702 1703 logBuilder.append(" "); 1704 logBuilder.append(ProcessList.makeOomAdjString(mi.oomAdj)); 1705 logBuilder.append(' '); 1706 logBuilder.append(ProcessList.makeProcStateString(mi.procState)); 1707 logBuilder.append(' '); 1708 ProcessList.appendRamKb(logBuilder, mi.pss); 1709 logBuilder.append(" kB: "); 1710 logBuilder.append(mi.name); 1711 logBuilder.append(" ("); 1712 logBuilder.append(mi.pid); 1713 logBuilder.append(") "); 1714 logBuilder.append(mi.adjType); 1715 logBuilder.append('\n'); 1716 if (mi.adjReason != null) { 1717 logBuilder.append(" "); 1718 logBuilder.append(mi.adjReason); 1719 logBuilder.append('\n'); 1720 } 1721 } 1722 1723 logBuilder.append(" "); 1724 ProcessList.appendRamKb(logBuilder, totalPss); 1725 logBuilder.append(" kB: TOTAL\n"); 1726 1727 long[] infos = new long[Debug.MEMINFO_COUNT]; 1728 Debug.getMemInfo(infos); 1729 logBuilder.append(" MemInfo: "); 1730 logBuilder.append(infos[Debug.MEMINFO_SLAB]).append(" kB slab, "); 1731 logBuilder.append(infos[Debug.MEMINFO_SHMEM]).append(" kB shmem, "); 1732 logBuilder.append(infos[Debug.MEMINFO_BUFFERS]).append(" kB buffers, "); 1733 logBuilder.append(infos[Debug.MEMINFO_CACHED]).append(" kB cached, "); 1734 logBuilder.append(infos[Debug.MEMINFO_FREE]).append(" kB free\n"); 1735 if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) { 1736 logBuilder.append(" ZRAM: "); 1737 logBuilder.append(infos[Debug.MEMINFO_ZRAM_TOTAL]); 1738 logBuilder.append(" kB RAM, "); 1739 logBuilder.append(infos[Debug.MEMINFO_SWAP_TOTAL]); 1740 logBuilder.append(" kB swap total, "); 1741 logBuilder.append(infos[Debug.MEMINFO_SWAP_FREE]); 1742 logBuilder.append(" kB swap free\n"); 1743 } 1744 Slog.i(TAG, logBuilder.toString()); 1745 1746 StringBuilder dropBuilder = new StringBuilder(1024); 1747 /* 1748 StringWriter oomSw = new StringWriter(); 1749 PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256); 1750 StringWriter catSw = new StringWriter(); 1751 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 1752 String[] emptyArgs = new String[] { }; 1753 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw); 1754 oomPw.flush(); 1755 String oomString = oomSw.toString(); 1756 */ 1757 dropBuilder.append(stack); 1758 dropBuilder.append('\n'); 1759 dropBuilder.append('\n'); 1760 dropBuilder.append(logBuilder); 1761 dropBuilder.append('\n'); 1762 /* 1763 dropBuilder.append(oomString); 1764 dropBuilder.append('\n'); 1765 */ 1766 StringWriter catSw = new StringWriter(); 1767 synchronized (ActivityManagerService.this) { 1768 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 1769 String[] emptyArgs = new String[] { }; 1770 catPw.println(); 1771 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 1772 catPw.println(); 1773 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0, 1774 false, false, null); 1775 catPw.println(); 1776 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 1777 catPw.flush(); 1778 } 1779 dropBuilder.append(catSw.toString()); 1780 addErrorToDropBox("lowmem", null, "system_server", null, 1781 null, tag.toString(), dropBuilder.toString(), null, null); 1782 //Slog.i(TAG, "Sent to dropbox:"); 1783 //Slog.i(TAG, dropBuilder.toString()); 1784 synchronized (ActivityManagerService.this) { 1785 long now = SystemClock.uptimeMillis(); 1786 if (mLastMemUsageReportTime < now) { 1787 mLastMemUsageReportTime = now; 1788 } 1789 } 1790 } 1791 }; 1792 thread.start(); 1793 break; 1794 } 1795 case START_USER_SWITCH_MSG: { 1796 showUserSwitchDialog(msg.arg1, (String) msg.obj); 1797 break; 1798 } 1799 case REPORT_USER_SWITCH_MSG: { 1800 dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1801 break; 1802 } 1803 case CONTINUE_USER_SWITCH_MSG: { 1804 continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1805 break; 1806 } 1807 case USER_SWITCH_TIMEOUT_MSG: { 1808 timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1809 break; 1810 } 1811 case IMMERSIVE_MODE_LOCK_MSG: { 1812 final boolean nextState = (msg.arg1 != 0); 1813 if (mUpdateLock.isHeld() != nextState) { 1814 if (DEBUG_IMMERSIVE) { 1815 final ActivityRecord r = (ActivityRecord) msg.obj; 1816 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r); 1817 } 1818 if (nextState) { 1819 mUpdateLock.acquire(); 1820 } else { 1821 mUpdateLock.release(); 1822 } 1823 } 1824 break; 1825 } 1826 case PERSIST_URI_GRANTS_MSG: { 1827 writeGrantedUriPermissions(); 1828 break; 1829 } 1830 case REQUEST_ALL_PSS_MSG: { 1831 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 1832 break; 1833 } 1834 case START_PROFILES_MSG: { 1835 synchronized (ActivityManagerService.this) { 1836 startProfilesLocked(); 1837 } 1838 break; 1839 } 1840 case UPDATE_TIME: { 1841 synchronized (ActivityManagerService.this) { 1842 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1843 ProcessRecord r = mLruProcesses.get(i); 1844 if (r.thread != null) { 1845 try { 1846 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true); 1847 } catch (RemoteException ex) { 1848 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName); 1849 } 1850 } 1851 } 1852 } 1853 break; 1854 } 1855 case SYSTEM_USER_START_MSG: { 1856 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 1857 Integer.toString(msg.arg1), msg.arg1); 1858 mSystemServiceManager.startUser(msg.arg1); 1859 break; 1860 } 1861 case SYSTEM_USER_CURRENT_MSG: { 1862 mBatteryStatsService.noteEvent( 1863 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH, 1864 Integer.toString(msg.arg2), msg.arg2); 1865 mBatteryStatsService.noteEvent( 1866 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 1867 Integer.toString(msg.arg1), msg.arg1); 1868 mSystemServiceManager.switchUser(msg.arg1); 1869 mLockToAppRequest.clearPrompt(); 1870 break; 1871 } 1872 case ENTER_ANIMATION_COMPLETE_MSG: { 1873 synchronized (ActivityManagerService.this) { 1874 ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj); 1875 if (r != null && r.app != null && r.app.thread != null) { 1876 try { 1877 r.app.thread.scheduleEnterAnimationComplete(r.appToken); 1878 } catch (RemoteException e) { 1879 } 1880 } 1881 } 1882 break; 1883 } 1884 case ENABLE_SCREEN_AFTER_BOOT_MSG: { 1885 enableScreenAfterBoot(); 1886 break; 1887 } 1888 } 1889 } 1890 }; 1891 1892 static final int COLLECT_PSS_BG_MSG = 1; 1893 1894 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 1895 @Override 1896 public void handleMessage(Message msg) { 1897 switch (msg.what) { 1898 case COLLECT_PSS_BG_MSG: { 1899 long start = SystemClock.uptimeMillis(); 1900 MemInfoReader memInfo = null; 1901 synchronized (ActivityManagerService.this) { 1902 if (mFullPssPending) { 1903 mFullPssPending = false; 1904 memInfo = new MemInfoReader(); 1905 } 1906 } 1907 if (memInfo != null) { 1908 updateCpuStatsNow(); 1909 long nativeTotalPss = 0; 1910 synchronized (mProcessCpuTracker) { 1911 final int N = mProcessCpuTracker.countStats(); 1912 for (int j=0; j<N; j++) { 1913 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j); 1914 if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) { 1915 // This is definitely an application process; skip it. 1916 continue; 1917 } 1918 synchronized (mPidsSelfLocked) { 1919 if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) { 1920 // This is one of our own processes; skip it. 1921 continue; 1922 } 1923 } 1924 nativeTotalPss += Debug.getPss(st.pid, null); 1925 } 1926 } 1927 memInfo.readMemInfo(); 1928 synchronized (ActivityManagerService.this) { 1929 if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in " 1930 + (SystemClock.uptimeMillis()-start) + "ms"); 1931 mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(), 1932 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(), 1933 memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb() 1934 +memInfo.getSlabSizeKb(), 1935 nativeTotalPss); 1936 } 1937 } 1938 1939 int i=0, num=0; 1940 long[] tmp = new long[1]; 1941 do { 1942 ProcessRecord proc; 1943 int procState; 1944 int pid; 1945 synchronized (ActivityManagerService.this) { 1946 if (i >= mPendingPssProcesses.size()) { 1947 if (DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num + " of " + i 1948 + " processes in " + (SystemClock.uptimeMillis()-start) + "ms"); 1949 mPendingPssProcesses.clear(); 1950 return; 1951 } 1952 proc = mPendingPssProcesses.get(i); 1953 procState = proc.pssProcState; 1954 if (proc.thread != null && procState == proc.setProcState) { 1955 pid = proc.pid; 1956 } else { 1957 proc = null; 1958 pid = 0; 1959 } 1960 i++; 1961 } 1962 if (proc != null) { 1963 long pss = Debug.getPss(pid, tmp); 1964 synchronized (ActivityManagerService.this) { 1965 if (proc.thread != null && proc.setProcState == procState 1966 && proc.pid == pid) { 1967 num++; 1968 proc.lastPssTime = SystemClock.uptimeMillis(); 1969 proc.baseProcessTracker.addPss(pss, tmp[0], true, proc.pkgList); 1970 if (DEBUG_PSS) Slog.d(TAG, "PSS of " + proc.toShortString() 1971 + ": " + pss + " lastPss=" + proc.lastPss 1972 + " state=" + ProcessList.makeProcStateString(procState)); 1973 if (proc.initialIdlePss == 0) { 1974 proc.initialIdlePss = pss; 1975 } 1976 proc.lastPss = pss; 1977 if (procState >= ActivityManager.PROCESS_STATE_HOME) { 1978 proc.lastCachedPss = pss; 1979 } 1980 } 1981 } 1982 } 1983 } while (true); 1984 } 1985 } 1986 } 1987 }; 1988 1989 /** 1990 * Monitor for package changes and update our internal state. 1991 */ 1992 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 1993 @Override 1994 public void onPackageRemoved(String packageName, int uid) { 1995 // Remove all tasks with activities in the specified package from the list of recent tasks 1996 synchronized (ActivityManagerService.this) { 1997 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 1998 TaskRecord tr = mRecentTasks.get(i); 1999 ComponentName cn = tr.intent.getComponent(); 2000 if (cn != null && cn.getPackageName().equals(packageName)) { 2001 // If the package name matches, remove the task and kill the process 2002 removeTaskByIdLocked(tr.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS); 2003 } 2004 } 2005 } 2006 } 2007 2008 @Override 2009 public boolean onPackageChanged(String packageName, int uid, String[] components) { 2010 onPackageModified(packageName); 2011 return true; 2012 } 2013 2014 @Override 2015 public void onPackageModified(String packageName) { 2016 final PackageManager pm = mContext.getPackageManager(); 2017 final ArrayList<Pair<Intent, Integer>> recentTaskIntents = 2018 new ArrayList<Pair<Intent, Integer>>(); 2019 final ArrayList<Integer> tasksToRemove = new ArrayList<Integer>(); 2020 // Copy the list of recent tasks so that we don't hold onto the lock on 2021 // ActivityManagerService for long periods while checking if components exist. 2022 synchronized (ActivityManagerService.this) { 2023 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 2024 TaskRecord tr = mRecentTasks.get(i); 2025 recentTaskIntents.add(new Pair<Intent, Integer>(tr.intent, tr.taskId)); 2026 } 2027 } 2028 // Check the recent tasks and filter out all tasks with components that no longer exist. 2029 Intent tmpI = new Intent(); 2030 for (int i = recentTaskIntents.size() - 1; i >= 0; i--) { 2031 Pair<Intent, Integer> p = recentTaskIntents.get(i); 2032 ComponentName cn = p.first.getComponent(); 2033 if (cn != null && cn.getPackageName().equals(packageName)) { 2034 try { 2035 // Add the task to the list to remove if the component no longer exists 2036 tmpI.setComponent(cn); 2037 if (pm.queryIntentActivities(tmpI, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) { 2038 tasksToRemove.add(p.second); 2039 } 2040 } catch (Exception e) {} 2041 } 2042 } 2043 // Prune all the tasks with removed components from the list of recent tasks 2044 synchronized (ActivityManagerService.this) { 2045 for (int i = tasksToRemove.size() - 1; i >= 0; i--) { 2046 // Remove the task but don't kill the process (since other components in that 2047 // package may still be running and in the background) 2048 removeTaskByIdLocked(tasksToRemove.get(i), 0); 2049 } 2050 } 2051 } 2052 2053 @Override 2054 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) { 2055 // Force stop the specified packages 2056 if (packages != null) { 2057 for (String pkg : packages) { 2058 synchronized (ActivityManagerService.this) { 2059 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 0, 2060 "finished booting")) { 2061 return true; 2062 } 2063 } 2064 } 2065 } 2066 return false; 2067 } 2068 }; 2069 2070 public void setSystemProcess() { 2071 try { 2072 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); 2073 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2074 ServiceManager.addService("meminfo", new MemBinder(this)); 2075 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2076 ServiceManager.addService("dbinfo", new DbBinder(this)); 2077 if (MONITOR_CPU_USAGE) { 2078 ServiceManager.addService("cpuinfo", new CpuBinder(this)); 2079 } 2080 ServiceManager.addService("permission", new PermissionController(this)); 2081 2082 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2083 "android", STOCK_PM_FLAGS); 2084 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 2085 2086 synchronized (this) { 2087 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); 2088 app.persistent = true; 2089 app.pid = MY_PID; 2090 app.maxAdj = ProcessList.SYSTEM_ADJ; 2091 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2092 mProcessNames.put(app.processName, app.uid, app); 2093 synchronized (mPidsSelfLocked) { 2094 mPidsSelfLocked.put(app.pid, app); 2095 } 2096 updateLruProcessLocked(app, false, null); 2097 updateOomAdjLocked(); 2098 } 2099 } catch (PackageManager.NameNotFoundException e) { 2100 throw new RuntimeException( 2101 "Unable to find android system package", e); 2102 } 2103 } 2104 2105 public void setWindowManager(WindowManagerService wm) { 2106 mWindowManager = wm; 2107 mStackSupervisor.setWindowManager(wm); 2108 } 2109 2110 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2111 mUsageStatsService = usageStatsManager; 2112 } 2113 2114 public void startObservingNativeCrashes() { 2115 final NativeCrashListener ncl = new NativeCrashListener(this); 2116 ncl.start(); 2117 } 2118 2119 public IAppOpsService getAppOpsService() { 2120 return mAppOpsService; 2121 } 2122 2123 static class MemBinder extends Binder { 2124 ActivityManagerService mActivityManagerService; 2125 MemBinder(ActivityManagerService activityManagerService) { 2126 mActivityManagerService = activityManagerService; 2127 } 2128 2129 @Override 2130 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2131 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2132 != PackageManager.PERMISSION_GRANTED) { 2133 pw.println("Permission Denial: can't dump meminfo from from pid=" 2134 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2135 + " without permission " + android.Manifest.permission.DUMP); 2136 return; 2137 } 2138 2139 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null); 2140 } 2141 } 2142 2143 static class GraphicsBinder extends Binder { 2144 ActivityManagerService mActivityManagerService; 2145 GraphicsBinder(ActivityManagerService activityManagerService) { 2146 mActivityManagerService = activityManagerService; 2147 } 2148 2149 @Override 2150 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2151 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2152 != PackageManager.PERMISSION_GRANTED) { 2153 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 2154 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2155 + " without permission " + android.Manifest.permission.DUMP); 2156 return; 2157 } 2158 2159 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2160 } 2161 } 2162 2163 static class DbBinder extends Binder { 2164 ActivityManagerService mActivityManagerService; 2165 DbBinder(ActivityManagerService activityManagerService) { 2166 mActivityManagerService = activityManagerService; 2167 } 2168 2169 @Override 2170 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2171 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2172 != PackageManager.PERMISSION_GRANTED) { 2173 pw.println("Permission Denial: can't dump dbinfo from from pid=" 2174 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2175 + " without permission " + android.Manifest.permission.DUMP); 2176 return; 2177 } 2178 2179 mActivityManagerService.dumpDbInfo(fd, pw, args); 2180 } 2181 } 2182 2183 static class CpuBinder extends Binder { 2184 ActivityManagerService mActivityManagerService; 2185 CpuBinder(ActivityManagerService activityManagerService) { 2186 mActivityManagerService = activityManagerService; 2187 } 2188 2189 @Override 2190 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2191 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2192 != PackageManager.PERMISSION_GRANTED) { 2193 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 2194 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2195 + " without permission " + android.Manifest.permission.DUMP); 2196 return; 2197 } 2198 2199 synchronized (mActivityManagerService.mProcessCpuTracker) { 2200 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 2201 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 2202 SystemClock.uptimeMillis())); 2203 } 2204 } 2205 } 2206 2207 public static final class Lifecycle extends SystemService { 2208 private final ActivityManagerService mService; 2209 2210 public Lifecycle(Context context) { 2211 super(context); 2212 mService = new ActivityManagerService(context); 2213 } 2214 2215 @Override 2216 public void onStart() { 2217 mService.start(); 2218 } 2219 2220 public ActivityManagerService getService() { 2221 return mService; 2222 } 2223 } 2224 2225 // Note: This method is invoked on the main thread but may need to attach various 2226 // handlers to other threads. So take care to be explicit about the looper. 2227 public ActivityManagerService(Context systemContext) { 2228 mContext = systemContext; 2229 mFactoryTest = FactoryTest.getMode(); 2230 mSystemThread = ActivityThread.currentActivityThread(); 2231 2232 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2233 2234 mHandlerThread = new ServiceThread(TAG, 2235 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2236 mHandlerThread.start(); 2237 mHandler = new MainHandler(mHandlerThread.getLooper()); 2238 2239 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2240 "foreground", BROADCAST_FG_TIMEOUT, false); 2241 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2242 "background", BROADCAST_BG_TIMEOUT, true); 2243 mBroadcastQueues[0] = mFgBroadcastQueue; 2244 mBroadcastQueues[1] = mBgBroadcastQueue; 2245 2246 mServices = new ActiveServices(this); 2247 mProviderMap = new ProviderMap(this); 2248 2249 // TODO: Move creation of battery stats service outside of activity manager service. 2250 File dataDir = Environment.getDataDirectory(); 2251 File systemDir = new File(dataDir, "system"); 2252 systemDir.mkdirs(); 2253 mBatteryStatsService = new BatteryStatsService(systemDir, mHandler); 2254 mBatteryStatsService.getActiveStatistics().readLocked(); 2255 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 2256 mOnBattery = DEBUG_POWER ? true 2257 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2258 mBatteryStatsService.getActiveStatistics().setCallback(this); 2259 2260 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2261 2262 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler); 2263 2264 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml")); 2265 2266 // User 0 is the first and only user that runs at boot. 2267 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true)); 2268 mUserLru.add(Integer.valueOf(0)); 2269 updateStartedUserArrayLocked(); 2270 2271 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 2272 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 2273 2274 mConfiguration.setToDefaults(); 2275 mConfiguration.setLocale(Locale.getDefault()); 2276 2277 mConfigurationSeq = mConfiguration.seq = 1; 2278 mProcessCpuTracker.init(); 2279 2280 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler); 2281 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2282 mStackSupervisor = new ActivityStackSupervisor(this); 2283 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor); 2284 2285 mProcessCpuThread = new Thread("CpuTracker") { 2286 @Override 2287 public void run() { 2288 while (true) { 2289 try { 2290 try { 2291 synchronized(this) { 2292 final long now = SystemClock.uptimeMillis(); 2293 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 2294 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 2295 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 2296 // + ", write delay=" + nextWriteDelay); 2297 if (nextWriteDelay < nextCpuDelay) { 2298 nextCpuDelay = nextWriteDelay; 2299 } 2300 if (nextCpuDelay > 0) { 2301 mProcessCpuMutexFree.set(true); 2302 this.wait(nextCpuDelay); 2303 } 2304 } 2305 } catch (InterruptedException e) { 2306 } 2307 updateCpuStatsNow(); 2308 } catch (Exception e) { 2309 Slog.e(TAG, "Unexpected exception collecting process stats", e); 2310 } 2311 } 2312 } 2313 }; 2314 2315 mLockToAppRequest = new LockToAppRequestDialog(mContext, this); 2316 2317 Watchdog.getInstance().addMonitor(this); 2318 Watchdog.getInstance().addThread(mHandler); 2319 } 2320 2321 public void setSystemServiceManager(SystemServiceManager mgr) { 2322 mSystemServiceManager = mgr; 2323 } 2324 2325 private void start() { 2326 Process.removeAllProcessGroups(); 2327 mProcessCpuThread.start(); 2328 2329 mBatteryStatsService.publish(mContext); 2330 mAppOpsService.publish(mContext); 2331 Slog.d("AppOps", "AppOpsService published"); 2332 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 2333 } 2334 2335 public void initPowerManagement() { 2336 mStackSupervisor.initPowerManagement(); 2337 mBatteryStatsService.initPowerManagement(); 2338 } 2339 2340 @Override 2341 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2342 throws RemoteException { 2343 if (code == SYSPROPS_TRANSACTION) { 2344 // We need to tell all apps about the system property change. 2345 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2346 synchronized(this) { 2347 final int NP = mProcessNames.getMap().size(); 2348 for (int ip=0; ip<NP; ip++) { 2349 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2350 final int NA = apps.size(); 2351 for (int ia=0; ia<NA; ia++) { 2352 ProcessRecord app = apps.valueAt(ia); 2353 if (app.thread != null) { 2354 procs.add(app.thread.asBinder()); 2355 } 2356 } 2357 } 2358 } 2359 2360 int N = procs.size(); 2361 for (int i=0; i<N; i++) { 2362 Parcel data2 = Parcel.obtain(); 2363 try { 2364 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0); 2365 } catch (RemoteException e) { 2366 } 2367 data2.recycle(); 2368 } 2369 } 2370 try { 2371 return super.onTransact(code, data, reply, flags); 2372 } catch (RuntimeException e) { 2373 // The activity manager only throws security exceptions, so let's 2374 // log all others. 2375 if (!(e instanceof SecurityException)) { 2376 Slog.wtf(TAG, "Activity Manager Crash", e); 2377 } 2378 throw e; 2379 } 2380 } 2381 2382 void updateCpuStats() { 2383 final long now = SystemClock.uptimeMillis(); 2384 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 2385 return; 2386 } 2387 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 2388 synchronized (mProcessCpuThread) { 2389 mProcessCpuThread.notify(); 2390 } 2391 } 2392 } 2393 2394 void updateCpuStatsNow() { 2395 synchronized (mProcessCpuTracker) { 2396 mProcessCpuMutexFree.set(false); 2397 final long now = SystemClock.uptimeMillis(); 2398 boolean haveNewCpuStats = false; 2399 2400 if (MONITOR_CPU_USAGE && 2401 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 2402 mLastCpuTime.set(now); 2403 haveNewCpuStats = true; 2404 mProcessCpuTracker.update(); 2405 //Slog.i(TAG, mProcessCpu.printCurrentState()); 2406 //Slog.i(TAG, "Total CPU usage: " 2407 // + mProcessCpu.getTotalCpuPercent() + "%"); 2408 2409 // Slog the cpu usage if the property is set. 2410 if ("true".equals(SystemProperties.get("events.cpu"))) { 2411 int user = mProcessCpuTracker.getLastUserTime(); 2412 int system = mProcessCpuTracker.getLastSystemTime(); 2413 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 2414 int irq = mProcessCpuTracker.getLastIrqTime(); 2415 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 2416 int idle = mProcessCpuTracker.getLastIdleTime(); 2417 2418 int total = user + system + iowait + irq + softIrq + idle; 2419 if (total == 0) total = 1; 2420 2421 EventLog.writeEvent(EventLogTags.CPU, 2422 ((user+system+iowait+irq+softIrq) * 100) / total, 2423 (user * 100) / total, 2424 (system * 100) / total, 2425 (iowait * 100) / total, 2426 (irq * 100) / total, 2427 (softIrq * 100) / total); 2428 } 2429 } 2430 2431 long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes(); 2432 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 2433 synchronized(bstats) { 2434 synchronized(mPidsSelfLocked) { 2435 if (haveNewCpuStats) { 2436 if (mOnBattery) { 2437 int perc = bstats.startAddingCpuLocked(); 2438 int totalUTime = 0; 2439 int totalSTime = 0; 2440 final int N = mProcessCpuTracker.countStats(); 2441 for (int i=0; i<N; i++) { 2442 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 2443 if (!st.working) { 2444 continue; 2445 } 2446 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 2447 int otherUTime = (st.rel_utime*perc)/100; 2448 int otherSTime = (st.rel_stime*perc)/100; 2449 totalUTime += otherUTime; 2450 totalSTime += otherSTime; 2451 if (pr != null) { 2452 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 2453 if (ps == null || !ps.isActive()) { 2454 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 2455 pr.info.uid, pr.processName); 2456 } 2457 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 2458 st.rel_stime-otherSTime); 2459 ps.addSpeedStepTimes(cpuSpeedTimes); 2460 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10; 2461 } else { 2462 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 2463 if (ps == null || !ps.isActive()) { 2464 st.batteryStats = ps = bstats.getProcessStatsLocked( 2465 bstats.mapUid(st.uid), st.name); 2466 } 2467 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 2468 st.rel_stime-otherSTime); 2469 ps.addSpeedStepTimes(cpuSpeedTimes); 2470 } 2471 } 2472 bstats.finishAddingCpuLocked(perc, totalUTime, 2473 totalSTime, cpuSpeedTimes); 2474 } 2475 } 2476 } 2477 2478 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 2479 mLastWriteTime = now; 2480 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 2481 } 2482 } 2483 } 2484 } 2485 2486 @Override 2487 public void batteryNeedsCpuUpdate() { 2488 updateCpuStatsNow(); 2489 } 2490 2491 @Override 2492 public void batteryPowerChanged(boolean onBattery) { 2493 // When plugging in, update the CPU stats first before changing 2494 // the plug state. 2495 updateCpuStatsNow(); 2496 synchronized (this) { 2497 synchronized(mPidsSelfLocked) { 2498 mOnBattery = DEBUG_POWER ? true : onBattery; 2499 } 2500 } 2501 } 2502 2503 /** 2504 * Initialize the application bind args. These are passed to each 2505 * process when the bindApplication() IPC is sent to the process. They're 2506 * lazily setup to make sure the services are running when they're asked for. 2507 */ 2508 private HashMap<String, IBinder> getCommonServicesLocked() { 2509 if (mAppBindArgs == null) { 2510 mAppBindArgs = new HashMap<String, IBinder>(); 2511 2512 // Setup the application init args 2513 mAppBindArgs.put("package", ServiceManager.getService("package")); 2514 mAppBindArgs.put("window", ServiceManager.getService("window")); 2515 mAppBindArgs.put(Context.ALARM_SERVICE, 2516 ServiceManager.getService(Context.ALARM_SERVICE)); 2517 } 2518 return mAppBindArgs; 2519 } 2520 2521 final void setFocusedActivityLocked(ActivityRecord r) { 2522 if (mFocusedActivity != r) { 2523 if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r); 2524 mFocusedActivity = r; 2525 if (r.task != null && r.task.voiceInteractor != null) { 2526 startRunningVoiceLocked(); 2527 } else { 2528 finishRunningVoiceLocked(); 2529 } 2530 mStackSupervisor.setFocusedStack(r); 2531 if (r != null) { 2532 mWindowManager.setFocusedApp(r.appToken, true); 2533 } 2534 applyUpdateLockStateLocked(r); 2535 } 2536 } 2537 2538 final void clearFocusedActivity(ActivityRecord r) { 2539 if (mFocusedActivity == r) { 2540 mFocusedActivity = null; 2541 } 2542 } 2543 2544 @Override 2545 public void setFocusedStack(int stackId) { 2546 if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId); 2547 synchronized (ActivityManagerService.this) { 2548 ActivityStack stack = mStackSupervisor.getStack(stackId); 2549 if (stack != null) { 2550 ActivityRecord r = stack.topRunningActivityLocked(null); 2551 if (r != null) { 2552 setFocusedActivityLocked(r); 2553 } 2554 } 2555 } 2556 } 2557 2558 @Override 2559 public void notifyActivityDrawn(IBinder token) { 2560 if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token); 2561 synchronized (this) { 2562 ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token); 2563 if (r != null) { 2564 r.task.stack.notifyActivityDrawnLocked(r); 2565 } 2566 } 2567 } 2568 2569 final void applyUpdateLockStateLocked(ActivityRecord r) { 2570 // Modifications to the UpdateLock state are done on our handler, outside 2571 // the activity manager's locks. The new state is determined based on the 2572 // state *now* of the relevant activity record. The object is passed to 2573 // the handler solely for logging detail, not to be consulted/modified. 2574 final boolean nextState = r != null && r.immersive; 2575 mHandler.sendMessage( 2576 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 2577 } 2578 2579 final void showAskCompatModeDialogLocked(ActivityRecord r) { 2580 Message msg = Message.obtain(); 2581 msg.what = SHOW_COMPAT_MODE_DIALOG_MSG; 2582 msg.obj = r.task.askedCompatMode ? null : r; 2583 mHandler.sendMessage(msg); 2584 } 2585 2586 private final int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 2587 String what, Object obj, ProcessRecord srcApp) { 2588 app.lastActivityTime = now; 2589 2590 if (app.activities.size() > 0) { 2591 // Don't want to touch dependent processes that are hosting activities. 2592 return index; 2593 } 2594 2595 int lrui = mLruProcesses.lastIndexOf(app); 2596 if (lrui < 0) { 2597 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 2598 + what + " " + obj + " from " + srcApp); 2599 return index; 2600 } 2601 2602 if (lrui >= index) { 2603 // Don't want to cause this to move dependent processes *back* in the 2604 // list as if they were less frequently used. 2605 return index; 2606 } 2607 2608 if (lrui >= mLruProcessActivityStart) { 2609 // Don't want to touch dependent processes that are hosting activities. 2610 return index; 2611 } 2612 2613 mLruProcesses.remove(lrui); 2614 if (index > 0) { 2615 index--; 2616 } 2617 if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index 2618 + " in LRU list: " + app); 2619 mLruProcesses.add(index, app); 2620 return index; 2621 } 2622 2623 final void removeLruProcessLocked(ProcessRecord app) { 2624 int lrui = mLruProcesses.lastIndexOf(app); 2625 if (lrui >= 0) { 2626 if (lrui <= mLruProcessActivityStart) { 2627 mLruProcessActivityStart--; 2628 } 2629 if (lrui <= mLruProcessServiceStart) { 2630 mLruProcessServiceStart--; 2631 } 2632 mLruProcesses.remove(lrui); 2633 } 2634 } 2635 2636 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2637 ProcessRecord client) { 2638 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities 2639 || app.treatLikeActivity; 2640 final boolean hasService = false; // not impl yet. app.services.size() > 0; 2641 if (!activityChange && hasActivity) { 2642 // The process has activities, so we are only allowing activity-based adjustments 2643 // to move it. It should be kept in the front of the list with other 2644 // processes that have activities, and we don't want those to change their 2645 // order except due to activity operations. 2646 return; 2647 } 2648 2649 mLruSeq++; 2650 final long now = SystemClock.uptimeMillis(); 2651 app.lastActivityTime = now; 2652 2653 // First a quick reject: if the app is already at the position we will 2654 // put it, then there is nothing to do. 2655 if (hasActivity) { 2656 final int N = mLruProcesses.size(); 2657 if (N > 0 && mLruProcesses.get(N-1) == app) { 2658 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app); 2659 return; 2660 } 2661 } else { 2662 if (mLruProcessServiceStart > 0 2663 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 2664 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app); 2665 return; 2666 } 2667 } 2668 2669 int lrui = mLruProcesses.lastIndexOf(app); 2670 2671 if (app.persistent && lrui >= 0) { 2672 // We don't care about the position of persistent processes, as long as 2673 // they are in the list. 2674 if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app); 2675 return; 2676 } 2677 2678 /* In progress: compute new position first, so we can avoid doing work 2679 if the process is not actually going to move. Not yet working. 2680 int addIndex; 2681 int nextIndex; 2682 boolean inActivity = false, inService = false; 2683 if (hasActivity) { 2684 // Process has activities, put it at the very tipsy-top. 2685 addIndex = mLruProcesses.size(); 2686 nextIndex = mLruProcessServiceStart; 2687 inActivity = true; 2688 } else if (hasService) { 2689 // Process has services, put it at the top of the service list. 2690 addIndex = mLruProcessActivityStart; 2691 nextIndex = mLruProcessServiceStart; 2692 inActivity = true; 2693 inService = true; 2694 } else { 2695 // Process not otherwise of interest, it goes to the top of the non-service area. 2696 addIndex = mLruProcessServiceStart; 2697 if (client != null) { 2698 int clientIndex = mLruProcesses.lastIndexOf(client); 2699 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 2700 + app); 2701 if (clientIndex >= 0 && addIndex > clientIndex) { 2702 addIndex = clientIndex; 2703 } 2704 } 2705 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 2706 } 2707 2708 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 2709 + mLruProcessActivityStart + "): " + app); 2710 */ 2711 2712 if (lrui >= 0) { 2713 if (lrui < mLruProcessActivityStart) { 2714 mLruProcessActivityStart--; 2715 } 2716 if (lrui < mLruProcessServiceStart) { 2717 mLruProcessServiceStart--; 2718 } 2719 /* 2720 if (addIndex > lrui) { 2721 addIndex--; 2722 } 2723 if (nextIndex > lrui) { 2724 nextIndex--; 2725 } 2726 */ 2727 mLruProcesses.remove(lrui); 2728 } 2729 2730 /* 2731 mLruProcesses.add(addIndex, app); 2732 if (inActivity) { 2733 mLruProcessActivityStart++; 2734 } 2735 if (inService) { 2736 mLruProcessActivityStart++; 2737 } 2738 */ 2739 2740 int nextIndex; 2741 if (hasActivity) { 2742 final int N = mLruProcesses.size(); 2743 if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) { 2744 // Process doesn't have activities, but has clients with 2745 // activities... move it up, but one below the top (the top 2746 // should always have a real activity). 2747 if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app); 2748 mLruProcesses.add(N-1, app); 2749 // To keep it from spamming the LRU list (by making a bunch of clients), 2750 // we will push down any other entries owned by the app. 2751 final int uid = app.info.uid; 2752 for (int i=N-2; i>mLruProcessActivityStart; i--) { 2753 ProcessRecord subProc = mLruProcesses.get(i); 2754 if (subProc.info.uid == uid) { 2755 // We want to push this one down the list. If the process after 2756 // it is for the same uid, however, don't do so, because we don't 2757 // want them internally to be re-ordered. 2758 if (mLruProcesses.get(i-1).info.uid != uid) { 2759 if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i 2760 + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1)); 2761 ProcessRecord tmp = mLruProcesses.get(i); 2762 mLruProcesses.set(i, mLruProcesses.get(i-1)); 2763 mLruProcesses.set(i-1, tmp); 2764 i--; 2765 } 2766 } else { 2767 // A gap, we can stop here. 2768 break; 2769 } 2770 } 2771 } else { 2772 // Process has activities, put it at the very tipsy-top. 2773 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app); 2774 mLruProcesses.add(app); 2775 } 2776 nextIndex = mLruProcessServiceStart; 2777 } else if (hasService) { 2778 // Process has services, put it at the top of the service list. 2779 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU service list: " + app); 2780 mLruProcesses.add(mLruProcessActivityStart, app); 2781 nextIndex = mLruProcessServiceStart; 2782 mLruProcessActivityStart++; 2783 } else { 2784 // Process not otherwise of interest, it goes to the top of the non-service area. 2785 int index = mLruProcessServiceStart; 2786 if (client != null) { 2787 // If there is a client, don't allow the process to be moved up higher 2788 // in the list than that client. 2789 int clientIndex = mLruProcesses.lastIndexOf(client); 2790 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG, "Unknown client " + client 2791 + " when updating " + app); 2792 if (clientIndex <= lrui) { 2793 // Don't allow the client index restriction to push it down farther in the 2794 // list than it already is. 2795 clientIndex = lrui; 2796 } 2797 if (clientIndex >= 0 && index > clientIndex) { 2798 index = clientIndex; 2799 } 2800 } 2801 if (DEBUG_LRU) Slog.d(TAG, "Adding at " + index + " of LRU list: " + app); 2802 mLruProcesses.add(index, app); 2803 nextIndex = index-1; 2804 mLruProcessActivityStart++; 2805 mLruProcessServiceStart++; 2806 } 2807 2808 // If the app is currently using a content provider or service, 2809 // bump those processes as well. 2810 for (int j=app.connections.size()-1; j>=0; j--) { 2811 ConnectionRecord cr = app.connections.valueAt(j); 2812 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 2813 && cr.binding.service.app != null 2814 && cr.binding.service.app.lruSeq != mLruSeq 2815 && !cr.binding.service.app.persistent) { 2816 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex, 2817 "service connection", cr, app); 2818 } 2819 } 2820 for (int j=app.conProviders.size()-1; j>=0; j--) { 2821 ContentProviderRecord cpr = app.conProviders.get(j).provider; 2822 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) { 2823 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, 2824 "provider reference", cpr, app); 2825 } 2826 } 2827 } 2828 2829 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 2830 if (uid == Process.SYSTEM_UID) { 2831 // The system gets to run in any process. If there are multiple 2832 // processes with the same uid, just pick the first (this 2833 // should never happen). 2834 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 2835 if (procs == null) return null; 2836 final int N = procs.size(); 2837 for (int i = 0; i < N; i++) { 2838 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i); 2839 } 2840 } 2841 ProcessRecord proc = mProcessNames.get(processName, uid); 2842 if (false && proc != null && !keepIfLarge 2843 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 2844 && proc.lastCachedPss >= 4000) { 2845 // Turn this condition on to cause killing to happen regularly, for testing. 2846 if (proc.baseProcessTracker != null) { 2847 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 2848 } 2849 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 2850 } else if (proc != null && !keepIfLarge 2851 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 2852 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 2853 if (DEBUG_PSS) Slog.d(TAG, "May not keep " + proc + ": pss=" + proc.lastCachedPss); 2854 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) { 2855 if (proc.baseProcessTracker != null) { 2856 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 2857 } 2858 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 2859 } 2860 } 2861 return proc; 2862 } 2863 2864 void ensurePackageDexOpt(String packageName) { 2865 IPackageManager pm = AppGlobals.getPackageManager(); 2866 try { 2867 if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) { 2868 mDidDexOpt = true; 2869 } 2870 } catch (RemoteException e) { 2871 } 2872 } 2873 2874 boolean isNextTransitionForward() { 2875 int transit = mWindowManager.getPendingAppTransition(); 2876 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN 2877 || transit == AppTransition.TRANSIT_TASK_OPEN 2878 || transit == AppTransition.TRANSIT_TASK_TO_FRONT; 2879 } 2880 2881 int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2882 String processName, String abiOverride, int uid, Runnable crashHandler) { 2883 synchronized(this) { 2884 ApplicationInfo info = new ApplicationInfo(); 2885 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2886 // For isolated processes, the former contains the parent's uid and the latter the 2887 // actual uid of the isolated process. 2888 // In the special case introduced by this method (which is, starting an isolated 2889 // process directly from the SystemServer without an actual parent app process) the 2890 // closest thing to a parent's uid is SYSTEM_UID. 2891 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2892 // the |isolated| logic in the ProcessRecord constructor. 2893 info.uid = Process.SYSTEM_UID; 2894 info.processName = processName; 2895 info.className = entryPoint; 2896 info.packageName = "android"; 2897 ProcessRecord proc = startProcessLocked(processName, info /* info */, 2898 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */, 2899 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */, 2900 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 2901 crashHandler); 2902 return proc != null ? proc.pid : 0; 2903 } 2904 } 2905 2906 final ProcessRecord startProcessLocked(String processName, 2907 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2908 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 2909 boolean isolated, boolean keepIfLarge) { 2910 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, 2911 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 2912 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 2913 null /* crashHandler */); 2914 } 2915 2916 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 2917 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, 2918 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, 2919 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { 2920 long startTime = SystemClock.elapsedRealtime(); 2921 ProcessRecord app; 2922 if (!isolated) { 2923 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 2924 checkTime(startTime, "startProcess: after getProcessRecord"); 2925 } else { 2926 // If this is an isolated process, it can't re-use an existing process. 2927 app = null; 2928 } 2929 // We don't have to do anything more if: 2930 // (1) There is an existing application record; and 2931 // (2) The caller doesn't think it is dead, OR there is no thread 2932 // object attached to it so we know it couldn't have crashed; and 2933 // (3) There is a pid assigned to it, so it is either starting or 2934 // already running. 2935 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName 2936 + " app=" + app + " knownToBeDead=" + knownToBeDead 2937 + " thread=" + (app != null ? app.thread : null) 2938 + " pid=" + (app != null ? app.pid : -1)); 2939 if (app != null && app.pid > 0) { 2940 if (!knownToBeDead || app.thread == null) { 2941 // We already have the app running, or are waiting for it to 2942 // come up (we have a pid but not yet its thread), so keep it. 2943 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app); 2944 // If this is a new package in the process, add the package to the list 2945 app.addPackage(info.packageName, info.versionCode, mProcessStats); 2946 checkTime(startTime, "startProcess: done, added package to proc"); 2947 return app; 2948 } 2949 2950 // An application record is attached to a previous process, 2951 // clean it up now. 2952 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app); 2953 checkTime(startTime, "startProcess: bad proc running, killing"); 2954 Process.killProcessGroup(app.info.uid, app.pid); 2955 handleAppDiedLocked(app, true, true); 2956 checkTime(startTime, "startProcess: done killing old proc"); 2957 } 2958 2959 String hostingNameStr = hostingName != null 2960 ? hostingName.flattenToShortString() : null; 2961 2962 if (!isolated) { 2963 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) { 2964 // If we are in the background, then check to see if this process 2965 // is bad. If so, we will just silently fail. 2966 if (mBadProcesses.get(info.processName, info.uid) != null) { 2967 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 2968 + "/" + info.processName); 2969 return null; 2970 } 2971 } else { 2972 // When the user is explicitly starting a process, then clear its 2973 // crash count so that we won't make it bad until they see at 2974 // least one crash dialog again, and make the process good again 2975 // if it had been bad. 2976 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 2977 + "/" + info.processName); 2978 mProcessCrashTimes.remove(info.processName, info.uid); 2979 if (mBadProcesses.get(info.processName, info.uid) != null) { 2980 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 2981 UserHandle.getUserId(info.uid), info.uid, 2982 info.processName); 2983 mBadProcesses.remove(info.processName, info.uid); 2984 if (app != null) { 2985 app.bad = false; 2986 } 2987 } 2988 } 2989 } 2990 2991 if (app == null) { 2992 checkTime(startTime, "startProcess: creating new process record"); 2993 app = newProcessRecordLocked(info, processName, isolated, isolatedUid); 2994 app.crashHandler = crashHandler; 2995 if (app == null) { 2996 Slog.w(TAG, "Failed making new process record for " 2997 + processName + "/" + info.uid + " isolated=" + isolated); 2998 return null; 2999 } 3000 mProcessNames.put(processName, app.uid, app); 3001 if (isolated) { 3002 mIsolatedProcesses.put(app.uid, app); 3003 } 3004 checkTime(startTime, "startProcess: done creating new process record"); 3005 } else { 3006 // If this is a new package in the process, add the package to the list 3007 app.addPackage(info.packageName, info.versionCode, mProcessStats); 3008 checkTime(startTime, "startProcess: added package to existing proc"); 3009 } 3010 3011 // If the system is not ready yet, then hold off on starting this 3012 // process until it is. 3013 if (!mProcessesReady 3014 && !isAllowedWhileBooting(info) 3015 && !allowWhileBooting) { 3016 if (!mProcessesOnHold.contains(app)) { 3017 mProcessesOnHold.add(app); 3018 } 3019 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app); 3020 checkTime(startTime, "startProcess: returning with proc on hold"); 3021 return app; 3022 } 3023 3024 checkTime(startTime, "startProcess: stepping in to startProcess"); 3025 startProcessLocked( 3026 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs); 3027 checkTime(startTime, "startProcess: done starting proc!"); 3028 return (app.pid != 0) ? app : null; 3029 } 3030 3031 boolean isAllowedWhileBooting(ApplicationInfo ai) { 3032 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3033 } 3034 3035 private final void startProcessLocked(ProcessRecord app, 3036 String hostingType, String hostingNameStr) { 3037 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */, 3038 null /* entryPoint */, null /* entryPointArgs */); 3039 } 3040 3041 private final void startProcessLocked(ProcessRecord app, String hostingType, 3042 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { 3043 long startTime = SystemClock.elapsedRealtime(); 3044 if (app.pid > 0 && app.pid != MY_PID) { 3045 checkTime(startTime, "startProcess: removing from pids map"); 3046 synchronized (mPidsSelfLocked) { 3047 mPidsSelfLocked.remove(app.pid); 3048 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 3049 } 3050 checkTime(startTime, "startProcess: done removing from pids map"); 3051 app.setPid(0); 3052 } 3053 3054 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 3055 "startProcessLocked removing on hold: " + app); 3056 mProcessesOnHold.remove(app); 3057 3058 checkTime(startTime, "startProcess: starting to update cpu stats"); 3059 updateCpuStats(); 3060 checkTime(startTime, "startProcess: done updating cpu stats"); 3061 3062 try { 3063 int uid = app.uid; 3064 3065 int[] gids = null; 3066 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 3067 if (!app.isolated) { 3068 int[] permGids = null; 3069 try { 3070 checkTime(startTime, "startProcess: getting gids from package manager"); 3071 final PackageManager pm = mContext.getPackageManager(); 3072 permGids = pm.getPackageGids(app.info.packageName); 3073 3074 if (Environment.isExternalStorageEmulated()) { 3075 checkTime(startTime, "startProcess: checking external storage perm"); 3076 if (pm.checkPermission( 3077 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE, 3078 app.info.packageName) == PERMISSION_GRANTED) { 3079 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL; 3080 } else { 3081 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER; 3082 } 3083 } 3084 } catch (PackageManager.NameNotFoundException e) { 3085 Slog.w(TAG, "Unable to retrieve gids", e); 3086 } 3087 3088 /* 3089 * Add shared application and profile GIDs so applications can share some 3090 * resources like shared libraries and access user-wide resources 3091 */ 3092 if (permGids == null) { 3093 gids = new int[2]; 3094 } else { 3095 gids = new int[permGids.length + 2]; 3096 System.arraycopy(permGids, 0, gids, 2, permGids.length); 3097 } 3098 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 3099 gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 3100 } 3101 checkTime(startTime, "startProcess: building args"); 3102 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) { 3103 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3104 && mTopComponent != null 3105 && app.processName.equals(mTopComponent.getPackageName())) { 3106 uid = 0; 3107 } 3108 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL 3109 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 3110 uid = 0; 3111 } 3112 } 3113 int debugFlags = 0; 3114 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 3115 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 3116 // Also turn on CheckJNI for debuggable apps. It's quite 3117 // awkward to turn on otherwise. 3118 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3119 } 3120 // Run the app in safe mode if its manifest requests so or the 3121 // system is booted in safe mode. 3122 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 3123 mSafeMode == true) { 3124 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 3125 } 3126 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 3127 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3128 } 3129 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 3130 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 3131 } 3132 if ("1".equals(SystemProperties.get("debug.assert"))) { 3133 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 3134 } 3135 3136 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 3137 if (requiredAbi == null) { 3138 requiredAbi = Build.SUPPORTED_ABIS[0]; 3139 } 3140 3141 String instructionSet = null; 3142 if (app.info.primaryCpuAbi != null) { 3143 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi); 3144 } 3145 3146 // Start the process. It will either succeed and return a result containing 3147 // the PID of the new process, or else throw a RuntimeException. 3148 boolean isActivityProcess = (entryPoint == null); 3149 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 3150 checkTime(startTime, "startProcess: asking zygote to start proc"); 3151 Process.ProcessStartResult startResult = Process.start(entryPoint, 3152 app.processName, uid, uid, gids, debugFlags, mountExternal, 3153 app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet, 3154 entryPointArgs); 3155 checkTime(startTime, "startProcess: returned from zygote!"); 3156 3157 if (app.isolated) { 3158 mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid); 3159 } 3160 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 3161 checkTime(startTime, "startProcess: done updating battery stats"); 3162 3163 EventLog.writeEvent(EventLogTags.AM_PROC_START, 3164 UserHandle.getUserId(uid), startResult.pid, uid, 3165 app.processName, hostingType, 3166 hostingNameStr != null ? hostingNameStr : ""); 3167 3168 if (app.persistent) { 3169 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 3170 } 3171 3172 checkTime(startTime, "startProcess: building log message"); 3173 StringBuilder buf = mStringBuilder; 3174 buf.setLength(0); 3175 buf.append("Start proc "); 3176 buf.append(app.processName); 3177 if (!isActivityProcess) { 3178 buf.append(" ["); 3179 buf.append(entryPoint); 3180 buf.append("]"); 3181 } 3182 buf.append(" for "); 3183 buf.append(hostingType); 3184 if (hostingNameStr != null) { 3185 buf.append(" "); 3186 buf.append(hostingNameStr); 3187 } 3188 buf.append(": pid="); 3189 buf.append(startResult.pid); 3190 buf.append(" uid="); 3191 buf.append(uid); 3192 buf.append(" gids={"); 3193 if (gids != null) { 3194 for (int gi=0; gi<gids.length; gi++) { 3195 if (gi != 0) buf.append(", "); 3196 buf.append(gids[gi]); 3197 3198 } 3199 } 3200 buf.append("}"); 3201 if (requiredAbi != null) { 3202 buf.append(" abi="); 3203 buf.append(requiredAbi); 3204 } 3205 Slog.i(TAG, buf.toString()); 3206 app.setPid(startResult.pid); 3207 app.usingWrapper = startResult.usingWrapper; 3208 app.removed = false; 3209 app.killedByAm = false; 3210 checkTime(startTime, "startProcess: starting to update pids map"); 3211 synchronized (mPidsSelfLocked) { 3212 this.mPidsSelfLocked.put(startResult.pid, app); 3213 if (isActivityProcess) { 3214 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 3215 msg.obj = app; 3216 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 3217 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 3218 } 3219 } 3220 checkTime(startTime, "startProcess: done updating pids map"); 3221 } catch (RuntimeException e) { 3222 // XXX do better error recovery. 3223 app.setPid(0); 3224 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 3225 if (app.isolated) { 3226 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 3227 } 3228 Slog.e(TAG, "Failure starting process " + app.processName, e); 3229 } 3230 } 3231 3232 void updateUsageStats(ActivityRecord component, boolean resumed) { 3233 if (DEBUG_SWITCH) Slog.d(TAG, "updateUsageStats: comp=" + component + "res=" + resumed); 3234 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3235 if (resumed) { 3236 if (mUsageStatsService != null) { 3237 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3238 UsageEvents.Event.MOVE_TO_FOREGROUND); 3239 } 3240 synchronized (stats) { 3241 stats.noteActivityResumedLocked(component.app.uid); 3242 } 3243 } else { 3244 if (mUsageStatsService != null) { 3245 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3246 UsageEvents.Event.MOVE_TO_BACKGROUND); 3247 } 3248 synchronized (stats) { 3249 stats.noteActivityPausedLocked(component.app.uid); 3250 } 3251 } 3252 } 3253 3254 Intent getHomeIntent() { 3255 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); 3256 intent.setComponent(mTopComponent); 3257 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 3258 intent.addCategory(Intent.CATEGORY_HOME); 3259 } 3260 return intent; 3261 } 3262 3263 boolean startHomeActivityLocked(int userId) { 3264 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3265 && mTopAction == null) { 3266 // We are running in factory test mode, but unable to find 3267 // the factory test app, so just sit around displaying the 3268 // error message and don't try to start anything. 3269 return false; 3270 } 3271 Intent intent = getHomeIntent(); 3272 ActivityInfo aInfo = 3273 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 3274 if (aInfo != null) { 3275 intent.setComponent(new ComponentName( 3276 aInfo.applicationInfo.packageName, aInfo.name)); 3277 // Don't do this if the home app is currently being 3278 // instrumented. 3279 aInfo = new ActivityInfo(aInfo); 3280 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 3281 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 3282 aInfo.applicationInfo.uid, true); 3283 if (app == null || app.instrumentationClass == null) { 3284 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 3285 mStackSupervisor.startHomeActivity(intent, aInfo); 3286 } 3287 } 3288 3289 return true; 3290 } 3291 3292 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 3293 ActivityInfo ai = null; 3294 ComponentName comp = intent.getComponent(); 3295 try { 3296 if (comp != null) { 3297 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 3298 } else { 3299 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 3300 intent, 3301 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 3302 flags, userId); 3303 3304 if (info != null) { 3305 ai = info.activityInfo; 3306 } 3307 } 3308 } catch (RemoteException e) { 3309 // ignore 3310 } 3311 3312 return ai; 3313 } 3314 3315 /** 3316 * Starts the "new version setup screen" if appropriate. 3317 */ 3318 void startSetupActivityLocked() { 3319 // Only do this once per boot. 3320 if (mCheckedForSetup) { 3321 return; 3322 } 3323 3324 // We will show this screen if the current one is a different 3325 // version than the last one shown, and we are not running in 3326 // low-level factory test mode. 3327 final ContentResolver resolver = mContext.getContentResolver(); 3328 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL && 3329 Settings.Global.getInt(resolver, 3330 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 3331 mCheckedForSetup = true; 3332 3333 // See if we should be showing the platform update setup UI. 3334 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 3335 List<ResolveInfo> ris = mContext.getPackageManager() 3336 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 3337 3338 // We don't allow third party apps to replace this. 3339 ResolveInfo ri = null; 3340 for (int i=0; ris != null && i<ris.size(); i++) { 3341 if ((ris.get(i).activityInfo.applicationInfo.flags 3342 & ApplicationInfo.FLAG_SYSTEM) != 0) { 3343 ri = ris.get(i); 3344 break; 3345 } 3346 } 3347 3348 if (ri != null) { 3349 String vers = ri.activityInfo.metaData != null 3350 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 3351 : null; 3352 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 3353 vers = ri.activityInfo.applicationInfo.metaData.getString( 3354 Intent.METADATA_SETUP_VERSION); 3355 } 3356 String lastVers = Settings.Secure.getString( 3357 resolver, Settings.Secure.LAST_SETUP_SHOWN); 3358 if (vers != null && !vers.equals(lastVers)) { 3359 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 3360 intent.setComponent(new ComponentName( 3361 ri.activityInfo.packageName, ri.activityInfo.name)); 3362 mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo, 3363 null, null, null, null, 0, 0, 0, null, 0, null, false, null, null, 3364 null); 3365 } 3366 } 3367 } 3368 } 3369 3370 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 3371 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 3372 } 3373 3374 void enforceNotIsolatedCaller(String caller) { 3375 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3376 throw new SecurityException("Isolated process not allowed to call " + caller); 3377 } 3378 } 3379 3380 void enforceShellRestriction(String restriction, int userHandle) { 3381 if (Binder.getCallingUid() == Process.SHELL_UID) { 3382 if (userHandle < 0 3383 || mUserManager.hasUserRestriction(restriction, userHandle)) { 3384 throw new SecurityException("Shell does not have permission to access user " 3385 + userHandle); 3386 } 3387 } 3388 } 3389 3390 @Override 3391 public int getFrontActivityScreenCompatMode() { 3392 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 3393 synchronized (this) { 3394 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 3395 } 3396 } 3397 3398 @Override 3399 public void setFrontActivityScreenCompatMode(int mode) { 3400 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3401 "setFrontActivityScreenCompatMode"); 3402 synchronized (this) { 3403 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 3404 } 3405 } 3406 3407 @Override 3408 public int getPackageScreenCompatMode(String packageName) { 3409 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 3410 synchronized (this) { 3411 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 3412 } 3413 } 3414 3415 @Override 3416 public void setPackageScreenCompatMode(String packageName, int mode) { 3417 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3418 "setPackageScreenCompatMode"); 3419 synchronized (this) { 3420 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 3421 } 3422 } 3423 3424 @Override 3425 public boolean getPackageAskScreenCompat(String packageName) { 3426 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 3427 synchronized (this) { 3428 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 3429 } 3430 } 3431 3432 @Override 3433 public void setPackageAskScreenCompat(String packageName, boolean ask) { 3434 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3435 "setPackageAskScreenCompat"); 3436 synchronized (this) { 3437 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 3438 } 3439 } 3440 3441 private void dispatchProcessesChanged() { 3442 int N; 3443 synchronized (this) { 3444 N = mPendingProcessChanges.size(); 3445 if (mActiveProcessChanges.length < N) { 3446 mActiveProcessChanges = new ProcessChangeItem[N]; 3447 } 3448 mPendingProcessChanges.toArray(mActiveProcessChanges); 3449 mAvailProcessChanges.addAll(mPendingProcessChanges); 3450 mPendingProcessChanges.clear(); 3451 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes"); 3452 } 3453 3454 int i = mProcessObservers.beginBroadcast(); 3455 while (i > 0) { 3456 i--; 3457 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3458 if (observer != null) { 3459 try { 3460 for (int j=0; j<N; j++) { 3461 ProcessChangeItem item = mActiveProcessChanges[j]; 3462 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 3463 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid=" 3464 + item.pid + " uid=" + item.uid + ": " 3465 + item.foregroundActivities); 3466 observer.onForegroundActivitiesChanged(item.pid, item.uid, 3467 item.foregroundActivities); 3468 } 3469 if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) { 3470 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "PROCSTATE CHANGED pid=" 3471 + item.pid + " uid=" + item.uid + ": " + item.processState); 3472 observer.onProcessStateChanged(item.pid, item.uid, item.processState); 3473 } 3474 } 3475 } catch (RemoteException e) { 3476 } 3477 } 3478 } 3479 mProcessObservers.finishBroadcast(); 3480 } 3481 3482 private void dispatchProcessDied(int pid, int uid) { 3483 int i = mProcessObservers.beginBroadcast(); 3484 while (i > 0) { 3485 i--; 3486 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3487 if (observer != null) { 3488 try { 3489 observer.onProcessDied(pid, uid); 3490 } catch (RemoteException e) { 3491 } 3492 } 3493 } 3494 mProcessObservers.finishBroadcast(); 3495 } 3496 3497 @Override 3498 public final int startActivity(IApplicationThread caller, String callingPackage, 3499 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3500 int startFlags, ProfilerInfo profilerInfo, Bundle options) { 3501 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 3502 resultWho, requestCode, startFlags, profilerInfo, options, 3503 UserHandle.getCallingUserId()); 3504 } 3505 3506 @Override 3507 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3508 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3509 int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { 3510 enforceNotIsolatedCaller("startActivity"); 3511 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3512 false, ALLOW_FULL_ONLY, "startActivity", null); 3513 // TODO: Switch to user app stacks here. 3514 return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, 3515 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3516 profilerInfo, null, null, options, userId, null, null); 3517 } 3518 3519 @Override 3520 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage, 3521 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3522 int startFlags, ProfilerInfo profilerInfo, Bundle options) { 3523 3524 // This is very dangerous -- it allows you to perform a start activity (including 3525 // permission grants) as any app that may launch one of your own activities. So 3526 // we will only allow this to be done from activities that are part of the core framework, 3527 // and then only when they are running as the system. 3528 final ActivityRecord sourceRecord; 3529 final int targetUid; 3530 final String targetPackage; 3531 synchronized (this) { 3532 if (resultTo == null) { 3533 throw new SecurityException("Must be called from an activity"); 3534 } 3535 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo); 3536 if (sourceRecord == null) { 3537 throw new SecurityException("Called with bad activity token: " + resultTo); 3538 } 3539 if (!sourceRecord.info.packageName.equals("android")) { 3540 throw new SecurityException( 3541 "Must be called from an activity that is declared in the android package"); 3542 } 3543 if (sourceRecord.app == null) { 3544 throw new SecurityException("Called without a process attached to activity"); 3545 } 3546 if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) { 3547 // This is still okay, as long as this activity is running under the 3548 // uid of the original calling activity. 3549 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) { 3550 throw new SecurityException( 3551 "Calling activity in uid " + sourceRecord.app.uid 3552 + " must be system uid or original calling uid " 3553 + sourceRecord.launchedFromUid); 3554 } 3555 } 3556 targetUid = sourceRecord.launchedFromUid; 3557 targetPackage = sourceRecord.launchedFromPackage; 3558 } 3559 3560 // TODO: Switch to user app stacks here. 3561 try { 3562 int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent, 3563 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null, 3564 null, null, options, UserHandle.getUserId(sourceRecord.app.uid), null, null); 3565 return ret; 3566 } catch (SecurityException e) { 3567 // XXX need to figure out how to propagate to original app. 3568 // A SecurityException here is generally actually a fault of the original 3569 // calling activity (such as a fairly granting permissions), so propagate it 3570 // back to them. 3571 /* 3572 StringBuilder msg = new StringBuilder(); 3573 msg.append("While launching"); 3574 msg.append(intent.toString()); 3575 msg.append(": "); 3576 msg.append(e.getMessage()); 3577 */ 3578 throw e; 3579 } 3580 } 3581 3582 @Override 3583 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3584 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3585 int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { 3586 enforceNotIsolatedCaller("startActivityAndWait"); 3587 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3588 false, ALLOW_FULL_ONLY, "startActivityAndWait", null); 3589 WaitResult res = new WaitResult(); 3590 // TODO: Switch to user app stacks here. 3591 mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 3592 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null, 3593 options, userId, null, null); 3594 return res; 3595 } 3596 3597 @Override 3598 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 3599 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3600 int startFlags, Configuration config, Bundle options, int userId) { 3601 enforceNotIsolatedCaller("startActivityWithConfig"); 3602 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3603 false, ALLOW_FULL_ONLY, "startActivityWithConfig", null); 3604 // TODO: Switch to user app stacks here. 3605 int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, 3606 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3607 null, null, config, options, userId, null, null); 3608 return ret; 3609 } 3610 3611 @Override 3612 public int startActivityIntentSender(IApplicationThread caller, 3613 IntentSender intent, Intent fillInIntent, String resolvedType, 3614 IBinder resultTo, String resultWho, int requestCode, 3615 int flagsMask, int flagsValues, Bundle options) { 3616 enforceNotIsolatedCaller("startActivityIntentSender"); 3617 // Refuse possible leaked file descriptors 3618 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 3619 throw new IllegalArgumentException("File descriptors passed in Intent"); 3620 } 3621 3622 IIntentSender sender = intent.getTarget(); 3623 if (!(sender instanceof PendingIntentRecord)) { 3624 throw new IllegalArgumentException("Bad PendingIntent object"); 3625 } 3626 3627 PendingIntentRecord pir = (PendingIntentRecord)sender; 3628 3629 synchronized (this) { 3630 // If this is coming from the currently resumed activity, it is 3631 // effectively saying that app switches are allowed at this point. 3632 final ActivityStack stack = getFocusedStack(); 3633 if (stack.mResumedActivity != null && 3634 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) { 3635 mAppSwitchesAllowedTime = 0; 3636 } 3637 } 3638 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null, 3639 resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null); 3640 return ret; 3641 } 3642 3643 @Override 3644 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid, 3645 Intent intent, String resolvedType, IVoiceInteractionSession session, 3646 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, 3647 Bundle options, int userId) { 3648 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 3649 != PackageManager.PERMISSION_GRANTED) { 3650 String msg = "Permission Denial: startVoiceActivity() from pid=" 3651 + Binder.getCallingPid() 3652 + ", uid=" + Binder.getCallingUid() 3653 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION; 3654 Slog.w(TAG, msg); 3655 throw new SecurityException(msg); 3656 } 3657 if (session == null || interactor == null) { 3658 throw new NullPointerException("null session or interactor"); 3659 } 3660 userId = handleIncomingUser(callingPid, callingUid, userId, 3661 false, ALLOW_FULL_ONLY, "startVoiceActivity", null); 3662 // TODO: Switch to user app stacks here. 3663 return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent, 3664 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null, 3665 null, options, userId, null, null); 3666 } 3667 3668 @Override 3669 public boolean startNextMatchingActivity(IBinder callingActivity, 3670 Intent intent, Bundle options) { 3671 // Refuse possible leaked file descriptors 3672 if (intent != null && intent.hasFileDescriptors() == true) { 3673 throw new IllegalArgumentException("File descriptors passed in Intent"); 3674 } 3675 3676 synchronized (this) { 3677 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity); 3678 if (r == null) { 3679 ActivityOptions.abort(options); 3680 return false; 3681 } 3682 if (r.app == null || r.app.thread == null) { 3683 // The caller is not running... d'oh! 3684 ActivityOptions.abort(options); 3685 return false; 3686 } 3687 intent = new Intent(intent); 3688 // The caller is not allowed to change the data. 3689 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 3690 // And we are resetting to find the next component... 3691 intent.setComponent(null); 3692 3693 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3694 3695 ActivityInfo aInfo = null; 3696 try { 3697 List<ResolveInfo> resolves = 3698 AppGlobals.getPackageManager().queryIntentActivities( 3699 intent, r.resolvedType, 3700 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 3701 UserHandle.getCallingUserId()); 3702 3703 // Look for the original activity in the list... 3704 final int N = resolves != null ? resolves.size() : 0; 3705 for (int i=0; i<N; i++) { 3706 ResolveInfo rInfo = resolves.get(i); 3707 if (rInfo.activityInfo.packageName.equals(r.packageName) 3708 && rInfo.activityInfo.name.equals(r.info.name)) { 3709 // We found the current one... the next matching is 3710 // after it. 3711 i++; 3712 if (i<N) { 3713 aInfo = resolves.get(i).activityInfo; 3714 } 3715 if (debug) { 3716 Slog.v(TAG, "Next matching activity: found current " + r.packageName 3717 + "/" + r.info.name); 3718 Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName 3719 + "/" + aInfo.name); 3720 } 3721 break; 3722 } 3723 } 3724 } catch (RemoteException e) { 3725 } 3726 3727 if (aInfo == null) { 3728 // Nobody who is next! 3729 ActivityOptions.abort(options); 3730 if (debug) Slog.d(TAG, "Next matching activity: nothing found"); 3731 return false; 3732 } 3733 3734 intent.setComponent(new ComponentName( 3735 aInfo.applicationInfo.packageName, aInfo.name)); 3736 intent.setFlags(intent.getFlags()&~( 3737 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 3738 Intent.FLAG_ACTIVITY_CLEAR_TOP| 3739 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 3740 Intent.FLAG_ACTIVITY_NEW_TASK)); 3741 3742 // Okay now we need to start the new activity, replacing the 3743 // currently running activity. This is a little tricky because 3744 // we want to start the new one as if the current one is finished, 3745 // but not finish the current one first so that there is no flicker. 3746 // And thus... 3747 final boolean wasFinishing = r.finishing; 3748 r.finishing = true; 3749 3750 // Propagate reply information over to the new activity. 3751 final ActivityRecord resultTo = r.resultTo; 3752 final String resultWho = r.resultWho; 3753 final int requestCode = r.requestCode; 3754 r.resultTo = null; 3755 if (resultTo != null) { 3756 resultTo.removeResultsLocked(r, resultWho, requestCode); 3757 } 3758 3759 final long origId = Binder.clearCallingIdentity(); 3760 int res = mStackSupervisor.startActivityLocked(r.app.thread, intent, 3761 r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null, 3762 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0, 3763 options, false, null, null, null); 3764 Binder.restoreCallingIdentity(origId); 3765 3766 r.finishing = wasFinishing; 3767 if (res != ActivityManager.START_SUCCESS) { 3768 return false; 3769 } 3770 return true; 3771 } 3772 } 3773 3774 @Override 3775 public final int startActivityFromRecents(int taskId, Bundle options) { 3776 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) { 3777 String msg = "Permission Denial: startActivityFromRecents called without " + 3778 START_TASKS_FROM_RECENTS; 3779 Slog.w(TAG, msg); 3780 throw new SecurityException(msg); 3781 } 3782 return startActivityFromRecentsInner(taskId, options); 3783 } 3784 3785 final int startActivityFromRecentsInner(int taskId, Bundle options) { 3786 final TaskRecord task; 3787 final int callingUid; 3788 final String callingPackage; 3789 final Intent intent; 3790 final int userId; 3791 synchronized (this) { 3792 task = recentTaskForIdLocked(taskId); 3793 if (task == null) { 3794 throw new IllegalArgumentException("Task " + taskId + " not found."); 3795 } 3796 callingUid = task.mCallingUid; 3797 callingPackage = task.mCallingPackage; 3798 intent = task.intent; 3799 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 3800 userId = task.userId; 3801 } 3802 return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0, 3803 options, userId, null, task); 3804 } 3805 3806 final int startActivityInPackage(int uid, String callingPackage, 3807 Intent intent, String resolvedType, IBinder resultTo, 3808 String resultWho, int requestCode, int startFlags, Bundle options, int userId, 3809 IActivityContainer container, TaskRecord inTask) { 3810 3811 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3812 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 3813 3814 // TODO: Switch to user app stacks here. 3815 int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent, 3816 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3817 null, null, null, options, userId, container, inTask); 3818 return ret; 3819 } 3820 3821 @Override 3822 public final int startActivities(IApplicationThread caller, String callingPackage, 3823 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, 3824 int userId) { 3825 enforceNotIsolatedCaller("startActivities"); 3826 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3827 false, ALLOW_FULL_ONLY, "startActivity", null); 3828 // TODO: Switch to user app stacks here. 3829 int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents, 3830 resolvedTypes, resultTo, options, userId); 3831 return ret; 3832 } 3833 3834 final int startActivitiesInPackage(int uid, String callingPackage, 3835 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 3836 Bundle options, int userId) { 3837 3838 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3839 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 3840 // TODO: Switch to user app stacks here. 3841 int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes, 3842 resultTo, options, userId); 3843 return ret; 3844 } 3845 3846 //explicitly remove thd old information in mRecentTasks when removing existing user. 3847 private void removeRecentTasksForUserLocked(int userId) { 3848 if(userId <= 0) { 3849 Slog.i(TAG, "Can't remove recent task on user " + userId); 3850 return; 3851 } 3852 3853 for (int i = mRecentTasks.size() - 1; i >= 0; --i) { 3854 TaskRecord tr = mRecentTasks.get(i); 3855 if (tr.userId == userId) { 3856 if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr 3857 + " when finishing user" + userId); 3858 mRecentTasks.remove(i); 3859 tr.removedFromRecents(mTaskPersister); 3860 } 3861 } 3862 3863 // Remove tasks from persistent storage. 3864 mTaskPersister.wakeup(null, true); 3865 } 3866 3867 // Sort by taskId 3868 private Comparator<TaskRecord> mTaskRecordComparator = new Comparator<TaskRecord>() { 3869 @Override 3870 public int compare(TaskRecord lhs, TaskRecord rhs) { 3871 return rhs.taskId - lhs.taskId; 3872 } 3873 }; 3874 3875 // Extract the affiliates of the chain containing mRecentTasks[start]. 3876 private int processNextAffiliateChain(int start) { 3877 final TaskRecord startTask = mRecentTasks.get(start); 3878 final int affiliateId = startTask.mAffiliatedTaskId; 3879 3880 // Quick identification of isolated tasks. I.e. those not launched behind. 3881 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null && 3882 startTask.mNextAffiliate == null) { 3883 // There is still a slim chance that there are other tasks that point to this task 3884 // and that the chain is so messed up that this task no longer points to them but 3885 // the gain of this optimization outweighs the risk. 3886 startTask.inRecents = true; 3887 return start + 1; 3888 } 3889 3890 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents. 3891 mTmpRecents.clear(); 3892 for (int i = mRecentTasks.size() - 1; i >= start; --i) { 3893 final TaskRecord task = mRecentTasks.get(i); 3894 if (task.mAffiliatedTaskId == affiliateId) { 3895 mRecentTasks.remove(i); 3896 mTmpRecents.add(task); 3897 } 3898 } 3899 3900 // Sort them all by taskId. That is the order they were create in and that order will 3901 // always be correct. 3902 Collections.sort(mTmpRecents, mTaskRecordComparator); 3903 3904 // Go through and fix up the linked list. 3905 // The first one is the end of the chain and has no next. 3906 final TaskRecord first = mTmpRecents.get(0); 3907 first.inRecents = true; 3908 if (first.mNextAffiliate != null) { 3909 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate); 3910 first.setNextAffiliate(null); 3911 mTaskPersister.wakeup(first, false); 3912 } 3913 // Everything in the middle is doubly linked from next to prev. 3914 final int tmpSize = mTmpRecents.size(); 3915 for (int i = 0; i < tmpSize - 1; ++i) { 3916 final TaskRecord next = mTmpRecents.get(i); 3917 final TaskRecord prev = mTmpRecents.get(i + 1); 3918 if (next.mPrevAffiliate != prev) { 3919 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate + 3920 " setting prev=" + prev); 3921 next.setPrevAffiliate(prev); 3922 mTaskPersister.wakeup(next, false); 3923 } 3924 if (prev.mNextAffiliate != next) { 3925 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate + 3926 " setting next=" + next); 3927 prev.setNextAffiliate(next); 3928 mTaskPersister.wakeup(prev, false); 3929 } 3930 prev.inRecents = true; 3931 } 3932 // The last one is the beginning of the list and has no prev. 3933 final TaskRecord last = mTmpRecents.get(tmpSize - 1); 3934 if (last.mPrevAffiliate != null) { 3935 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate); 3936 last.setPrevAffiliate(null); 3937 mTaskPersister.wakeup(last, false); 3938 } 3939 3940 // Insert the group back into mRecentTasks at start. 3941 mRecentTasks.addAll(start, mTmpRecents); 3942 3943 // Let the caller know where we left off. 3944 return start + tmpSize; 3945 } 3946 3947 /** 3948 * Update the recent tasks lists: make sure tasks should still be here (their 3949 * applications / activities still exist), update their availability, fixup ordering 3950 * of affiliations. 3951 */ 3952 void cleanupRecentTasksLocked(int userId) { 3953 if (mRecentTasks == null) { 3954 // Happens when called from the packagemanager broadcast before boot. 3955 return; 3956 } 3957 3958 final HashMap<ComponentName, ActivityInfo> availActCache = new HashMap<>(); 3959 final HashMap<String, ApplicationInfo> availAppCache = new HashMap<>(); 3960 final IPackageManager pm = AppGlobals.getPackageManager(); 3961 final ActivityInfo dummyAct = new ActivityInfo(); 3962 final ApplicationInfo dummyApp = new ApplicationInfo(); 3963 3964 int N = mRecentTasks.size(); 3965 3966 int[] users = userId == UserHandle.USER_ALL 3967 ? getUsersLocked() : new int[] { userId }; 3968 for (int user : users) { 3969 for (int i = 0; i < N; i++) { 3970 TaskRecord task = mRecentTasks.get(i); 3971 if (task.userId != user) { 3972 // Only look at tasks for the user ID of interest. 3973 continue; 3974 } 3975 if (task.autoRemoveRecents && task.getTopActivity() == null) { 3976 // This situation is broken, and we should just get rid of it now. 3977 mRecentTasks.remove(i); 3978 task.removedFromRecents(mTaskPersister); 3979 i--; 3980 N--; 3981 Slog.w(TAG, "Removing auto-remove without activity: " + task); 3982 continue; 3983 } 3984 // Check whether this activity is currently available. 3985 if (task.realActivity != null) { 3986 ActivityInfo ai = availActCache.get(task.realActivity); 3987 if (ai == null) { 3988 try { 3989 ai = pm.getActivityInfo(task.realActivity, 3990 PackageManager.GET_UNINSTALLED_PACKAGES 3991 | PackageManager.GET_DISABLED_COMPONENTS, user); 3992 } catch (RemoteException e) { 3993 // Will never happen. 3994 continue; 3995 } 3996 if (ai == null) { 3997 ai = dummyAct; 3998 } 3999 availActCache.put(task.realActivity, ai); 4000 } 4001 if (ai == dummyAct) { 4002 // This could be either because the activity no longer exists, or the 4003 // app is temporarily gone. For the former we want to remove the recents 4004 // entry; for the latter we want to mark it as unavailable. 4005 ApplicationInfo app = availAppCache.get(task.realActivity.getPackageName()); 4006 if (app == null) { 4007 try { 4008 app = pm.getApplicationInfo(task.realActivity.getPackageName(), 4009 PackageManager.GET_UNINSTALLED_PACKAGES 4010 | PackageManager.GET_DISABLED_COMPONENTS, user); 4011 } catch (RemoteException e) { 4012 // Will never happen. 4013 continue; 4014 } 4015 if (app == null) { 4016 app = dummyApp; 4017 } 4018 availAppCache.put(task.realActivity.getPackageName(), app); 4019 } 4020 if (app == dummyApp || (app.flags&ApplicationInfo.FLAG_INSTALLED) == 0) { 4021 // Doesn't exist any more! Good-bye. 4022 mRecentTasks.remove(i); 4023 task.removedFromRecents(mTaskPersister); 4024 i--; 4025 N--; 4026 Slog.w(TAG, "Removing no longer valid recent: " + task); 4027 continue; 4028 } else { 4029 // Otherwise just not available for now. 4030 if (task.isAvailable) { 4031 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: " 4032 + task); 4033 } 4034 task.isAvailable = false; 4035 } 4036 } else { 4037 if (!ai.enabled || !ai.applicationInfo.enabled 4038 || (ai.applicationInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) { 4039 if (task.isAvailable) { 4040 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: " 4041 + task + " (enabled=" + ai.enabled + "/" 4042 + ai.applicationInfo.enabled + " flags=" 4043 + Integer.toHexString(ai.applicationInfo.flags) + ")"); 4044 } 4045 task.isAvailable = false; 4046 } else { 4047 if (!task.isAvailable) { 4048 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent available: " 4049 + task); 4050 } 4051 task.isAvailable = true; 4052 } 4053 } 4054 } 4055 } 4056 } 4057 4058 // Verify the affiliate chain for each task. 4059 for (int i = 0; i < N; i = processNextAffiliateChain(i)) { 4060 } 4061 4062 mTmpRecents.clear(); 4063 // mRecentTasks is now in sorted, affiliated order. 4064 } 4065 4066 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) { 4067 int N = mRecentTasks.size(); 4068 TaskRecord top = task; 4069 int topIndex = taskIndex; 4070 while (top.mNextAffiliate != null && topIndex > 0) { 4071 top = top.mNextAffiliate; 4072 topIndex--; 4073 } 4074 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding affilliates starting at " 4075 + topIndex + " from intial " + taskIndex); 4076 // Find the end of the chain, doing a sanity check along the way. 4077 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId; 4078 int endIndex = topIndex; 4079 TaskRecord prev = top; 4080 while (endIndex < N) { 4081 TaskRecord cur = mRecentTasks.get(endIndex); 4082 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: looking at next chain @" 4083 + endIndex + " " + cur); 4084 if (cur == top) { 4085 // Verify start of the chain. 4086 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != -1) { 4087 Slog.wtf(TAG, "Bad chain @" + endIndex 4088 + ": first task has next affiliate: " + prev); 4089 sane = false; 4090 break; 4091 } 4092 } else { 4093 // Verify middle of the chain's next points back to the one before. 4094 if (cur.mNextAffiliate != prev 4095 || cur.mNextAffiliateTaskId != prev.taskId) { 4096 Slog.wtf(TAG, "Bad chain @" + endIndex 4097 + ": middle task " + cur + " @" + endIndex 4098 + " has bad next affiliate " 4099 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId 4100 + ", expected " + prev); 4101 sane = false; 4102 break; 4103 } 4104 } 4105 if (cur.mPrevAffiliateTaskId == -1) { 4106 // Chain ends here. 4107 if (cur.mPrevAffiliate != null) { 4108 Slog.wtf(TAG, "Bad chain @" + endIndex 4109 + ": last task " + cur + " has previous affiliate " 4110 + cur.mPrevAffiliate); 4111 sane = false; 4112 } 4113 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: end of chain @" + endIndex); 4114 break; 4115 } else { 4116 // Verify middle of the chain's prev points to a valid item. 4117 if (cur.mPrevAffiliate == null) { 4118 Slog.wtf(TAG, "Bad chain @" + endIndex 4119 + ": task " + cur + " has previous affiliate " 4120 + cur.mPrevAffiliate + " but should be id " 4121 + cur.mPrevAffiliate); 4122 sane = false; 4123 break; 4124 } 4125 } 4126 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) { 4127 Slog.wtf(TAG, "Bad chain @" + endIndex 4128 + ": task " + cur + " has affiliated id " 4129 + cur.mAffiliatedTaskId + " but should be " 4130 + task.mAffiliatedTaskId); 4131 sane = false; 4132 break; 4133 } 4134 prev = cur; 4135 endIndex++; 4136 if (endIndex >= N) { 4137 Slog.wtf(TAG, "Bad chain ran off index " + endIndex 4138 + ": last task " + prev); 4139 sane = false; 4140 break; 4141 } 4142 } 4143 if (sane) { 4144 if (endIndex < taskIndex) { 4145 Slog.wtf(TAG, "Bad chain @" + endIndex 4146 + ": did not extend to task " + task + " @" + taskIndex); 4147 sane = false; 4148 } 4149 } 4150 if (sane) { 4151 // All looks good, we can just move all of the affiliated tasks 4152 // to the top. 4153 for (int i=topIndex; i<=endIndex; i++) { 4154 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving affiliated " + task 4155 + " from " + i + " to " + (i-topIndex)); 4156 TaskRecord cur = mRecentTasks.remove(i); 4157 mRecentTasks.add(i-topIndex, cur); 4158 } 4159 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: done moving tasks " + topIndex 4160 + " to " + endIndex); 4161 return true; 4162 } 4163 4164 // Whoops, couldn't do it. 4165 return false; 4166 } 4167 4168 final void addRecentTaskLocked(TaskRecord task) { 4169 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId 4170 || task.mNextAffiliateTaskId != -1 || task.mPrevAffiliateTaskId != -1; 4171 4172 int N = mRecentTasks.size(); 4173 // Quick case: check if the top-most recent task is the same. 4174 if (!isAffiliated && N > 0 && mRecentTasks.get(0) == task) { 4175 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: already at top: " + task); 4176 return; 4177 } 4178 // Another quick case: check if this is part of a set of affiliated 4179 // tasks that are at the top. 4180 if (isAffiliated && N > 0 && task.inRecents 4181 && task.mAffiliatedTaskId == mRecentTasks.get(0).mAffiliatedTaskId) { 4182 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: affiliated " + mRecentTasks.get(0) 4183 + " at top when adding " + task); 4184 return; 4185 } 4186 // Another quick case: never add voice sessions. 4187 if (task.voiceSession != null) { 4188 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: not adding voice interaction " + task); 4189 return; 4190 } 4191 4192 boolean needAffiliationFix = false; 4193 4194 // Slightly less quick case: the task is already in recents, so all we need 4195 // to do is move it. 4196 if (task.inRecents) { 4197 int taskIndex = mRecentTasks.indexOf(task); 4198 if (taskIndex >= 0) { 4199 if (!isAffiliated) { 4200 // Simple case: this is not an affiliated task, so we just move it to the front. 4201 mRecentTasks.remove(taskIndex); 4202 mRecentTasks.add(0, task); 4203 notifyTaskPersisterLocked(task, false); 4204 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving to top " + task 4205 + " from " + taskIndex); 4206 return; 4207 } else { 4208 // More complicated: need to keep all affiliated tasks together. 4209 if (moveAffiliatedTasksToFront(task, taskIndex)) { 4210 // All went well. 4211 return; 4212 } 4213 4214 // Uh oh... something bad in the affiliation chain, try to rebuild 4215 // everything and then go through our general path of adding a new task. 4216 needAffiliationFix = true; 4217 } 4218 } else { 4219 Slog.wtf(TAG, "Task with inRecent not in recents: " + task); 4220 needAffiliationFix = true; 4221 } 4222 } 4223 4224 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: trimming tasks for " + task); 4225 trimRecentsForTask(task, true); 4226 4227 N = mRecentTasks.size(); 4228 while (N >= ActivityManager.getMaxRecentTasksStatic()) { 4229 final TaskRecord tr = mRecentTasks.remove(N - 1); 4230 tr.removedFromRecents(mTaskPersister); 4231 N--; 4232 } 4233 task.inRecents = true; 4234 if (!isAffiliated || needAffiliationFix) { 4235 // If this is a simple non-affiliated task, or we had some failure trying to 4236 // handle it as part of an affilated task, then just place it at the top. 4237 mRecentTasks.add(0, task); 4238 } else if (isAffiliated) { 4239 // If this is a new affiliated task, then move all of the affiliated tasks 4240 // to the front and insert this new one. 4241 TaskRecord other = task.mNextAffiliate; 4242 if (other == null) { 4243 other = task.mPrevAffiliate; 4244 } 4245 if (other != null) { 4246 int otherIndex = mRecentTasks.indexOf(other); 4247 if (otherIndex >= 0) { 4248 // Insert new task at appropriate location. 4249 int taskIndex; 4250 if (other == task.mNextAffiliate) { 4251 // We found the index of our next affiliation, which is who is 4252 // before us in the list, so add after that point. 4253 taskIndex = otherIndex+1; 4254 } else { 4255 // We found the index of our previous affiliation, which is who is 4256 // after us in the list, so add at their position. 4257 taskIndex = otherIndex; 4258 } 4259 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: new affiliated task added at " 4260 + taskIndex + ": " + task); 4261 mRecentTasks.add(taskIndex, task); 4262 4263 // Now move everything to the front. 4264 if (moveAffiliatedTasksToFront(task, taskIndex)) { 4265 // All went well. 4266 return; 4267 } 4268 4269 // Uh oh... something bad in the affiliation chain, try to rebuild 4270 // everything and then go through our general path of adding a new task. 4271 needAffiliationFix = true; 4272 } else { 4273 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: couldn't find other affiliation " 4274 + other); 4275 needAffiliationFix = true; 4276 } 4277 } else { 4278 if (DEBUG_RECENTS) Slog.d(TAG, 4279 "addRecent: adding affiliated task without next/prev:" + task); 4280 needAffiliationFix = true; 4281 } 4282 } 4283 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding " + task); 4284 4285 if (needAffiliationFix) { 4286 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: regrouping affiliations"); 4287 cleanupRecentTasksLocked(task.userId); 4288 } 4289 } 4290 4291 /** 4292 * If needed, remove oldest existing entries in recents that are for the same kind 4293 * of task as the given one. 4294 */ 4295 int trimRecentsForTask(TaskRecord task, boolean doTrim) { 4296 int N = mRecentTasks.size(); 4297 final Intent intent = task.intent; 4298 final boolean document = intent != null && intent.isDocument(); 4299 4300 int maxRecents = task.maxRecents - 1; 4301 for (int i=0; i<N; i++) { 4302 final TaskRecord tr = mRecentTasks.get(i); 4303 if (task != tr) { 4304 if (task.userId != tr.userId) { 4305 continue; 4306 } 4307 if (i > MAX_RECENT_BITMAPS) { 4308 tr.freeLastThumbnail(); 4309 } 4310 final Intent trIntent = tr.intent; 4311 if ((task.affinity == null || !task.affinity.equals(tr.affinity)) && 4312 (intent == null || !intent.filterEquals(trIntent))) { 4313 continue; 4314 } 4315 final boolean trIsDocument = trIntent != null && trIntent.isDocument(); 4316 if (document && trIsDocument) { 4317 // These are the same document activity (not necessarily the same doc). 4318 if (maxRecents > 0) { 4319 --maxRecents; 4320 continue; 4321 } 4322 // Hit the maximum number of documents for this task. Fall through 4323 // and remove this document from recents. 4324 } else if (document || trIsDocument) { 4325 // Only one of these is a document. Not the droid we're looking for. 4326 continue; 4327 } 4328 } 4329 4330 if (!doTrim) { 4331 // If the caller is not actually asking for a trim, just tell them we reached 4332 // a point where the trim would happen. 4333 return i; 4334 } 4335 4336 // Either task and tr are the same or, their affinities match or their intents match 4337 // and neither of them is a document, or they are documents using the same activity 4338 // and their maxRecents has been reached. 4339 tr.disposeThumbnail(); 4340 mRecentTasks.remove(i); 4341 if (task != tr) { 4342 tr.removedFromRecents(mTaskPersister); 4343 } 4344 i--; 4345 N--; 4346 if (task.intent == null) { 4347 // If the new recent task we are adding is not fully 4348 // specified, then replace it with the existing recent task. 4349 task = tr; 4350 } 4351 notifyTaskPersisterLocked(tr, false); 4352 } 4353 4354 return -1; 4355 } 4356 4357 @Override 4358 public void reportActivityFullyDrawn(IBinder token) { 4359 synchronized (this) { 4360 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4361 if (r == null) { 4362 return; 4363 } 4364 r.reportFullyDrawnLocked(); 4365 } 4366 } 4367 4368 @Override 4369 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 4370 synchronized (this) { 4371 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4372 if (r == null) { 4373 return; 4374 } 4375 final long origId = Binder.clearCallingIdentity(); 4376 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 4377 Configuration config = mWindowManager.updateOrientationFromAppTokens( 4378 mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 4379 if (config != null) { 4380 r.frozenBeforeDestroy = true; 4381 if (!updateConfigurationLocked(config, r, false, false)) { 4382 mStackSupervisor.resumeTopActivitiesLocked(); 4383 } 4384 } 4385 Binder.restoreCallingIdentity(origId); 4386 } 4387 } 4388 4389 @Override 4390 public int getRequestedOrientation(IBinder token) { 4391 synchronized (this) { 4392 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4393 if (r == null) { 4394 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 4395 } 4396 return mWindowManager.getAppOrientation(r.appToken); 4397 } 4398 } 4399 4400 /** 4401 * This is the internal entry point for handling Activity.finish(). 4402 * 4403 * @param token The Binder token referencing the Activity we want to finish. 4404 * @param resultCode Result code, if any, from this Activity. 4405 * @param resultData Result data (Intent), if any, from this Activity. 4406 * @param finishTask Whether to finish the task associated with this Activity. Only applies to 4407 * the root Activity in the task. 4408 * 4409 * @return Returns true if the activity successfully finished, or false if it is still running. 4410 */ 4411 @Override 4412 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 4413 boolean finishTask) { 4414 // Refuse possible leaked file descriptors 4415 if (resultData != null && resultData.hasFileDescriptors() == true) { 4416 throw new IllegalArgumentException("File descriptors passed in Intent"); 4417 } 4418 4419 synchronized(this) { 4420 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4421 if (r == null) { 4422 return true; 4423 } 4424 // Keep track of the root activity of the task before we finish it 4425 TaskRecord tr = r.task; 4426 ActivityRecord rootR = tr.getRootActivity(); 4427 // Do not allow task to finish in Lock Task mode. 4428 if (tr == mStackSupervisor.mLockTaskModeTask) { 4429 if (rootR == r) { 4430 mStackSupervisor.showLockTaskToast(); 4431 return false; 4432 } 4433 } 4434 if (mController != null) { 4435 // Find the first activity that is not finishing. 4436 ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0); 4437 if (next != null) { 4438 // ask watcher if this is allowed 4439 boolean resumeOK = true; 4440 try { 4441 resumeOK = mController.activityResuming(next.packageName); 4442 } catch (RemoteException e) { 4443 mController = null; 4444 Watchdog.getInstance().setActivityController(null); 4445 } 4446 4447 if (!resumeOK) { 4448 return false; 4449 } 4450 } 4451 } 4452 final long origId = Binder.clearCallingIdentity(); 4453 try { 4454 boolean res; 4455 if (finishTask && r == rootR) { 4456 // If requested, remove the task that is associated to this activity only if it 4457 // was the root activity in the task. The result code and data is ignored because 4458 // we don't support returning them across task boundaries. 4459 res = removeTaskByIdLocked(tr.taskId, 0); 4460 } else { 4461 res = tr.stack.requestFinishActivityLocked(token, resultCode, 4462 resultData, "app-request", true); 4463 } 4464 return res; 4465 } finally { 4466 Binder.restoreCallingIdentity(origId); 4467 } 4468 } 4469 } 4470 4471 @Override 4472 public final void finishHeavyWeightApp() { 4473 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4474 != PackageManager.PERMISSION_GRANTED) { 4475 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 4476 + Binder.getCallingPid() 4477 + ", uid=" + Binder.getCallingUid() 4478 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4479 Slog.w(TAG, msg); 4480 throw new SecurityException(msg); 4481 } 4482 4483 synchronized(this) { 4484 if (mHeavyWeightProcess == null) { 4485 return; 4486 } 4487 4488 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>( 4489 mHeavyWeightProcess.activities); 4490 for (int i=0; i<activities.size(); i++) { 4491 ActivityRecord r = activities.get(i); 4492 if (!r.finishing) { 4493 r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED, 4494 null, "finish-heavy", true); 4495 } 4496 } 4497 4498 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4499 mHeavyWeightProcess.userId, 0)); 4500 mHeavyWeightProcess = null; 4501 } 4502 } 4503 4504 @Override 4505 public void crashApplication(int uid, int initialPid, String packageName, 4506 String message) { 4507 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4508 != PackageManager.PERMISSION_GRANTED) { 4509 String msg = "Permission Denial: crashApplication() from pid=" 4510 + Binder.getCallingPid() 4511 + ", uid=" + Binder.getCallingUid() 4512 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4513 Slog.w(TAG, msg); 4514 throw new SecurityException(msg); 4515 } 4516 4517 synchronized(this) { 4518 ProcessRecord proc = null; 4519 4520 // Figure out which process to kill. We don't trust that initialPid 4521 // still has any relation to current pids, so must scan through the 4522 // list. 4523 synchronized (mPidsSelfLocked) { 4524 for (int i=0; i<mPidsSelfLocked.size(); i++) { 4525 ProcessRecord p = mPidsSelfLocked.valueAt(i); 4526 if (p.uid != uid) { 4527 continue; 4528 } 4529 if (p.pid == initialPid) { 4530 proc = p; 4531 break; 4532 } 4533 if (p.pkgList.containsKey(packageName)) { 4534 proc = p; 4535 } 4536 } 4537 } 4538 4539 if (proc == null) { 4540 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 4541 + " initialPid=" + initialPid 4542 + " packageName=" + packageName); 4543 return; 4544 } 4545 4546 if (proc.thread != null) { 4547 if (proc.pid == Process.myPid()) { 4548 Log.w(TAG, "crashApplication: trying to crash self!"); 4549 return; 4550 } 4551 long ident = Binder.clearCallingIdentity(); 4552 try { 4553 proc.thread.scheduleCrash(message); 4554 } catch (RemoteException e) { 4555 } 4556 Binder.restoreCallingIdentity(ident); 4557 } 4558 } 4559 } 4560 4561 @Override 4562 public final void finishSubActivity(IBinder token, String resultWho, 4563 int requestCode) { 4564 synchronized(this) { 4565 final long origId = Binder.clearCallingIdentity(); 4566 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4567 if (r != null) { 4568 r.task.stack.finishSubActivityLocked(r, resultWho, requestCode); 4569 } 4570 Binder.restoreCallingIdentity(origId); 4571 } 4572 } 4573 4574 @Override 4575 public boolean finishActivityAffinity(IBinder token) { 4576 synchronized(this) { 4577 final long origId = Binder.clearCallingIdentity(); 4578 try { 4579 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4580 4581 ActivityRecord rootR = r.task.getRootActivity(); 4582 // Do not allow task to finish in Lock Task mode. 4583 if (r.task == mStackSupervisor.mLockTaskModeTask) { 4584 if (rootR == r) { 4585 mStackSupervisor.showLockTaskToast(); 4586 return false; 4587 } 4588 } 4589 boolean res = false; 4590 if (r != null) { 4591 res = r.task.stack.finishActivityAffinityLocked(r); 4592 } 4593 return res; 4594 } finally { 4595 Binder.restoreCallingIdentity(origId); 4596 } 4597 } 4598 } 4599 4600 @Override 4601 public void finishVoiceTask(IVoiceInteractionSession session) { 4602 synchronized(this) { 4603 final long origId = Binder.clearCallingIdentity(); 4604 try { 4605 mStackSupervisor.finishVoiceTask(session); 4606 } finally { 4607 Binder.restoreCallingIdentity(origId); 4608 } 4609 } 4610 4611 } 4612 4613 @Override 4614 public boolean releaseActivityInstance(IBinder token) { 4615 synchronized(this) { 4616 final long origId = Binder.clearCallingIdentity(); 4617 try { 4618 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4619 if (r.task == null || r.task.stack == null) { 4620 return false; 4621 } 4622 return r.task.stack.safelyDestroyActivityLocked(r, "app-req"); 4623 } finally { 4624 Binder.restoreCallingIdentity(origId); 4625 } 4626 } 4627 } 4628 4629 @Override 4630 public void releaseSomeActivities(IApplicationThread appInt) { 4631 synchronized(this) { 4632 final long origId = Binder.clearCallingIdentity(); 4633 try { 4634 ProcessRecord app = getRecordForAppLocked(appInt); 4635 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem"); 4636 } finally { 4637 Binder.restoreCallingIdentity(origId); 4638 } 4639 } 4640 } 4641 4642 @Override 4643 public boolean willActivityBeVisible(IBinder token) { 4644 synchronized(this) { 4645 ActivityStack stack = ActivityRecord.getStackLocked(token); 4646 if (stack != null) { 4647 return stack.willActivityBeVisibleLocked(token); 4648 } 4649 return false; 4650 } 4651 } 4652 4653 @Override 4654 public void overridePendingTransition(IBinder token, String packageName, 4655 int enterAnim, int exitAnim) { 4656 synchronized(this) { 4657 ActivityRecord self = ActivityRecord.isInStackLocked(token); 4658 if (self == null) { 4659 return; 4660 } 4661 4662 final long origId = Binder.clearCallingIdentity(); 4663 4664 if (self.state == ActivityState.RESUMED 4665 || self.state == ActivityState.PAUSING) { 4666 mWindowManager.overridePendingAppTransition(packageName, 4667 enterAnim, exitAnim, null); 4668 } 4669 4670 Binder.restoreCallingIdentity(origId); 4671 } 4672 } 4673 4674 /** 4675 * Main function for removing an existing process from the activity manager 4676 * as a result of that process going away. Clears out all connections 4677 * to the process. 4678 */ 4679 private final void handleAppDiedLocked(ProcessRecord app, 4680 boolean restarting, boolean allowRestart) { 4681 int pid = app.pid; 4682 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 4683 if (!restarting) { 4684 removeLruProcessLocked(app); 4685 if (pid > 0) { 4686 ProcessList.remove(pid); 4687 } 4688 } 4689 4690 if (mProfileProc == app) { 4691 clearProfilerLocked(); 4692 } 4693 4694 // Remove this application's activities from active lists. 4695 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app); 4696 4697 app.activities.clear(); 4698 4699 if (app.instrumentationClass != null) { 4700 Slog.w(TAG, "Crash of app " + app.processName 4701 + " running instrumentation " + app.instrumentationClass); 4702 Bundle info = new Bundle(); 4703 info.putString("shortMsg", "Process crashed."); 4704 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4705 } 4706 4707 if (!restarting) { 4708 if (!mStackSupervisor.resumeTopActivitiesLocked()) { 4709 // If there was nothing to resume, and we are not already 4710 // restarting this process, but there is a visible activity that 4711 // is hosted by the process... then make sure all visible 4712 // activities are running, taking care of restarting this 4713 // process. 4714 if (hasVisibleActivities) { 4715 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 4716 } 4717 } 4718 } 4719 } 4720 4721 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 4722 IBinder threadBinder = thread.asBinder(); 4723 // Find the application record. 4724 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4725 ProcessRecord rec = mLruProcesses.get(i); 4726 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 4727 return i; 4728 } 4729 } 4730 return -1; 4731 } 4732 4733 final ProcessRecord getRecordForAppLocked( 4734 IApplicationThread thread) { 4735 if (thread == null) { 4736 return null; 4737 } 4738 4739 int appIndex = getLRURecordIndexForAppLocked(thread); 4740 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 4741 } 4742 4743 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 4744 // If there are no longer any background processes running, 4745 // and the app that died was not running instrumentation, 4746 // then tell everyone we are now low on memory. 4747 boolean haveBg = false; 4748 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4749 ProcessRecord rec = mLruProcesses.get(i); 4750 if (rec.thread != null 4751 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 4752 haveBg = true; 4753 break; 4754 } 4755 } 4756 4757 if (!haveBg) { 4758 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 4759 if (doReport) { 4760 long now = SystemClock.uptimeMillis(); 4761 if (now < (mLastMemUsageReportTime+5*60*1000)) { 4762 doReport = false; 4763 } else { 4764 mLastMemUsageReportTime = now; 4765 } 4766 } 4767 final ArrayList<ProcessMemInfo> memInfos 4768 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null; 4769 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 4770 long now = SystemClock.uptimeMillis(); 4771 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4772 ProcessRecord rec = mLruProcesses.get(i); 4773 if (rec == dyingProc || rec.thread == null) { 4774 continue; 4775 } 4776 if (doReport) { 4777 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 4778 rec.setProcState, rec.adjType, rec.makeAdjReason())); 4779 } 4780 if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 4781 // The low memory report is overriding any current 4782 // state for a GC request. Make sure to do 4783 // heavy/important/visible/foreground processes first. 4784 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 4785 rec.lastRequestedGc = 0; 4786 } else { 4787 rec.lastRequestedGc = rec.lastLowMemory; 4788 } 4789 rec.reportLowMemory = true; 4790 rec.lastLowMemory = now; 4791 mProcessesToGc.remove(rec); 4792 addProcessToGcListLocked(rec); 4793 } 4794 } 4795 if (doReport) { 4796 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 4797 mHandler.sendMessage(msg); 4798 } 4799 scheduleAppGcsLocked(); 4800 } 4801 } 4802 4803 final void appDiedLocked(ProcessRecord app) { 4804 appDiedLocked(app, app.pid, app.thread); 4805 } 4806 4807 final void appDiedLocked(ProcessRecord app, int pid, 4808 IApplicationThread thread) { 4809 4810 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 4811 synchronized (stats) { 4812 stats.noteProcessDiedLocked(app.info.uid, pid); 4813 } 4814 4815 Process.killProcessGroup(app.info.uid, pid); 4816 4817 // Clean up already done if the process has been re-started. 4818 if (app.pid == pid && app.thread != null && 4819 app.thread.asBinder() == thread.asBinder()) { 4820 boolean doLowMem = app.instrumentationClass == null; 4821 boolean doOomAdj = doLowMem; 4822 if (!app.killedByAm) { 4823 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4824 + ") has died."); 4825 mAllowLowerMemLevel = true; 4826 } else { 4827 // Note that we always want to do oom adj to update our state with the 4828 // new number of procs. 4829 mAllowLowerMemLevel = false; 4830 doLowMem = false; 4831 } 4832 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4833 if (DEBUG_CLEANUP) Slog.v( 4834 TAG, "Dying app: " + app + ", pid: " + pid 4835 + ", thread: " + thread.asBinder()); 4836 handleAppDiedLocked(app, false, true); 4837 4838 if (doOomAdj) { 4839 updateOomAdjLocked(); 4840 } 4841 if (doLowMem) { 4842 doLowMemReportIfNeededLocked(app); 4843 } 4844 } else if (app.pid != pid) { 4845 // A new process has already been started. 4846 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4847 + ") has died and restarted (pid " + app.pid + ")."); 4848 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4849 } else if (DEBUG_PROCESSES) { 4850 Slog.d(TAG, "Received spurious death notification for thread " 4851 + thread.asBinder()); 4852 } 4853 } 4854 4855 /** 4856 * If a stack trace dump file is configured, dump process stack traces. 4857 * @param clearTraces causes the dump file to be erased prior to the new 4858 * traces being written, if true; when false, the new traces will be 4859 * appended to any existing file content. 4860 * @param firstPids of dalvik VM processes to dump stack traces for first 4861 * @param lastPids of dalvik VM processes to dump stack traces for last 4862 * @param nativeProcs optional list of native process names to dump stack crawls 4863 * @return file containing stack traces, or null if no dump file is configured 4864 */ 4865 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 4866 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4867 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4868 if (tracesPath == null || tracesPath.length() == 0) { 4869 return null; 4870 } 4871 4872 File tracesFile = new File(tracesPath); 4873 try { 4874 File tracesDir = tracesFile.getParentFile(); 4875 if (!tracesDir.exists()) { 4876 tracesDir.mkdirs(); 4877 if (!SELinux.restorecon(tracesDir)) { 4878 return null; 4879 } 4880 } 4881 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4882 4883 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 4884 tracesFile.createNewFile(); 4885 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 4886 } catch (IOException e) { 4887 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 4888 return null; 4889 } 4890 4891 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs); 4892 return tracesFile; 4893 } 4894 4895 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 4896 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4897 // Use a FileObserver to detect when traces finish writing. 4898 // The order of traces is considered important to maintain for legibility. 4899 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 4900 @Override 4901 public synchronized void onEvent(int event, String path) { notify(); } 4902 }; 4903 4904 try { 4905 observer.startWatching(); 4906 4907 // First collect all of the stacks of the most important pids. 4908 if (firstPids != null) { 4909 try { 4910 int num = firstPids.size(); 4911 for (int i = 0; i < num; i++) { 4912 synchronized (observer) { 4913 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 4914 observer.wait(200); // Wait for write-close, give up after 200msec 4915 } 4916 } 4917 } catch (InterruptedException e) { 4918 Log.wtf(TAG, e); 4919 } 4920 } 4921 4922 // Next collect the stacks of the native pids 4923 if (nativeProcs != null) { 4924 int[] pids = Process.getPidsForCommands(nativeProcs); 4925 if (pids != null) { 4926 for (int pid : pids) { 4927 Debug.dumpNativeBacktraceToFile(pid, tracesPath); 4928 } 4929 } 4930 } 4931 4932 // Lastly, measure CPU usage. 4933 if (processCpuTracker != null) { 4934 processCpuTracker.init(); 4935 System.gc(); 4936 processCpuTracker.update(); 4937 try { 4938 synchronized (processCpuTracker) { 4939 processCpuTracker.wait(500); // measure over 1/2 second. 4940 } 4941 } catch (InterruptedException e) { 4942 } 4943 processCpuTracker.update(); 4944 4945 // We'll take the stack crawls of just the top apps using CPU. 4946 final int N = processCpuTracker.countWorkingStats(); 4947 int numProcs = 0; 4948 for (int i=0; i<N && numProcs<5; i++) { 4949 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 4950 if (lastPids.indexOfKey(stats.pid) >= 0) { 4951 numProcs++; 4952 try { 4953 synchronized (observer) { 4954 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 4955 observer.wait(200); // Wait for write-close, give up after 200msec 4956 } 4957 } catch (InterruptedException e) { 4958 Log.wtf(TAG, e); 4959 } 4960 4961 } 4962 } 4963 } 4964 } finally { 4965 observer.stopWatching(); 4966 } 4967 } 4968 4969 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 4970 if (true || IS_USER_BUILD) { 4971 return; 4972 } 4973 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4974 if (tracesPath == null || tracesPath.length() == 0) { 4975 return; 4976 } 4977 4978 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 4979 StrictMode.allowThreadDiskWrites(); 4980 try { 4981 final File tracesFile = new File(tracesPath); 4982 final File tracesDir = tracesFile.getParentFile(); 4983 final File tracesTmp = new File(tracesDir, "__tmp__"); 4984 try { 4985 if (!tracesDir.exists()) { 4986 tracesDir.mkdirs(); 4987 if (!SELinux.restorecon(tracesDir.getPath())) { 4988 return; 4989 } 4990 } 4991 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4992 4993 if (tracesFile.exists()) { 4994 tracesTmp.delete(); 4995 tracesFile.renameTo(tracesTmp); 4996 } 4997 StringBuilder sb = new StringBuilder(); 4998 Time tobj = new Time(); 4999 tobj.set(System.currentTimeMillis()); 5000 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 5001 sb.append(": "); 5002 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 5003 sb.append(" since "); 5004 sb.append(msg); 5005 FileOutputStream fos = new FileOutputStream(tracesFile); 5006 fos.write(sb.toString().getBytes()); 5007 if (app == null) { 5008 fos.write("\n*** No application process!".getBytes()); 5009 } 5010 fos.close(); 5011 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 5012 } catch (IOException e) { 5013 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 5014 return; 5015 } 5016 5017 if (app != null) { 5018 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 5019 firstPids.add(app.pid); 5020 dumpStackTraces(tracesPath, firstPids, null, null, null); 5021 } 5022 5023 File lastTracesFile = null; 5024 File curTracesFile = null; 5025 for (int i=9; i>=0; i--) { 5026 String name = String.format(Locale.US, "slow%02d.txt", i); 5027 curTracesFile = new File(tracesDir, name); 5028 if (curTracesFile.exists()) { 5029 if (lastTracesFile != null) { 5030 curTracesFile.renameTo(lastTracesFile); 5031 } else { 5032 curTracesFile.delete(); 5033 } 5034 } 5035 lastTracesFile = curTracesFile; 5036 } 5037 tracesFile.renameTo(curTracesFile); 5038 if (tracesTmp.exists()) { 5039 tracesTmp.renameTo(tracesFile); 5040 } 5041 } finally { 5042 StrictMode.setThreadPolicy(oldPolicy); 5043 } 5044 } 5045 5046 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 5047 ActivityRecord parent, boolean aboveSystem, final String annotation) { 5048 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 5049 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 5050 5051 if (mController != null) { 5052 try { 5053 // 0 == continue, -1 = kill process immediately 5054 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 5055 if (res < 0 && app.pid != MY_PID) { 5056 app.kill("anr", true); 5057 } 5058 } catch (RemoteException e) { 5059 mController = null; 5060 Watchdog.getInstance().setActivityController(null); 5061 } 5062 } 5063 5064 long anrTime = SystemClock.uptimeMillis(); 5065 if (MONITOR_CPU_USAGE) { 5066 updateCpuStatsNow(); 5067 } 5068 5069 synchronized (this) { 5070 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 5071 if (mShuttingDown) { 5072 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 5073 return; 5074 } else if (app.notResponding) { 5075 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 5076 return; 5077 } else if (app.crashing) { 5078 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 5079 return; 5080 } 5081 5082 // In case we come through here for the same app before completing 5083 // this one, mark as anring now so we will bail out. 5084 app.notResponding = true; 5085 5086 // Log the ANR to the event log. 5087 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 5088 app.processName, app.info.flags, annotation); 5089 5090 // Dump thread traces as quickly as we can, starting with "interesting" processes. 5091 firstPids.add(app.pid); 5092 5093 int parentPid = app.pid; 5094 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 5095 if (parentPid != app.pid) firstPids.add(parentPid); 5096 5097 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 5098 5099 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 5100 ProcessRecord r = mLruProcesses.get(i); 5101 if (r != null && r.thread != null) { 5102 int pid = r.pid; 5103 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 5104 if (r.persistent) { 5105 firstPids.add(pid); 5106 } else { 5107 lastPids.put(pid, Boolean.TRUE); 5108 } 5109 } 5110 } 5111 } 5112 } 5113 5114 // Log the ANR to the main log. 5115 StringBuilder info = new StringBuilder(); 5116 info.setLength(0); 5117 info.append("ANR in ").append(app.processName); 5118 if (activity != null && activity.shortComponentName != null) { 5119 info.append(" (").append(activity.shortComponentName).append(")"); 5120 } 5121 info.append("\n"); 5122 info.append("PID: ").append(app.pid).append("\n"); 5123 if (annotation != null) { 5124 info.append("Reason: ").append(annotation).append("\n"); 5125 } 5126 if (parent != null && parent != activity) { 5127 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 5128 } 5129 5130 final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true); 5131 5132 File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids, 5133 NATIVE_STACKS_OF_INTEREST); 5134 5135 String cpuInfo = null; 5136 if (MONITOR_CPU_USAGE) { 5137 updateCpuStatsNow(); 5138 synchronized (mProcessCpuTracker) { 5139 cpuInfo = mProcessCpuTracker.printCurrentState(anrTime); 5140 } 5141 info.append(processCpuTracker.printCurrentLoad()); 5142 info.append(cpuInfo); 5143 } 5144 5145 info.append(processCpuTracker.printCurrentState(anrTime)); 5146 5147 Slog.e(TAG, info.toString()); 5148 if (tracesFile == null) { 5149 // There is no trace file, so dump (only) the alleged culprit's threads to the log 5150 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 5151 } 5152 5153 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 5154 cpuInfo, tracesFile, null); 5155 5156 if (mController != null) { 5157 try { 5158 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 5159 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 5160 if (res != 0) { 5161 if (res < 0 && app.pid != MY_PID) { 5162 app.kill("anr", true); 5163 } else { 5164 synchronized (this) { 5165 mServices.scheduleServiceTimeoutLocked(app); 5166 } 5167 } 5168 return; 5169 } 5170 } catch (RemoteException e) { 5171 mController = null; 5172 Watchdog.getInstance().setActivityController(null); 5173 } 5174 } 5175 5176 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 5177 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 5178 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 5179 5180 synchronized (this) { 5181 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 5182 app.kill("bg anr", true); 5183 return; 5184 } 5185 5186 // Set the app's notResponding state, and look up the errorReportReceiver 5187 makeAppNotRespondingLocked(app, 5188 activity != null ? activity.shortComponentName : null, 5189 annotation != null ? "ANR " + annotation : "ANR", 5190 info.toString()); 5191 5192 // Bring up the infamous App Not Responding dialog 5193 Message msg = Message.obtain(); 5194 HashMap<String, Object> map = new HashMap<String, Object>(); 5195 msg.what = SHOW_NOT_RESPONDING_MSG; 5196 msg.obj = map; 5197 msg.arg1 = aboveSystem ? 1 : 0; 5198 map.put("app", app); 5199 if (activity != null) { 5200 map.put("activity", activity); 5201 } 5202 5203 mHandler.sendMessage(msg); 5204 } 5205 } 5206 5207 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 5208 if (!mLaunchWarningShown) { 5209 mLaunchWarningShown = true; 5210 mHandler.post(new Runnable() { 5211 @Override 5212 public void run() { 5213 synchronized (ActivityManagerService.this) { 5214 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 5215 d.show(); 5216 mHandler.postDelayed(new Runnable() { 5217 @Override 5218 public void run() { 5219 synchronized (ActivityManagerService.this) { 5220 d.dismiss(); 5221 mLaunchWarningShown = false; 5222 } 5223 } 5224 }, 4000); 5225 } 5226 } 5227 }); 5228 } 5229 } 5230 5231 @Override 5232 public boolean clearApplicationUserData(final String packageName, 5233 final IPackageDataObserver observer, int userId) { 5234 enforceNotIsolatedCaller("clearApplicationUserData"); 5235 int uid = Binder.getCallingUid(); 5236 int pid = Binder.getCallingPid(); 5237 userId = handleIncomingUser(pid, uid, 5238 userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null); 5239 long callingId = Binder.clearCallingIdentity(); 5240 try { 5241 IPackageManager pm = AppGlobals.getPackageManager(); 5242 int pkgUid = -1; 5243 synchronized(this) { 5244 try { 5245 pkgUid = pm.getPackageUid(packageName, userId); 5246 } catch (RemoteException e) { 5247 } 5248 if (pkgUid == -1) { 5249 Slog.w(TAG, "Invalid packageName: " + packageName); 5250 if (observer != null) { 5251 try { 5252 observer.onRemoveCompleted(packageName, false); 5253 } catch (RemoteException e) { 5254 Slog.i(TAG, "Observer no longer exists."); 5255 } 5256 } 5257 return false; 5258 } 5259 if (uid == pkgUid || checkComponentPermission( 5260 android.Manifest.permission.CLEAR_APP_USER_DATA, 5261 pid, uid, -1, true) 5262 == PackageManager.PERMISSION_GRANTED) { 5263 forceStopPackageLocked(packageName, pkgUid, "clear data"); 5264 } else { 5265 throw new SecurityException("PID " + pid + " does not have permission " 5266 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 5267 + " of package " + packageName); 5268 } 5269 5270 // Remove all tasks match the cleared application package and user 5271 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 5272 final TaskRecord tr = mRecentTasks.get(i); 5273 final String taskPackageName = 5274 tr.getBaseIntent().getComponent().getPackageName(); 5275 if (tr.userId != userId) continue; 5276 if (!taskPackageName.equals(packageName)) continue; 5277 removeTaskByIdLocked(tr.taskId, 0); 5278 } 5279 } 5280 5281 try { 5282 // Clear application user data 5283 pm.clearApplicationUserData(packageName, observer, userId); 5284 5285 synchronized(this) { 5286 // Remove all permissions granted from/to this package 5287 removeUriPermissionsForPackageLocked(packageName, userId, true); 5288 } 5289 5290 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 5291 Uri.fromParts("package", packageName, null)); 5292 intent.putExtra(Intent.EXTRA_UID, pkgUid); 5293 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 5294 null, null, 0, null, null, null, false, false, userId); 5295 } catch (RemoteException e) { 5296 } 5297 } finally { 5298 Binder.restoreCallingIdentity(callingId); 5299 } 5300 return true; 5301 } 5302 5303 @Override 5304 public void killBackgroundProcesses(final String packageName, int userId) { 5305 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 5306 != PackageManager.PERMISSION_GRANTED && 5307 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 5308 != PackageManager.PERMISSION_GRANTED) { 5309 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 5310 + Binder.getCallingPid() 5311 + ", uid=" + Binder.getCallingUid() 5312 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 5313 Slog.w(TAG, msg); 5314 throw new SecurityException(msg); 5315 } 5316 5317 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 5318 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 5319 long callingId = Binder.clearCallingIdentity(); 5320 try { 5321 IPackageManager pm = AppGlobals.getPackageManager(); 5322 synchronized(this) { 5323 int appId = -1; 5324 try { 5325 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0)); 5326 } catch (RemoteException e) { 5327 } 5328 if (appId == -1) { 5329 Slog.w(TAG, "Invalid packageName: " + packageName); 5330 return; 5331 } 5332 killPackageProcessesLocked(packageName, appId, userId, 5333 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 5334 } 5335 } finally { 5336 Binder.restoreCallingIdentity(callingId); 5337 } 5338 } 5339 5340 @Override 5341 public void killAllBackgroundProcesses() { 5342 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 5343 != PackageManager.PERMISSION_GRANTED) { 5344 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 5345 + Binder.getCallingPid() 5346 + ", uid=" + Binder.getCallingUid() 5347 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 5348 Slog.w(TAG, msg); 5349 throw new SecurityException(msg); 5350 } 5351 5352 long callingId = Binder.clearCallingIdentity(); 5353 try { 5354 synchronized(this) { 5355 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 5356 final int NP = mProcessNames.getMap().size(); 5357 for (int ip=0; ip<NP; ip++) { 5358 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 5359 final int NA = apps.size(); 5360 for (int ia=0; ia<NA; ia++) { 5361 ProcessRecord app = apps.valueAt(ia); 5362 if (app.persistent) { 5363 // we don't kill persistent processes 5364 continue; 5365 } 5366 if (app.removed) { 5367 procs.add(app); 5368 } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 5369 app.removed = true; 5370 procs.add(app); 5371 } 5372 } 5373 } 5374 5375 int N = procs.size(); 5376 for (int i=0; i<N; i++) { 5377 removeProcessLocked(procs.get(i), false, true, "kill all background"); 5378 } 5379 mAllowLowerMemLevel = true; 5380 updateOomAdjLocked(); 5381 doLowMemReportIfNeededLocked(null); 5382 } 5383 } finally { 5384 Binder.restoreCallingIdentity(callingId); 5385 } 5386 } 5387 5388 @Override 5389 public void forceStopPackage(final String packageName, int userId) { 5390 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 5391 != PackageManager.PERMISSION_GRANTED) { 5392 String msg = "Permission Denial: forceStopPackage() from pid=" 5393 + Binder.getCallingPid() 5394 + ", uid=" + Binder.getCallingUid() 5395 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 5396 Slog.w(TAG, msg); 5397 throw new SecurityException(msg); 5398 } 5399 final int callingPid = Binder.getCallingPid(); 5400 userId = handleIncomingUser(callingPid, Binder.getCallingUid(), 5401 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 5402 long callingId = Binder.clearCallingIdentity(); 5403 try { 5404 IPackageManager pm = AppGlobals.getPackageManager(); 5405 synchronized(this) { 5406 int[] users = userId == UserHandle.USER_ALL 5407 ? getUsersLocked() : new int[] { userId }; 5408 for (int user : users) { 5409 int pkgUid = -1; 5410 try { 5411 pkgUid = pm.getPackageUid(packageName, user); 5412 } catch (RemoteException e) { 5413 } 5414 if (pkgUid == -1) { 5415 Slog.w(TAG, "Invalid packageName: " + packageName); 5416 continue; 5417 } 5418 try { 5419 pm.setPackageStoppedState(packageName, true, user); 5420 } catch (RemoteException e) { 5421 } catch (IllegalArgumentException e) { 5422 Slog.w(TAG, "Failed trying to unstop package " 5423 + packageName + ": " + e); 5424 } 5425 if (isUserRunningLocked(user, false)) { 5426 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 5427 } 5428 } 5429 } 5430 } finally { 5431 Binder.restoreCallingIdentity(callingId); 5432 } 5433 } 5434 5435 @Override 5436 public void addPackageDependency(String packageName) { 5437 synchronized (this) { 5438 int callingPid = Binder.getCallingPid(); 5439 if (callingPid == Process.myPid()) { 5440 // Yeah, um, no. 5441 Slog.w(TAG, "Can't addPackageDependency on system process"); 5442 return; 5443 } 5444 ProcessRecord proc; 5445 synchronized (mPidsSelfLocked) { 5446 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 5447 } 5448 if (proc != null) { 5449 if (proc.pkgDeps == null) { 5450 proc.pkgDeps = new ArraySet<String>(1); 5451 } 5452 proc.pkgDeps.add(packageName); 5453 } 5454 } 5455 } 5456 5457 /* 5458 * The pkg name and app id have to be specified. 5459 */ 5460 @Override 5461 public void killApplicationWithAppId(String pkg, int appid, String reason) { 5462 if (pkg == null) { 5463 return; 5464 } 5465 // Make sure the uid is valid. 5466 if (appid < 0) { 5467 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 5468 return; 5469 } 5470 int callerUid = Binder.getCallingUid(); 5471 // Only the system server can kill an application 5472 if (callerUid == Process.SYSTEM_UID) { 5473 // Post an aysnc message to kill the application 5474 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 5475 msg.arg1 = appid; 5476 msg.arg2 = 0; 5477 Bundle bundle = new Bundle(); 5478 bundle.putString("pkg", pkg); 5479 bundle.putString("reason", reason); 5480 msg.obj = bundle; 5481 mHandler.sendMessage(msg); 5482 } else { 5483 throw new SecurityException(callerUid + " cannot kill pkg: " + 5484 pkg); 5485 } 5486 } 5487 5488 @Override 5489 public void closeSystemDialogs(String reason) { 5490 enforceNotIsolatedCaller("closeSystemDialogs"); 5491 5492 final int pid = Binder.getCallingPid(); 5493 final int uid = Binder.getCallingUid(); 5494 final long origId = Binder.clearCallingIdentity(); 5495 try { 5496 synchronized (this) { 5497 // Only allow this from foreground processes, so that background 5498 // applications can't abuse it to prevent system UI from being shown. 5499 if (uid >= Process.FIRST_APPLICATION_UID) { 5500 ProcessRecord proc; 5501 synchronized (mPidsSelfLocked) { 5502 proc = mPidsSelfLocked.get(pid); 5503 } 5504 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 5505 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 5506 + " from background process " + proc); 5507 return; 5508 } 5509 } 5510 closeSystemDialogsLocked(reason); 5511 } 5512 } finally { 5513 Binder.restoreCallingIdentity(origId); 5514 } 5515 } 5516 5517 void closeSystemDialogsLocked(String reason) { 5518 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 5519 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5520 | Intent.FLAG_RECEIVER_FOREGROUND); 5521 if (reason != null) { 5522 intent.putExtra("reason", reason); 5523 } 5524 mWindowManager.closeSystemDialogs(reason); 5525 5526 mStackSupervisor.closeSystemDialogsLocked(); 5527 5528 broadcastIntentLocked(null, null, intent, null, 5529 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1, 5530 Process.SYSTEM_UID, UserHandle.USER_ALL); 5531 } 5532 5533 @Override 5534 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 5535 enforceNotIsolatedCaller("getProcessMemoryInfo"); 5536 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 5537 for (int i=pids.length-1; i>=0; i--) { 5538 ProcessRecord proc; 5539 int oomAdj; 5540 synchronized (this) { 5541 synchronized (mPidsSelfLocked) { 5542 proc = mPidsSelfLocked.get(pids[i]); 5543 oomAdj = proc != null ? proc.setAdj : 0; 5544 } 5545 } 5546 infos[i] = new Debug.MemoryInfo(); 5547 Debug.getMemoryInfo(pids[i], infos[i]); 5548 if (proc != null) { 5549 synchronized (this) { 5550 if (proc.thread != null && proc.setAdj == oomAdj) { 5551 // Record this for posterity if the process has been stable. 5552 proc.baseProcessTracker.addPss(infos[i].getTotalPss(), 5553 infos[i].getTotalUss(), false, proc.pkgList); 5554 } 5555 } 5556 } 5557 } 5558 return infos; 5559 } 5560 5561 @Override 5562 public long[] getProcessPss(int[] pids) { 5563 enforceNotIsolatedCaller("getProcessPss"); 5564 long[] pss = new long[pids.length]; 5565 for (int i=pids.length-1; i>=0; i--) { 5566 ProcessRecord proc; 5567 int oomAdj; 5568 synchronized (this) { 5569 synchronized (mPidsSelfLocked) { 5570 proc = mPidsSelfLocked.get(pids[i]); 5571 oomAdj = proc != null ? proc.setAdj : 0; 5572 } 5573 } 5574 long[] tmpUss = new long[1]; 5575 pss[i] = Debug.getPss(pids[i], tmpUss); 5576 if (proc != null) { 5577 synchronized (this) { 5578 if (proc.thread != null && proc.setAdj == oomAdj) { 5579 // Record this for posterity if the process has been stable. 5580 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList); 5581 } 5582 } 5583 } 5584 } 5585 return pss; 5586 } 5587 5588 @Override 5589 public void killApplicationProcess(String processName, int uid) { 5590 if (processName == null) { 5591 return; 5592 } 5593 5594 int callerUid = Binder.getCallingUid(); 5595 // Only the system server can kill an application 5596 if (callerUid == Process.SYSTEM_UID) { 5597 synchronized (this) { 5598 ProcessRecord app = getProcessRecordLocked(processName, uid, true); 5599 if (app != null && app.thread != null) { 5600 try { 5601 app.thread.scheduleSuicide(); 5602 } catch (RemoteException e) { 5603 // If the other end already died, then our work here is done. 5604 } 5605 } else { 5606 Slog.w(TAG, "Process/uid not found attempting kill of " 5607 + processName + " / " + uid); 5608 } 5609 } 5610 } else { 5611 throw new SecurityException(callerUid + " cannot kill app process: " + 5612 processName); 5613 } 5614 } 5615 5616 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 5617 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 5618 false, true, false, false, UserHandle.getUserId(uid), reason); 5619 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 5620 Uri.fromParts("package", packageName, null)); 5621 if (!mProcessesReady) { 5622 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5623 | Intent.FLAG_RECEIVER_FOREGROUND); 5624 } 5625 intent.putExtra(Intent.EXTRA_UID, uid); 5626 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 5627 broadcastIntentLocked(null, null, intent, 5628 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5629 false, false, 5630 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); 5631 } 5632 5633 private void forceStopUserLocked(int userId, String reason) { 5634 forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason); 5635 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 5636 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5637 | Intent.FLAG_RECEIVER_FOREGROUND); 5638 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 5639 broadcastIntentLocked(null, null, intent, 5640 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5641 false, false, 5642 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 5643 } 5644 5645 private final boolean killPackageProcessesLocked(String packageName, int appId, 5646 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 5647 boolean doit, boolean evenPersistent, String reason) { 5648 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 5649 5650 // Remove all processes this package may have touched: all with the 5651 // same UID (except for the system or root user), and all whose name 5652 // matches the package name. 5653 final int NP = mProcessNames.getMap().size(); 5654 for (int ip=0; ip<NP; ip++) { 5655 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 5656 final int NA = apps.size(); 5657 for (int ia=0; ia<NA; ia++) { 5658 ProcessRecord app = apps.valueAt(ia); 5659 if (app.persistent && !evenPersistent) { 5660 // we don't kill persistent processes 5661 continue; 5662 } 5663 if (app.removed) { 5664 if (doit) { 5665 procs.add(app); 5666 } 5667 continue; 5668 } 5669 5670 // Skip process if it doesn't meet our oom adj requirement. 5671 if (app.setAdj < minOomAdj) { 5672 continue; 5673 } 5674 5675 // If no package is specified, we call all processes under the 5676 // give user id. 5677 if (packageName == null) { 5678 if (app.userId != userId) { 5679 continue; 5680 } 5681 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 5682 continue; 5683 } 5684 // Package has been specified, we want to hit all processes 5685 // that match it. We need to qualify this by the processes 5686 // that are running under the specified app and user ID. 5687 } else { 5688 final boolean isDep = app.pkgDeps != null 5689 && app.pkgDeps.contains(packageName); 5690 if (!isDep && UserHandle.getAppId(app.uid) != appId) { 5691 continue; 5692 } 5693 if (userId != UserHandle.USER_ALL && app.userId != userId) { 5694 continue; 5695 } 5696 if (!app.pkgList.containsKey(packageName) && !isDep) { 5697 continue; 5698 } 5699 } 5700 5701 // Process has passed all conditions, kill it! 5702 if (!doit) { 5703 return true; 5704 } 5705 app.removed = true; 5706 procs.add(app); 5707 } 5708 } 5709 5710 int N = procs.size(); 5711 for (int i=0; i<N; i++) { 5712 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 5713 } 5714 updateOomAdjLocked(); 5715 return N > 0; 5716 } 5717 5718 private final boolean forceStopPackageLocked(String name, int appId, 5719 boolean callerWillRestart, boolean purgeCache, boolean doit, 5720 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 5721 int i; 5722 int N; 5723 5724 if (userId == UserHandle.USER_ALL && name == null) { 5725 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 5726 } 5727 5728 if (appId < 0 && name != null) { 5729 try { 5730 appId = UserHandle.getAppId( 5731 AppGlobals.getPackageManager().getPackageUid(name, 0)); 5732 } catch (RemoteException e) { 5733 } 5734 } 5735 5736 if (doit) { 5737 if (name != null) { 5738 Slog.i(TAG, "Force stopping " + name + " appid=" + appId 5739 + " user=" + userId + ": " + reason); 5740 } else { 5741 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 5742 } 5743 5744 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 5745 for (int ip=pmap.size()-1; ip>=0; ip--) { 5746 SparseArray<Long> ba = pmap.valueAt(ip); 5747 for (i=ba.size()-1; i>=0; i--) { 5748 boolean remove = false; 5749 final int entUid = ba.keyAt(i); 5750 if (name != null) { 5751 if (userId == UserHandle.USER_ALL) { 5752 if (UserHandle.getAppId(entUid) == appId) { 5753 remove = true; 5754 } 5755 } else { 5756 if (entUid == UserHandle.getUid(userId, appId)) { 5757 remove = true; 5758 } 5759 } 5760 } else if (UserHandle.getUserId(entUid) == userId) { 5761 remove = true; 5762 } 5763 if (remove) { 5764 ba.removeAt(i); 5765 } 5766 } 5767 if (ba.size() == 0) { 5768 pmap.removeAt(ip); 5769 } 5770 } 5771 } 5772 5773 boolean didSomething = killPackageProcessesLocked(name, appId, userId, 5774 -100, callerWillRestart, true, doit, evenPersistent, 5775 name == null ? ("stop user " + userId) : ("stop " + name)); 5776 5777 if (mStackSupervisor.forceStopPackageLocked(name, doit, evenPersistent, userId)) { 5778 if (!doit) { 5779 return true; 5780 } 5781 didSomething = true; 5782 } 5783 5784 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) { 5785 if (!doit) { 5786 return true; 5787 } 5788 didSomething = true; 5789 } 5790 5791 if (name == null) { 5792 // Remove all sticky broadcasts from this user. 5793 mStickyBroadcasts.remove(userId); 5794 } 5795 5796 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>(); 5797 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent, 5798 userId, providers)) { 5799 if (!doit) { 5800 return true; 5801 } 5802 didSomething = true; 5803 } 5804 N = providers.size(); 5805 for (i=0; i<N; i++) { 5806 removeDyingProviderLocked(null, providers.get(i), true); 5807 } 5808 5809 // Remove transient permissions granted from/to this package/user 5810 removeUriPermissionsForPackageLocked(name, userId, false); 5811 5812 if (name == null || uninstalling) { 5813 // Remove pending intents. For now we only do this when force 5814 // stopping users, because we have some problems when doing this 5815 // for packages -- app widgets are not currently cleaned up for 5816 // such packages, so they can be left with bad pending intents. 5817 if (mIntentSenderRecords.size() > 0) { 5818 Iterator<WeakReference<PendingIntentRecord>> it 5819 = mIntentSenderRecords.values().iterator(); 5820 while (it.hasNext()) { 5821 WeakReference<PendingIntentRecord> wpir = it.next(); 5822 if (wpir == null) { 5823 it.remove(); 5824 continue; 5825 } 5826 PendingIntentRecord pir = wpir.get(); 5827 if (pir == null) { 5828 it.remove(); 5829 continue; 5830 } 5831 if (name == null) { 5832 // Stopping user, remove all objects for the user. 5833 if (pir.key.userId != userId) { 5834 // Not the same user, skip it. 5835 continue; 5836 } 5837 } else { 5838 if (UserHandle.getAppId(pir.uid) != appId) { 5839 // Different app id, skip it. 5840 continue; 5841 } 5842 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 5843 // Different user, skip it. 5844 continue; 5845 } 5846 if (!pir.key.packageName.equals(name)) { 5847 // Different package, skip it. 5848 continue; 5849 } 5850 } 5851 if (!doit) { 5852 return true; 5853 } 5854 didSomething = true; 5855 it.remove(); 5856 pir.canceled = true; 5857 if (pir.key.activity != null) { 5858 pir.key.activity.pendingResults.remove(pir.ref); 5859 } 5860 } 5861 } 5862 } 5863 5864 if (doit) { 5865 if (purgeCache && name != null) { 5866 AttributeCache ac = AttributeCache.instance(); 5867 if (ac != null) { 5868 ac.removePackage(name); 5869 } 5870 } 5871 if (mBooted) { 5872 mStackSupervisor.resumeTopActivitiesLocked(); 5873 mStackSupervisor.scheduleIdleLocked(); 5874 } 5875 } 5876 5877 return didSomething; 5878 } 5879 5880 private final boolean removeProcessLocked(ProcessRecord app, 5881 boolean callerWillRestart, boolean allowRestart, String reason) { 5882 final String name = app.processName; 5883 final int uid = app.uid; 5884 if (DEBUG_PROCESSES) Slog.d( 5885 TAG, "Force removing proc " + app.toShortString() + " (" + name 5886 + "/" + uid + ")"); 5887 5888 mProcessNames.remove(name, uid); 5889 mIsolatedProcesses.remove(app.uid); 5890 if (mHeavyWeightProcess == app) { 5891 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5892 mHeavyWeightProcess.userId, 0)); 5893 mHeavyWeightProcess = null; 5894 } 5895 boolean needRestart = false; 5896 if (app.pid > 0 && app.pid != MY_PID) { 5897 int pid = app.pid; 5898 synchronized (mPidsSelfLocked) { 5899 mPidsSelfLocked.remove(pid); 5900 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 5901 } 5902 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5903 if (app.isolated) { 5904 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5905 } 5906 app.kill(reason, true); 5907 handleAppDiedLocked(app, true, allowRestart); 5908 removeLruProcessLocked(app); 5909 5910 if (app.persistent && !app.isolated) { 5911 if (!callerWillRestart) { 5912 addAppLocked(app.info, false, null /* ABI override */); 5913 } else { 5914 needRestart = true; 5915 } 5916 } 5917 } else { 5918 mRemovedProcesses.add(app); 5919 } 5920 5921 return needRestart; 5922 } 5923 5924 private final void processStartTimedOutLocked(ProcessRecord app) { 5925 final int pid = app.pid; 5926 boolean gone = false; 5927 synchronized (mPidsSelfLocked) { 5928 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 5929 if (knownApp != null && knownApp.thread == null) { 5930 mPidsSelfLocked.remove(pid); 5931 gone = true; 5932 } 5933 } 5934 5935 if (gone) { 5936 Slog.w(TAG, "Process " + app + " failed to attach"); 5937 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 5938 pid, app.uid, app.processName); 5939 mProcessNames.remove(app.processName, app.uid); 5940 mIsolatedProcesses.remove(app.uid); 5941 if (mHeavyWeightProcess == app) { 5942 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5943 mHeavyWeightProcess.userId, 0)); 5944 mHeavyWeightProcess = null; 5945 } 5946 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5947 if (app.isolated) { 5948 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5949 } 5950 // Take care of any launching providers waiting for this process. 5951 checkAppInLaunchingProvidersLocked(app, true); 5952 // Take care of any services that are waiting for the process. 5953 mServices.processStartTimedOutLocked(app); 5954 app.kill("start timeout", true); 5955 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 5956 Slog.w(TAG, "Unattached app died before backup, skipping"); 5957 try { 5958 IBackupManager bm = IBackupManager.Stub.asInterface( 5959 ServiceManager.getService(Context.BACKUP_SERVICE)); 5960 bm.agentDisconnected(app.info.packageName); 5961 } catch (RemoteException e) { 5962 // Can't happen; the backup manager is local 5963 } 5964 } 5965 if (isPendingBroadcastProcessLocked(pid)) { 5966 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 5967 skipPendingBroadcastLocked(pid); 5968 } 5969 } else { 5970 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 5971 } 5972 } 5973 5974 private final boolean attachApplicationLocked(IApplicationThread thread, 5975 int pid) { 5976 5977 // Find the application record that is being attached... either via 5978 // the pid if we are running in multiple processes, or just pull the 5979 // next app record if we are emulating process with anonymous threads. 5980 ProcessRecord app; 5981 if (pid != MY_PID && pid >= 0) { 5982 synchronized (mPidsSelfLocked) { 5983 app = mPidsSelfLocked.get(pid); 5984 } 5985 } else { 5986 app = null; 5987 } 5988 5989 if (app == null) { 5990 Slog.w(TAG, "No pending application record for pid " + pid 5991 + " (IApplicationThread " + thread + "); dropping process"); 5992 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 5993 if (pid > 0 && pid != MY_PID) { 5994 Process.killProcessQuiet(pid); 5995 //TODO: Process.killProcessGroup(app.info.uid, pid); 5996 } else { 5997 try { 5998 thread.scheduleExit(); 5999 } catch (Exception e) { 6000 // Ignore exceptions. 6001 } 6002 } 6003 return false; 6004 } 6005 6006 // If this application record is still attached to a previous 6007 // process, clean it up now. 6008 if (app.thread != null) { 6009 handleAppDiedLocked(app, true, true); 6010 } 6011 6012 // Tell the process all about itself. 6013 6014 if (localLOGV) Slog.v( 6015 TAG, "Binding process pid " + pid + " to record " + app); 6016 6017 final String processName = app.processName; 6018 try { 6019 AppDeathRecipient adr = new AppDeathRecipient( 6020 app, pid, thread); 6021 thread.asBinder().linkToDeath(adr, 0); 6022 app.deathRecipient = adr; 6023 } catch (RemoteException e) { 6024 app.resetPackageList(mProcessStats); 6025 startProcessLocked(app, "link fail", processName); 6026 return false; 6027 } 6028 6029 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 6030 6031 app.makeActive(thread, mProcessStats); 6032 app.curAdj = app.setAdj = -100; 6033 app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT; 6034 app.forcingToForeground = null; 6035 updateProcessForegroundLocked(app, false, false); 6036 app.hasShownUi = false; 6037 app.debugging = false; 6038 app.cached = false; 6039 6040 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 6041 6042 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 6043 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null; 6044 6045 if (!normalMode) { 6046 Slog.i(TAG, "Launching preboot mode app: " + app); 6047 } 6048 6049 if (localLOGV) Slog.v( 6050 TAG, "New app record " + app 6051 + " thread=" + thread.asBinder() + " pid=" + pid); 6052 try { 6053 int testMode = IApplicationThread.DEBUG_OFF; 6054 if (mDebugApp != null && mDebugApp.equals(processName)) { 6055 testMode = mWaitForDebugger 6056 ? IApplicationThread.DEBUG_WAIT 6057 : IApplicationThread.DEBUG_ON; 6058 app.debugging = true; 6059 if (mDebugTransient) { 6060 mDebugApp = mOrigDebugApp; 6061 mWaitForDebugger = mOrigWaitForDebugger; 6062 } 6063 } 6064 String profileFile = app.instrumentationProfileFile; 6065 ParcelFileDescriptor profileFd = null; 6066 int samplingInterval = 0; 6067 boolean profileAutoStop = false; 6068 if (mProfileApp != null && mProfileApp.equals(processName)) { 6069 mProfileProc = app; 6070 profileFile = mProfileFile; 6071 profileFd = mProfileFd; 6072 samplingInterval = mSamplingInterval; 6073 profileAutoStop = mAutoStopProfiler; 6074 } 6075 boolean enableOpenGlTrace = false; 6076 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) { 6077 enableOpenGlTrace = true; 6078 mOpenGlTraceApp = null; 6079 } 6080 6081 // If the app is being launched for restore or full backup, set it up specially 6082 boolean isRestrictedBackupMode = false; 6083 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 6084 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 6085 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 6086 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 6087 } 6088 6089 ensurePackageDexOpt(app.instrumentationInfo != null 6090 ? app.instrumentationInfo.packageName 6091 : app.info.packageName); 6092 if (app.instrumentationClass != null) { 6093 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 6094 } 6095 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc " 6096 + processName + " with config " + mConfiguration); 6097 ApplicationInfo appInfo = app.instrumentationInfo != null 6098 ? app.instrumentationInfo : app.info; 6099 app.compat = compatibilityInfoForPackageLocked(appInfo); 6100 if (profileFd != null) { 6101 profileFd = profileFd.dup(); 6102 } 6103 ProfilerInfo profilerInfo = profileFile == null ? null 6104 : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop); 6105 thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, 6106 profilerInfo, app.instrumentationArguments, app.instrumentationWatcher, 6107 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, 6108 isRestrictedBackupMode || !normalMode, app.persistent, 6109 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), 6110 mCoreSettingsObserver.getCoreSettingsLocked()); 6111 updateLruProcessLocked(app, false, null); 6112 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 6113 } catch (Exception e) { 6114 // todo: Yikes! What should we do? For now we will try to 6115 // start another process, but that could easily get us in 6116 // an infinite loop of restarting processes... 6117 Slog.w(TAG, "Exception thrown during bind!", e); 6118 6119 app.resetPackageList(mProcessStats); 6120 app.unlinkDeathRecipient(); 6121 startProcessLocked(app, "bind fail", processName); 6122 return false; 6123 } 6124 6125 // Remove this record from the list of starting applications. 6126 mPersistentStartingProcesses.remove(app); 6127 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 6128 "Attach application locked removing on hold: " + app); 6129 mProcessesOnHold.remove(app); 6130 6131 boolean badApp = false; 6132 boolean didSomething = false; 6133 6134 // See if the top visible activity is waiting to run in this process... 6135 if (normalMode) { 6136 try { 6137 if (mStackSupervisor.attachApplicationLocked(app)) { 6138 didSomething = true; 6139 } 6140 } catch (Exception e) { 6141 badApp = true; 6142 } 6143 } 6144 6145 // Find any services that should be running in this process... 6146 if (!badApp) { 6147 try { 6148 didSomething |= mServices.attachApplicationLocked(app, processName); 6149 } catch (Exception e) { 6150 badApp = true; 6151 } 6152 } 6153 6154 // Check if a next-broadcast receiver is in this process... 6155 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 6156 try { 6157 didSomething |= sendPendingBroadcastsLocked(app); 6158 } catch (Exception e) { 6159 // If the app died trying to launch the receiver we declare it 'bad' 6160 badApp = true; 6161 } 6162 } 6163 6164 // Check whether the next backup agent is in this process... 6165 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) { 6166 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app); 6167 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 6168 try { 6169 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 6170 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 6171 mBackupTarget.backupMode); 6172 } catch (Exception e) { 6173 Slog.w(TAG, "Exception scheduling backup agent creation: "); 6174 e.printStackTrace(); 6175 } 6176 } 6177 6178 if (badApp) { 6179 // todo: Also need to kill application to deal with all 6180 // kinds of exceptions. 6181 handleAppDiedLocked(app, false, true); 6182 return false; 6183 } 6184 6185 if (!didSomething) { 6186 updateOomAdjLocked(); 6187 } 6188 6189 return true; 6190 } 6191 6192 @Override 6193 public final void attachApplication(IApplicationThread thread) { 6194 synchronized (this) { 6195 int callingPid = Binder.getCallingPid(); 6196 final long origId = Binder.clearCallingIdentity(); 6197 attachApplicationLocked(thread, callingPid); 6198 Binder.restoreCallingIdentity(origId); 6199 } 6200 } 6201 6202 @Override 6203 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 6204 final long origId = Binder.clearCallingIdentity(); 6205 synchronized (this) { 6206 ActivityStack stack = ActivityRecord.getStackLocked(token); 6207 if (stack != null) { 6208 ActivityRecord r = 6209 mStackSupervisor.activityIdleInternalLocked(token, false, config); 6210 if (stopProfiling) { 6211 if ((mProfileProc == r.app) && (mProfileFd != null)) { 6212 try { 6213 mProfileFd.close(); 6214 } catch (IOException e) { 6215 } 6216 clearProfilerLocked(); 6217 } 6218 } 6219 } 6220 } 6221 Binder.restoreCallingIdentity(origId); 6222 } 6223 6224 void postEnableScreenAfterBootLocked() { 6225 mHandler.sendEmptyMessage(ENABLE_SCREEN_AFTER_BOOT_MSG); 6226 } 6227 6228 void enableScreenAfterBoot() { 6229 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 6230 SystemClock.uptimeMillis()); 6231 mWindowManager.enableScreenAfterBoot(); 6232 6233 synchronized (this) { 6234 updateEventDispatchingLocked(); 6235 } 6236 } 6237 6238 @Override 6239 public void showBootMessage(final CharSequence msg, final boolean always) { 6240 enforceNotIsolatedCaller("showBootMessage"); 6241 mWindowManager.showBootMessage(msg, always); 6242 } 6243 6244 @Override 6245 public void keyguardWaitingForActivityDrawn() { 6246 enforceNotIsolatedCaller("keyguardWaitingForActivityDrawn"); 6247 final long token = Binder.clearCallingIdentity(); 6248 try { 6249 synchronized (this) { 6250 if (DEBUG_LOCKSCREEN) logLockScreen(""); 6251 mWindowManager.keyguardWaitingForActivityDrawn(); 6252 mKeyguardWaitingForDraw = true; 6253 } 6254 } finally { 6255 Binder.restoreCallingIdentity(token); 6256 } 6257 } 6258 6259 final void finishBooting() { 6260 synchronized (this) { 6261 if (!mBootAnimationComplete) { 6262 mCallFinishBooting = true; 6263 return; 6264 } 6265 mCallFinishBooting = false; 6266 } 6267 6268 // Register receivers to handle package update events 6269 mPackageMonitor.register(mContext, Looper.getMainLooper(), false); 6270 6271 // Let system services know. 6272 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); 6273 6274 synchronized (this) { 6275 // Ensure that any processes we had put on hold are now started 6276 // up. 6277 final int NP = mProcessesOnHold.size(); 6278 if (NP > 0) { 6279 ArrayList<ProcessRecord> procs = 6280 new ArrayList<ProcessRecord>(mProcessesOnHold); 6281 for (int ip=0; ip<NP; ip++) { 6282 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: " 6283 + procs.get(ip)); 6284 startProcessLocked(procs.get(ip), "on-hold", null); 6285 } 6286 } 6287 6288 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 6289 // Start looking for apps that are abusing wake locks. 6290 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 6291 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 6292 // Tell anyone interested that we are done booting! 6293 SystemProperties.set("sys.boot_completed", "1"); 6294 SystemProperties.set("dev.bootcomplete", "1"); 6295 for (int i=0; i<mStartedUsers.size(); i++) { 6296 UserStartedState uss = mStartedUsers.valueAt(i); 6297 if (uss.mState == UserStartedState.STATE_BOOTING) { 6298 uss.mState = UserStartedState.STATE_RUNNING; 6299 final int userId = mStartedUsers.keyAt(i); 6300 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 6301 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 6302 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 6303 broadcastIntentLocked(null, null, intent, null, 6304 new IIntentReceiver.Stub() { 6305 @Override 6306 public void performReceive(Intent intent, int resultCode, 6307 String data, Bundle extras, boolean ordered, 6308 boolean sticky, int sendingUser) { 6309 synchronized (ActivityManagerService.this) { 6310 requestPssAllProcsLocked(SystemClock.uptimeMillis(), 6311 true, false); 6312 } 6313 } 6314 }, 6315 0, null, null, 6316 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, 6317 AppOpsManager.OP_NONE, true, false, MY_PID, Process.SYSTEM_UID, 6318 userId); 6319 } 6320 } 6321 scheduleStartProfilesLocked(); 6322 } 6323 } 6324 } 6325 6326 @Override 6327 public void bootAnimationComplete() { 6328 final boolean callFinishBooting; 6329 synchronized (this) { 6330 callFinishBooting = mCallFinishBooting; 6331 mBootAnimationComplete = true; 6332 } 6333 if (callFinishBooting) { 6334 finishBooting(); 6335 } 6336 } 6337 6338 final void ensureBootCompleted() { 6339 boolean booting; 6340 boolean enableScreen; 6341 synchronized (this) { 6342 booting = mBooting; 6343 mBooting = false; 6344 enableScreen = !mBooted; 6345 mBooted = true; 6346 } 6347 6348 if (booting) { 6349 finishBooting(); 6350 } 6351 6352 if (enableScreen) { 6353 enableScreenAfterBoot(); 6354 } 6355 } 6356 6357 @Override 6358 public final void activityResumed(IBinder token) { 6359 final long origId = Binder.clearCallingIdentity(); 6360 synchronized(this) { 6361 ActivityStack stack = ActivityRecord.getStackLocked(token); 6362 if (stack != null) { 6363 ActivityRecord.activityResumedLocked(token); 6364 } 6365 } 6366 Binder.restoreCallingIdentity(origId); 6367 } 6368 6369 @Override 6370 public final void activityPaused(IBinder token) { 6371 final long origId = Binder.clearCallingIdentity(); 6372 synchronized(this) { 6373 ActivityStack stack = ActivityRecord.getStackLocked(token); 6374 if (stack != null) { 6375 stack.activityPausedLocked(token, false); 6376 } 6377 } 6378 Binder.restoreCallingIdentity(origId); 6379 } 6380 6381 @Override 6382 public final void activityStopped(IBinder token, Bundle icicle, 6383 PersistableBundle persistentState, CharSequence description) { 6384 if (localLOGV) Slog.v(TAG, "Activity stopped: token=" + token); 6385 6386 // Refuse possible leaked file descriptors 6387 if (icicle != null && icicle.hasFileDescriptors()) { 6388 throw new IllegalArgumentException("File descriptors passed in Bundle"); 6389 } 6390 6391 final long origId = Binder.clearCallingIdentity(); 6392 6393 synchronized (this) { 6394 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6395 if (r != null) { 6396 r.task.stack.activityStoppedLocked(r, icicle, persistentState, description); 6397 } 6398 } 6399 6400 trimApplications(); 6401 6402 Binder.restoreCallingIdentity(origId); 6403 } 6404 6405 @Override 6406 public final void activityDestroyed(IBinder token) { 6407 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token); 6408 synchronized (this) { 6409 ActivityStack stack = ActivityRecord.getStackLocked(token); 6410 if (stack != null) { 6411 stack.activityDestroyedLocked(token); 6412 } 6413 } 6414 } 6415 6416 @Override 6417 public final void backgroundResourcesReleased(IBinder token) { 6418 final long origId = Binder.clearCallingIdentity(); 6419 try { 6420 synchronized (this) { 6421 ActivityStack stack = ActivityRecord.getStackLocked(token); 6422 if (stack != null) { 6423 stack.backgroundResourcesReleased(token); 6424 } 6425 } 6426 } finally { 6427 Binder.restoreCallingIdentity(origId); 6428 } 6429 } 6430 6431 @Override 6432 public final void notifyLaunchTaskBehindComplete(IBinder token) { 6433 mStackSupervisor.scheduleLaunchTaskBehindComplete(token); 6434 } 6435 6436 @Override 6437 public final void notifyEnterAnimationComplete(IBinder token) { 6438 mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token)); 6439 } 6440 6441 @Override 6442 public String getCallingPackage(IBinder token) { 6443 synchronized (this) { 6444 ActivityRecord r = getCallingRecordLocked(token); 6445 return r != null ? r.info.packageName : null; 6446 } 6447 } 6448 6449 @Override 6450 public ComponentName getCallingActivity(IBinder token) { 6451 synchronized (this) { 6452 ActivityRecord r = getCallingRecordLocked(token); 6453 return r != null ? r.intent.getComponent() : null; 6454 } 6455 } 6456 6457 private ActivityRecord getCallingRecordLocked(IBinder token) { 6458 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6459 if (r == null) { 6460 return null; 6461 } 6462 return r.resultTo; 6463 } 6464 6465 @Override 6466 public ComponentName getActivityClassForToken(IBinder token) { 6467 synchronized(this) { 6468 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6469 if (r == null) { 6470 return null; 6471 } 6472 return r.intent.getComponent(); 6473 } 6474 } 6475 6476 @Override 6477 public String getPackageForToken(IBinder token) { 6478 synchronized(this) { 6479 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6480 if (r == null) { 6481 return null; 6482 } 6483 return r.packageName; 6484 } 6485 } 6486 6487 @Override 6488 public IIntentSender getIntentSender(int type, 6489 String packageName, IBinder token, String resultWho, 6490 int requestCode, Intent[] intents, String[] resolvedTypes, 6491 int flags, Bundle options, int userId) { 6492 enforceNotIsolatedCaller("getIntentSender"); 6493 // Refuse possible leaked file descriptors 6494 if (intents != null) { 6495 if (intents.length < 1) { 6496 throw new IllegalArgumentException("Intents array length must be >= 1"); 6497 } 6498 for (int i=0; i<intents.length; i++) { 6499 Intent intent = intents[i]; 6500 if (intent != null) { 6501 if (intent.hasFileDescriptors()) { 6502 throw new IllegalArgumentException("File descriptors passed in Intent"); 6503 } 6504 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 6505 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 6506 throw new IllegalArgumentException( 6507 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 6508 } 6509 intents[i] = new Intent(intent); 6510 } 6511 } 6512 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 6513 throw new IllegalArgumentException( 6514 "Intent array length does not match resolvedTypes length"); 6515 } 6516 } 6517 if (options != null) { 6518 if (options.hasFileDescriptors()) { 6519 throw new IllegalArgumentException("File descriptors passed in options"); 6520 } 6521 } 6522 6523 synchronized(this) { 6524 int callingUid = Binder.getCallingUid(); 6525 int origUserId = userId; 6526 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 6527 type == ActivityManager.INTENT_SENDER_BROADCAST, 6528 ALLOW_NON_FULL, "getIntentSender", null); 6529 if (origUserId == UserHandle.USER_CURRENT) { 6530 // We don't want to evaluate this until the pending intent is 6531 // actually executed. However, we do want to always do the 6532 // security checking for it above. 6533 userId = UserHandle.USER_CURRENT; 6534 } 6535 try { 6536 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 6537 int uid = AppGlobals.getPackageManager() 6538 .getPackageUid(packageName, UserHandle.getUserId(callingUid)); 6539 if (!UserHandle.isSameApp(callingUid, uid)) { 6540 String msg = "Permission Denial: getIntentSender() from pid=" 6541 + Binder.getCallingPid() 6542 + ", uid=" + Binder.getCallingUid() 6543 + ", (need uid=" + uid + ")" 6544 + " is not allowed to send as package " + packageName; 6545 Slog.w(TAG, msg); 6546 throw new SecurityException(msg); 6547 } 6548 } 6549 6550 return getIntentSenderLocked(type, packageName, callingUid, userId, 6551 token, resultWho, requestCode, intents, resolvedTypes, flags, options); 6552 6553 } catch (RemoteException e) { 6554 throw new SecurityException(e); 6555 } 6556 } 6557 } 6558 6559 IIntentSender getIntentSenderLocked(int type, String packageName, 6560 int callingUid, int userId, IBinder token, String resultWho, 6561 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 6562 Bundle options) { 6563 if (DEBUG_MU) 6564 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 6565 ActivityRecord activity = null; 6566 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 6567 activity = ActivityRecord.isInStackLocked(token); 6568 if (activity == null) { 6569 return null; 6570 } 6571 if (activity.finishing) { 6572 return null; 6573 } 6574 } 6575 6576 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 6577 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 6578 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 6579 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 6580 |PendingIntent.FLAG_UPDATE_CURRENT); 6581 6582 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 6583 type, packageName, activity, resultWho, 6584 requestCode, intents, resolvedTypes, flags, options, userId); 6585 WeakReference<PendingIntentRecord> ref; 6586 ref = mIntentSenderRecords.get(key); 6587 PendingIntentRecord rec = ref != null ? ref.get() : null; 6588 if (rec != null) { 6589 if (!cancelCurrent) { 6590 if (updateCurrent) { 6591 if (rec.key.requestIntent != null) { 6592 rec.key.requestIntent.replaceExtras(intents != null ? 6593 intents[intents.length - 1] : null); 6594 } 6595 if (intents != null) { 6596 intents[intents.length-1] = rec.key.requestIntent; 6597 rec.key.allIntents = intents; 6598 rec.key.allResolvedTypes = resolvedTypes; 6599 } else { 6600 rec.key.allIntents = null; 6601 rec.key.allResolvedTypes = null; 6602 } 6603 } 6604 return rec; 6605 } 6606 rec.canceled = true; 6607 mIntentSenderRecords.remove(key); 6608 } 6609 if (noCreate) { 6610 return rec; 6611 } 6612 rec = new PendingIntentRecord(this, key, callingUid); 6613 mIntentSenderRecords.put(key, rec.ref); 6614 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 6615 if (activity.pendingResults == null) { 6616 activity.pendingResults 6617 = new HashSet<WeakReference<PendingIntentRecord>>(); 6618 } 6619 activity.pendingResults.add(rec.ref); 6620 } 6621 return rec; 6622 } 6623 6624 @Override 6625 public void cancelIntentSender(IIntentSender sender) { 6626 if (!(sender instanceof PendingIntentRecord)) { 6627 return; 6628 } 6629 synchronized(this) { 6630 PendingIntentRecord rec = (PendingIntentRecord)sender; 6631 try { 6632 int uid = AppGlobals.getPackageManager() 6633 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId()); 6634 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 6635 String msg = "Permission Denial: cancelIntentSender() from pid=" 6636 + Binder.getCallingPid() 6637 + ", uid=" + Binder.getCallingUid() 6638 + " is not allowed to cancel packges " 6639 + rec.key.packageName; 6640 Slog.w(TAG, msg); 6641 throw new SecurityException(msg); 6642 } 6643 } catch (RemoteException e) { 6644 throw new SecurityException(e); 6645 } 6646 cancelIntentSenderLocked(rec, true); 6647 } 6648 } 6649 6650 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 6651 rec.canceled = true; 6652 mIntentSenderRecords.remove(rec.key); 6653 if (cleanActivity && rec.key.activity != null) { 6654 rec.key.activity.pendingResults.remove(rec.ref); 6655 } 6656 } 6657 6658 @Override 6659 public String getPackageForIntentSender(IIntentSender pendingResult) { 6660 if (!(pendingResult instanceof PendingIntentRecord)) { 6661 return null; 6662 } 6663 try { 6664 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6665 return res.key.packageName; 6666 } catch (ClassCastException e) { 6667 } 6668 return null; 6669 } 6670 6671 @Override 6672 public int getUidForIntentSender(IIntentSender sender) { 6673 if (sender instanceof PendingIntentRecord) { 6674 try { 6675 PendingIntentRecord res = (PendingIntentRecord)sender; 6676 return res.uid; 6677 } catch (ClassCastException e) { 6678 } 6679 } 6680 return -1; 6681 } 6682 6683 @Override 6684 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 6685 if (!(pendingResult instanceof PendingIntentRecord)) { 6686 return false; 6687 } 6688 try { 6689 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6690 if (res.key.allIntents == null) { 6691 return false; 6692 } 6693 for (int i=0; i<res.key.allIntents.length; i++) { 6694 Intent intent = res.key.allIntents[i]; 6695 if (intent.getPackage() != null && intent.getComponent() != null) { 6696 return false; 6697 } 6698 } 6699 return true; 6700 } catch (ClassCastException e) { 6701 } 6702 return false; 6703 } 6704 6705 @Override 6706 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 6707 if (!(pendingResult instanceof PendingIntentRecord)) { 6708 return false; 6709 } 6710 try { 6711 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6712 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 6713 return true; 6714 } 6715 return false; 6716 } catch (ClassCastException e) { 6717 } 6718 return false; 6719 } 6720 6721 @Override 6722 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 6723 if (!(pendingResult instanceof PendingIntentRecord)) { 6724 return null; 6725 } 6726 try { 6727 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6728 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 6729 } catch (ClassCastException e) { 6730 } 6731 return null; 6732 } 6733 6734 @Override 6735 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 6736 if (!(pendingResult instanceof PendingIntentRecord)) { 6737 return null; 6738 } 6739 try { 6740 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6741 Intent intent = res.key.requestIntent; 6742 if (intent != null) { 6743 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 6744 || res.lastTagPrefix.equals(prefix))) { 6745 return res.lastTag; 6746 } 6747 res.lastTagPrefix = prefix; 6748 StringBuilder sb = new StringBuilder(128); 6749 if (prefix != null) { 6750 sb.append(prefix); 6751 } 6752 if (intent.getAction() != null) { 6753 sb.append(intent.getAction()); 6754 } else if (intent.getComponent() != null) { 6755 intent.getComponent().appendShortString(sb); 6756 } else { 6757 sb.append("?"); 6758 } 6759 return res.lastTag = sb.toString(); 6760 } 6761 } catch (ClassCastException e) { 6762 } 6763 return null; 6764 } 6765 6766 @Override 6767 public void setProcessLimit(int max) { 6768 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6769 "setProcessLimit()"); 6770 synchronized (this) { 6771 mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max; 6772 mProcessLimitOverride = max; 6773 } 6774 trimApplications(); 6775 } 6776 6777 @Override 6778 public int getProcessLimit() { 6779 synchronized (this) { 6780 return mProcessLimitOverride; 6781 } 6782 } 6783 6784 void foregroundTokenDied(ForegroundToken token) { 6785 synchronized (ActivityManagerService.this) { 6786 synchronized (mPidsSelfLocked) { 6787 ForegroundToken cur 6788 = mForegroundProcesses.get(token.pid); 6789 if (cur != token) { 6790 return; 6791 } 6792 mForegroundProcesses.remove(token.pid); 6793 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 6794 if (pr == null) { 6795 return; 6796 } 6797 pr.forcingToForeground = null; 6798 updateProcessForegroundLocked(pr, false, false); 6799 } 6800 updateOomAdjLocked(); 6801 } 6802 } 6803 6804 @Override 6805 public void setProcessForeground(IBinder token, int pid, boolean isForeground) { 6806 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6807 "setProcessForeground()"); 6808 synchronized(this) { 6809 boolean changed = false; 6810 6811 synchronized (mPidsSelfLocked) { 6812 ProcessRecord pr = mPidsSelfLocked.get(pid); 6813 if (pr == null && isForeground) { 6814 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 6815 return; 6816 } 6817 ForegroundToken oldToken = mForegroundProcesses.get(pid); 6818 if (oldToken != null) { 6819 oldToken.token.unlinkToDeath(oldToken, 0); 6820 mForegroundProcesses.remove(pid); 6821 if (pr != null) { 6822 pr.forcingToForeground = null; 6823 } 6824 changed = true; 6825 } 6826 if (isForeground && token != null) { 6827 ForegroundToken newToken = new ForegroundToken() { 6828 @Override 6829 public void binderDied() { 6830 foregroundTokenDied(this); 6831 } 6832 }; 6833 newToken.pid = pid; 6834 newToken.token = token; 6835 try { 6836 token.linkToDeath(newToken, 0); 6837 mForegroundProcesses.put(pid, newToken); 6838 pr.forcingToForeground = token; 6839 changed = true; 6840 } catch (RemoteException e) { 6841 // If the process died while doing this, we will later 6842 // do the cleanup with the process death link. 6843 } 6844 } 6845 } 6846 6847 if (changed) { 6848 updateOomAdjLocked(); 6849 } 6850 } 6851 } 6852 6853 // ========================================================= 6854 // PERMISSIONS 6855 // ========================================================= 6856 6857 static class PermissionController extends IPermissionController.Stub { 6858 ActivityManagerService mActivityManagerService; 6859 PermissionController(ActivityManagerService activityManagerService) { 6860 mActivityManagerService = activityManagerService; 6861 } 6862 6863 @Override 6864 public boolean checkPermission(String permission, int pid, int uid) { 6865 return mActivityManagerService.checkPermission(permission, pid, 6866 uid) == PackageManager.PERMISSION_GRANTED; 6867 } 6868 } 6869 6870 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 6871 @Override 6872 public int checkComponentPermission(String permission, int pid, int uid, 6873 int owningUid, boolean exported) { 6874 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 6875 owningUid, exported); 6876 } 6877 6878 @Override 6879 public Object getAMSLock() { 6880 return ActivityManagerService.this; 6881 } 6882 } 6883 6884 /** 6885 * This can be called with or without the global lock held. 6886 */ 6887 int checkComponentPermission(String permission, int pid, int uid, 6888 int owningUid, boolean exported) { 6889 // We might be performing an operation on behalf of an indirect binder 6890 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 6891 // client identity accordingly before proceeding. 6892 Identity tlsIdentity = sCallerIdentity.get(); 6893 if (tlsIdentity != null) { 6894 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 6895 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 6896 uid = tlsIdentity.uid; 6897 pid = tlsIdentity.pid; 6898 } 6899 6900 if (pid == MY_PID) { 6901 return PackageManager.PERMISSION_GRANTED; 6902 } 6903 6904 return ActivityManager.checkComponentPermission(permission, uid, 6905 owningUid, exported); 6906 } 6907 6908 /** 6909 * As the only public entry point for permissions checking, this method 6910 * can enforce the semantic that requesting a check on a null global 6911 * permission is automatically denied. (Internally a null permission 6912 * string is used when calling {@link #checkComponentPermission} in cases 6913 * when only uid-based security is needed.) 6914 * 6915 * This can be called with or without the global lock held. 6916 */ 6917 @Override 6918 public int checkPermission(String permission, int pid, int uid) { 6919 if (permission == null) { 6920 return PackageManager.PERMISSION_DENIED; 6921 } 6922 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true); 6923 } 6924 6925 /** 6926 * Binder IPC calls go through the public entry point. 6927 * This can be called with or without the global lock held. 6928 */ 6929 int checkCallingPermission(String permission) { 6930 return checkPermission(permission, 6931 Binder.getCallingPid(), 6932 UserHandle.getAppId(Binder.getCallingUid())); 6933 } 6934 6935 /** 6936 * This can be called with or without the global lock held. 6937 */ 6938 void enforceCallingPermission(String permission, String func) { 6939 if (checkCallingPermission(permission) 6940 == PackageManager.PERMISSION_GRANTED) { 6941 return; 6942 } 6943 6944 String msg = "Permission Denial: " + func + " from pid=" 6945 + Binder.getCallingPid() 6946 + ", uid=" + Binder.getCallingUid() 6947 + " requires " + permission; 6948 Slog.w(TAG, msg); 6949 throw new SecurityException(msg); 6950 } 6951 6952 /** 6953 * Determine if UID is holding permissions required to access {@link Uri} in 6954 * the given {@link ProviderInfo}. Final permission checking is always done 6955 * in {@link ContentProvider}. 6956 */ 6957 private final boolean checkHoldingPermissionsLocked( 6958 IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) { 6959 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6960 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid); 6961 if (UserHandle.getUserId(uid) != grantUri.sourceUserId) { 6962 if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true) 6963 != PERMISSION_GRANTED) { 6964 return false; 6965 } 6966 } 6967 return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true); 6968 } 6969 6970 private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi, 6971 GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) { 6972 if (pi.applicationInfo.uid == uid) { 6973 return true; 6974 } else if (!pi.exported) { 6975 return false; 6976 } 6977 6978 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 6979 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 6980 try { 6981 // check if target holds top-level <provider> permissions 6982 if (!readMet && pi.readPermission != null && considerUidPermissions 6983 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 6984 readMet = true; 6985 } 6986 if (!writeMet && pi.writePermission != null && considerUidPermissions 6987 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 6988 writeMet = true; 6989 } 6990 6991 // track if unprotected read/write is allowed; any denied 6992 // <path-permission> below removes this ability 6993 boolean allowDefaultRead = pi.readPermission == null; 6994 boolean allowDefaultWrite = pi.writePermission == null; 6995 6996 // check if target holds any <path-permission> that match uri 6997 final PathPermission[] pps = pi.pathPermissions; 6998 if (pps != null) { 6999 final String path = grantUri.uri.getPath(); 7000 int i = pps.length; 7001 while (i > 0 && (!readMet || !writeMet)) { 7002 i--; 7003 PathPermission pp = pps[i]; 7004 if (pp.match(path)) { 7005 if (!readMet) { 7006 final String pprperm = pp.getReadPermission(); 7007 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for " 7008 + pprperm + " for " + pp.getPath() 7009 + ": match=" + pp.match(path) 7010 + " check=" + pm.checkUidPermission(pprperm, uid)); 7011 if (pprperm != null) { 7012 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid) 7013 == PERMISSION_GRANTED) { 7014 readMet = true; 7015 } else { 7016 allowDefaultRead = false; 7017 } 7018 } 7019 } 7020 if (!writeMet) { 7021 final String ppwperm = pp.getWritePermission(); 7022 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm " 7023 + ppwperm + " for " + pp.getPath() 7024 + ": match=" + pp.match(path) 7025 + " check=" + pm.checkUidPermission(ppwperm, uid)); 7026 if (ppwperm != null) { 7027 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid) 7028 == PERMISSION_GRANTED) { 7029 writeMet = true; 7030 } else { 7031 allowDefaultWrite = false; 7032 } 7033 } 7034 } 7035 } 7036 } 7037 } 7038 7039 // grant unprotected <provider> read/write, if not blocked by 7040 // <path-permission> above 7041 if (allowDefaultRead) readMet = true; 7042 if (allowDefaultWrite) writeMet = true; 7043 7044 } catch (RemoteException e) { 7045 return false; 7046 } 7047 7048 return readMet && writeMet; 7049 } 7050 7051 private ProviderInfo getProviderInfoLocked(String authority, int userHandle) { 7052 ProviderInfo pi = null; 7053 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle); 7054 if (cpr != null) { 7055 pi = cpr.info; 7056 } else { 7057 try { 7058 pi = AppGlobals.getPackageManager().resolveContentProvider( 7059 authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle); 7060 } catch (RemoteException ex) { 7061 } 7062 } 7063 return pi; 7064 } 7065 7066 private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) { 7067 final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 7068 if (targetUris != null) { 7069 return targetUris.get(grantUri); 7070 } 7071 return null; 7072 } 7073 7074 private UriPermission findOrCreateUriPermissionLocked(String sourcePkg, 7075 String targetPkg, int targetUid, GrantUri grantUri) { 7076 ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 7077 if (targetUris == null) { 7078 targetUris = Maps.newArrayMap(); 7079 mGrantedUriPermissions.put(targetUid, targetUris); 7080 } 7081 7082 UriPermission perm = targetUris.get(grantUri); 7083 if (perm == null) { 7084 perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri); 7085 targetUris.put(grantUri, perm); 7086 } 7087 7088 return perm; 7089 } 7090 7091 private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid, 7092 final int modeFlags) { 7093 final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0; 7094 final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE 7095 : UriPermission.STRENGTH_OWNED; 7096 7097 // Root gets to do everything. 7098 if (uid == 0) { 7099 return true; 7100 } 7101 7102 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 7103 if (perms == null) return false; 7104 7105 // First look for exact match 7106 final UriPermission exactPerm = perms.get(grantUri); 7107 if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) { 7108 return true; 7109 } 7110 7111 // No exact match, look for prefixes 7112 final int N = perms.size(); 7113 for (int i = 0; i < N; i++) { 7114 final UriPermission perm = perms.valueAt(i); 7115 if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri) 7116 && perm.getStrength(modeFlags) >= minStrength) { 7117 return true; 7118 } 7119 } 7120 7121 return false; 7122 } 7123 7124 /** 7125 * @param uri This uri must NOT contain an embedded userId. 7126 * @param userId The userId in which the uri is to be resolved. 7127 */ 7128 @Override 7129 public int checkUriPermission(Uri uri, int pid, int uid, 7130 final int modeFlags, int userId) { 7131 enforceNotIsolatedCaller("checkUriPermission"); 7132 7133 // Another redirected-binder-call permissions check as in 7134 // {@link checkComponentPermission}. 7135 Identity tlsIdentity = sCallerIdentity.get(); 7136 if (tlsIdentity != null) { 7137 uid = tlsIdentity.uid; 7138 pid = tlsIdentity.pid; 7139 } 7140 7141 // Our own process gets to do everything. 7142 if (pid == MY_PID) { 7143 return PackageManager.PERMISSION_GRANTED; 7144 } 7145 synchronized (this) { 7146 return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags) 7147 ? PackageManager.PERMISSION_GRANTED 7148 : PackageManager.PERMISSION_DENIED; 7149 } 7150 } 7151 7152 /** 7153 * Check if the targetPkg can be granted permission to access uri by 7154 * the callingUid using the given modeFlags. Throws a security exception 7155 * if callingUid is not allowed to do this. Returns the uid of the target 7156 * if the URI permission grant should be performed; returns -1 if it is not 7157 * needed (for example targetPkg already has permission to access the URI). 7158 * If you already know the uid of the target, you can supply it in 7159 * lastTargetUid else set that to -1. 7160 */ 7161 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 7162 final int modeFlags, int lastTargetUid) { 7163 if (!Intent.isAccessUriMode(modeFlags)) { 7164 return -1; 7165 } 7166 7167 if (targetPkg != null) { 7168 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7169 "Checking grant " + targetPkg + " permission to " + grantUri); 7170 } 7171 7172 final IPackageManager pm = AppGlobals.getPackageManager(); 7173 7174 // If this is not a content: uri, we can't do anything with it. 7175 if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) { 7176 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7177 "Can't grant URI permission for non-content URI: " + grantUri); 7178 return -1; 7179 } 7180 7181 final String authority = grantUri.uri.getAuthority(); 7182 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7183 if (pi == null) { 7184 Slog.w(TAG, "No content provider found for permission check: " + 7185 grantUri.uri.toSafeString()); 7186 return -1; 7187 } 7188 7189 int targetUid = lastTargetUid; 7190 if (targetUid < 0 && targetPkg != null) { 7191 try { 7192 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid)); 7193 if (targetUid < 0) { 7194 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7195 "Can't grant URI permission no uid for: " + targetPkg); 7196 return -1; 7197 } 7198 } catch (RemoteException ex) { 7199 return -1; 7200 } 7201 } 7202 7203 if (targetUid >= 0) { 7204 // First... does the target actually need this permission? 7205 if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) { 7206 // No need to grant the target this permission. 7207 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7208 "Target " + targetPkg + " already has full permission to " + grantUri); 7209 return -1; 7210 } 7211 } else { 7212 // First... there is no target package, so can anyone access it? 7213 boolean allowed = pi.exported; 7214 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 7215 if (pi.readPermission != null) { 7216 allowed = false; 7217 } 7218 } 7219 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 7220 if (pi.writePermission != null) { 7221 allowed = false; 7222 } 7223 } 7224 if (allowed) { 7225 return -1; 7226 } 7227 } 7228 7229 /* There is a special cross user grant if: 7230 * - The target is on another user. 7231 * - Apps on the current user can access the uri without any uid permissions. 7232 * In this case, we grant a uri permission, even if the ContentProvider does not normally 7233 * grant uri permissions. 7234 */ 7235 boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId 7236 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid, 7237 modeFlags, false /*without considering the uid permissions*/); 7238 7239 // Second... is the provider allowing granting of URI permissions? 7240 if (!specialCrossUserGrant) { 7241 if (!pi.grantUriPermissions) { 7242 throw new SecurityException("Provider " + pi.packageName 7243 + "/" + pi.name 7244 + " does not allow granting of Uri permissions (uri " 7245 + grantUri + ")"); 7246 } 7247 if (pi.uriPermissionPatterns != null) { 7248 final int N = pi.uriPermissionPatterns.length; 7249 boolean allowed = false; 7250 for (int i=0; i<N; i++) { 7251 if (pi.uriPermissionPatterns[i] != null 7252 && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) { 7253 allowed = true; 7254 break; 7255 } 7256 } 7257 if (!allowed) { 7258 throw new SecurityException("Provider " + pi.packageName 7259 + "/" + pi.name 7260 + " does not allow granting of permission to path of Uri " 7261 + grantUri); 7262 } 7263 } 7264 } 7265 7266 // Third... does the caller itself have permission to access 7267 // this uri? 7268 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) { 7269 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 7270 // Require they hold a strong enough Uri permission 7271 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) { 7272 throw new SecurityException("Uid " + callingUid 7273 + " does not have permission to uri " + grantUri); 7274 } 7275 } 7276 } 7277 return targetUid; 7278 } 7279 7280 /** 7281 * @param uri This uri must NOT contain an embedded userId. 7282 * @param userId The userId in which the uri is to be resolved. 7283 */ 7284 @Override 7285 public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri, 7286 final int modeFlags, int userId) { 7287 enforceNotIsolatedCaller("checkGrantUriPermission"); 7288 synchronized(this) { 7289 return checkGrantUriPermissionLocked(callingUid, targetPkg, 7290 new GrantUri(userId, uri, false), modeFlags, -1); 7291 } 7292 } 7293 7294 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri, 7295 final int modeFlags, UriPermissionOwner owner) { 7296 if (!Intent.isAccessUriMode(modeFlags)) { 7297 return; 7298 } 7299 7300 // So here we are: the caller has the assumed permission 7301 // to the uri, and the target doesn't. Let's now give this to 7302 // the target. 7303 7304 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7305 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri); 7306 7307 final String authority = grantUri.uri.getAuthority(); 7308 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7309 if (pi == null) { 7310 Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString()); 7311 return; 7312 } 7313 7314 if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) { 7315 grantUri.prefix = true; 7316 } 7317 final UriPermission perm = findOrCreateUriPermissionLocked( 7318 pi.packageName, targetPkg, targetUid, grantUri); 7319 perm.grantModes(modeFlags, owner); 7320 } 7321 7322 void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 7323 final int modeFlags, UriPermissionOwner owner, int targetUserId) { 7324 if (targetPkg == null) { 7325 throw new NullPointerException("targetPkg"); 7326 } 7327 int targetUid; 7328 final IPackageManager pm = AppGlobals.getPackageManager(); 7329 try { 7330 targetUid = pm.getPackageUid(targetPkg, targetUserId); 7331 } catch (RemoteException ex) { 7332 return; 7333 } 7334 7335 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags, 7336 targetUid); 7337 if (targetUid < 0) { 7338 return; 7339 } 7340 7341 grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags, 7342 owner); 7343 } 7344 7345 static class NeededUriGrants extends ArrayList<GrantUri> { 7346 final String targetPkg; 7347 final int targetUid; 7348 final int flags; 7349 7350 NeededUriGrants(String targetPkg, int targetUid, int flags) { 7351 this.targetPkg = targetPkg; 7352 this.targetUid = targetUid; 7353 this.flags = flags; 7354 } 7355 } 7356 7357 /** 7358 * Like checkGrantUriPermissionLocked, but takes an Intent. 7359 */ 7360 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid, 7361 String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) { 7362 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7363 "Checking URI perm to data=" + (intent != null ? intent.getData() : null) 7364 + " clip=" + (intent != null ? intent.getClipData() : null) 7365 + " from " + intent + "; flags=0x" 7366 + Integer.toHexString(intent != null ? intent.getFlags() : 0)); 7367 7368 if (targetPkg == null) { 7369 throw new NullPointerException("targetPkg"); 7370 } 7371 7372 if (intent == null) { 7373 return null; 7374 } 7375 Uri data = intent.getData(); 7376 ClipData clip = intent.getClipData(); 7377 if (data == null && clip == null) { 7378 return null; 7379 } 7380 // Default userId for uris in the intent (if they don't specify it themselves) 7381 int contentUserHint = intent.getContentUserHint(); 7382 if (contentUserHint == UserHandle.USER_CURRENT) { 7383 contentUserHint = UserHandle.getUserId(callingUid); 7384 } 7385 final IPackageManager pm = AppGlobals.getPackageManager(); 7386 int targetUid; 7387 if (needed != null) { 7388 targetUid = needed.targetUid; 7389 } else { 7390 try { 7391 targetUid = pm.getPackageUid(targetPkg, targetUserId); 7392 } catch (RemoteException ex) { 7393 return null; 7394 } 7395 if (targetUid < 0) { 7396 if (DEBUG_URI_PERMISSION) { 7397 Slog.v(TAG, "Can't grant URI permission no uid for: " + targetPkg 7398 + " on user " + targetUserId); 7399 } 7400 return null; 7401 } 7402 } 7403 if (data != null) { 7404 GrantUri grantUri = GrantUri.resolve(contentUserHint, data); 7405 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 7406 targetUid); 7407 if (targetUid > 0) { 7408 if (needed == null) { 7409 needed = new NeededUriGrants(targetPkg, targetUid, mode); 7410 } 7411 needed.add(grantUri); 7412 } 7413 } 7414 if (clip != null) { 7415 for (int i=0; i<clip.getItemCount(); i++) { 7416 Uri uri = clip.getItemAt(i).getUri(); 7417 if (uri != null) { 7418 GrantUri grantUri = GrantUri.resolve(contentUserHint, uri); 7419 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 7420 targetUid); 7421 if (targetUid > 0) { 7422 if (needed == null) { 7423 needed = new NeededUriGrants(targetPkg, targetUid, mode); 7424 } 7425 needed.add(grantUri); 7426 } 7427 } else { 7428 Intent clipIntent = clip.getItemAt(i).getIntent(); 7429 if (clipIntent != null) { 7430 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked( 7431 callingUid, targetPkg, clipIntent, mode, needed, targetUserId); 7432 if (newNeeded != null) { 7433 needed = newNeeded; 7434 } 7435 } 7436 } 7437 } 7438 } 7439 7440 return needed; 7441 } 7442 7443 /** 7444 * Like grantUriPermissionUncheckedLocked, but takes an Intent. 7445 */ 7446 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, 7447 UriPermissionOwner owner) { 7448 if (needed != null) { 7449 for (int i=0; i<needed.size(); i++) { 7450 GrantUri grantUri = needed.get(i); 7451 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg, 7452 grantUri, needed.flags, owner); 7453 } 7454 } 7455 } 7456 7457 void grantUriPermissionFromIntentLocked(int callingUid, 7458 String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) { 7459 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, 7460 intent, intent != null ? intent.getFlags() : 0, null, targetUserId); 7461 if (needed == null) { 7462 return; 7463 } 7464 7465 grantUriPermissionUncheckedFromIntentLocked(needed, owner); 7466 } 7467 7468 /** 7469 * @param uri This uri must NOT contain an embedded userId. 7470 * @param userId The userId in which the uri is to be resolved. 7471 */ 7472 @Override 7473 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 7474 final int modeFlags, int userId) { 7475 enforceNotIsolatedCaller("grantUriPermission"); 7476 GrantUri grantUri = new GrantUri(userId, uri, false); 7477 synchronized(this) { 7478 final ProcessRecord r = getRecordForAppLocked(caller); 7479 if (r == null) { 7480 throw new SecurityException("Unable to find app for caller " 7481 + caller 7482 + " when granting permission to uri " + grantUri); 7483 } 7484 if (targetPkg == null) { 7485 throw new IllegalArgumentException("null target"); 7486 } 7487 if (grantUri == null) { 7488 throw new IllegalArgumentException("null uri"); 7489 } 7490 7491 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 7492 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 7493 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 7494 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 7495 7496 grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null, 7497 UserHandle.getUserId(r.uid)); 7498 } 7499 } 7500 7501 void removeUriPermissionIfNeededLocked(UriPermission perm) { 7502 if (perm.modeFlags == 0) { 7503 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 7504 perm.targetUid); 7505 if (perms != null) { 7506 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 7507 "Removing " + perm.targetUid + " permission to " + perm.uri); 7508 7509 perms.remove(perm.uri); 7510 if (perms.isEmpty()) { 7511 mGrantedUriPermissions.remove(perm.targetUid); 7512 } 7513 } 7514 } 7515 } 7516 7517 private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) { 7518 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Revoking all granted permissions to " + grantUri); 7519 7520 final IPackageManager pm = AppGlobals.getPackageManager(); 7521 final String authority = grantUri.uri.getAuthority(); 7522 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7523 if (pi == null) { 7524 Slog.w(TAG, "No content provider found for permission revoke: " 7525 + grantUri.toSafeString()); 7526 return; 7527 } 7528 7529 // Does the caller have this permission on the URI? 7530 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 7531 // Have they don't have direct access to the URI, then revoke any URI 7532 // permissions that have been granted to them. 7533 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 7534 if (perms != null) { 7535 boolean persistChanged = false; 7536 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7537 final UriPermission perm = it.next(); 7538 if (perm.uri.sourceUserId == grantUri.sourceUserId 7539 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 7540 if (DEBUG_URI_PERMISSION) 7541 Slog.v(TAG, 7542 "Revoking " + perm.targetUid + " permission to " + perm.uri); 7543 persistChanged |= perm.revokeModes( 7544 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 7545 if (perm.modeFlags == 0) { 7546 it.remove(); 7547 } 7548 } 7549 } 7550 if (perms.isEmpty()) { 7551 mGrantedUriPermissions.remove(callingUid); 7552 } 7553 if (persistChanged) { 7554 schedulePersistUriGrants(); 7555 } 7556 } 7557 return; 7558 } 7559 7560 boolean persistChanged = false; 7561 7562 // Go through all of the permissions and remove any that match. 7563 int N = mGrantedUriPermissions.size(); 7564 for (int i = 0; i < N; i++) { 7565 final int targetUid = mGrantedUriPermissions.keyAt(i); 7566 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7567 7568 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7569 final UriPermission perm = it.next(); 7570 if (perm.uri.sourceUserId == grantUri.sourceUserId 7571 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 7572 if (DEBUG_URI_PERMISSION) 7573 Slog.v(TAG, 7574 "Revoking " + perm.targetUid + " permission to " + perm.uri); 7575 persistChanged |= perm.revokeModes( 7576 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 7577 if (perm.modeFlags == 0) { 7578 it.remove(); 7579 } 7580 } 7581 } 7582 7583 if (perms.isEmpty()) { 7584 mGrantedUriPermissions.remove(targetUid); 7585 N--; 7586 i--; 7587 } 7588 } 7589 7590 if (persistChanged) { 7591 schedulePersistUriGrants(); 7592 } 7593 } 7594 7595 /** 7596 * @param uri This uri must NOT contain an embedded userId. 7597 * @param userId The userId in which the uri is to be resolved. 7598 */ 7599 @Override 7600 public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags, 7601 int userId) { 7602 enforceNotIsolatedCaller("revokeUriPermission"); 7603 synchronized(this) { 7604 final ProcessRecord r = getRecordForAppLocked(caller); 7605 if (r == null) { 7606 throw new SecurityException("Unable to find app for caller " 7607 + caller 7608 + " when revoking permission to uri " + uri); 7609 } 7610 if (uri == null) { 7611 Slog.w(TAG, "revokeUriPermission: null uri"); 7612 return; 7613 } 7614 7615 if (!Intent.isAccessUriMode(modeFlags)) { 7616 return; 7617 } 7618 7619 final IPackageManager pm = AppGlobals.getPackageManager(); 7620 final String authority = uri.getAuthority(); 7621 final ProviderInfo pi = getProviderInfoLocked(authority, userId); 7622 if (pi == null) { 7623 Slog.w(TAG, "No content provider found for permission revoke: " 7624 + uri.toSafeString()); 7625 return; 7626 } 7627 7628 revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags); 7629 } 7630 } 7631 7632 /** 7633 * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the 7634 * given package. 7635 * 7636 * @param packageName Package name to match, or {@code null} to apply to all 7637 * packages. 7638 * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply 7639 * to all users. 7640 * @param persistable If persistable grants should be removed. 7641 */ 7642 private void removeUriPermissionsForPackageLocked( 7643 String packageName, int userHandle, boolean persistable) { 7644 if (userHandle == UserHandle.USER_ALL && packageName == null) { 7645 throw new IllegalArgumentException("Must narrow by either package or user"); 7646 } 7647 7648 boolean persistChanged = false; 7649 7650 int N = mGrantedUriPermissions.size(); 7651 for (int i = 0; i < N; i++) { 7652 final int targetUid = mGrantedUriPermissions.keyAt(i); 7653 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7654 7655 // Only inspect grants matching user 7656 if (userHandle == UserHandle.USER_ALL 7657 || userHandle == UserHandle.getUserId(targetUid)) { 7658 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7659 final UriPermission perm = it.next(); 7660 7661 // Only inspect grants matching package 7662 if (packageName == null || perm.sourcePkg.equals(packageName) 7663 || perm.targetPkg.equals(packageName)) { 7664 persistChanged |= perm.revokeModes( 7665 persistable ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 7666 7667 // Only remove when no modes remain; any persisted grants 7668 // will keep this alive. 7669 if (perm.modeFlags == 0) { 7670 it.remove(); 7671 } 7672 } 7673 } 7674 7675 if (perms.isEmpty()) { 7676 mGrantedUriPermissions.remove(targetUid); 7677 N--; 7678 i--; 7679 } 7680 } 7681 } 7682 7683 if (persistChanged) { 7684 schedulePersistUriGrants(); 7685 } 7686 } 7687 7688 @Override 7689 public IBinder newUriPermissionOwner(String name) { 7690 enforceNotIsolatedCaller("newUriPermissionOwner"); 7691 synchronized(this) { 7692 UriPermissionOwner owner = new UriPermissionOwner(this, name); 7693 return owner.getExternalTokenLocked(); 7694 } 7695 } 7696 7697 /** 7698 * @param uri This uri must NOT contain an embedded userId. 7699 * @param sourceUserId The userId in which the uri is to be resolved. 7700 * @param targetUserId The userId of the app that receives the grant. 7701 */ 7702 @Override 7703 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri, 7704 final int modeFlags, int sourceUserId, int targetUserId) { 7705 targetUserId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7706 targetUserId, false, ALLOW_FULL_ONLY, "grantUriPermissionFromOwner", null); 7707 synchronized(this) { 7708 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7709 if (owner == null) { 7710 throw new IllegalArgumentException("Unknown owner: " + token); 7711 } 7712 if (fromUid != Binder.getCallingUid()) { 7713 if (Binder.getCallingUid() != Process.myUid()) { 7714 // Only system code can grant URI permissions on behalf 7715 // of other users. 7716 throw new SecurityException("nice try"); 7717 } 7718 } 7719 if (targetPkg == null) { 7720 throw new IllegalArgumentException("null target"); 7721 } 7722 if (uri == null) { 7723 throw new IllegalArgumentException("null uri"); 7724 } 7725 7726 grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false), 7727 modeFlags, owner, targetUserId); 7728 } 7729 } 7730 7731 /** 7732 * @param uri This uri must NOT contain an embedded userId. 7733 * @param userId The userId in which the uri is to be resolved. 7734 */ 7735 @Override 7736 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) { 7737 synchronized(this) { 7738 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7739 if (owner == null) { 7740 throw new IllegalArgumentException("Unknown owner: " + token); 7741 } 7742 7743 if (uri == null) { 7744 owner.removeUriPermissionsLocked(mode); 7745 } else { 7746 owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode); 7747 } 7748 } 7749 } 7750 7751 private void schedulePersistUriGrants() { 7752 if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) { 7753 mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG), 7754 10 * DateUtils.SECOND_IN_MILLIS); 7755 } 7756 } 7757 7758 private void writeGrantedUriPermissions() { 7759 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "writeGrantedUriPermissions()"); 7760 7761 // Snapshot permissions so we can persist without lock 7762 ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList(); 7763 synchronized (this) { 7764 final int size = mGrantedUriPermissions.size(); 7765 for (int i = 0; i < size; i++) { 7766 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7767 for (UriPermission perm : perms.values()) { 7768 if (perm.persistedModeFlags != 0) { 7769 persist.add(perm.snapshot()); 7770 } 7771 } 7772 } 7773 } 7774 7775 FileOutputStream fos = null; 7776 try { 7777 fos = mGrantFile.startWrite(); 7778 7779 XmlSerializer out = new FastXmlSerializer(); 7780 out.setOutput(fos, "utf-8"); 7781 out.startDocument(null, true); 7782 out.startTag(null, TAG_URI_GRANTS); 7783 for (UriPermission.Snapshot perm : persist) { 7784 out.startTag(null, TAG_URI_GRANT); 7785 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId); 7786 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId); 7787 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg); 7788 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg); 7789 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri)); 7790 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix); 7791 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags); 7792 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime); 7793 out.endTag(null, TAG_URI_GRANT); 7794 } 7795 out.endTag(null, TAG_URI_GRANTS); 7796 out.endDocument(); 7797 7798 mGrantFile.finishWrite(fos); 7799 } catch (IOException e) { 7800 if (fos != null) { 7801 mGrantFile.failWrite(fos); 7802 } 7803 } 7804 } 7805 7806 private void readGrantedUriPermissionsLocked() { 7807 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "readGrantedUriPermissions()"); 7808 7809 final long now = System.currentTimeMillis(); 7810 7811 FileInputStream fis = null; 7812 try { 7813 fis = mGrantFile.openRead(); 7814 final XmlPullParser in = Xml.newPullParser(); 7815 in.setInput(fis, null); 7816 7817 int type; 7818 while ((type = in.next()) != END_DOCUMENT) { 7819 final String tag = in.getName(); 7820 if (type == START_TAG) { 7821 if (TAG_URI_GRANT.equals(tag)) { 7822 final int sourceUserId; 7823 final int targetUserId; 7824 final int userHandle = readIntAttribute(in, 7825 ATTR_USER_HANDLE, UserHandle.USER_NULL); 7826 if (userHandle != UserHandle.USER_NULL) { 7827 // For backwards compatibility. 7828 sourceUserId = userHandle; 7829 targetUserId = userHandle; 7830 } else { 7831 sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID); 7832 targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID); 7833 } 7834 final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG); 7835 final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG); 7836 final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI)); 7837 final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX); 7838 final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS); 7839 final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now); 7840 7841 // Sanity check that provider still belongs to source package 7842 final ProviderInfo pi = getProviderInfoLocked( 7843 uri.getAuthority(), sourceUserId); 7844 if (pi != null && sourcePkg.equals(pi.packageName)) { 7845 int targetUid = -1; 7846 try { 7847 targetUid = AppGlobals.getPackageManager() 7848 .getPackageUid(targetPkg, targetUserId); 7849 } catch (RemoteException e) { 7850 } 7851 if (targetUid != -1) { 7852 final UriPermission perm = findOrCreateUriPermissionLocked( 7853 sourcePkg, targetPkg, targetUid, 7854 new GrantUri(sourceUserId, uri, prefix)); 7855 perm.initPersistedModes(modeFlags, createdTime); 7856 } 7857 } else { 7858 Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg 7859 + " but instead found " + pi); 7860 } 7861 } 7862 } 7863 } 7864 } catch (FileNotFoundException e) { 7865 // Missing grants is okay 7866 } catch (IOException e) { 7867 Log.wtf(TAG, "Failed reading Uri grants", e); 7868 } catch (XmlPullParserException e) { 7869 Log.wtf(TAG, "Failed reading Uri grants", e); 7870 } finally { 7871 IoUtils.closeQuietly(fis); 7872 } 7873 } 7874 7875 /** 7876 * @param uri This uri must NOT contain an embedded userId. 7877 * @param userId The userId in which the uri is to be resolved. 7878 */ 7879 @Override 7880 public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 7881 enforceNotIsolatedCaller("takePersistableUriPermission"); 7882 7883 Preconditions.checkFlagsArgument(modeFlags, 7884 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 7885 7886 synchronized (this) { 7887 final int callingUid = Binder.getCallingUid(); 7888 boolean persistChanged = false; 7889 GrantUri grantUri = new GrantUri(userId, uri, false); 7890 7891 UriPermission exactPerm = findUriPermissionLocked(callingUid, 7892 new GrantUri(userId, uri, false)); 7893 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 7894 new GrantUri(userId, uri, true)); 7895 7896 final boolean exactValid = (exactPerm != null) 7897 && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags); 7898 final boolean prefixValid = (prefixPerm != null) 7899 && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags); 7900 7901 if (!(exactValid || prefixValid)) { 7902 throw new SecurityException("No persistable permission grants found for UID " 7903 + callingUid + " and Uri " + grantUri.toSafeString()); 7904 } 7905 7906 if (exactValid) { 7907 persistChanged |= exactPerm.takePersistableModes(modeFlags); 7908 } 7909 if (prefixValid) { 7910 persistChanged |= prefixPerm.takePersistableModes(modeFlags); 7911 } 7912 7913 persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid); 7914 7915 if (persistChanged) { 7916 schedulePersistUriGrants(); 7917 } 7918 } 7919 } 7920 7921 /** 7922 * @param uri This uri must NOT contain an embedded userId. 7923 * @param userId The userId in which the uri is to be resolved. 7924 */ 7925 @Override 7926 public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 7927 enforceNotIsolatedCaller("releasePersistableUriPermission"); 7928 7929 Preconditions.checkFlagsArgument(modeFlags, 7930 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 7931 7932 synchronized (this) { 7933 final int callingUid = Binder.getCallingUid(); 7934 boolean persistChanged = false; 7935 7936 UriPermission exactPerm = findUriPermissionLocked(callingUid, 7937 new GrantUri(userId, uri, false)); 7938 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 7939 new GrantUri(userId, uri, true)); 7940 if (exactPerm == null && prefixPerm == null) { 7941 throw new SecurityException("No permission grants found for UID " + callingUid 7942 + " and Uri " + uri.toSafeString()); 7943 } 7944 7945 if (exactPerm != null) { 7946 persistChanged |= exactPerm.releasePersistableModes(modeFlags); 7947 removeUriPermissionIfNeededLocked(exactPerm); 7948 } 7949 if (prefixPerm != null) { 7950 persistChanged |= prefixPerm.releasePersistableModes(modeFlags); 7951 removeUriPermissionIfNeededLocked(prefixPerm); 7952 } 7953 7954 if (persistChanged) { 7955 schedulePersistUriGrants(); 7956 } 7957 } 7958 } 7959 7960 /** 7961 * Prune any older {@link UriPermission} for the given UID until outstanding 7962 * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}. 7963 * 7964 * @return if any mutations occured that require persisting. 7965 */ 7966 private boolean maybePrunePersistedUriGrantsLocked(int uid) { 7967 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 7968 if (perms == null) return false; 7969 if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false; 7970 7971 final ArrayList<UriPermission> persisted = Lists.newArrayList(); 7972 for (UriPermission perm : perms.values()) { 7973 if (perm.persistedModeFlags != 0) { 7974 persisted.add(perm); 7975 } 7976 } 7977 7978 final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS; 7979 if (trimCount <= 0) return false; 7980 7981 Collections.sort(persisted, new UriPermission.PersistedTimeComparator()); 7982 for (int i = 0; i < trimCount; i++) { 7983 final UriPermission perm = persisted.get(i); 7984 7985 if (DEBUG_URI_PERMISSION) { 7986 Slog.v(TAG, "Trimming grant created at " + perm.persistedCreateTime); 7987 } 7988 7989 perm.releasePersistableModes(~0); 7990 removeUriPermissionIfNeededLocked(perm); 7991 } 7992 7993 return true; 7994 } 7995 7996 @Override 7997 public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions( 7998 String packageName, boolean incoming) { 7999 enforceNotIsolatedCaller("getPersistedUriPermissions"); 8000 Preconditions.checkNotNull(packageName, "packageName"); 8001 8002 final int callingUid = Binder.getCallingUid(); 8003 final IPackageManager pm = AppGlobals.getPackageManager(); 8004 try { 8005 final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid)); 8006 if (packageUid != callingUid) { 8007 throw new SecurityException( 8008 "Package " + packageName + " does not belong to calling UID " + callingUid); 8009 } 8010 } catch (RemoteException e) { 8011 throw new SecurityException("Failed to verify package name ownership"); 8012 } 8013 8014 final ArrayList<android.content.UriPermission> result = Lists.newArrayList(); 8015 synchronized (this) { 8016 if (incoming) { 8017 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 8018 callingUid); 8019 if (perms == null) { 8020 Slog.w(TAG, "No permission grants found for " + packageName); 8021 } else { 8022 for (UriPermission perm : perms.values()) { 8023 if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) { 8024 result.add(perm.buildPersistedPublicApiObject()); 8025 } 8026 } 8027 } 8028 } else { 8029 final int size = mGrantedUriPermissions.size(); 8030 for (int i = 0; i < size; i++) { 8031 final ArrayMap<GrantUri, UriPermission> perms = 8032 mGrantedUriPermissions.valueAt(i); 8033 for (UriPermission perm : perms.values()) { 8034 if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) { 8035 result.add(perm.buildPersistedPublicApiObject()); 8036 } 8037 } 8038 } 8039 } 8040 } 8041 return new ParceledListSlice<android.content.UriPermission>(result); 8042 } 8043 8044 @Override 8045 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 8046 synchronized (this) { 8047 ProcessRecord app = 8048 who != null ? getRecordForAppLocked(who) : null; 8049 if (app == null) return; 8050 8051 Message msg = Message.obtain(); 8052 msg.what = WAIT_FOR_DEBUGGER_MSG; 8053 msg.obj = app; 8054 msg.arg1 = waiting ? 1 : 0; 8055 mHandler.sendMessage(msg); 8056 } 8057 } 8058 8059 @Override 8060 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 8061 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ); 8062 final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ); 8063 outInfo.availMem = Process.getFreeMemory(); 8064 outInfo.totalMem = Process.getTotalMemory(); 8065 outInfo.threshold = homeAppMem; 8066 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2)); 8067 outInfo.hiddenAppThreshold = cachedAppMem; 8068 outInfo.secondaryServerThreshold = mProcessList.getMemLevel( 8069 ProcessList.SERVICE_ADJ); 8070 outInfo.visibleAppThreshold = mProcessList.getMemLevel( 8071 ProcessList.VISIBLE_APP_ADJ); 8072 outInfo.foregroundAppThreshold = mProcessList.getMemLevel( 8073 ProcessList.FOREGROUND_APP_ADJ); 8074 } 8075 8076 // ========================================================= 8077 // TASK MANAGEMENT 8078 // ========================================================= 8079 8080 @Override 8081 public List<IAppTask> getAppTasks(String callingPackage) { 8082 int callingUid = Binder.getCallingUid(); 8083 long ident = Binder.clearCallingIdentity(); 8084 8085 synchronized(this) { 8086 ArrayList<IAppTask> list = new ArrayList<IAppTask>(); 8087 try { 8088 if (localLOGV) Slog.v(TAG, "getAppTasks"); 8089 8090 final int N = mRecentTasks.size(); 8091 for (int i = 0; i < N; i++) { 8092 TaskRecord tr = mRecentTasks.get(i); 8093 // Skip tasks that do not match the caller. We don't need to verify 8094 // callingPackage, because we are also limiting to callingUid and know 8095 // that will limit to the correct security sandbox. 8096 if (tr.effectiveUid != callingUid) { 8097 continue; 8098 } 8099 Intent intent = tr.getBaseIntent(); 8100 if (intent == null || 8101 !callingPackage.equals(intent.getComponent().getPackageName())) { 8102 continue; 8103 } 8104 ActivityManager.RecentTaskInfo taskInfo = 8105 createRecentTaskInfoFromTaskRecord(tr); 8106 AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid); 8107 list.add(taskImpl); 8108 } 8109 } finally { 8110 Binder.restoreCallingIdentity(ident); 8111 } 8112 return list; 8113 } 8114 } 8115 8116 @Override 8117 public List<RunningTaskInfo> getTasks(int maxNum, int flags) { 8118 final int callingUid = Binder.getCallingUid(); 8119 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>(); 8120 8121 synchronized(this) { 8122 if (localLOGV) Slog.v( 8123 TAG, "getTasks: max=" + maxNum + ", flags=" + flags); 8124 8125 final boolean allowed = checkCallingPermission( 8126 android.Manifest.permission.GET_TASKS) 8127 == PackageManager.PERMISSION_GRANTED; 8128 if (!allowed) { 8129 Slog.w(TAG, "getTasks: caller " + callingUid 8130 + " does not hold GET_TASKS; limiting output"); 8131 } 8132 8133 // TODO: Improve with MRU list from all ActivityStacks. 8134 mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed); 8135 } 8136 8137 return list; 8138 } 8139 8140 TaskRecord getMostRecentTask() { 8141 return mRecentTasks.get(0); 8142 } 8143 8144 /** 8145 * Creates a new RecentTaskInfo from a TaskRecord. 8146 */ 8147 private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) { 8148 // Update the task description to reflect any changes in the task stack 8149 tr.updateTaskDescription(); 8150 8151 // Compose the recent task info 8152 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); 8153 rti.id = tr.getTopActivity() == null ? -1 : tr.taskId; 8154 rti.persistentId = tr.taskId; 8155 rti.baseIntent = new Intent(tr.getBaseIntent()); 8156 rti.origActivity = tr.origActivity; 8157 rti.description = tr.lastDescription; 8158 rti.stackId = tr.stack != null ? tr.stack.mStackId : -1; 8159 rti.userId = tr.userId; 8160 rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription); 8161 rti.firstActiveTime = tr.firstActiveTime; 8162 rti.lastActiveTime = tr.lastActiveTime; 8163 rti.affiliatedTaskId = tr.mAffiliatedTaskId; 8164 rti.affiliatedTaskColor = tr.mAffiliatedTaskColor; 8165 return rti; 8166 } 8167 8168 @Override 8169 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) { 8170 final int callingUid = Binder.getCallingUid(); 8171 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 8172 false, ALLOW_FULL_ONLY, "getRecentTasks", null); 8173 8174 final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0; 8175 final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0; 8176 synchronized (this) { 8177 final boolean allowed = checkCallingPermission(android.Manifest.permission.GET_TASKS) 8178 == PackageManager.PERMISSION_GRANTED; 8179 if (!allowed) { 8180 Slog.w(TAG, "getRecentTasks: caller " + callingUid 8181 + " does not hold GET_TASKS; limiting output"); 8182 } 8183 final boolean detailed = checkCallingPermission( 8184 android.Manifest.permission.GET_DETAILED_TASKS) 8185 == PackageManager.PERMISSION_GRANTED; 8186 8187 final int N = mRecentTasks.size(); 8188 ArrayList<ActivityManager.RecentTaskInfo> res 8189 = new ArrayList<ActivityManager.RecentTaskInfo>( 8190 maxNum < N ? maxNum : N); 8191 8192 final Set<Integer> includedUsers; 8193 if (includeProfiles) { 8194 includedUsers = getProfileIdsLocked(userId); 8195 } else { 8196 includedUsers = new HashSet<Integer>(); 8197 } 8198 includedUsers.add(Integer.valueOf(userId)); 8199 8200 for (int i=0; i<N && maxNum > 0; i++) { 8201 TaskRecord tr = mRecentTasks.get(i); 8202 // Only add calling user or related users recent tasks 8203 if (!includedUsers.contains(Integer.valueOf(tr.userId))) { 8204 if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not user: " + tr); 8205 continue; 8206 } 8207 8208 // Return the entry if desired by the caller. We always return 8209 // the first entry, because callers always expect this to be the 8210 // foreground app. We may filter others if the caller has 8211 // not supplied RECENT_WITH_EXCLUDED and there is some reason 8212 // we should exclude the entry. 8213 8214 if (i == 0 8215 || withExcluded 8216 || (tr.intent == null) 8217 || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) 8218 == 0)) { 8219 if (!allowed) { 8220 // If the caller doesn't have the GET_TASKS permission, then only 8221 // allow them to see a small subset of tasks -- their own and home. 8222 if (!tr.isHomeTask() && tr.effectiveUid != callingUid) { 8223 if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not allowed: " + tr); 8224 continue; 8225 } 8226 } 8227 if ((flags & ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS) != 0) { 8228 if (tr.stack != null && tr.stack.isHomeStack()) { 8229 if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, home stack task: " + tr); 8230 continue; 8231 } 8232 } 8233 if (tr.autoRemoveRecents && tr.getTopActivity() == null) { 8234 // Don't include auto remove tasks that are finished or finishing. 8235 if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, auto-remove without activity: " 8236 + tr); 8237 continue; 8238 } 8239 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0 8240 && !tr.isAvailable) { 8241 if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, unavail real act: " + tr); 8242 continue; 8243 } 8244 8245 ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr); 8246 if (!detailed) { 8247 rti.baseIntent.replaceExtras((Bundle)null); 8248 } 8249 8250 res.add(rti); 8251 maxNum--; 8252 } 8253 } 8254 return res; 8255 } 8256 } 8257 8258 private TaskRecord recentTaskForIdLocked(int id) { 8259 final int N = mRecentTasks.size(); 8260 for (int i=0; i<N; i++) { 8261 TaskRecord tr = mRecentTasks.get(i); 8262 if (tr.taskId == id) { 8263 return tr; 8264 } 8265 } 8266 return null; 8267 } 8268 8269 @Override 8270 public ActivityManager.TaskThumbnail getTaskThumbnail(int id) { 8271 synchronized (this) { 8272 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 8273 "getTaskThumbnail()"); 8274 TaskRecord tr = recentTaskForIdLocked(id); 8275 if (tr != null) { 8276 return tr.getTaskThumbnailLocked(); 8277 } 8278 } 8279 return null; 8280 } 8281 8282 @Override 8283 public int addAppTask(IBinder activityToken, Intent intent, 8284 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException { 8285 final int callingUid = Binder.getCallingUid(); 8286 final long callingIdent = Binder.clearCallingIdentity(); 8287 8288 try { 8289 synchronized (this) { 8290 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken); 8291 if (r == null) { 8292 throw new IllegalArgumentException("Activity does not exist; token=" 8293 + activityToken); 8294 } 8295 ComponentName comp = intent.getComponent(); 8296 if (comp == null) { 8297 throw new IllegalArgumentException("Intent " + intent 8298 + " must specify explicit component"); 8299 } 8300 if (thumbnail.getWidth() != mThumbnailWidth 8301 || thumbnail.getHeight() != mThumbnailHeight) { 8302 throw new IllegalArgumentException("Bad thumbnail size: got " 8303 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require " 8304 + mThumbnailWidth + "x" + mThumbnailHeight); 8305 } 8306 if (intent.getSelector() != null) { 8307 intent.setSelector(null); 8308 } 8309 if (intent.getSourceBounds() != null) { 8310 intent.setSourceBounds(null); 8311 } 8312 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) { 8313 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) { 8314 // The caller has added this as an auto-remove task... that makes no 8315 // sense, so turn off auto-remove. 8316 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS); 8317 } 8318 } else if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { 8319 // Must be a new task. 8320 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 8321 } 8322 if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) { 8323 mLastAddedTaskActivity = null; 8324 } 8325 ActivityInfo ainfo = mLastAddedTaskActivity; 8326 if (ainfo == null) { 8327 ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo( 8328 comp, 0, UserHandle.getUserId(callingUid)); 8329 if (ainfo.applicationInfo.uid != callingUid) { 8330 throw new SecurityException( 8331 "Can't add task for another application: target uid=" 8332 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid); 8333 } 8334 } 8335 8336 TaskRecord task = new TaskRecord(this, mStackSupervisor.getNextTaskId(), ainfo, 8337 intent, description); 8338 8339 int trimIdx = trimRecentsForTask(task, false); 8340 if (trimIdx >= 0) { 8341 // If this would have caused a trim, then we'll abort because that 8342 // means it would be added at the end of the list but then just removed. 8343 return -1; 8344 } 8345 8346 final int N = mRecentTasks.size(); 8347 if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) { 8348 final TaskRecord tr = mRecentTasks.remove(N - 1); 8349 tr.removedFromRecents(mTaskPersister); 8350 } 8351 8352 task.inRecents = true; 8353 mRecentTasks.add(task); 8354 r.task.stack.addTask(task, false, false); 8355 8356 task.setLastThumbnail(thumbnail); 8357 task.freeLastThumbnail(); 8358 8359 return task.taskId; 8360 } 8361 } finally { 8362 Binder.restoreCallingIdentity(callingIdent); 8363 } 8364 } 8365 8366 @Override 8367 public Point getAppTaskThumbnailSize() { 8368 synchronized (this) { 8369 return new Point(mThumbnailWidth, mThumbnailHeight); 8370 } 8371 } 8372 8373 @Override 8374 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) { 8375 synchronized (this) { 8376 ActivityRecord r = ActivityRecord.isInStackLocked(token); 8377 if (r != null) { 8378 r.taskDescription = td; 8379 r.task.updateTaskDescription(); 8380 } 8381 } 8382 } 8383 8384 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) { 8385 mRecentTasks.remove(tr); 8386 tr.removedFromRecents(mTaskPersister); 8387 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0; 8388 Intent baseIntent = new Intent( 8389 tr.intent != null ? tr.intent : tr.affinityIntent); 8390 ComponentName component = baseIntent.getComponent(); 8391 if (component == null) { 8392 Slog.w(TAG, "Now component for base intent of task: " + tr); 8393 return; 8394 } 8395 8396 // Find any running services associated with this app. 8397 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent); 8398 8399 if (killProcesses) { 8400 // Find any running processes associated with this app. 8401 final String pkg = component.getPackageName(); 8402 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 8403 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 8404 for (int i=0; i<pmap.size(); i++) { 8405 SparseArray<ProcessRecord> uids = pmap.valueAt(i); 8406 for (int j=0; j<uids.size(); j++) { 8407 ProcessRecord proc = uids.valueAt(j); 8408 if (proc.userId != tr.userId) { 8409 continue; 8410 } 8411 if (!proc.pkgList.containsKey(pkg)) { 8412 continue; 8413 } 8414 procs.add(proc); 8415 } 8416 } 8417 8418 // Kill the running processes. 8419 for (int i=0; i<procs.size(); i++) { 8420 ProcessRecord pr = procs.get(i); 8421 if (pr == mHomeProcess) { 8422 // Don't kill the home process along with tasks from the same package. 8423 continue; 8424 } 8425 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 8426 pr.kill("remove task", true); 8427 } else { 8428 pr.waitingToKill = "remove task"; 8429 } 8430 } 8431 } 8432 } 8433 8434 /** 8435 * Removes the task with the specified task id. 8436 * 8437 * @param taskId Identifier of the task to be removed. 8438 * @param flags Additional operational flags. May be 0 or 8439 * {@link ActivityManager#REMOVE_TASK_KILL_PROCESS}. 8440 * @return Returns true if the given task was found and removed. 8441 */ 8442 private boolean removeTaskByIdLocked(int taskId, int flags) { 8443 TaskRecord tr = recentTaskForIdLocked(taskId); 8444 if (tr != null) { 8445 tr.removeTaskActivitiesLocked(); 8446 cleanUpRemovedTaskLocked(tr, flags); 8447 if (tr.isPersistable) { 8448 notifyTaskPersisterLocked(null, true); 8449 } 8450 return true; 8451 } 8452 return false; 8453 } 8454 8455 @Override 8456 public boolean removeTask(int taskId, int flags) { 8457 synchronized (this) { 8458 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 8459 "removeTask()"); 8460 long ident = Binder.clearCallingIdentity(); 8461 try { 8462 return removeTaskByIdLocked(taskId, flags); 8463 } finally { 8464 Binder.restoreCallingIdentity(ident); 8465 } 8466 } 8467 } 8468 8469 /** 8470 * TODO: Add mController hook 8471 */ 8472 @Override 8473 public void moveTaskToFront(int taskId, int flags, Bundle options) { 8474 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8475 "moveTaskToFront()"); 8476 8477 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToFront: moving taskId=" + taskId); 8478 synchronized(this) { 8479 moveTaskToFrontLocked(taskId, flags, options); 8480 } 8481 } 8482 8483 void moveTaskToFrontLocked(int taskId, int flags, Bundle options) { 8484 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8485 Binder.getCallingUid(), "Task to front")) { 8486 ActivityOptions.abort(options); 8487 return; 8488 } 8489 final long origId = Binder.clearCallingIdentity(); 8490 try { 8491 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 8492 if (task == null) { 8493 return; 8494 } 8495 if (mStackSupervisor.isLockTaskModeViolation(task)) { 8496 mStackSupervisor.showLockTaskToast(); 8497 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode"); 8498 return; 8499 } 8500 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked(); 8501 if (prev != null && prev.isRecentsActivity()) { 8502 task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE); 8503 } 8504 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options); 8505 } finally { 8506 Binder.restoreCallingIdentity(origId); 8507 } 8508 ActivityOptions.abort(options); 8509 } 8510 8511 @Override 8512 public void moveTaskToBack(int taskId) { 8513 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8514 "moveTaskToBack()"); 8515 8516 synchronized(this) { 8517 TaskRecord tr = recentTaskForIdLocked(taskId); 8518 if (tr != null) { 8519 if (tr == mStackSupervisor.mLockTaskModeTask) { 8520 mStackSupervisor.showLockTaskToast(); 8521 return; 8522 } 8523 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToBack: moving task=" + tr); 8524 ActivityStack stack = tr.stack; 8525 if (stack.mResumedActivity != null && stack.mResumedActivity.task == tr) { 8526 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8527 Binder.getCallingUid(), "Task to back")) { 8528 return; 8529 } 8530 } 8531 final long origId = Binder.clearCallingIdentity(); 8532 try { 8533 stack.moveTaskToBackLocked(taskId, null); 8534 } finally { 8535 Binder.restoreCallingIdentity(origId); 8536 } 8537 } 8538 } 8539 } 8540 8541 /** 8542 * Moves an activity, and all of the other activities within the same task, to the bottom 8543 * of the history stack. The activity's order within the task is unchanged. 8544 * 8545 * @param token A reference to the activity we wish to move 8546 * @param nonRoot If false then this only works if the activity is the root 8547 * of a task; if true it will work for any activity in a task. 8548 * @return Returns true if the move completed, false if not. 8549 */ 8550 @Override 8551 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 8552 enforceNotIsolatedCaller("moveActivityTaskToBack"); 8553 synchronized(this) { 8554 final long origId = Binder.clearCallingIdentity(); 8555 try { 8556 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); 8557 if (taskId >= 0) { 8558 if ((mStackSupervisor.mLockTaskModeTask != null) 8559 && (mStackSupervisor.mLockTaskModeTask.taskId == taskId)) { 8560 mStackSupervisor.showLockTaskToast(); 8561 return false; 8562 } 8563 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId, null); 8564 } 8565 } finally { 8566 Binder.restoreCallingIdentity(origId); 8567 } 8568 } 8569 return false; 8570 } 8571 8572 @Override 8573 public void moveTaskBackwards(int task) { 8574 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8575 "moveTaskBackwards()"); 8576 8577 synchronized(this) { 8578 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8579 Binder.getCallingUid(), "Task backwards")) { 8580 return; 8581 } 8582 final long origId = Binder.clearCallingIdentity(); 8583 moveTaskBackwardsLocked(task); 8584 Binder.restoreCallingIdentity(origId); 8585 } 8586 } 8587 8588 private final void moveTaskBackwardsLocked(int task) { 8589 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 8590 } 8591 8592 @Override 8593 public IBinder getHomeActivityToken() throws RemoteException { 8594 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8595 "getHomeActivityToken()"); 8596 synchronized (this) { 8597 return mStackSupervisor.getHomeActivityToken(); 8598 } 8599 } 8600 8601 @Override 8602 public IActivityContainer createActivityContainer(IBinder parentActivityToken, 8603 IActivityContainerCallback callback) throws RemoteException { 8604 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8605 "createActivityContainer()"); 8606 synchronized (this) { 8607 if (parentActivityToken == null) { 8608 throw new IllegalArgumentException("parent token must not be null"); 8609 } 8610 ActivityRecord r = ActivityRecord.forToken(parentActivityToken); 8611 if (r == null) { 8612 return null; 8613 } 8614 if (callback == null) { 8615 throw new IllegalArgumentException("callback must not be null"); 8616 } 8617 return mStackSupervisor.createActivityContainer(r, callback); 8618 } 8619 } 8620 8621 @Override 8622 public void deleteActivityContainer(IActivityContainer container) throws RemoteException { 8623 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8624 "deleteActivityContainer()"); 8625 synchronized (this) { 8626 mStackSupervisor.deleteActivityContainer(container); 8627 } 8628 } 8629 8630 @Override 8631 public IActivityContainer getEnclosingActivityContainer(IBinder activityToken) 8632 throws RemoteException { 8633 synchronized (this) { 8634 ActivityStack stack = ActivityRecord.getStackLocked(activityToken); 8635 if (stack != null) { 8636 return stack.mActivityContainer; 8637 } 8638 return null; 8639 } 8640 } 8641 8642 @Override 8643 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 8644 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8645 "moveTaskToStack()"); 8646 if (stackId == HOME_STACK_ID) { 8647 Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack", 8648 new RuntimeException("here").fillInStackTrace()); 8649 } 8650 synchronized (this) { 8651 long ident = Binder.clearCallingIdentity(); 8652 try { 8653 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToStack: moving task=" + taskId + " to stackId=" 8654 + stackId + " toTop=" + toTop); 8655 mStackSupervisor.moveTaskToStack(taskId, stackId, toTop); 8656 } finally { 8657 Binder.restoreCallingIdentity(ident); 8658 } 8659 } 8660 } 8661 8662 @Override 8663 public void resizeStack(int stackBoxId, Rect bounds) { 8664 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8665 "resizeStackBox()"); 8666 long ident = Binder.clearCallingIdentity(); 8667 try { 8668 mWindowManager.resizeStack(stackBoxId, bounds); 8669 } finally { 8670 Binder.restoreCallingIdentity(ident); 8671 } 8672 } 8673 8674 @Override 8675 public List<StackInfo> getAllStackInfos() { 8676 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8677 "getAllStackInfos()"); 8678 long ident = Binder.clearCallingIdentity(); 8679 try { 8680 synchronized (this) { 8681 return mStackSupervisor.getAllStackInfosLocked(); 8682 } 8683 } finally { 8684 Binder.restoreCallingIdentity(ident); 8685 } 8686 } 8687 8688 @Override 8689 public StackInfo getStackInfo(int stackId) { 8690 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8691 "getStackInfo()"); 8692 long ident = Binder.clearCallingIdentity(); 8693 try { 8694 synchronized (this) { 8695 return mStackSupervisor.getStackInfoLocked(stackId); 8696 } 8697 } finally { 8698 Binder.restoreCallingIdentity(ident); 8699 } 8700 } 8701 8702 @Override 8703 public boolean isInHomeStack(int taskId) { 8704 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8705 "getStackInfo()"); 8706 long ident = Binder.clearCallingIdentity(); 8707 try { 8708 synchronized (this) { 8709 TaskRecord tr = recentTaskForIdLocked(taskId); 8710 return tr != null && tr.stack != null && tr.stack.isHomeStack(); 8711 } 8712 } finally { 8713 Binder.restoreCallingIdentity(ident); 8714 } 8715 } 8716 8717 @Override 8718 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 8719 synchronized(this) { 8720 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot); 8721 } 8722 } 8723 8724 private boolean isLockTaskAuthorized(String pkg) { 8725 final DevicePolicyManager dpm = (DevicePolicyManager) 8726 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 8727 try { 8728 int uid = mContext.getPackageManager().getPackageUid(pkg, 8729 Binder.getCallingUserHandle().getIdentifier()); 8730 return (uid == Binder.getCallingUid()) && dpm != null && dpm.isLockTaskPermitted(pkg); 8731 } catch (NameNotFoundException e) { 8732 return false; 8733 } 8734 } 8735 8736 void startLockTaskMode(TaskRecord task) { 8737 final String pkg; 8738 synchronized (this) { 8739 pkg = task.intent.getComponent().getPackageName(); 8740 } 8741 boolean isSystemInitiated = Binder.getCallingUid() == Process.SYSTEM_UID; 8742 if (!isSystemInitiated && !isLockTaskAuthorized(pkg)) { 8743 final TaskRecord taskRecord = task; 8744 mHandler.post(new Runnable() { 8745 @Override 8746 public void run() { 8747 mLockToAppRequest.showLockTaskPrompt(taskRecord); 8748 } 8749 }); 8750 return; 8751 } 8752 long ident = Binder.clearCallingIdentity(); 8753 try { 8754 synchronized (this) { 8755 // Since we lost lock on task, make sure it is still there. 8756 task = mStackSupervisor.anyTaskForIdLocked(task.taskId); 8757 if (task != null) { 8758 if (!isSystemInitiated 8759 && ((mFocusedActivity == null) || (task != mFocusedActivity.task))) { 8760 throw new IllegalArgumentException("Invalid task, not in foreground"); 8761 } 8762 mStackSupervisor.setLockTaskModeLocked(task, !isSystemInitiated); 8763 } 8764 } 8765 } finally { 8766 Binder.restoreCallingIdentity(ident); 8767 } 8768 } 8769 8770 @Override 8771 public void startLockTaskMode(int taskId) { 8772 final TaskRecord task; 8773 long ident = Binder.clearCallingIdentity(); 8774 try { 8775 synchronized (this) { 8776 task = mStackSupervisor.anyTaskForIdLocked(taskId); 8777 } 8778 } finally { 8779 Binder.restoreCallingIdentity(ident); 8780 } 8781 if (task != null) { 8782 startLockTaskMode(task); 8783 } 8784 } 8785 8786 @Override 8787 public void startLockTaskMode(IBinder token) { 8788 final TaskRecord task; 8789 long ident = Binder.clearCallingIdentity(); 8790 try { 8791 synchronized (this) { 8792 final ActivityRecord r = ActivityRecord.forToken(token); 8793 if (r == null) { 8794 return; 8795 } 8796 task = r.task; 8797 } 8798 } finally { 8799 Binder.restoreCallingIdentity(ident); 8800 } 8801 if (task != null) { 8802 startLockTaskMode(task); 8803 } 8804 } 8805 8806 @Override 8807 public void startLockTaskModeOnCurrent() throws RemoteException { 8808 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8809 "startLockTaskModeOnCurrent"); 8810 ActivityRecord r = null; 8811 synchronized (this) { 8812 r = mStackSupervisor.topRunningActivityLocked(); 8813 } 8814 startLockTaskMode(r.task); 8815 } 8816 8817 @Override 8818 public void stopLockTaskMode() { 8819 // Verify that the user matches the package of the intent for the TaskRecord 8820 // we are locked to or systtem. This will ensure the same caller for startLockTaskMode 8821 // and stopLockTaskMode. 8822 final int callingUid = Binder.getCallingUid(); 8823 if (callingUid != Process.SYSTEM_UID) { 8824 try { 8825 String pkg = 8826 mStackSupervisor.mLockTaskModeTask.intent.getComponent().getPackageName(); 8827 int uid = mContext.getPackageManager().getPackageUid(pkg, 8828 Binder.getCallingUserHandle().getIdentifier()); 8829 if (uid != callingUid) { 8830 throw new SecurityException("Invalid uid, expected " + uid); 8831 } 8832 } catch (NameNotFoundException e) { 8833 Log.d(TAG, "stopLockTaskMode " + e); 8834 return; 8835 } 8836 } 8837 long ident = Binder.clearCallingIdentity(); 8838 try { 8839 Log.d(TAG, "stopLockTaskMode"); 8840 // Stop lock task 8841 synchronized (this) { 8842 mStackSupervisor.setLockTaskModeLocked(null, false); 8843 } 8844 } finally { 8845 Binder.restoreCallingIdentity(ident); 8846 } 8847 } 8848 8849 @Override 8850 public void stopLockTaskModeOnCurrent() throws RemoteException { 8851 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8852 "stopLockTaskModeOnCurrent"); 8853 long ident = Binder.clearCallingIdentity(); 8854 try { 8855 stopLockTaskMode(); 8856 } finally { 8857 Binder.restoreCallingIdentity(ident); 8858 } 8859 } 8860 8861 @Override 8862 public boolean isInLockTaskMode() { 8863 synchronized (this) { 8864 return mStackSupervisor.isInLockTaskMode(); 8865 } 8866 } 8867 8868 // ========================================================= 8869 // CONTENT PROVIDERS 8870 // ========================================================= 8871 8872 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 8873 List<ProviderInfo> providers = null; 8874 try { 8875 providers = AppGlobals.getPackageManager(). 8876 queryContentProviders(app.processName, app.uid, 8877 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS); 8878 } catch (RemoteException ex) { 8879 } 8880 if (DEBUG_MU) 8881 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 8882 int userId = app.userId; 8883 if (providers != null) { 8884 int N = providers.size(); 8885 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 8886 for (int i=0; i<N; i++) { 8887 ProviderInfo cpi = 8888 (ProviderInfo)providers.get(i); 8889 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 8890 cpi.name, cpi.flags); 8891 if (singleton && UserHandle.getUserId(app.uid) != 0) { 8892 // This is a singleton provider, but a user besides the 8893 // default user is asking to initialize a process it runs 8894 // in... well, no, it doesn't actually run in this process, 8895 // it runs in the process of the default user. Get rid of it. 8896 providers.remove(i); 8897 N--; 8898 i--; 8899 continue; 8900 } 8901 8902 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 8903 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 8904 if (cpr == null) { 8905 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 8906 mProviderMap.putProviderByClass(comp, cpr); 8907 } 8908 if (DEBUG_MU) 8909 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 8910 app.pubProviders.put(cpi.name, cpr); 8911 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 8912 // Don't add this if it is a platform component that is marked 8913 // to run in multiple processes, because this is actually 8914 // part of the framework so doesn't make sense to track as a 8915 // separate apk in the process. 8916 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode, 8917 mProcessStats); 8918 } 8919 ensurePackageDexOpt(cpi.applicationInfo.packageName); 8920 } 8921 } 8922 return providers; 8923 } 8924 8925 /** 8926 * Check if {@link ProcessRecord} has a possible chance at accessing the 8927 * given {@link ProviderInfo}. Final permission checking is always done 8928 * in {@link ContentProvider}. 8929 */ 8930 private final String checkContentProviderPermissionLocked( 8931 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 8932 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 8933 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 8934 boolean checkedGrants = false; 8935 if (checkUser) { 8936 // Looking for cross-user grants before enforcing the typical cross-users permissions 8937 int tmpTargetUserId = unsafeConvertIncomingUser(userId); 8938 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 8939 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) { 8940 return null; 8941 } 8942 checkedGrants = true; 8943 } 8944 userId = handleIncomingUser(callingPid, callingUid, userId, 8945 false, ALLOW_NON_FULL, 8946 "checkContentProviderPermissionLocked " + cpi.authority, null); 8947 if (userId != tmpTargetUserId) { 8948 // When we actually went to determine the final targer user ID, this ended 8949 // up different than our initial check for the authority. This is because 8950 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 8951 // SELF. So we need to re-check the grants again. 8952 checkedGrants = false; 8953 } 8954 } 8955 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 8956 cpi.applicationInfo.uid, cpi.exported) 8957 == PackageManager.PERMISSION_GRANTED) { 8958 return null; 8959 } 8960 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 8961 cpi.applicationInfo.uid, cpi.exported) 8962 == PackageManager.PERMISSION_GRANTED) { 8963 return null; 8964 } 8965 8966 PathPermission[] pps = cpi.pathPermissions; 8967 if (pps != null) { 8968 int i = pps.length; 8969 while (i > 0) { 8970 i--; 8971 PathPermission pp = pps[i]; 8972 String pprperm = pp.getReadPermission(); 8973 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 8974 cpi.applicationInfo.uid, cpi.exported) 8975 == PackageManager.PERMISSION_GRANTED) { 8976 return null; 8977 } 8978 String ppwperm = pp.getWritePermission(); 8979 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 8980 cpi.applicationInfo.uid, cpi.exported) 8981 == PackageManager.PERMISSION_GRANTED) { 8982 return null; 8983 } 8984 } 8985 } 8986 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 8987 return null; 8988 } 8989 8990 String msg; 8991 if (!cpi.exported) { 8992 msg = "Permission Denial: opening provider " + cpi.name 8993 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 8994 + ", uid=" + callingUid + ") that is not exported from uid " 8995 + cpi.applicationInfo.uid; 8996 } else { 8997 msg = "Permission Denial: opening provider " + cpi.name 8998 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 8999 + ", uid=" + callingUid + ") requires " 9000 + cpi.readPermission + " or " + cpi.writePermission; 9001 } 9002 Slog.w(TAG, msg); 9003 return msg; 9004 } 9005 9006 /** 9007 * Returns if the ContentProvider has granted a uri to callingUid 9008 */ 9009 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) { 9010 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 9011 if (perms != null) { 9012 for (int i=perms.size()-1; i>=0; i--) { 9013 GrantUri grantUri = perms.keyAt(i); 9014 if (grantUri.sourceUserId == userId || !checkUser) { 9015 if (matchesProvider(grantUri.uri, cpi)) { 9016 return true; 9017 } 9018 } 9019 } 9020 } 9021 return false; 9022 } 9023 9024 /** 9025 * Returns true if the uri authority is one of the authorities specified in the provider. 9026 */ 9027 boolean matchesProvider(Uri uri, ProviderInfo cpi) { 9028 String uriAuth = uri.getAuthority(); 9029 String cpiAuth = cpi.authority; 9030 if (cpiAuth.indexOf(';') == -1) { 9031 return cpiAuth.equals(uriAuth); 9032 } 9033 String[] cpiAuths = cpiAuth.split(";"); 9034 int length = cpiAuths.length; 9035 for (int i = 0; i < length; i++) { 9036 if (cpiAuths[i].equals(uriAuth)) return true; 9037 } 9038 return false; 9039 } 9040 9041 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 9042 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9043 if (r != null) { 9044 for (int i=0; i<r.conProviders.size(); i++) { 9045 ContentProviderConnection conn = r.conProviders.get(i); 9046 if (conn.provider == cpr) { 9047 if (DEBUG_PROVIDER) Slog.v(TAG, 9048 "Adding provider requested by " 9049 + r.processName + " from process " 9050 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9051 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9052 if (stable) { 9053 conn.stableCount++; 9054 conn.numStableIncs++; 9055 } else { 9056 conn.unstableCount++; 9057 conn.numUnstableIncs++; 9058 } 9059 return conn; 9060 } 9061 } 9062 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 9063 if (stable) { 9064 conn.stableCount = 1; 9065 conn.numStableIncs = 1; 9066 } else { 9067 conn.unstableCount = 1; 9068 conn.numUnstableIncs = 1; 9069 } 9070 cpr.connections.add(conn); 9071 r.conProviders.add(conn); 9072 return conn; 9073 } 9074 cpr.addExternalProcessHandleLocked(externalProcessToken); 9075 return null; 9076 } 9077 9078 boolean decProviderCountLocked(ContentProviderConnection conn, 9079 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9080 if (conn != null) { 9081 cpr = conn.provider; 9082 if (DEBUG_PROVIDER) Slog.v(TAG, 9083 "Removing provider requested by " 9084 + conn.client.processName + " from process " 9085 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9086 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9087 if (stable) { 9088 conn.stableCount--; 9089 } else { 9090 conn.unstableCount--; 9091 } 9092 if (conn.stableCount == 0 && conn.unstableCount == 0) { 9093 cpr.connections.remove(conn); 9094 conn.client.conProviders.remove(conn); 9095 return true; 9096 } 9097 return false; 9098 } 9099 cpr.removeExternalProcessHandleLocked(externalProcessToken); 9100 return false; 9101 } 9102 9103 private void checkTime(long startTime, String where) { 9104 long now = SystemClock.elapsedRealtime(); 9105 if ((now-startTime) > 1000) { 9106 // If we are taking more than a second, log about it. 9107 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where); 9108 } 9109 } 9110 9111 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 9112 String name, IBinder token, boolean stable, int userId) { 9113 ContentProviderRecord cpr; 9114 ContentProviderConnection conn = null; 9115 ProviderInfo cpi = null; 9116 9117 synchronized(this) { 9118 long startTime = SystemClock.elapsedRealtime(); 9119 9120 ProcessRecord r = null; 9121 if (caller != null) { 9122 r = getRecordForAppLocked(caller); 9123 if (r == null) { 9124 throw new SecurityException( 9125 "Unable to find app for caller " + caller 9126 + " (pid=" + Binder.getCallingPid() 9127 + ") when getting content provider " + name); 9128 } 9129 } 9130 9131 boolean checkCrossUser = true; 9132 9133 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 9134 9135 // First check if this content provider has been published... 9136 cpr = mProviderMap.getProviderByName(name, userId); 9137 // If that didn't work, check if it exists for user 0 and then 9138 // verify that it's a singleton provider before using it. 9139 if (cpr == null && userId != UserHandle.USER_OWNER) { 9140 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER); 9141 if (cpr != null) { 9142 cpi = cpr.info; 9143 if (isSingleton(cpi.processName, cpi.applicationInfo, 9144 cpi.name, cpi.flags) 9145 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 9146 userId = UserHandle.USER_OWNER; 9147 checkCrossUser = false; 9148 } else { 9149 cpr = null; 9150 cpi = null; 9151 } 9152 } 9153 } 9154 9155 boolean providerRunning = cpr != null; 9156 if (providerRunning) { 9157 cpi = cpr.info; 9158 String msg; 9159 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9160 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 9161 != null) { 9162 throw new SecurityException(msg); 9163 } 9164 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9165 9166 if (r != null && cpr.canRunHere(r)) { 9167 // This provider has been published or is in the process 9168 // of being published... but it is also allowed to run 9169 // in the caller's process, so don't make a connection 9170 // and just let the caller instantiate its own instance. 9171 ContentProviderHolder holder = cpr.newHolder(null); 9172 // don't give caller the provider object, it needs 9173 // to make its own. 9174 holder.provider = null; 9175 return holder; 9176 } 9177 9178 final long origId = Binder.clearCallingIdentity(); 9179 9180 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 9181 9182 // In this case the provider instance already exists, so we can 9183 // return it right away. 9184 conn = incProviderCountLocked(r, cpr, token, stable); 9185 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 9186 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 9187 // If this is a perceptible app accessing the provider, 9188 // make sure to count it as being accessed and thus 9189 // back up on the LRU list. This is good because 9190 // content providers are often expensive to start. 9191 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 9192 updateLruProcessLocked(cpr.proc, false, null); 9193 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 9194 } 9195 } 9196 9197 if (cpr.proc != null) { 9198 if (false) { 9199 if (cpr.name.flattenToShortString().equals( 9200 "com.android.providers.calendar/.CalendarProvider2")) { 9201 Slog.v(TAG, "****************** KILLING " 9202 + cpr.name.flattenToShortString()); 9203 Process.killProcess(cpr.proc.pid); 9204 } 9205 } 9206 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 9207 boolean success = updateOomAdjLocked(cpr.proc); 9208 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 9209 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success); 9210 // NOTE: there is still a race here where a signal could be 9211 // pending on the process even though we managed to update its 9212 // adj level. Not sure what to do about this, but at least 9213 // the race is now smaller. 9214 if (!success) { 9215 // Uh oh... it looks like the provider's process 9216 // has been killed on us. We need to wait for a new 9217 // process to be started, and make sure its death 9218 // doesn't kill our process. 9219 Slog.i(TAG, 9220 "Existing provider " + cpr.name.flattenToShortString() 9221 + " is crashing; detaching " + r); 9222 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 9223 checkTime(startTime, "getContentProviderImpl: before appDied"); 9224 appDiedLocked(cpr.proc); 9225 checkTime(startTime, "getContentProviderImpl: after appDied"); 9226 if (!lastRef) { 9227 // This wasn't the last ref our process had on 9228 // the provider... we have now been killed, bail. 9229 return null; 9230 } 9231 providerRunning = false; 9232 conn = null; 9233 } 9234 } 9235 9236 Binder.restoreCallingIdentity(origId); 9237 } 9238 9239 boolean singleton; 9240 if (!providerRunning) { 9241 try { 9242 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 9243 cpi = AppGlobals.getPackageManager(). 9244 resolveContentProvider(name, 9245 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 9246 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 9247 } catch (RemoteException ex) { 9248 } 9249 if (cpi == null) { 9250 return null; 9251 } 9252 // If the provider is a singleton AND 9253 // (it's a call within the same user || the provider is a 9254 // privileged app) 9255 // Then allow connecting to the singleton provider 9256 singleton = isSingleton(cpi.processName, cpi.applicationInfo, 9257 cpi.name, cpi.flags) 9258 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 9259 if (singleton) { 9260 userId = UserHandle.USER_OWNER; 9261 } 9262 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 9263 checkTime(startTime, "getContentProviderImpl: got app info for user"); 9264 9265 String msg; 9266 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9267 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 9268 != null) { 9269 throw new SecurityException(msg); 9270 } 9271 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9272 9273 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate 9274 && !cpi.processName.equals("system")) { 9275 // If this content provider does not run in the system 9276 // process, and the system is not yet ready to run other 9277 // processes, then fail fast instead of hanging. 9278 throw new IllegalArgumentException( 9279 "Attempt to launch content provider before system ready"); 9280 } 9281 9282 // Make sure that the user who owns this provider is started. If not, 9283 // we don't want to allow it to run. 9284 if (mStartedUsers.get(userId) == null) { 9285 Slog.w(TAG, "Unable to launch app " 9286 + cpi.applicationInfo.packageName + "/" 9287 + cpi.applicationInfo.uid + " for provider " 9288 + name + ": user " + userId + " is stopped"); 9289 return null; 9290 } 9291 9292 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 9293 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 9294 cpr = mProviderMap.getProviderByClass(comp, userId); 9295 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 9296 final boolean firstClass = cpr == null; 9297 if (firstClass) { 9298 try { 9299 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 9300 ApplicationInfo ai = 9301 AppGlobals.getPackageManager(). 9302 getApplicationInfo( 9303 cpi.applicationInfo.packageName, 9304 STOCK_PM_FLAGS, userId); 9305 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 9306 if (ai == null) { 9307 Slog.w(TAG, "No package info for content provider " 9308 + cpi.name); 9309 return null; 9310 } 9311 ai = getAppInfoForUser(ai, userId); 9312 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 9313 } catch (RemoteException ex) { 9314 // pm is in same process, this will never happen. 9315 } 9316 } 9317 9318 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 9319 9320 if (r != null && cpr.canRunHere(r)) { 9321 // If this is a multiprocess provider, then just return its 9322 // info and allow the caller to instantiate it. Only do 9323 // this if the provider is the same user as the caller's 9324 // process, or can run as root (so can be in any process). 9325 return cpr.newHolder(null); 9326 } 9327 9328 if (DEBUG_PROVIDER) { 9329 RuntimeException e = new RuntimeException("here"); 9330 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null) 9331 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e); 9332 } 9333 9334 // This is single process, and our app is now connecting to it. 9335 // See if we are already in the process of launching this 9336 // provider. 9337 final int N = mLaunchingProviders.size(); 9338 int i; 9339 for (i=0; i<N; i++) { 9340 if (mLaunchingProviders.get(i) == cpr) { 9341 break; 9342 } 9343 } 9344 9345 // If the provider is not already being launched, then get it 9346 // started. 9347 if (i >= N) { 9348 final long origId = Binder.clearCallingIdentity(); 9349 9350 try { 9351 // Content provider is now in use, its package can't be stopped. 9352 try { 9353 checkTime(startTime, "getContentProviderImpl: before set stopped state"); 9354 AppGlobals.getPackageManager().setPackageStoppedState( 9355 cpr.appInfo.packageName, false, userId); 9356 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 9357 } catch (RemoteException e) { 9358 } catch (IllegalArgumentException e) { 9359 Slog.w(TAG, "Failed trying to unstop package " 9360 + cpr.appInfo.packageName + ": " + e); 9361 } 9362 9363 // Use existing process if already started 9364 checkTime(startTime, "getContentProviderImpl: looking for process record"); 9365 ProcessRecord proc = getProcessRecordLocked( 9366 cpi.processName, cpr.appInfo.uid, false); 9367 if (proc != null && proc.thread != null) { 9368 if (DEBUG_PROVIDER) { 9369 Slog.d(TAG, "Installing in existing process " + proc); 9370 } 9371 checkTime(startTime, "getContentProviderImpl: scheduling install"); 9372 proc.pubProviders.put(cpi.name, cpr); 9373 try { 9374 proc.thread.scheduleInstallProvider(cpi); 9375 } catch (RemoteException e) { 9376 } 9377 } else { 9378 checkTime(startTime, "getContentProviderImpl: before start process"); 9379 proc = startProcessLocked(cpi.processName, 9380 cpr.appInfo, false, 0, "content provider", 9381 new ComponentName(cpi.applicationInfo.packageName, 9382 cpi.name), false, false, false); 9383 checkTime(startTime, "getContentProviderImpl: after start process"); 9384 if (proc == null) { 9385 Slog.w(TAG, "Unable to launch app " 9386 + cpi.applicationInfo.packageName + "/" 9387 + cpi.applicationInfo.uid + " for provider " 9388 + name + ": process is bad"); 9389 return null; 9390 } 9391 } 9392 cpr.launchingApp = proc; 9393 mLaunchingProviders.add(cpr); 9394 } finally { 9395 Binder.restoreCallingIdentity(origId); 9396 } 9397 } 9398 9399 checkTime(startTime, "getContentProviderImpl: updating data structures"); 9400 9401 // Make sure the provider is published (the same provider class 9402 // may be published under multiple names). 9403 if (firstClass) { 9404 mProviderMap.putProviderByClass(comp, cpr); 9405 } 9406 9407 mProviderMap.putProviderByName(name, cpr); 9408 conn = incProviderCountLocked(r, cpr, token, stable); 9409 if (conn != null) { 9410 conn.waiting = true; 9411 } 9412 } 9413 checkTime(startTime, "getContentProviderImpl: done!"); 9414 } 9415 9416 // Wait for the provider to be published... 9417 synchronized (cpr) { 9418 while (cpr.provider == null) { 9419 if (cpr.launchingApp == null) { 9420 Slog.w(TAG, "Unable to launch app " 9421 + cpi.applicationInfo.packageName + "/" 9422 + cpi.applicationInfo.uid + " for provider " 9423 + name + ": launching app became null"); 9424 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 9425 UserHandle.getUserId(cpi.applicationInfo.uid), 9426 cpi.applicationInfo.packageName, 9427 cpi.applicationInfo.uid, name); 9428 return null; 9429 } 9430 try { 9431 if (DEBUG_MU) { 9432 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp=" 9433 + cpr.launchingApp); 9434 } 9435 if (conn != null) { 9436 conn.waiting = true; 9437 } 9438 cpr.wait(); 9439 } catch (InterruptedException ex) { 9440 } finally { 9441 if (conn != null) { 9442 conn.waiting = false; 9443 } 9444 } 9445 } 9446 } 9447 return cpr != null ? cpr.newHolder(conn) : null; 9448 } 9449 9450 @Override 9451 public final ContentProviderHolder getContentProvider( 9452 IApplicationThread caller, String name, int userId, boolean stable) { 9453 enforceNotIsolatedCaller("getContentProvider"); 9454 if (caller == null) { 9455 String msg = "null IApplicationThread when getting content provider " 9456 + name; 9457 Slog.w(TAG, msg); 9458 throw new SecurityException(msg); 9459 } 9460 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 9461 // with cross-user grant. 9462 return getContentProviderImpl(caller, name, null, stable, userId); 9463 } 9464 9465 public ContentProviderHolder getContentProviderExternal( 9466 String name, int userId, IBinder token) { 9467 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9468 "Do not have permission in call getContentProviderExternal()"); 9469 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 9470 false, ALLOW_FULL_ONLY, "getContentProvider", null); 9471 return getContentProviderExternalUnchecked(name, token, userId); 9472 } 9473 9474 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 9475 IBinder token, int userId) { 9476 return getContentProviderImpl(null, name, token, true, userId); 9477 } 9478 9479 /** 9480 * Drop a content provider from a ProcessRecord's bookkeeping 9481 */ 9482 public void removeContentProvider(IBinder connection, boolean stable) { 9483 enforceNotIsolatedCaller("removeContentProvider"); 9484 long ident = Binder.clearCallingIdentity(); 9485 try { 9486 synchronized (this) { 9487 ContentProviderConnection conn; 9488 try { 9489 conn = (ContentProviderConnection)connection; 9490 } catch (ClassCastException e) { 9491 String msg ="removeContentProvider: " + connection 9492 + " not a ContentProviderConnection"; 9493 Slog.w(TAG, msg); 9494 throw new IllegalArgumentException(msg); 9495 } 9496 if (conn == null) { 9497 throw new NullPointerException("connection is null"); 9498 } 9499 if (decProviderCountLocked(conn, null, null, stable)) { 9500 updateOomAdjLocked(); 9501 } 9502 } 9503 } finally { 9504 Binder.restoreCallingIdentity(ident); 9505 } 9506 } 9507 9508 public void removeContentProviderExternal(String name, IBinder token) { 9509 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9510 "Do not have permission in call removeContentProviderExternal()"); 9511 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId()); 9512 } 9513 9514 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 9515 synchronized (this) { 9516 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 9517 if(cpr == null) { 9518 //remove from mProvidersByClass 9519 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list"); 9520 return; 9521 } 9522 9523 //update content provider record entry info 9524 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 9525 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 9526 if (localCpr.hasExternalProcessHandles()) { 9527 if (localCpr.removeExternalProcessHandleLocked(token)) { 9528 updateOomAdjLocked(); 9529 } else { 9530 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 9531 + " with no external reference for token: " 9532 + token + "."); 9533 } 9534 } else { 9535 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 9536 + " with no external references."); 9537 } 9538 } 9539 } 9540 9541 public final void publishContentProviders(IApplicationThread caller, 9542 List<ContentProviderHolder> providers) { 9543 if (providers == null) { 9544 return; 9545 } 9546 9547 enforceNotIsolatedCaller("publishContentProviders"); 9548 synchronized (this) { 9549 final ProcessRecord r = getRecordForAppLocked(caller); 9550 if (DEBUG_MU) 9551 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 9552 if (r == null) { 9553 throw new SecurityException( 9554 "Unable to find app for caller " + caller 9555 + " (pid=" + Binder.getCallingPid() 9556 + ") when publishing content providers"); 9557 } 9558 9559 final long origId = Binder.clearCallingIdentity(); 9560 9561 final int N = providers.size(); 9562 for (int i=0; i<N; i++) { 9563 ContentProviderHolder src = providers.get(i); 9564 if (src == null || src.info == null || src.provider == null) { 9565 continue; 9566 } 9567 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 9568 if (DEBUG_MU) 9569 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 9570 if (dst != null) { 9571 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 9572 mProviderMap.putProviderByClass(comp, dst); 9573 String names[] = dst.info.authority.split(";"); 9574 for (int j = 0; j < names.length; j++) { 9575 mProviderMap.putProviderByName(names[j], dst); 9576 } 9577 9578 int NL = mLaunchingProviders.size(); 9579 int j; 9580 for (j=0; j<NL; j++) { 9581 if (mLaunchingProviders.get(j) == dst) { 9582 mLaunchingProviders.remove(j); 9583 j--; 9584 NL--; 9585 } 9586 } 9587 synchronized (dst) { 9588 dst.provider = src.provider; 9589 dst.proc = r; 9590 dst.notifyAll(); 9591 } 9592 updateOomAdjLocked(r); 9593 } 9594 } 9595 9596 Binder.restoreCallingIdentity(origId); 9597 } 9598 } 9599 9600 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 9601 ContentProviderConnection conn; 9602 try { 9603 conn = (ContentProviderConnection)connection; 9604 } catch (ClassCastException e) { 9605 String msg ="refContentProvider: " + connection 9606 + " not a ContentProviderConnection"; 9607 Slog.w(TAG, msg); 9608 throw new IllegalArgumentException(msg); 9609 } 9610 if (conn == null) { 9611 throw new NullPointerException("connection is null"); 9612 } 9613 9614 synchronized (this) { 9615 if (stable > 0) { 9616 conn.numStableIncs += stable; 9617 } 9618 stable = conn.stableCount + stable; 9619 if (stable < 0) { 9620 throw new IllegalStateException("stableCount < 0: " + stable); 9621 } 9622 9623 if (unstable > 0) { 9624 conn.numUnstableIncs += unstable; 9625 } 9626 unstable = conn.unstableCount + unstable; 9627 if (unstable < 0) { 9628 throw new IllegalStateException("unstableCount < 0: " + unstable); 9629 } 9630 9631 if ((stable+unstable) <= 0) { 9632 throw new IllegalStateException("ref counts can't go to zero here: stable=" 9633 + stable + " unstable=" + unstable); 9634 } 9635 conn.stableCount = stable; 9636 conn.unstableCount = unstable; 9637 return !conn.dead; 9638 } 9639 } 9640 9641 public void unstableProviderDied(IBinder connection) { 9642 ContentProviderConnection conn; 9643 try { 9644 conn = (ContentProviderConnection)connection; 9645 } catch (ClassCastException e) { 9646 String msg ="refContentProvider: " + connection 9647 + " not a ContentProviderConnection"; 9648 Slog.w(TAG, msg); 9649 throw new IllegalArgumentException(msg); 9650 } 9651 if (conn == null) { 9652 throw new NullPointerException("connection is null"); 9653 } 9654 9655 // Safely retrieve the content provider associated with the connection. 9656 IContentProvider provider; 9657 synchronized (this) { 9658 provider = conn.provider.provider; 9659 } 9660 9661 if (provider == null) { 9662 // Um, yeah, we're way ahead of you. 9663 return; 9664 } 9665 9666 // Make sure the caller is being honest with us. 9667 if (provider.asBinder().pingBinder()) { 9668 // Er, no, still looks good to us. 9669 synchronized (this) { 9670 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 9671 + " says " + conn + " died, but we don't agree"); 9672 return; 9673 } 9674 } 9675 9676 // Well look at that! It's dead! 9677 synchronized (this) { 9678 if (conn.provider.provider != provider) { 9679 // But something changed... good enough. 9680 return; 9681 } 9682 9683 ProcessRecord proc = conn.provider.proc; 9684 if (proc == null || proc.thread == null) { 9685 // Seems like the process is already cleaned up. 9686 return; 9687 } 9688 9689 // As far as we're concerned, this is just like receiving a 9690 // death notification... just a bit prematurely. 9691 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid 9692 + ") early provider death"); 9693 final long ident = Binder.clearCallingIdentity(); 9694 try { 9695 appDiedLocked(proc); 9696 } finally { 9697 Binder.restoreCallingIdentity(ident); 9698 } 9699 } 9700 } 9701 9702 @Override 9703 public void appNotRespondingViaProvider(IBinder connection) { 9704 enforceCallingPermission( 9705 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()"); 9706 9707 final ContentProviderConnection conn = (ContentProviderConnection) connection; 9708 if (conn == null) { 9709 Slog.w(TAG, "ContentProviderConnection is null"); 9710 return; 9711 } 9712 9713 final ProcessRecord host = conn.provider.proc; 9714 if (host == null) { 9715 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 9716 return; 9717 } 9718 9719 final long token = Binder.clearCallingIdentity(); 9720 try { 9721 appNotResponding(host, null, null, false, "ContentProvider not responding"); 9722 } finally { 9723 Binder.restoreCallingIdentity(token); 9724 } 9725 } 9726 9727 public final void installSystemProviders() { 9728 List<ProviderInfo> providers; 9729 synchronized (this) { 9730 ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID); 9731 providers = generateApplicationProvidersLocked(app); 9732 if (providers != null) { 9733 for (int i=providers.size()-1; i>=0; i--) { 9734 ProviderInfo pi = (ProviderInfo)providers.get(i); 9735 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9736 Slog.w(TAG, "Not installing system proc provider " + pi.name 9737 + ": not system .apk"); 9738 providers.remove(i); 9739 } 9740 } 9741 } 9742 } 9743 if (providers != null) { 9744 mSystemThread.installSystemProviders(providers); 9745 } 9746 9747 mCoreSettingsObserver = new CoreSettingsObserver(this); 9748 9749 //mUsageStatsService.monitorPackages(); 9750 } 9751 9752 /** 9753 * Allows apps to retrieve the MIME type of a URI. 9754 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 9755 * users, then it does not need permission to access the ContentProvider. 9756 * Either, it needs cross-user uri grants. 9757 * 9758 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 9759 * 9760 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 9761 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 9762 */ 9763 public String getProviderMimeType(Uri uri, int userId) { 9764 enforceNotIsolatedCaller("getProviderMimeType"); 9765 final String name = uri.getAuthority(); 9766 int callingUid = Binder.getCallingUid(); 9767 int callingPid = Binder.getCallingPid(); 9768 long ident = 0; 9769 boolean clearedIdentity = false; 9770 userId = unsafeConvertIncomingUser(userId); 9771 if (canClearIdentity(callingPid, callingUid, userId)) { 9772 clearedIdentity = true; 9773 ident = Binder.clearCallingIdentity(); 9774 } 9775 ContentProviderHolder holder = null; 9776 try { 9777 holder = getContentProviderExternalUnchecked(name, null, userId); 9778 if (holder != null) { 9779 return holder.provider.getType(uri); 9780 } 9781 } catch (RemoteException e) { 9782 Log.w(TAG, "Content provider dead retrieving " + uri, e); 9783 return null; 9784 } finally { 9785 // We need to clear the identity to call removeContentProviderExternalUnchecked 9786 if (!clearedIdentity) { 9787 ident = Binder.clearCallingIdentity(); 9788 } 9789 try { 9790 if (holder != null) { 9791 removeContentProviderExternalUnchecked(name, null, userId); 9792 } 9793 } finally { 9794 Binder.restoreCallingIdentity(ident); 9795 } 9796 } 9797 9798 return null; 9799 } 9800 9801 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 9802 if (UserHandle.getUserId(callingUid) == userId) { 9803 return true; 9804 } 9805 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 9806 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 9807 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 9808 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 9809 return true; 9810 } 9811 return false; 9812 } 9813 9814 // ========================================================= 9815 // GLOBAL MANAGEMENT 9816 // ========================================================= 9817 9818 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 9819 boolean isolated, int isolatedUid) { 9820 String proc = customProcess != null ? customProcess : info.processName; 9821 BatteryStatsImpl.Uid.Proc ps = null; 9822 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 9823 int uid = info.uid; 9824 if (isolated) { 9825 if (isolatedUid == 0) { 9826 int userId = UserHandle.getUserId(uid); 9827 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1; 9828 while (true) { 9829 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID 9830 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) { 9831 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID; 9832 } 9833 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid); 9834 mNextIsolatedProcessUid++; 9835 if (mIsolatedProcesses.indexOfKey(uid) < 0) { 9836 // No process for this uid, use it. 9837 break; 9838 } 9839 stepsLeft--; 9840 if (stepsLeft <= 0) { 9841 return null; 9842 } 9843 } 9844 } else { 9845 // Special case for startIsolatedProcess (internal only), where 9846 // the uid of the isolated process is specified by the caller. 9847 uid = isolatedUid; 9848 } 9849 } 9850 return new ProcessRecord(stats, info, proc, uid); 9851 } 9852 9853 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated, 9854 String abiOverride) { 9855 ProcessRecord app; 9856 if (!isolated) { 9857 app = getProcessRecordLocked(info.processName, info.uid, true); 9858 } else { 9859 app = null; 9860 } 9861 9862 if (app == null) { 9863 app = newProcessRecordLocked(info, null, isolated, 0); 9864 mProcessNames.put(info.processName, app.uid, app); 9865 if (isolated) { 9866 mIsolatedProcesses.put(app.uid, app); 9867 } 9868 updateLruProcessLocked(app, false, null); 9869 updateOomAdjLocked(); 9870 } 9871 9872 // This package really, really can not be stopped. 9873 try { 9874 AppGlobals.getPackageManager().setPackageStoppedState( 9875 info.packageName, false, UserHandle.getUserId(app.uid)); 9876 } catch (RemoteException e) { 9877 } catch (IllegalArgumentException e) { 9878 Slog.w(TAG, "Failed trying to unstop package " 9879 + info.packageName + ": " + e); 9880 } 9881 9882 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) 9883 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) { 9884 app.persistent = true; 9885 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 9886 } 9887 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 9888 mPersistentStartingProcesses.add(app); 9889 startProcessLocked(app, "added application", app.processName, abiOverride, 9890 null /* entryPoint */, null /* entryPointArgs */); 9891 } 9892 9893 return app; 9894 } 9895 9896 public void unhandledBack() { 9897 enforceCallingPermission(android.Manifest.permission.FORCE_BACK, 9898 "unhandledBack()"); 9899 9900 synchronized(this) { 9901 final long origId = Binder.clearCallingIdentity(); 9902 try { 9903 getFocusedStack().unhandledBackLocked(); 9904 } finally { 9905 Binder.restoreCallingIdentity(origId); 9906 } 9907 } 9908 } 9909 9910 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException { 9911 enforceNotIsolatedCaller("openContentUri"); 9912 final int userId = UserHandle.getCallingUserId(); 9913 String name = uri.getAuthority(); 9914 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId); 9915 ParcelFileDescriptor pfd = null; 9916 if (cph != null) { 9917 // We record the binder invoker's uid in thread-local storage before 9918 // going to the content provider to open the file. Later, in the code 9919 // that handles all permissions checks, we look for this uid and use 9920 // that rather than the Activity Manager's own uid. The effect is that 9921 // we do the check against the caller's permissions even though it looks 9922 // to the content provider like the Activity Manager itself is making 9923 // the request. 9924 sCallerIdentity.set(new Identity( 9925 Binder.getCallingPid(), Binder.getCallingUid())); 9926 try { 9927 pfd = cph.provider.openFile(null, uri, "r", null); 9928 } catch (FileNotFoundException e) { 9929 // do nothing; pfd will be returned null 9930 } finally { 9931 // Ensure that whatever happens, we clean up the identity state 9932 sCallerIdentity.remove(); 9933 } 9934 9935 // We've got the fd now, so we're done with the provider. 9936 removeContentProviderExternalUnchecked(name, null, userId); 9937 } else { 9938 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 9939 } 9940 return pfd; 9941 } 9942 9943 // Actually is sleeping or shutting down or whatever else in the future 9944 // is an inactive state. 9945 public boolean isSleepingOrShuttingDown() { 9946 return isSleeping() || mShuttingDown; 9947 } 9948 9949 public boolean isSleeping() { 9950 return mSleeping && !mKeyguardWaitingForDraw; 9951 } 9952 9953 void goingToSleep() { 9954 synchronized(this) { 9955 mWentToSleep = true; 9956 updateEventDispatchingLocked(); 9957 goToSleepIfNeededLocked(); 9958 } 9959 } 9960 9961 void finishRunningVoiceLocked() { 9962 if (mRunningVoice) { 9963 mRunningVoice = false; 9964 goToSleepIfNeededLocked(); 9965 } 9966 } 9967 9968 void goToSleepIfNeededLocked() { 9969 if (mWentToSleep && !mRunningVoice) { 9970 if (!mSleeping) { 9971 mSleeping = true; 9972 mKeyguardWaitingForDraw = false; 9973 mStackSupervisor.goingToSleepLocked(); 9974 9975 // Initialize the wake times of all processes. 9976 checkExcessivePowerUsageLocked(false); 9977 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9978 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9979 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 9980 } 9981 } 9982 } 9983 9984 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { 9985 if (task != null && task.stack != null && task.stack.isHomeStack()) { 9986 // Never persist the home stack. 9987 return; 9988 } 9989 mTaskPersister.wakeup(task, flush); 9990 } 9991 9992 @Override 9993 public boolean shutdown(int timeout) { 9994 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 9995 != PackageManager.PERMISSION_GRANTED) { 9996 throw new SecurityException("Requires permission " 9997 + android.Manifest.permission.SHUTDOWN); 9998 } 9999 10000 boolean timedout = false; 10001 10002 synchronized(this) { 10003 mShuttingDown = true; 10004 updateEventDispatchingLocked(); 10005 timedout = mStackSupervisor.shutdownLocked(timeout); 10006 } 10007 10008 mAppOpsService.shutdown(); 10009 if (mUsageStatsService != null) { 10010 mUsageStatsService.prepareShutdown(); 10011 } 10012 mBatteryStatsService.shutdown(); 10013 synchronized (this) { 10014 mProcessStats.shutdownLocked(); 10015 } 10016 notifyTaskPersisterLocked(null, true); 10017 10018 return timedout; 10019 } 10020 10021 public final void activitySlept(IBinder token) { 10022 if (localLOGV) Slog.v(TAG, "Activity slept: token=" + token); 10023 10024 final long origId = Binder.clearCallingIdentity(); 10025 10026 synchronized (this) { 10027 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10028 if (r != null) { 10029 mStackSupervisor.activitySleptLocked(r); 10030 } 10031 } 10032 10033 Binder.restoreCallingIdentity(origId); 10034 } 10035 10036 void logLockScreen(String msg) { 10037 if (DEBUG_LOCKSCREEN) Slog.d(TAG, Debug.getCallers(2) + ":" + msg + 10038 " mLockScreenShown=" + mLockScreenShown + " mWentToSleep=" + 10039 mWentToSleep + " mSleeping=" + mSleeping); 10040 } 10041 10042 private void comeOutOfSleepIfNeededLocked() { 10043 if ((!mWentToSleep && !mLockScreenShown) || mRunningVoice) { 10044 if (mSleeping) { 10045 mSleeping = false; 10046 mStackSupervisor.comeOutOfSleepIfNeededLocked(); 10047 } 10048 } 10049 } 10050 10051 void wakingUp() { 10052 synchronized(this) { 10053 mWentToSleep = false; 10054 updateEventDispatchingLocked(); 10055 comeOutOfSleepIfNeededLocked(); 10056 } 10057 } 10058 10059 void startRunningVoiceLocked() { 10060 if (!mRunningVoice) { 10061 mRunningVoice = true; 10062 comeOutOfSleepIfNeededLocked(); 10063 } 10064 } 10065 10066 private void updateEventDispatchingLocked() { 10067 mWindowManager.setEventDispatching(mBooted && !mShuttingDown); 10068 } 10069 10070 public void setLockScreenShown(boolean shown) { 10071 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER) 10072 != PackageManager.PERMISSION_GRANTED) { 10073 throw new SecurityException("Requires permission " 10074 + android.Manifest.permission.DEVICE_POWER); 10075 } 10076 10077 synchronized(this) { 10078 long ident = Binder.clearCallingIdentity(); 10079 try { 10080 if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown); 10081 mLockScreenShown = shown; 10082 mKeyguardWaitingForDraw = false; 10083 comeOutOfSleepIfNeededLocked(); 10084 } finally { 10085 Binder.restoreCallingIdentity(ident); 10086 } 10087 } 10088 } 10089 10090 @Override 10091 public void stopAppSwitches() { 10092 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10093 != PackageManager.PERMISSION_GRANTED) { 10094 throw new SecurityException("Requires permission " 10095 + android.Manifest.permission.STOP_APP_SWITCHES); 10096 } 10097 10098 synchronized(this) { 10099 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() 10100 + APP_SWITCH_DELAY_TIME; 10101 mDidAppSwitch = false; 10102 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10103 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10104 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME); 10105 } 10106 } 10107 10108 public void resumeAppSwitches() { 10109 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10110 != PackageManager.PERMISSION_GRANTED) { 10111 throw new SecurityException("Requires permission " 10112 + android.Manifest.permission.STOP_APP_SWITCHES); 10113 } 10114 10115 synchronized(this) { 10116 // Note that we don't execute any pending app switches... we will 10117 // let those wait until either the timeout, or the next start 10118 // activity request. 10119 mAppSwitchesAllowedTime = 0; 10120 } 10121 } 10122 10123 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid, 10124 String name) { 10125 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { 10126 return true; 10127 } 10128 10129 final int perm = checkComponentPermission( 10130 android.Manifest.permission.STOP_APP_SWITCHES, callingPid, 10131 callingUid, -1, true); 10132 if (perm == PackageManager.PERMISSION_GRANTED) { 10133 return true; 10134 } 10135 10136 Slog.w(TAG, name + " request from " + callingUid + " stopped"); 10137 return false; 10138 } 10139 10140 public void setDebugApp(String packageName, boolean waitForDebugger, 10141 boolean persistent) { 10142 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 10143 "setDebugApp()"); 10144 10145 long ident = Binder.clearCallingIdentity(); 10146 try { 10147 // Note that this is not really thread safe if there are multiple 10148 // callers into it at the same time, but that's not a situation we 10149 // care about. 10150 if (persistent) { 10151 final ContentResolver resolver = mContext.getContentResolver(); 10152 Settings.Global.putString( 10153 resolver, Settings.Global.DEBUG_APP, 10154 packageName); 10155 Settings.Global.putInt( 10156 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 10157 waitForDebugger ? 1 : 0); 10158 } 10159 10160 synchronized (this) { 10161 if (!persistent) { 10162 mOrigDebugApp = mDebugApp; 10163 mOrigWaitForDebugger = mWaitForDebugger; 10164 } 10165 mDebugApp = packageName; 10166 mWaitForDebugger = waitForDebugger; 10167 mDebugTransient = !persistent; 10168 if (packageName != null) { 10169 forceStopPackageLocked(packageName, -1, false, false, true, true, 10170 false, UserHandle.USER_ALL, "set debug app"); 10171 } 10172 } 10173 } finally { 10174 Binder.restoreCallingIdentity(ident); 10175 } 10176 } 10177 10178 void setOpenGlTraceApp(ApplicationInfo app, String processName) { 10179 synchronized (this) { 10180 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10181 if (!isDebuggable) { 10182 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10183 throw new SecurityException("Process not debuggable: " + app.packageName); 10184 } 10185 } 10186 10187 mOpenGlTraceApp = processName; 10188 } 10189 } 10190 10191 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 10192 synchronized (this) { 10193 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10194 if (!isDebuggable) { 10195 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10196 throw new SecurityException("Process not debuggable: " + app.packageName); 10197 } 10198 } 10199 mProfileApp = processName; 10200 mProfileFile = profilerInfo.profileFile; 10201 if (mProfileFd != null) { 10202 try { 10203 mProfileFd.close(); 10204 } catch (IOException e) { 10205 } 10206 mProfileFd = null; 10207 } 10208 mProfileFd = profilerInfo.profileFd; 10209 mSamplingInterval = profilerInfo.samplingInterval; 10210 mAutoStopProfiler = profilerInfo.autoStopProfiler; 10211 mProfileType = 0; 10212 } 10213 } 10214 10215 @Override 10216 public void setAlwaysFinish(boolean enabled) { 10217 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 10218 "setAlwaysFinish()"); 10219 10220 Settings.Global.putInt( 10221 mContext.getContentResolver(), 10222 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 10223 10224 synchronized (this) { 10225 mAlwaysFinishActivities = enabled; 10226 } 10227 } 10228 10229 @Override 10230 public void setActivityController(IActivityController controller) { 10231 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10232 "setActivityController()"); 10233 synchronized (this) { 10234 mController = controller; 10235 Watchdog.getInstance().setActivityController(controller); 10236 } 10237 } 10238 10239 @Override 10240 public void setUserIsMonkey(boolean userIsMonkey) { 10241 synchronized (this) { 10242 synchronized (mPidsSelfLocked) { 10243 final int callingPid = Binder.getCallingPid(); 10244 ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid); 10245 if (precessRecord == null) { 10246 throw new SecurityException("Unknown process: " + callingPid); 10247 } 10248 if (precessRecord.instrumentationUiAutomationConnection == null) { 10249 throw new SecurityException("Only an instrumentation process " 10250 + "with a UiAutomation can call setUserIsMonkey"); 10251 } 10252 } 10253 mUserIsMonkey = userIsMonkey; 10254 } 10255 } 10256 10257 @Override 10258 public boolean isUserAMonkey() { 10259 synchronized (this) { 10260 // If there is a controller also implies the user is a monkey. 10261 return (mUserIsMonkey || mController != null); 10262 } 10263 } 10264 10265 public void requestBugReport() { 10266 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 10267 SystemProperties.set("ctl.start", "bugreport"); 10268 } 10269 10270 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) { 10271 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT; 10272 } 10273 10274 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) { 10275 if (r != null && (r.instrumentationClass != null || r.usingWrapper)) { 10276 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT; 10277 } 10278 return KEY_DISPATCHING_TIMEOUT; 10279 } 10280 10281 @Override 10282 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 10283 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10284 != PackageManager.PERMISSION_GRANTED) { 10285 throw new SecurityException("Requires permission " 10286 + android.Manifest.permission.FILTER_EVENTS); 10287 } 10288 ProcessRecord proc; 10289 long timeout; 10290 synchronized (this) { 10291 synchronized (mPidsSelfLocked) { 10292 proc = mPidsSelfLocked.get(pid); 10293 } 10294 timeout = getInputDispatchingTimeoutLocked(proc); 10295 } 10296 10297 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) { 10298 return -1; 10299 } 10300 10301 return timeout; 10302 } 10303 10304 /** 10305 * Handle input dispatching timeouts. 10306 * Returns whether input dispatching should be aborted or not. 10307 */ 10308 public boolean inputDispatchingTimedOut(final ProcessRecord proc, 10309 final ActivityRecord activity, final ActivityRecord parent, 10310 final boolean aboveSystem, String reason) { 10311 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10312 != PackageManager.PERMISSION_GRANTED) { 10313 throw new SecurityException("Requires permission " 10314 + android.Manifest.permission.FILTER_EVENTS); 10315 } 10316 10317 final String annotation; 10318 if (reason == null) { 10319 annotation = "Input dispatching timed out"; 10320 } else { 10321 annotation = "Input dispatching timed out (" + reason + ")"; 10322 } 10323 10324 if (proc != null) { 10325 synchronized (this) { 10326 if (proc.debugging) { 10327 return false; 10328 } 10329 10330 if (mDidDexOpt) { 10331 // Give more time since we were dexopting. 10332 mDidDexOpt = false; 10333 return false; 10334 } 10335 10336 if (proc.instrumentationClass != null) { 10337 Bundle info = new Bundle(); 10338 info.putString("shortMsg", "keyDispatchingTimedOut"); 10339 info.putString("longMsg", annotation); 10340 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 10341 return true; 10342 } 10343 } 10344 mHandler.post(new Runnable() { 10345 @Override 10346 public void run() { 10347 appNotResponding(proc, activity, parent, aboveSystem, annotation); 10348 } 10349 }); 10350 } 10351 10352 return true; 10353 } 10354 10355 public Bundle getAssistContextExtras(int requestType) { 10356 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO, 10357 "getAssistContextExtras()"); 10358 PendingAssistExtras pae; 10359 Bundle extras = new Bundle(); 10360 synchronized (this) { 10361 ActivityRecord activity = getFocusedStack().mResumedActivity; 10362 if (activity == null) { 10363 Slog.w(TAG, "getAssistContextExtras failed: no resumed activity"); 10364 return null; 10365 } 10366 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName); 10367 if (activity.app == null || activity.app.thread == null) { 10368 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity); 10369 return extras; 10370 } 10371 if (activity.app.pid == Binder.getCallingPid()) { 10372 Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity); 10373 return extras; 10374 } 10375 pae = new PendingAssistExtras(activity); 10376 try { 10377 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, 10378 requestType); 10379 mPendingAssistExtras.add(pae); 10380 mHandler.postDelayed(pae, PENDING_ASSIST_EXTRAS_TIMEOUT); 10381 } catch (RemoteException e) { 10382 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity); 10383 return extras; 10384 } 10385 } 10386 synchronized (pae) { 10387 while (!pae.haveResult) { 10388 try { 10389 pae.wait(); 10390 } catch (InterruptedException e) { 10391 } 10392 } 10393 if (pae.result != null) { 10394 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result); 10395 } 10396 } 10397 synchronized (this) { 10398 mPendingAssistExtras.remove(pae); 10399 mHandler.removeCallbacks(pae); 10400 } 10401 return extras; 10402 } 10403 10404 public void reportAssistContextExtras(IBinder token, Bundle extras) { 10405 PendingAssistExtras pae = (PendingAssistExtras)token; 10406 synchronized (pae) { 10407 pae.result = extras; 10408 pae.haveResult = true; 10409 pae.notifyAll(); 10410 } 10411 } 10412 10413 public void registerProcessObserver(IProcessObserver observer) { 10414 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10415 "registerProcessObserver()"); 10416 synchronized (this) { 10417 mProcessObservers.register(observer); 10418 } 10419 } 10420 10421 @Override 10422 public void unregisterProcessObserver(IProcessObserver observer) { 10423 synchronized (this) { 10424 mProcessObservers.unregister(observer); 10425 } 10426 } 10427 10428 @Override 10429 public boolean convertFromTranslucent(IBinder token) { 10430 final long origId = Binder.clearCallingIdentity(); 10431 try { 10432 synchronized (this) { 10433 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10434 if (r == null) { 10435 return false; 10436 } 10437 final boolean translucentChanged = r.changeWindowTranslucency(true); 10438 if (translucentChanged) { 10439 r.task.stack.releaseBackgroundResources(); 10440 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 10441 } 10442 mWindowManager.setAppFullscreen(token, true); 10443 return translucentChanged; 10444 } 10445 } finally { 10446 Binder.restoreCallingIdentity(origId); 10447 } 10448 } 10449 10450 @Override 10451 public boolean convertToTranslucent(IBinder token, ActivityOptions options) { 10452 final long origId = Binder.clearCallingIdentity(); 10453 try { 10454 synchronized (this) { 10455 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10456 if (r == null) { 10457 return false; 10458 } 10459 int index = r.task.mActivities.lastIndexOf(r); 10460 if (index > 0) { 10461 ActivityRecord under = r.task.mActivities.get(index - 1); 10462 under.returningOptions = options; 10463 } 10464 final boolean translucentChanged = r.changeWindowTranslucency(false); 10465 if (translucentChanged) { 10466 r.task.stack.convertToTranslucent(r); 10467 } 10468 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 10469 mWindowManager.setAppFullscreen(token, false); 10470 return translucentChanged; 10471 } 10472 } finally { 10473 Binder.restoreCallingIdentity(origId); 10474 } 10475 } 10476 10477 @Override 10478 public boolean requestVisibleBehind(IBinder token, boolean visible) { 10479 final long origId = Binder.clearCallingIdentity(); 10480 try { 10481 synchronized (this) { 10482 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10483 if (r != null) { 10484 return mStackSupervisor.requestVisibleBehindLocked(r, visible); 10485 } 10486 } 10487 return false; 10488 } finally { 10489 Binder.restoreCallingIdentity(origId); 10490 } 10491 } 10492 10493 @Override 10494 public boolean isBackgroundVisibleBehind(IBinder token) { 10495 final long origId = Binder.clearCallingIdentity(); 10496 try { 10497 synchronized (this) { 10498 final ActivityStack stack = ActivityRecord.getStackLocked(token); 10499 final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity(); 10500 if (ActivityStackSupervisor.DEBUG_VISIBLE_BEHIND) Slog.d(TAG, 10501 "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible); 10502 return visible; 10503 } 10504 } finally { 10505 Binder.restoreCallingIdentity(origId); 10506 } 10507 } 10508 10509 @Override 10510 public ActivityOptions getActivityOptions(IBinder token) { 10511 final long origId = Binder.clearCallingIdentity(); 10512 try { 10513 synchronized (this) { 10514 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10515 if (r != null) { 10516 final ActivityOptions activityOptions = r.pendingOptions; 10517 r.pendingOptions = null; 10518 return activityOptions; 10519 } 10520 return null; 10521 } 10522 } finally { 10523 Binder.restoreCallingIdentity(origId); 10524 } 10525 } 10526 10527 @Override 10528 public void setImmersive(IBinder token, boolean immersive) { 10529 synchronized(this) { 10530 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10531 if (r == null) { 10532 throw new IllegalArgumentException(); 10533 } 10534 r.immersive = immersive; 10535 10536 // update associated state if we're frontmost 10537 if (r == mFocusedActivity) { 10538 if (DEBUG_IMMERSIVE) { 10539 Slog.d(TAG, "Frontmost changed immersion: "+ r); 10540 } 10541 applyUpdateLockStateLocked(r); 10542 } 10543 } 10544 } 10545 10546 @Override 10547 public boolean isImmersive(IBinder token) { 10548 synchronized (this) { 10549 ActivityRecord r = ActivityRecord.isInStackLocked(token); 10550 if (r == null) { 10551 throw new IllegalArgumentException(); 10552 } 10553 return r.immersive; 10554 } 10555 } 10556 10557 public boolean isTopActivityImmersive() { 10558 enforceNotIsolatedCaller("startActivity"); 10559 synchronized (this) { 10560 ActivityRecord r = getFocusedStack().topRunningActivityLocked(null); 10561 return (r != null) ? r.immersive : false; 10562 } 10563 } 10564 10565 @Override 10566 public boolean isTopOfTask(IBinder token) { 10567 synchronized (this) { 10568 ActivityRecord r = ActivityRecord.isInStackLocked(token); 10569 if (r == null) { 10570 throw new IllegalArgumentException(); 10571 } 10572 return r.task.getTopActivity() == r; 10573 } 10574 } 10575 10576 public final void enterSafeMode() { 10577 synchronized(this) { 10578 // It only makes sense to do this before the system is ready 10579 // and started launching other packages. 10580 if (!mSystemReady) { 10581 try { 10582 AppGlobals.getPackageManager().enterSafeMode(); 10583 } catch (RemoteException e) { 10584 } 10585 } 10586 10587 mSafeMode = true; 10588 } 10589 } 10590 10591 public final void showSafeModeOverlay() { 10592 View v = LayoutInflater.from(mContext).inflate( 10593 com.android.internal.R.layout.safe_mode, null); 10594 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 10595 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 10596 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 10597 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 10598 lp.gravity = Gravity.BOTTOM | Gravity.START; 10599 lp.format = v.getBackground().getOpacity(); 10600 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 10601 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 10602 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 10603 ((WindowManager)mContext.getSystemService( 10604 Context.WINDOW_SERVICE)).addView(v, lp); 10605 } 10606 10607 public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg) { 10608 if (!(sender instanceof PendingIntentRecord)) { 10609 return; 10610 } 10611 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 10612 synchronized (stats) { 10613 if (mBatteryStatsService.isOnBattery()) { 10614 mBatteryStatsService.enforceCallingPermission(); 10615 PendingIntentRecord rec = (PendingIntentRecord)sender; 10616 int MY_UID = Binder.getCallingUid(); 10617 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 10618 BatteryStatsImpl.Uid.Pkg pkg = 10619 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid, 10620 sourcePkg != null ? sourcePkg : rec.key.packageName); 10621 pkg.incWakeupsLocked(); 10622 } 10623 } 10624 } 10625 10626 public boolean killPids(int[] pids, String pReason, boolean secure) { 10627 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10628 throw new SecurityException("killPids only available to the system"); 10629 } 10630 String reason = (pReason == null) ? "Unknown" : pReason; 10631 // XXX Note: don't acquire main activity lock here, because the window 10632 // manager calls in with its locks held. 10633 10634 boolean killed = false; 10635 synchronized (mPidsSelfLocked) { 10636 int[] types = new int[pids.length]; 10637 int worstType = 0; 10638 for (int i=0; i<pids.length; i++) { 10639 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 10640 if (proc != null) { 10641 int type = proc.setAdj; 10642 types[i] = type; 10643 if (type > worstType) { 10644 worstType = type; 10645 } 10646 } 10647 } 10648 10649 // If the worst oom_adj is somewhere in the cached proc LRU range, 10650 // then constrain it so we will kill all cached procs. 10651 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 10652 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 10653 worstType = ProcessList.CACHED_APP_MIN_ADJ; 10654 } 10655 10656 // If this is not a secure call, don't let it kill processes that 10657 // are important. 10658 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 10659 worstType = ProcessList.SERVICE_ADJ; 10660 } 10661 10662 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 10663 for (int i=0; i<pids.length; i++) { 10664 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 10665 if (proc == null) { 10666 continue; 10667 } 10668 int adj = proc.setAdj; 10669 if (adj >= worstType && !proc.killedByAm) { 10670 proc.kill(reason, true); 10671 killed = true; 10672 } 10673 } 10674 } 10675 return killed; 10676 } 10677 10678 @Override 10679 public void killUid(int uid, String reason) { 10680 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10681 throw new SecurityException("killUid only available to the system"); 10682 } 10683 synchronized (this) { 10684 killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid), 10685 ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false, 10686 reason != null ? reason : "kill uid"); 10687 } 10688 } 10689 10690 @Override 10691 public boolean killProcessesBelowForeground(String reason) { 10692 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10693 throw new SecurityException("killProcessesBelowForeground() only available to system"); 10694 } 10695 10696 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 10697 } 10698 10699 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 10700 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10701 throw new SecurityException("killProcessesBelowAdj() only available to system"); 10702 } 10703 10704 boolean killed = false; 10705 synchronized (mPidsSelfLocked) { 10706 final int size = mPidsSelfLocked.size(); 10707 for (int i = 0; i < size; i++) { 10708 final int pid = mPidsSelfLocked.keyAt(i); 10709 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 10710 if (proc == null) continue; 10711 10712 final int adj = proc.setAdj; 10713 if (adj > belowAdj && !proc.killedByAm) { 10714 proc.kill(reason, true); 10715 killed = true; 10716 } 10717 } 10718 } 10719 return killed; 10720 } 10721 10722 @Override 10723 public void hang(final IBinder who, boolean allowRestart) { 10724 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10725 != PackageManager.PERMISSION_GRANTED) { 10726 throw new SecurityException("Requires permission " 10727 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10728 } 10729 10730 final IBinder.DeathRecipient death = new DeathRecipient() { 10731 @Override 10732 public void binderDied() { 10733 synchronized (this) { 10734 notifyAll(); 10735 } 10736 } 10737 }; 10738 10739 try { 10740 who.linkToDeath(death, 0); 10741 } catch (RemoteException e) { 10742 Slog.w(TAG, "hang: given caller IBinder is already dead."); 10743 return; 10744 } 10745 10746 synchronized (this) { 10747 Watchdog.getInstance().setAllowRestart(allowRestart); 10748 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 10749 synchronized (death) { 10750 while (who.isBinderAlive()) { 10751 try { 10752 death.wait(); 10753 } catch (InterruptedException e) { 10754 } 10755 } 10756 } 10757 Watchdog.getInstance().setAllowRestart(true); 10758 } 10759 } 10760 10761 @Override 10762 public void restart() { 10763 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10764 != PackageManager.PERMISSION_GRANTED) { 10765 throw new SecurityException("Requires permission " 10766 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10767 } 10768 10769 Log.i(TAG, "Sending shutdown broadcast..."); 10770 10771 BroadcastReceiver br = new BroadcastReceiver() { 10772 @Override public void onReceive(Context context, Intent intent) { 10773 // Now the broadcast is done, finish up the low-level shutdown. 10774 Log.i(TAG, "Shutting down activity manager..."); 10775 shutdown(10000); 10776 Log.i(TAG, "Shutdown complete, restarting!"); 10777 Process.killProcess(Process.myPid()); 10778 System.exit(10); 10779 } 10780 }; 10781 10782 // First send the high-level shut down broadcast. 10783 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 10784 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10785 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 10786 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 10787 mContext.sendOrderedBroadcastAsUser(intent, 10788 UserHandle.ALL, null, br, mHandler, 0, null, null); 10789 */ 10790 br.onReceive(mContext, intent); 10791 } 10792 10793 private long getLowRamTimeSinceIdle(long now) { 10794 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 10795 } 10796 10797 @Override 10798 public void performIdleMaintenance() { 10799 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10800 != PackageManager.PERMISSION_GRANTED) { 10801 throw new SecurityException("Requires permission " 10802 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10803 } 10804 10805 synchronized (this) { 10806 final long now = SystemClock.uptimeMillis(); 10807 final long timeSinceLastIdle = now - mLastIdleTime; 10808 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 10809 mLastIdleTime = now; 10810 mLowRamTimeSinceLastIdle = 0; 10811 if (mLowRamStartTime != 0) { 10812 mLowRamStartTime = now; 10813 } 10814 10815 StringBuilder sb = new StringBuilder(128); 10816 sb.append("Idle maintenance over "); 10817 TimeUtils.formatDuration(timeSinceLastIdle, sb); 10818 sb.append(" low RAM for "); 10819 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 10820 Slog.i(TAG, sb.toString()); 10821 10822 // If at least 1/3 of our time since the last idle period has been spent 10823 // with RAM low, then we want to kill processes. 10824 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 10825 10826 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 10827 ProcessRecord proc = mLruProcesses.get(i); 10828 if (proc.notCachedSinceIdle) { 10829 if (proc.setProcState > ActivityManager.PROCESS_STATE_TOP 10830 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 10831 if (doKilling && proc.initialIdlePss != 0 10832 && proc.lastPss > ((proc.initialIdlePss*3)/2)) { 10833 proc.kill("idle maint (pss " + proc.lastPss 10834 + " from " + proc.initialIdlePss + ")", true); 10835 } 10836 } 10837 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) { 10838 proc.notCachedSinceIdle = true; 10839 proc.initialIdlePss = 0; 10840 proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true, 10841 isSleeping(), now); 10842 } 10843 } 10844 10845 mHandler.removeMessages(REQUEST_ALL_PSS_MSG); 10846 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000); 10847 } 10848 } 10849 10850 private void retrieveSettings() { 10851 final ContentResolver resolver = mContext.getContentResolver(); 10852 String debugApp = Settings.Global.getString( 10853 resolver, Settings.Global.DEBUG_APP); 10854 boolean waitForDebugger = Settings.Global.getInt( 10855 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0; 10856 boolean alwaysFinishActivities = Settings.Global.getInt( 10857 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0; 10858 boolean forceRtl = Settings.Global.getInt( 10859 resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0; 10860 // Transfer any global setting for forcing RTL layout, into a System Property 10861 SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0"); 10862 10863 Configuration configuration = new Configuration(); 10864 Settings.System.getConfiguration(resolver, configuration); 10865 if (forceRtl) { 10866 // This will take care of setting the correct layout direction flags 10867 configuration.setLayoutDirection(configuration.locale); 10868 } 10869 10870 synchronized (this) { 10871 mDebugApp = mOrigDebugApp = debugApp; 10872 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 10873 mAlwaysFinishActivities = alwaysFinishActivities; 10874 // This happens before any activities are started, so we can 10875 // change mConfiguration in-place. 10876 updateConfigurationLocked(configuration, null, false, true); 10877 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration); 10878 } 10879 } 10880 10881 /** Loads resources after the current configuration has been set. */ 10882 private void loadResourcesOnSystemReady() { 10883 final Resources res = mContext.getResources(); 10884 mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents); 10885 mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 10886 mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 10887 } 10888 10889 public boolean testIsSystemReady() { 10890 // no need to synchronize(this) just to read & return the value 10891 return mSystemReady; 10892 } 10893 10894 private static File getCalledPreBootReceiversFile() { 10895 File dataDir = Environment.getDataDirectory(); 10896 File systemDir = new File(dataDir, "system"); 10897 File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME); 10898 return fname; 10899 } 10900 10901 private static ArrayList<ComponentName> readLastDonePreBootReceivers() { 10902 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>(); 10903 File file = getCalledPreBootReceiversFile(); 10904 FileInputStream fis = null; 10905 try { 10906 fis = new FileInputStream(file); 10907 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048)); 10908 int fvers = dis.readInt(); 10909 if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) { 10910 String vers = dis.readUTF(); 10911 String codename = dis.readUTF(); 10912 String build = dis.readUTF(); 10913 if (android.os.Build.VERSION.RELEASE.equals(vers) 10914 && android.os.Build.VERSION.CODENAME.equals(codename) 10915 && android.os.Build.VERSION.INCREMENTAL.equals(build)) { 10916 int num = dis.readInt(); 10917 while (num > 0) { 10918 num--; 10919 String pkg = dis.readUTF(); 10920 String cls = dis.readUTF(); 10921 lastDoneReceivers.add(new ComponentName(pkg, cls)); 10922 } 10923 } 10924 } 10925 } catch (FileNotFoundException e) { 10926 } catch (IOException e) { 10927 Slog.w(TAG, "Failure reading last done pre-boot receivers", e); 10928 } finally { 10929 if (fis != null) { 10930 try { 10931 fis.close(); 10932 } catch (IOException e) { 10933 } 10934 } 10935 } 10936 return lastDoneReceivers; 10937 } 10938 10939 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) { 10940 File file = getCalledPreBootReceiversFile(); 10941 FileOutputStream fos = null; 10942 DataOutputStream dos = null; 10943 try { 10944 fos = new FileOutputStream(file); 10945 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048)); 10946 dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION); 10947 dos.writeUTF(android.os.Build.VERSION.RELEASE); 10948 dos.writeUTF(android.os.Build.VERSION.CODENAME); 10949 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL); 10950 dos.writeInt(list.size()); 10951 for (int i=0; i<list.size(); i++) { 10952 dos.writeUTF(list.get(i).getPackageName()); 10953 dos.writeUTF(list.get(i).getClassName()); 10954 } 10955 } catch (IOException e) { 10956 Slog.w(TAG, "Failure writing last done pre-boot receivers", e); 10957 file.delete(); 10958 } finally { 10959 FileUtils.sync(fos); 10960 if (dos != null) { 10961 try { 10962 dos.close(); 10963 } catch (IOException e) { 10964 // TODO Auto-generated catch block 10965 e.printStackTrace(); 10966 } 10967 } 10968 } 10969 } 10970 10971 private boolean deliverPreBootCompleted(final Runnable onFinishCallback, 10972 ArrayList<ComponentName> doneReceivers, int userId) { 10973 boolean waitingUpdate = false; 10974 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 10975 List<ResolveInfo> ris = null; 10976 try { 10977 ris = AppGlobals.getPackageManager().queryIntentReceivers( 10978 intent, null, 0, userId); 10979 } catch (RemoteException e) { 10980 } 10981 if (ris != null) { 10982 for (int i=ris.size()-1; i>=0; i--) { 10983 if ((ris.get(i).activityInfo.applicationInfo.flags 10984 &ApplicationInfo.FLAG_SYSTEM) == 0) { 10985 ris.remove(i); 10986 } 10987 } 10988 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); 10989 10990 // For User 0, load the version number. When delivering to a new user, deliver 10991 // to all receivers. 10992 if (userId == UserHandle.USER_OWNER) { 10993 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers(); 10994 for (int i=0; i<ris.size(); i++) { 10995 ActivityInfo ai = ris.get(i).activityInfo; 10996 ComponentName comp = new ComponentName(ai.packageName, ai.name); 10997 if (lastDoneReceivers.contains(comp)) { 10998 // We already did the pre boot receiver for this app with the current 10999 // platform version, so don't do it again... 11000 ris.remove(i); 11001 i--; 11002 // ...however, do keep it as one that has been done, so we don't 11003 // forget about it when rewriting the file of last done receivers. 11004 doneReceivers.add(comp); 11005 } 11006 } 11007 } 11008 11009 // If primary user, send broadcast to all available users, else just to userId 11010 final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked() 11011 : new int[] { userId }; 11012 for (int i = 0; i < ris.size(); i++) { 11013 ActivityInfo ai = ris.get(i).activityInfo; 11014 ComponentName comp = new ComponentName(ai.packageName, ai.name); 11015 doneReceivers.add(comp); 11016 intent.setComponent(comp); 11017 for (int j=0; j<users.length; j++) { 11018 IIntentReceiver finisher = null; 11019 // On last receiver and user, set up a completion callback 11020 if (i == ris.size() - 1 && j == users.length - 1 && onFinishCallback != null) { 11021 finisher = new IIntentReceiver.Stub() { 11022 public void performReceive(Intent intent, int resultCode, 11023 String data, Bundle extras, boolean ordered, 11024 boolean sticky, int sendingUser) { 11025 // The raw IIntentReceiver interface is called 11026 // with the AM lock held, so redispatch to 11027 // execute our code without the lock. 11028 mHandler.post(onFinishCallback); 11029 } 11030 }; 11031 } 11032 Slog.i(TAG, "Sending system update to " + intent.getComponent() 11033 + " for user " + users[j]); 11034 broadcastIntentLocked(null, null, intent, null, finisher, 11035 0, null, null, null, AppOpsManager.OP_NONE, 11036 true, false, MY_PID, Process.SYSTEM_UID, 11037 users[j]); 11038 if (finisher != null) { 11039 waitingUpdate = true; 11040 } 11041 } 11042 } 11043 } 11044 11045 return waitingUpdate; 11046 } 11047 11048 public void systemReady(final Runnable goingCallback) { 11049 synchronized(this) { 11050 if (mSystemReady) { 11051 // If we're done calling all the receivers, run the next "boot phase" passed in 11052 // by the SystemServer 11053 if (goingCallback != null) { 11054 goingCallback.run(); 11055 } 11056 return; 11057 } 11058 11059 // Make sure we have the current profile info, since it is needed for 11060 // security checks. 11061 updateCurrentProfileIdsLocked(); 11062 11063 if (mRecentTasks == null) { 11064 mRecentTasks = mTaskPersister.restoreTasksLocked(); 11065 if (!mRecentTasks.isEmpty()) { 11066 mStackSupervisor.createStackForRestoredTaskHistory(mRecentTasks); 11067 } 11068 cleanupRecentTasksLocked(UserHandle.USER_ALL); 11069 mTaskPersister.startPersisting(); 11070 } 11071 11072 // Check to see if there are any update receivers to run. 11073 if (!mDidUpdate) { 11074 if (mWaitingUpdate) { 11075 return; 11076 } 11077 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); 11078 mWaitingUpdate = deliverPreBootCompleted(new Runnable() { 11079 public void run() { 11080 synchronized (ActivityManagerService.this) { 11081 mDidUpdate = true; 11082 } 11083 writeLastDonePreBootReceivers(doneReceivers); 11084 showBootMessage(mContext.getText( 11085 R.string.android_upgrading_complete), 11086 false); 11087 systemReady(goingCallback); 11088 } 11089 }, doneReceivers, UserHandle.USER_OWNER); 11090 11091 if (mWaitingUpdate) { 11092 return; 11093 } 11094 mDidUpdate = true; 11095 } 11096 11097 mAppOpsService.systemReady(); 11098 mSystemReady = true; 11099 } 11100 11101 ArrayList<ProcessRecord> procsToKill = null; 11102 synchronized(mPidsSelfLocked) { 11103 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 11104 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 11105 if (!isAllowedWhileBooting(proc.info)){ 11106 if (procsToKill == null) { 11107 procsToKill = new ArrayList<ProcessRecord>(); 11108 } 11109 procsToKill.add(proc); 11110 } 11111 } 11112 } 11113 11114 synchronized(this) { 11115 if (procsToKill != null) { 11116 for (int i=procsToKill.size()-1; i>=0; i--) { 11117 ProcessRecord proc = procsToKill.get(i); 11118 Slog.i(TAG, "Removing system update proc: " + proc); 11119 removeProcessLocked(proc, true, false, "system update done"); 11120 } 11121 } 11122 11123 // Now that we have cleaned up any update processes, we 11124 // are ready to start launching real processes and know that 11125 // we won't trample on them any more. 11126 mProcessesReady = true; 11127 } 11128 11129 Slog.i(TAG, "System now ready"); 11130 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, 11131 SystemClock.uptimeMillis()); 11132 11133 synchronized(this) { 11134 // Make sure we have no pre-ready processes sitting around. 11135 11136 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11137 ResolveInfo ri = mContext.getPackageManager() 11138 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), 11139 STOCK_PM_FLAGS); 11140 CharSequence errorMsg = null; 11141 if (ri != null) { 11142 ActivityInfo ai = ri.activityInfo; 11143 ApplicationInfo app = ai.applicationInfo; 11144 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11145 mTopAction = Intent.ACTION_FACTORY_TEST; 11146 mTopData = null; 11147 mTopComponent = new ComponentName(app.packageName, 11148 ai.name); 11149 } else { 11150 errorMsg = mContext.getResources().getText( 11151 com.android.internal.R.string.factorytest_not_system); 11152 } 11153 } else { 11154 errorMsg = mContext.getResources().getText( 11155 com.android.internal.R.string.factorytest_no_action); 11156 } 11157 if (errorMsg != null) { 11158 mTopAction = null; 11159 mTopData = null; 11160 mTopComponent = null; 11161 Message msg = Message.obtain(); 11162 msg.what = SHOW_FACTORY_ERROR_MSG; 11163 msg.getData().putCharSequence("msg", errorMsg); 11164 mHandler.sendMessage(msg); 11165 } 11166 } 11167 } 11168 11169 retrieveSettings(); 11170 loadResourcesOnSystemReady(); 11171 11172 synchronized (this) { 11173 readGrantedUriPermissionsLocked(); 11174 } 11175 11176 if (goingCallback != null) goingCallback.run(); 11177 11178 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 11179 Integer.toString(mCurrentUserId), mCurrentUserId); 11180 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 11181 Integer.toString(mCurrentUserId), mCurrentUserId); 11182 mSystemServiceManager.startUser(mCurrentUserId); 11183 11184 synchronized (this) { 11185 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11186 try { 11187 List apps = AppGlobals.getPackageManager(). 11188 getPersistentApplications(STOCK_PM_FLAGS); 11189 if (apps != null) { 11190 int N = apps.size(); 11191 int i; 11192 for (i=0; i<N; i++) { 11193 ApplicationInfo info 11194 = (ApplicationInfo)apps.get(i); 11195 if (info != null && 11196 !info.packageName.equals("android")) { 11197 addAppLocked(info, false, null /* ABI override */); 11198 } 11199 } 11200 } 11201 } catch (RemoteException ex) { 11202 // pm is in same process, this will never happen. 11203 } 11204 } 11205 11206 // Start up initial activity. 11207 mBooting = true; 11208 11209 try { 11210 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { 11211 Message msg = Message.obtain(); 11212 msg.what = SHOW_UID_ERROR_MSG; 11213 mHandler.sendMessage(msg); 11214 } 11215 } catch (RemoteException e) { 11216 } 11217 11218 long ident = Binder.clearCallingIdentity(); 11219 try { 11220 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 11221 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 11222 | Intent.FLAG_RECEIVER_FOREGROUND); 11223 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11224 broadcastIntentLocked(null, null, intent, 11225 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 11226 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId); 11227 intent = new Intent(Intent.ACTION_USER_STARTING); 11228 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 11229 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11230 broadcastIntentLocked(null, null, intent, 11231 null, new IIntentReceiver.Stub() { 11232 @Override 11233 public void performReceive(Intent intent, int resultCode, String data, 11234 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 11235 throws RemoteException { 11236 } 11237 }, 0, null, null, 11238 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 11239 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 11240 } catch (Throwable t) { 11241 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 11242 } finally { 11243 Binder.restoreCallingIdentity(ident); 11244 } 11245 mStackSupervisor.resumeTopActivitiesLocked(); 11246 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId); 11247 } 11248 } 11249 11250 private boolean makeAppCrashingLocked(ProcessRecord app, 11251 String shortMsg, String longMsg, String stackTrace) { 11252 app.crashing = true; 11253 app.crashingReport = generateProcessError(app, 11254 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace); 11255 startAppProblemLocked(app); 11256 app.stopFreezingAllLocked(); 11257 return handleAppCrashLocked(app, shortMsg, longMsg, stackTrace); 11258 } 11259 11260 private void makeAppNotRespondingLocked(ProcessRecord app, 11261 String activity, String shortMsg, String longMsg) { 11262 app.notResponding = true; 11263 app.notRespondingReport = generateProcessError(app, 11264 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 11265 activity, shortMsg, longMsg, null); 11266 startAppProblemLocked(app); 11267 app.stopFreezingAllLocked(); 11268 } 11269 11270 /** 11271 * Generate a process error record, suitable for attachment to a ProcessRecord. 11272 * 11273 * @param app The ProcessRecord in which the error occurred. 11274 * @param condition Crashing, Application Not Responding, etc. Values are defined in 11275 * ActivityManager.AppErrorStateInfo 11276 * @param activity The activity associated with the crash, if known. 11277 * @param shortMsg Short message describing the crash. 11278 * @param longMsg Long message describing the crash. 11279 * @param stackTrace Full crash stack trace, may be null. 11280 * 11281 * @return Returns a fully-formed AppErrorStateInfo record. 11282 */ 11283 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app, 11284 int condition, String activity, String shortMsg, String longMsg, String stackTrace) { 11285 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo(); 11286 11287 report.condition = condition; 11288 report.processName = app.processName; 11289 report.pid = app.pid; 11290 report.uid = app.info.uid; 11291 report.tag = activity; 11292 report.shortMsg = shortMsg; 11293 report.longMsg = longMsg; 11294 report.stackTrace = stackTrace; 11295 11296 return report; 11297 } 11298 11299 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 11300 synchronized (this) { 11301 app.crashing = false; 11302 app.crashingReport = null; 11303 app.notResponding = false; 11304 app.notRespondingReport = null; 11305 if (app.anrDialog == fromDialog) { 11306 app.anrDialog = null; 11307 } 11308 if (app.waitDialog == fromDialog) { 11309 app.waitDialog = null; 11310 } 11311 if (app.pid > 0 && app.pid != MY_PID) { 11312 handleAppCrashLocked(app, null, null, null); 11313 app.kill("user request after error", true); 11314 } 11315 } 11316 } 11317 11318 private boolean handleAppCrashLocked(ProcessRecord app, String shortMsg, String longMsg, 11319 String stackTrace) { 11320 long now = SystemClock.uptimeMillis(); 11321 11322 Long crashTime; 11323 if (!app.isolated) { 11324 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid); 11325 } else { 11326 crashTime = null; 11327 } 11328 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) { 11329 // This process loses! 11330 Slog.w(TAG, "Process " + app.info.processName 11331 + " has crashed too many times: killing!"); 11332 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, 11333 app.userId, app.info.processName, app.uid); 11334 mStackSupervisor.handleAppCrashLocked(app); 11335 if (!app.persistent) { 11336 // We don't want to start this process again until the user 11337 // explicitly does so... but for persistent process, we really 11338 // need to keep it running. If a persistent process is actually 11339 // repeatedly crashing, then badness for everyone. 11340 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, 11341 app.info.processName); 11342 if (!app.isolated) { 11343 // XXX We don't have a way to mark isolated processes 11344 // as bad, since they don't have a peristent identity. 11345 mBadProcesses.put(app.info.processName, app.uid, 11346 new BadProcessInfo(now, shortMsg, longMsg, stackTrace)); 11347 mProcessCrashTimes.remove(app.info.processName, app.uid); 11348 } 11349 app.bad = true; 11350 app.removed = true; 11351 // Don't let services in this process be restarted and potentially 11352 // annoy the user repeatedly. Unless it is persistent, since those 11353 // processes run critical code. 11354 removeProcessLocked(app, false, false, "crash"); 11355 mStackSupervisor.resumeTopActivitiesLocked(); 11356 return false; 11357 } 11358 mStackSupervisor.resumeTopActivitiesLocked(); 11359 } else { 11360 mStackSupervisor.finishTopRunningActivityLocked(app); 11361 } 11362 11363 // Bump up the crash count of any services currently running in the proc. 11364 for (int i=app.services.size()-1; i>=0; i--) { 11365 // Any services running in the application need to be placed 11366 // back in the pending list. 11367 ServiceRecord sr = app.services.valueAt(i); 11368 sr.crashCount++; 11369 } 11370 11371 // If the crashing process is what we consider to be the "home process" and it has been 11372 // replaced by a third-party app, clear the package preferred activities from packages 11373 // with a home activity running in the process to prevent a repeatedly crashing app 11374 // from blocking the user to manually clear the list. 11375 final ArrayList<ActivityRecord> activities = app.activities; 11376 if (app == mHomeProcess && activities.size() > 0 11377 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 11378 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 11379 final ActivityRecord r = activities.get(activityNdx); 11380 if (r.isHomeActivity()) { 11381 Log.i(TAG, "Clearing package preferred activities from " + r.packageName); 11382 try { 11383 ActivityThread.getPackageManager() 11384 .clearPackagePreferredActivities(r.packageName); 11385 } catch (RemoteException c) { 11386 // pm is in same process, this will never happen. 11387 } 11388 } 11389 } 11390 } 11391 11392 if (!app.isolated) { 11393 // XXX Can't keep track of crash times for isolated processes, 11394 // because they don't have a perisistent identity. 11395 mProcessCrashTimes.put(app.info.processName, app.uid, now); 11396 } 11397 11398 if (app.crashHandler != null) mHandler.post(app.crashHandler); 11399 return true; 11400 } 11401 11402 void startAppProblemLocked(ProcessRecord app) { 11403 // If this app is not running under the current user, then we 11404 // can't give it a report button because that would require 11405 // launching the report UI under a different user. 11406 app.errorReportReceiver = null; 11407 11408 for (int userId : mCurrentProfileIds) { 11409 if (app.userId == userId) { 11410 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver( 11411 mContext, app.info.packageName, app.info.flags); 11412 } 11413 } 11414 skipCurrentReceiverLocked(app); 11415 } 11416 11417 void skipCurrentReceiverLocked(ProcessRecord app) { 11418 for (BroadcastQueue queue : mBroadcastQueues) { 11419 queue.skipCurrentReceiverLocked(app); 11420 } 11421 } 11422 11423 /** 11424 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 11425 * The application process will exit immediately after this call returns. 11426 * @param app object of the crashing app, null for the system server 11427 * @param crashInfo describing the exception 11428 */ 11429 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) { 11430 ProcessRecord r = findAppProcess(app, "Crash"); 11431 final String processName = app == null ? "system_server" 11432 : (r == null ? "unknown" : r.processName); 11433 11434 handleApplicationCrashInner("crash", r, processName, crashInfo); 11435 } 11436 11437 /* Native crash reporting uses this inner version because it needs to be somewhat 11438 * decoupled from the AM-managed cleanup lifecycle 11439 */ 11440 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 11441 ApplicationErrorReport.CrashInfo crashInfo) { 11442 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(), 11443 UserHandle.getUserId(Binder.getCallingUid()), processName, 11444 r == null ? -1 : r.info.flags, 11445 crashInfo.exceptionClassName, 11446 crashInfo.exceptionMessage, 11447 crashInfo.throwFileName, 11448 crashInfo.throwLineNumber); 11449 11450 addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo); 11451 11452 crashApplication(r, crashInfo); 11453 } 11454 11455 public void handleApplicationStrictModeViolation( 11456 IBinder app, 11457 int violationMask, 11458 StrictMode.ViolationInfo info) { 11459 ProcessRecord r = findAppProcess(app, "StrictMode"); 11460 if (r == null) { 11461 return; 11462 } 11463 11464 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) { 11465 Integer stackFingerprint = info.hashCode(); 11466 boolean logIt = true; 11467 synchronized (mAlreadyLoggedViolatedStacks) { 11468 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 11469 logIt = false; 11470 // TODO: sub-sample into EventLog for these, with 11471 // the info.durationMillis? Then we'd get 11472 // the relative pain numbers, without logging all 11473 // the stack traces repeatedly. We'd want to do 11474 // likewise in the client code, which also does 11475 // dup suppression, before the Binder call. 11476 } else { 11477 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 11478 mAlreadyLoggedViolatedStacks.clear(); 11479 } 11480 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 11481 } 11482 } 11483 if (logIt) { 11484 logStrictModeViolationToDropBox(r, info); 11485 } 11486 } 11487 11488 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) { 11489 AppErrorResult result = new AppErrorResult(); 11490 synchronized (this) { 11491 final long origId = Binder.clearCallingIdentity(); 11492 11493 Message msg = Message.obtain(); 11494 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG; 11495 HashMap<String, Object> data = new HashMap<String, Object>(); 11496 data.put("result", result); 11497 data.put("app", r); 11498 data.put("violationMask", violationMask); 11499 data.put("info", info); 11500 msg.obj = data; 11501 mHandler.sendMessage(msg); 11502 11503 Binder.restoreCallingIdentity(origId); 11504 } 11505 int res = result.get(); 11506 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 11507 } 11508 } 11509 11510 // Depending on the policy in effect, there could be a bunch of 11511 // these in quick succession so we try to batch these together to 11512 // minimize disk writes, number of dropbox entries, and maximize 11513 // compression, by having more fewer, larger records. 11514 private void logStrictModeViolationToDropBox( 11515 ProcessRecord process, 11516 StrictMode.ViolationInfo info) { 11517 if (info == null) { 11518 return; 11519 } 11520 final boolean isSystemApp = process == null || 11521 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 11522 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 11523 final String processName = process == null ? "unknown" : process.processName; 11524 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode"; 11525 final DropBoxManager dbox = (DropBoxManager) 11526 mContext.getSystemService(Context.DROPBOX_SERVICE); 11527 11528 // Exit early if the dropbox isn't configured to accept this report type. 11529 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 11530 11531 boolean bufferWasEmpty; 11532 boolean needsFlush; 11533 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024); 11534 synchronized (sb) { 11535 bufferWasEmpty = sb.length() == 0; 11536 appendDropBoxProcessHeaders(process, processName, sb); 11537 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 11538 sb.append("System-App: ").append(isSystemApp).append("\n"); 11539 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 11540 if (info.violationNumThisLoop != 0) { 11541 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 11542 } 11543 if (info.numAnimationsRunning != 0) { 11544 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 11545 } 11546 if (info.broadcastIntentAction != null) { 11547 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 11548 } 11549 if (info.durationMillis != -1) { 11550 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 11551 } 11552 if (info.numInstances != -1) { 11553 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 11554 } 11555 if (info.tags != null) { 11556 for (String tag : info.tags) { 11557 sb.append("Span-Tag: ").append(tag).append("\n"); 11558 } 11559 } 11560 sb.append("\n"); 11561 if (info.crashInfo != null && info.crashInfo.stackTrace != null) { 11562 sb.append(info.crashInfo.stackTrace); 11563 } 11564 sb.append("\n"); 11565 11566 // Only buffer up to ~64k. Various logging bits truncate 11567 // things at 128k. 11568 needsFlush = (sb.length() > 64 * 1024); 11569 } 11570 11571 // Flush immediately if the buffer's grown too large, or this 11572 // is a non-system app. Non-system apps are isolated with a 11573 // different tag & policy and not batched. 11574 // 11575 // Batching is useful during internal testing with 11576 // StrictMode settings turned up high. Without batching, 11577 // thousands of separate files could be created on boot. 11578 if (!isSystemApp || needsFlush) { 11579 new Thread("Error dump: " + dropboxTag) { 11580 @Override 11581 public void run() { 11582 String report; 11583 synchronized (sb) { 11584 report = sb.toString(); 11585 sb.delete(0, sb.length()); 11586 sb.trimToSize(); 11587 } 11588 if (report.length() != 0) { 11589 dbox.addText(dropboxTag, report); 11590 } 11591 } 11592 }.start(); 11593 return; 11594 } 11595 11596 // System app batching: 11597 if (!bufferWasEmpty) { 11598 // An existing dropbox-writing thread is outstanding, so 11599 // we don't need to start it up. The existing thread will 11600 // catch the buffer appends we just did. 11601 return; 11602 } 11603 11604 // Worker thread to both batch writes and to avoid blocking the caller on I/O. 11605 // (After this point, we shouldn't access AMS internal data structures.) 11606 new Thread("Error dump: " + dropboxTag) { 11607 @Override 11608 public void run() { 11609 // 5 second sleep to let stacks arrive and be batched together 11610 try { 11611 Thread.sleep(5000); // 5 seconds 11612 } catch (InterruptedException e) {} 11613 11614 String errorReport; 11615 synchronized (mStrictModeBuffer) { 11616 errorReport = mStrictModeBuffer.toString(); 11617 if (errorReport.length() == 0) { 11618 return; 11619 } 11620 mStrictModeBuffer.delete(0, mStrictModeBuffer.length()); 11621 mStrictModeBuffer.trimToSize(); 11622 } 11623 dbox.addText(dropboxTag, errorReport); 11624 } 11625 }.start(); 11626 } 11627 11628 /** 11629 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 11630 * @param app object of the crashing app, null for the system server 11631 * @param tag reported by the caller 11632 * @param system whether this wtf is coming from the system 11633 * @param crashInfo describing the context of the error 11634 * @return true if the process should exit immediately (WTF is fatal) 11635 */ 11636 public boolean handleApplicationWtf(IBinder app, final String tag, boolean system, 11637 final ApplicationErrorReport.CrashInfo crashInfo) { 11638 final ProcessRecord r = findAppProcess(app, "WTF"); 11639 final String processName = app == null ? "system_server" 11640 : (r == null ? "unknown" : r.processName); 11641 11642 EventLog.writeEvent(EventLogTags.AM_WTF, 11643 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(), 11644 processName, 11645 r == null ? -1 : r.info.flags, 11646 tag, crashInfo.exceptionMessage); 11647 11648 if (system) { 11649 // If this is coming from the system, we could very well have low-level 11650 // system locks held, so we want to do this all asynchronously. And we 11651 // never want this to become fatal, so there is that too. 11652 mHandler.post(new Runnable() { 11653 @Override public void run() { 11654 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, 11655 crashInfo); 11656 } 11657 }); 11658 return false; 11659 } 11660 11661 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo); 11662 11663 if (r != null && r.pid != Process.myPid() && 11664 Settings.Global.getInt(mContext.getContentResolver(), 11665 Settings.Global.WTF_IS_FATAL, 0) != 0) { 11666 crashApplication(r, crashInfo); 11667 return true; 11668 } else { 11669 return false; 11670 } 11671 } 11672 11673 /** 11674 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 11675 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 11676 */ 11677 private ProcessRecord findAppProcess(IBinder app, String reason) { 11678 if (app == null) { 11679 return null; 11680 } 11681 11682 synchronized (this) { 11683 final int NP = mProcessNames.getMap().size(); 11684 for (int ip=0; ip<NP; ip++) { 11685 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 11686 final int NA = apps.size(); 11687 for (int ia=0; ia<NA; ia++) { 11688 ProcessRecord p = apps.valueAt(ia); 11689 if (p.thread != null && p.thread.asBinder() == app) { 11690 return p; 11691 } 11692 } 11693 } 11694 11695 Slog.w(TAG, "Can't find mystery application for " + reason 11696 + " from pid=" + Binder.getCallingPid() 11697 + " uid=" + Binder.getCallingUid() + ": " + app); 11698 return null; 11699 } 11700 } 11701 11702 /** 11703 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 11704 * to append various headers to the dropbox log text. 11705 */ 11706 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 11707 StringBuilder sb) { 11708 // Watchdog thread ends up invoking this function (with 11709 // a null ProcessRecord) to add the stack file to dropbox. 11710 // Do not acquire a lock on this (am) in such cases, as it 11711 // could cause a potential deadlock, if and when watchdog 11712 // is invoked due to unavailability of lock on am and it 11713 // would prevent watchdog from killing system_server. 11714 if (process == null) { 11715 sb.append("Process: ").append(processName).append("\n"); 11716 return; 11717 } 11718 // Note: ProcessRecord 'process' is guarded by the service 11719 // instance. (notably process.pkgList, which could otherwise change 11720 // concurrently during execution of this method) 11721 synchronized (this) { 11722 sb.append("Process: ").append(processName).append("\n"); 11723 int flags = process.info.flags; 11724 IPackageManager pm = AppGlobals.getPackageManager(); 11725 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n"); 11726 for (int ip=0; ip<process.pkgList.size(); ip++) { 11727 String pkg = process.pkgList.keyAt(ip); 11728 sb.append("Package: ").append(pkg); 11729 try { 11730 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId()); 11731 if (pi != null) { 11732 sb.append(" v").append(pi.versionCode); 11733 if (pi.versionName != null) { 11734 sb.append(" (").append(pi.versionName).append(")"); 11735 } 11736 } 11737 } catch (RemoteException e) { 11738 Slog.e(TAG, "Error getting package info: " + pkg, e); 11739 } 11740 sb.append("\n"); 11741 } 11742 } 11743 } 11744 11745 private static String processClass(ProcessRecord process) { 11746 if (process == null || process.pid == MY_PID) { 11747 return "system_server"; 11748 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11749 return "system_app"; 11750 } else { 11751 return "data_app"; 11752 } 11753 } 11754 11755 /** 11756 * Write a description of an error (crash, WTF, ANR) to the drop box. 11757 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 11758 * @param process which caused the error, null means the system server 11759 * @param activity which triggered the error, null if unknown 11760 * @param parent activity related to the error, null if unknown 11761 * @param subject line related to the error, null if absent 11762 * @param report in long form describing the error, null if absent 11763 * @param logFile to include in the report, null if none 11764 * @param crashInfo giving an application stack trace, null if absent 11765 */ 11766 public void addErrorToDropBox(String eventType, 11767 ProcessRecord process, String processName, ActivityRecord activity, 11768 ActivityRecord parent, String subject, 11769 final String report, final File logFile, 11770 final ApplicationErrorReport.CrashInfo crashInfo) { 11771 // NOTE -- this must never acquire the ActivityManagerService lock, 11772 // otherwise the watchdog may be prevented from resetting the system. 11773 11774 final String dropboxTag = processClass(process) + "_" + eventType; 11775 final DropBoxManager dbox = (DropBoxManager) 11776 mContext.getSystemService(Context.DROPBOX_SERVICE); 11777 11778 // Exit early if the dropbox isn't configured to accept this report type. 11779 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 11780 11781 final StringBuilder sb = new StringBuilder(1024); 11782 appendDropBoxProcessHeaders(process, processName, sb); 11783 if (activity != null) { 11784 sb.append("Activity: ").append(activity.shortComponentName).append("\n"); 11785 } 11786 if (parent != null && parent.app != null && parent.app.pid != process.pid) { 11787 sb.append("Parent-Process: ").append(parent.app.processName).append("\n"); 11788 } 11789 if (parent != null && parent != activity) { 11790 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n"); 11791 } 11792 if (subject != null) { 11793 sb.append("Subject: ").append(subject).append("\n"); 11794 } 11795 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 11796 if (Debug.isDebuggerConnected()) { 11797 sb.append("Debugger: Connected\n"); 11798 } 11799 sb.append("\n"); 11800 11801 // Do the rest in a worker thread to avoid blocking the caller on I/O 11802 // (After this point, we shouldn't access AMS internal data structures.) 11803 Thread worker = new Thread("Error dump: " + dropboxTag) { 11804 @Override 11805 public void run() { 11806 if (report != null) { 11807 sb.append(report); 11808 } 11809 if (logFile != null) { 11810 try { 11811 sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE, 11812 "\n\n[[TRUNCATED]]")); 11813 } catch (IOException e) { 11814 Slog.e(TAG, "Error reading " + logFile, e); 11815 } 11816 } 11817 if (crashInfo != null && crashInfo.stackTrace != null) { 11818 sb.append(crashInfo.stackTrace); 11819 } 11820 11821 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 11822 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0); 11823 if (lines > 0) { 11824 sb.append("\n"); 11825 11826 // Merge several logcat streams, and take the last N lines 11827 InputStreamReader input = null; 11828 try { 11829 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat", 11830 "-v", "time", "-b", "events", "-b", "system", "-b", "main", 11831 "-b", "crash", 11832 "-t", String.valueOf(lines)).redirectErrorStream(true).start(); 11833 11834 try { logcat.getOutputStream().close(); } catch (IOException e) {} 11835 try { logcat.getErrorStream().close(); } catch (IOException e) {} 11836 input = new InputStreamReader(logcat.getInputStream()); 11837 11838 int num; 11839 char[] buf = new char[8192]; 11840 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 11841 } catch (IOException e) { 11842 Slog.e(TAG, "Error running logcat", e); 11843 } finally { 11844 if (input != null) try { input.close(); } catch (IOException e) {} 11845 } 11846 } 11847 11848 dbox.addText(dropboxTag, sb.toString()); 11849 } 11850 }; 11851 11852 if (process == null) { 11853 // If process is null, we are being called from some internal code 11854 // and may be about to die -- run this synchronously. 11855 worker.run(); 11856 } else { 11857 worker.start(); 11858 } 11859 } 11860 11861 /** 11862 * Bring up the "unexpected error" dialog box for a crashing app. 11863 * Deal with edge cases (intercepts from instrumented applications, 11864 * ActivityController, error intent receivers, that sort of thing). 11865 * @param r the application crashing 11866 * @param crashInfo describing the failure 11867 */ 11868 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) { 11869 long timeMillis = System.currentTimeMillis(); 11870 String shortMsg = crashInfo.exceptionClassName; 11871 String longMsg = crashInfo.exceptionMessage; 11872 String stackTrace = crashInfo.stackTrace; 11873 if (shortMsg != null && longMsg != null) { 11874 longMsg = shortMsg + ": " + longMsg; 11875 } else if (shortMsg != null) { 11876 longMsg = shortMsg; 11877 } 11878 11879 AppErrorResult result = new AppErrorResult(); 11880 synchronized (this) { 11881 if (mController != null) { 11882 try { 11883 String name = r != null ? r.processName : null; 11884 int pid = r != null ? r.pid : Binder.getCallingPid(); 11885 int uid = r != null ? r.info.uid : Binder.getCallingUid(); 11886 if (!mController.appCrashed(name, pid, 11887 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) { 11888 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")) 11889 && "Native crash".equals(crashInfo.exceptionClassName)) { 11890 Slog.w(TAG, "Skip killing native crashed app " + name 11891 + "(" + pid + ") during testing"); 11892 } else { 11893 Slog.w(TAG, "Force-killing crashed app " + name 11894 + " at watcher's request"); 11895 if (r != null) { 11896 r.kill("crash", true); 11897 } else { 11898 // Huh. 11899 Process.killProcess(pid); 11900 Process.killProcessGroup(uid, pid); 11901 } 11902 } 11903 return; 11904 } 11905 } catch (RemoteException e) { 11906 mController = null; 11907 Watchdog.getInstance().setActivityController(null); 11908 } 11909 } 11910 11911 final long origId = Binder.clearCallingIdentity(); 11912 11913 // If this process is running instrumentation, finish it. 11914 if (r != null && r.instrumentationClass != null) { 11915 Slog.w(TAG, "Error in app " + r.processName 11916 + " running instrumentation " + r.instrumentationClass + ":"); 11917 if (shortMsg != null) Slog.w(TAG, " " + shortMsg); 11918 if (longMsg != null) Slog.w(TAG, " " + longMsg); 11919 Bundle info = new Bundle(); 11920 info.putString("shortMsg", shortMsg); 11921 info.putString("longMsg", longMsg); 11922 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info); 11923 Binder.restoreCallingIdentity(origId); 11924 return; 11925 } 11926 11927 // If we can't identify the process or it's already exceeded its crash quota, 11928 // quit right away without showing a crash dialog. 11929 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) { 11930 Binder.restoreCallingIdentity(origId); 11931 return; 11932 } 11933 11934 Message msg = Message.obtain(); 11935 msg.what = SHOW_ERROR_MSG; 11936 HashMap data = new HashMap(); 11937 data.put("result", result); 11938 data.put("app", r); 11939 msg.obj = data; 11940 mHandler.sendMessage(msg); 11941 11942 Binder.restoreCallingIdentity(origId); 11943 } 11944 11945 int res = result.get(); 11946 11947 Intent appErrorIntent = null; 11948 synchronized (this) { 11949 if (r != null && !r.isolated) { 11950 // XXX Can't keep track of crash time for isolated processes, 11951 // since they don't have a persistent identity. 11952 mProcessCrashTimes.put(r.info.processName, r.uid, 11953 SystemClock.uptimeMillis()); 11954 } 11955 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) { 11956 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo); 11957 } 11958 } 11959 11960 if (appErrorIntent != null) { 11961 try { 11962 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId)); 11963 } catch (ActivityNotFoundException e) { 11964 Slog.w(TAG, "bug report receiver dissappeared", e); 11965 } 11966 } 11967 } 11968 11969 Intent createAppErrorIntentLocked(ProcessRecord r, 11970 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11971 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo); 11972 if (report == null) { 11973 return null; 11974 } 11975 Intent result = new Intent(Intent.ACTION_APP_ERROR); 11976 result.setComponent(r.errorReportReceiver); 11977 result.putExtra(Intent.EXTRA_BUG_REPORT, report); 11978 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11979 return result; 11980 } 11981 11982 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r, 11983 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11984 if (r.errorReportReceiver == null) { 11985 return null; 11986 } 11987 11988 if (!r.crashing && !r.notResponding && !r.forceCrashReport) { 11989 return null; 11990 } 11991 11992 ApplicationErrorReport report = new ApplicationErrorReport(); 11993 report.packageName = r.info.packageName; 11994 report.installerPackageName = r.errorReportReceiver.getPackageName(); 11995 report.processName = r.processName; 11996 report.time = timeMillis; 11997 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11998 11999 if (r.crashing || r.forceCrashReport) { 12000 report.type = ApplicationErrorReport.TYPE_CRASH; 12001 report.crashInfo = crashInfo; 12002 } else if (r.notResponding) { 12003 report.type = ApplicationErrorReport.TYPE_ANR; 12004 report.anrInfo = new ApplicationErrorReport.AnrInfo(); 12005 12006 report.anrInfo.activity = r.notRespondingReport.tag; 12007 report.anrInfo.cause = r.notRespondingReport.shortMsg; 12008 report.anrInfo.info = r.notRespondingReport.longMsg; 12009 } 12010 12011 return report; 12012 } 12013 12014 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 12015 enforceNotIsolatedCaller("getProcessesInErrorState"); 12016 // assume our apps are happy - lazy create the list 12017 List<ActivityManager.ProcessErrorStateInfo> errList = null; 12018 12019 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12020 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 12021 int userId = UserHandle.getUserId(Binder.getCallingUid()); 12022 12023 synchronized (this) { 12024 12025 // iterate across all processes 12026 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12027 ProcessRecord app = mLruProcesses.get(i); 12028 if (!allUsers && app.userId != userId) { 12029 continue; 12030 } 12031 if ((app.thread != null) && (app.crashing || app.notResponding)) { 12032 // This one's in trouble, so we'll generate a report for it 12033 // crashes are higher priority (in case there's a crash *and* an anr) 12034 ActivityManager.ProcessErrorStateInfo report = null; 12035 if (app.crashing) { 12036 report = app.crashingReport; 12037 } else if (app.notResponding) { 12038 report = app.notRespondingReport; 12039 } 12040 12041 if (report != null) { 12042 if (errList == null) { 12043 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1); 12044 } 12045 errList.add(report); 12046 } else { 12047 Slog.w(TAG, "Missing app error report, app = " + app.processName + 12048 " crashing = " + app.crashing + 12049 " notResponding = " + app.notResponding); 12050 } 12051 } 12052 } 12053 } 12054 12055 return errList; 12056 } 12057 12058 static int procStateToImportance(int procState, int memAdj, 12059 ActivityManager.RunningAppProcessInfo currApp) { 12060 int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState); 12061 if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { 12062 currApp.lru = memAdj; 12063 } else { 12064 currApp.lru = 0; 12065 } 12066 return imp; 12067 } 12068 12069 private void fillInProcMemInfo(ProcessRecord app, 12070 ActivityManager.RunningAppProcessInfo outInfo) { 12071 outInfo.pid = app.pid; 12072 outInfo.uid = app.info.uid; 12073 if (mHeavyWeightProcess == app) { 12074 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE; 12075 } 12076 if (app.persistent) { 12077 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT; 12078 } 12079 if (app.activities.size() > 0) { 12080 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES; 12081 } 12082 outInfo.lastTrimLevel = app.trimMemoryLevel; 12083 int adj = app.curAdj; 12084 int procState = app.curProcState; 12085 outInfo.importance = procStateToImportance(procState, adj, outInfo); 12086 outInfo.importanceReasonCode = app.adjTypeCode; 12087 outInfo.processState = app.curProcState; 12088 } 12089 12090 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 12091 enforceNotIsolatedCaller("getRunningAppProcesses"); 12092 // Lazy instantiation of list 12093 List<ActivityManager.RunningAppProcessInfo> runList = null; 12094 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12095 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 12096 int userId = UserHandle.getUserId(Binder.getCallingUid()); 12097 synchronized (this) { 12098 // Iterate across all processes 12099 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12100 ProcessRecord app = mLruProcesses.get(i); 12101 if (!allUsers && app.userId != userId) { 12102 continue; 12103 } 12104 if ((app.thread != null) && (!app.crashing && !app.notResponding)) { 12105 // Generate process state info for running application 12106 ActivityManager.RunningAppProcessInfo currApp = 12107 new ActivityManager.RunningAppProcessInfo(app.processName, 12108 app.pid, app.getPackageList()); 12109 fillInProcMemInfo(app, currApp); 12110 if (app.adjSource instanceof ProcessRecord) { 12111 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid; 12112 currApp.importanceReasonImportance = 12113 ActivityManager.RunningAppProcessInfo.procStateToImportance( 12114 app.adjSourceProcState); 12115 } else if (app.adjSource instanceof ActivityRecord) { 12116 ActivityRecord r = (ActivityRecord)app.adjSource; 12117 if (r.app != null) currApp.importanceReasonPid = r.app.pid; 12118 } 12119 if (app.adjTarget instanceof ComponentName) { 12120 currApp.importanceReasonComponent = (ComponentName)app.adjTarget; 12121 } 12122 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance 12123 // + " lru=" + currApp.lru); 12124 if (runList == null) { 12125 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>(); 12126 } 12127 runList.add(currApp); 12128 } 12129 } 12130 } 12131 return runList; 12132 } 12133 12134 public List<ApplicationInfo> getRunningExternalApplications() { 12135 enforceNotIsolatedCaller("getRunningExternalApplications"); 12136 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 12137 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 12138 if (runningApps != null && runningApps.size() > 0) { 12139 Set<String> extList = new HashSet<String>(); 12140 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 12141 if (app.pkgList != null) { 12142 for (String pkg : app.pkgList) { 12143 extList.add(pkg); 12144 } 12145 } 12146 } 12147 IPackageManager pm = AppGlobals.getPackageManager(); 12148 for (String pkg : extList) { 12149 try { 12150 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 12151 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 12152 retList.add(info); 12153 } 12154 } catch (RemoteException e) { 12155 } 12156 } 12157 } 12158 return retList; 12159 } 12160 12161 @Override 12162 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) { 12163 enforceNotIsolatedCaller("getMyMemoryState"); 12164 synchronized (this) { 12165 ProcessRecord proc; 12166 synchronized (mPidsSelfLocked) { 12167 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 12168 } 12169 fillInProcMemInfo(proc, outInfo); 12170 } 12171 } 12172 12173 @Override 12174 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12175 if (checkCallingPermission(android.Manifest.permission.DUMP) 12176 != PackageManager.PERMISSION_GRANTED) { 12177 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12178 + Binder.getCallingPid() 12179 + ", uid=" + Binder.getCallingUid() 12180 + " without permission " 12181 + android.Manifest.permission.DUMP); 12182 return; 12183 } 12184 12185 boolean dumpAll = false; 12186 boolean dumpClient = false; 12187 String dumpPackage = null; 12188 12189 int opti = 0; 12190 while (opti < args.length) { 12191 String opt = args[opti]; 12192 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12193 break; 12194 } 12195 opti++; 12196 if ("-a".equals(opt)) { 12197 dumpAll = true; 12198 } else if ("-c".equals(opt)) { 12199 dumpClient = true; 12200 } else if ("-h".equals(opt)) { 12201 pw.println("Activity manager dump options:"); 12202 pw.println(" [-a] [-c] [-h] [cmd] ..."); 12203 pw.println(" cmd may be one of:"); 12204 pw.println(" a[ctivities]: activity stack state"); 12205 pw.println(" r[recents]: recent activities state"); 12206 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state"); 12207 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state"); 12208 pw.println(" p[rocesses] [PACKAGE_NAME]: process state"); 12209 pw.println(" o[om]: out of memory management"); 12210 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state"); 12211 pw.println(" provider [COMP_SPEC]: provider client-side state"); 12212 pw.println(" s[ervices] [COMP_SPEC ...]: service state"); 12213 pw.println(" service [COMP_SPEC]: service client-side state"); 12214 pw.println(" package [PACKAGE_NAME]: all state related to given package"); 12215 pw.println(" all: dump all activities"); 12216 pw.println(" top: dump the top activity"); 12217 pw.println(" cmd may also be a COMP_SPEC to dump activities."); 12218 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),"); 12219 pw.println(" a partial substring in a component name, a"); 12220 pw.println(" hex object identifier."); 12221 pw.println(" -a: include all available server state."); 12222 pw.println(" -c: include client state."); 12223 return; 12224 } else { 12225 pw.println("Unknown argument: " + opt + "; use -h for help"); 12226 } 12227 } 12228 12229 long origId = Binder.clearCallingIdentity(); 12230 boolean more = false; 12231 // Is the caller requesting to dump a particular piece of data? 12232 if (opti < args.length) { 12233 String cmd = args[opti]; 12234 opti++; 12235 if ("activities".equals(cmd) || "a".equals(cmd)) { 12236 synchronized (this) { 12237 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null); 12238 } 12239 } else if ("recents".equals(cmd) || "r".equals(cmd)) { 12240 synchronized (this) { 12241 dumpRecentsLocked(fd, pw, args, opti, true, null); 12242 } 12243 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 12244 String[] newArgs; 12245 String name; 12246 if (opti >= args.length) { 12247 name = null; 12248 newArgs = EMPTY_STRING_ARRAY; 12249 } else { 12250 name = args[opti]; 12251 opti++; 12252 newArgs = new String[args.length - opti]; 12253 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12254 args.length - opti); 12255 } 12256 synchronized (this) { 12257 dumpBroadcastsLocked(fd, pw, args, opti, true, name); 12258 } 12259 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 12260 String[] newArgs; 12261 String name; 12262 if (opti >= args.length) { 12263 name = null; 12264 newArgs = EMPTY_STRING_ARRAY; 12265 } else { 12266 name = args[opti]; 12267 opti++; 12268 newArgs = new String[args.length - opti]; 12269 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12270 args.length - opti); 12271 } 12272 synchronized (this) { 12273 dumpPendingIntentsLocked(fd, pw, args, opti, true, name); 12274 } 12275 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 12276 String[] newArgs; 12277 String name; 12278 if (opti >= args.length) { 12279 name = null; 12280 newArgs = EMPTY_STRING_ARRAY; 12281 } else { 12282 name = args[opti]; 12283 opti++; 12284 newArgs = new String[args.length - opti]; 12285 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12286 args.length - opti); 12287 } 12288 synchronized (this) { 12289 dumpProcessesLocked(fd, pw, args, opti, true, name); 12290 } 12291 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 12292 synchronized (this) { 12293 dumpOomLocked(fd, pw, args, opti, true); 12294 } 12295 } else if ("provider".equals(cmd)) { 12296 String[] newArgs; 12297 String name; 12298 if (opti >= args.length) { 12299 name = null; 12300 newArgs = EMPTY_STRING_ARRAY; 12301 } else { 12302 name = args[opti]; 12303 opti++; 12304 newArgs = new String[args.length - opti]; 12305 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 12306 } 12307 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 12308 pw.println("No providers match: " + name); 12309 pw.println("Use -h for help."); 12310 } 12311 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 12312 synchronized (this) { 12313 dumpProvidersLocked(fd, pw, args, opti, true, null); 12314 } 12315 } else if ("service".equals(cmd)) { 12316 String[] newArgs; 12317 String name; 12318 if (opti >= args.length) { 12319 name = null; 12320 newArgs = EMPTY_STRING_ARRAY; 12321 } else { 12322 name = args[opti]; 12323 opti++; 12324 newArgs = new String[args.length - opti]; 12325 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12326 args.length - opti); 12327 } 12328 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) { 12329 pw.println("No services match: " + name); 12330 pw.println("Use -h for help."); 12331 } 12332 } else if ("package".equals(cmd)) { 12333 String[] newArgs; 12334 if (opti >= args.length) { 12335 pw.println("package: no package name specified"); 12336 pw.println("Use -h for help."); 12337 } else { 12338 dumpPackage = args[opti]; 12339 opti++; 12340 newArgs = new String[args.length - opti]; 12341 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12342 args.length - opti); 12343 args = newArgs; 12344 opti = 0; 12345 more = true; 12346 } 12347 } else if ("services".equals(cmd) || "s".equals(cmd)) { 12348 synchronized (this) { 12349 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null); 12350 } 12351 } else { 12352 // Dumping a single activity? 12353 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) { 12354 pw.println("Bad activity command, or no activities match: " + cmd); 12355 pw.println("Use -h for help."); 12356 } 12357 } 12358 if (!more) { 12359 Binder.restoreCallingIdentity(origId); 12360 return; 12361 } 12362 } 12363 12364 // No piece of data specified, dump everything. 12365 synchronized (this) { 12366 dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12367 pw.println(); 12368 if (dumpAll) { 12369 pw.println("-------------------------------------------------------------------------------"); 12370 } 12371 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12372 pw.println(); 12373 if (dumpAll) { 12374 pw.println("-------------------------------------------------------------------------------"); 12375 } 12376 dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12377 pw.println(); 12378 if (dumpAll) { 12379 pw.println("-------------------------------------------------------------------------------"); 12380 } 12381 mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 12382 pw.println(); 12383 if (dumpAll) { 12384 pw.println("-------------------------------------------------------------------------------"); 12385 } 12386 dumpRecentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12387 pw.println(); 12388 if (dumpAll) { 12389 pw.println("-------------------------------------------------------------------------------"); 12390 } 12391 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 12392 pw.println(); 12393 if (dumpAll) { 12394 pw.println("-------------------------------------------------------------------------------"); 12395 } 12396 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12397 } 12398 Binder.restoreCallingIdentity(origId); 12399 } 12400 12401 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12402 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 12403 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)"); 12404 12405 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, 12406 dumpPackage); 12407 boolean needSep = printedAnything; 12408 12409 boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity, 12410 dumpPackage, needSep, " mFocusedActivity: "); 12411 if (printed) { 12412 printedAnything = true; 12413 needSep = false; 12414 } 12415 12416 if (dumpPackage == null) { 12417 if (needSep) { 12418 pw.println(); 12419 } 12420 needSep = true; 12421 printedAnything = true; 12422 mStackSupervisor.dump(pw, " "); 12423 } 12424 12425 if (!printedAnything) { 12426 pw.println(" (nothing)"); 12427 } 12428 } 12429 12430 void dumpRecentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12431 int opti, boolean dumpAll, String dumpPackage) { 12432 pw.println("ACTIVITY MANAGER RECENT ACTIVITIES (dumpsys activity recents)"); 12433 12434 boolean printedAnything = false; 12435 12436 if (mRecentTasks.size() > 0) { 12437 boolean printedHeader = false; 12438 12439 final int N = mRecentTasks.size(); 12440 for (int i=0; i<N; i++) { 12441 TaskRecord tr = mRecentTasks.get(i); 12442 if (dumpPackage != null) { 12443 if (tr.realActivity == null || 12444 !dumpPackage.equals(tr.realActivity)) { 12445 continue; 12446 } 12447 } 12448 if (!printedHeader) { 12449 pw.println(" Recent tasks:"); 12450 printedHeader = true; 12451 printedAnything = true; 12452 } 12453 pw.print(" * Recent #"); pw.print(i); pw.print(": "); 12454 pw.println(tr); 12455 if (dumpAll) { 12456 mRecentTasks.get(i).dump(pw, " "); 12457 } 12458 } 12459 } 12460 12461 if (!printedAnything) { 12462 pw.println(" (nothing)"); 12463 } 12464 } 12465 12466 void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12467 int opti, boolean dumpAll, String dumpPackage) { 12468 boolean needSep = false; 12469 boolean printedAnything = false; 12470 int numPers = 0; 12471 12472 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)"); 12473 12474 if (dumpAll) { 12475 final int NP = mProcessNames.getMap().size(); 12476 for (int ip=0; ip<NP; ip++) { 12477 SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip); 12478 final int NA = procs.size(); 12479 for (int ia=0; ia<NA; ia++) { 12480 ProcessRecord r = procs.valueAt(ia); 12481 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12482 continue; 12483 } 12484 if (!needSep) { 12485 pw.println(" All known processes:"); 12486 needSep = true; 12487 printedAnything = true; 12488 } 12489 pw.print(r.persistent ? " *PERS*" : " *APP*"); 12490 pw.print(" UID "); pw.print(procs.keyAt(ia)); 12491 pw.print(" "); pw.println(r); 12492 r.dump(pw, " "); 12493 if (r.persistent) { 12494 numPers++; 12495 } 12496 } 12497 } 12498 } 12499 12500 if (mIsolatedProcesses.size() > 0) { 12501 boolean printed = false; 12502 for (int i=0; i<mIsolatedProcesses.size(); i++) { 12503 ProcessRecord r = mIsolatedProcesses.valueAt(i); 12504 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12505 continue; 12506 } 12507 if (!printed) { 12508 if (needSep) { 12509 pw.println(); 12510 } 12511 pw.println(" Isolated process list (sorted by uid):"); 12512 printedAnything = true; 12513 printed = true; 12514 needSep = true; 12515 } 12516 pw.println(String.format("%sIsolated #%2d: %s", 12517 " ", i, r.toString())); 12518 } 12519 } 12520 12521 if (mLruProcesses.size() > 0) { 12522 if (needSep) { 12523 pw.println(); 12524 } 12525 pw.print(" Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size()); 12526 pw.print(" total, non-act at "); 12527 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 12528 pw.print(", non-svc at "); 12529 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 12530 pw.println("):"); 12531 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", false, dumpPackage); 12532 needSep = true; 12533 printedAnything = true; 12534 } 12535 12536 if (dumpAll || dumpPackage != null) { 12537 synchronized (mPidsSelfLocked) { 12538 boolean printed = false; 12539 for (int i=0; i<mPidsSelfLocked.size(); i++) { 12540 ProcessRecord r = mPidsSelfLocked.valueAt(i); 12541 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12542 continue; 12543 } 12544 if (!printed) { 12545 if (needSep) pw.println(); 12546 needSep = true; 12547 pw.println(" PID mappings:"); 12548 printed = true; 12549 printedAnything = true; 12550 } 12551 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 12552 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 12553 } 12554 } 12555 } 12556 12557 if (mForegroundProcesses.size() > 0) { 12558 synchronized (mPidsSelfLocked) { 12559 boolean printed = false; 12560 for (int i=0; i<mForegroundProcesses.size(); i++) { 12561 ProcessRecord r = mPidsSelfLocked.get( 12562 mForegroundProcesses.valueAt(i).pid); 12563 if (dumpPackage != null && (r == null 12564 || !r.pkgList.containsKey(dumpPackage))) { 12565 continue; 12566 } 12567 if (!printed) { 12568 if (needSep) pw.println(); 12569 needSep = true; 12570 pw.println(" Foreground Processes:"); 12571 printed = true; 12572 printedAnything = true; 12573 } 12574 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i)); 12575 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i)); 12576 } 12577 } 12578 } 12579 12580 if (mPersistentStartingProcesses.size() > 0) { 12581 if (needSep) pw.println(); 12582 needSep = true; 12583 printedAnything = true; 12584 pw.println(" Persisent processes that are starting:"); 12585 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 12586 "Starting Norm", "Restarting PERS", dumpPackage); 12587 } 12588 12589 if (mRemovedProcesses.size() > 0) { 12590 if (needSep) pw.println(); 12591 needSep = true; 12592 printedAnything = true; 12593 pw.println(" Processes that are being removed:"); 12594 dumpProcessList(pw, this, mRemovedProcesses, " ", 12595 "Removed Norm", "Removed PERS", dumpPackage); 12596 } 12597 12598 if (mProcessesOnHold.size() > 0) { 12599 if (needSep) pw.println(); 12600 needSep = true; 12601 printedAnything = true; 12602 pw.println(" Processes that are on old until the system is ready:"); 12603 dumpProcessList(pw, this, mProcessesOnHold, " ", 12604 "OnHold Norm", "OnHold PERS", dumpPackage); 12605 } 12606 12607 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage); 12608 12609 if (mProcessCrashTimes.getMap().size() > 0) { 12610 boolean printed = false; 12611 long now = SystemClock.uptimeMillis(); 12612 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 12613 final int NP = pmap.size(); 12614 for (int ip=0; ip<NP; ip++) { 12615 String pname = pmap.keyAt(ip); 12616 SparseArray<Long> uids = pmap.valueAt(ip); 12617 final int N = uids.size(); 12618 for (int i=0; i<N; i++) { 12619 int puid = uids.keyAt(i); 12620 ProcessRecord r = mProcessNames.get(pname, puid); 12621 if (dumpPackage != null && (r == null 12622 || !r.pkgList.containsKey(dumpPackage))) { 12623 continue; 12624 } 12625 if (!printed) { 12626 if (needSep) pw.println(); 12627 needSep = true; 12628 pw.println(" Time since processes crashed:"); 12629 printed = true; 12630 printedAnything = true; 12631 } 12632 pw.print(" Process "); pw.print(pname); 12633 pw.print(" uid "); pw.print(puid); 12634 pw.print(": last crashed "); 12635 TimeUtils.formatDuration(now-uids.valueAt(i), pw); 12636 pw.println(" ago"); 12637 } 12638 } 12639 } 12640 12641 if (mBadProcesses.getMap().size() > 0) { 12642 boolean printed = false; 12643 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap(); 12644 final int NP = pmap.size(); 12645 for (int ip=0; ip<NP; ip++) { 12646 String pname = pmap.keyAt(ip); 12647 SparseArray<BadProcessInfo> uids = pmap.valueAt(ip); 12648 final int N = uids.size(); 12649 for (int i=0; i<N; i++) { 12650 int puid = uids.keyAt(i); 12651 ProcessRecord r = mProcessNames.get(pname, puid); 12652 if (dumpPackage != null && (r == null 12653 || !r.pkgList.containsKey(dumpPackage))) { 12654 continue; 12655 } 12656 if (!printed) { 12657 if (needSep) pw.println(); 12658 needSep = true; 12659 pw.println(" Bad processes:"); 12660 printedAnything = true; 12661 } 12662 BadProcessInfo info = uids.valueAt(i); 12663 pw.print(" Bad process "); pw.print(pname); 12664 pw.print(" uid "); pw.print(puid); 12665 pw.print(": crashed at time "); pw.println(info.time); 12666 if (info.shortMsg != null) { 12667 pw.print(" Short msg: "); pw.println(info.shortMsg); 12668 } 12669 if (info.longMsg != null) { 12670 pw.print(" Long msg: "); pw.println(info.longMsg); 12671 } 12672 if (info.stack != null) { 12673 pw.println(" Stack:"); 12674 int lastPos = 0; 12675 for (int pos=0; pos<info.stack.length(); pos++) { 12676 if (info.stack.charAt(pos) == '\n') { 12677 pw.print(" "); 12678 pw.write(info.stack, lastPos, pos-lastPos); 12679 pw.println(); 12680 lastPos = pos+1; 12681 } 12682 } 12683 if (lastPos < info.stack.length()) { 12684 pw.print(" "); 12685 pw.write(info.stack, lastPos, info.stack.length()-lastPos); 12686 pw.println(); 12687 } 12688 } 12689 } 12690 } 12691 } 12692 12693 if (dumpPackage == null) { 12694 pw.println(); 12695 needSep = false; 12696 pw.println(" mStartedUsers:"); 12697 for (int i=0; i<mStartedUsers.size(); i++) { 12698 UserStartedState uss = mStartedUsers.valueAt(i); 12699 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier()); 12700 pw.print(": "); uss.dump("", pw); 12701 } 12702 pw.print(" mStartedUserArray: ["); 12703 for (int i=0; i<mStartedUserArray.length; i++) { 12704 if (i > 0) pw.print(", "); 12705 pw.print(mStartedUserArray[i]); 12706 } 12707 pw.println("]"); 12708 pw.print(" mUserLru: ["); 12709 for (int i=0; i<mUserLru.size(); i++) { 12710 if (i > 0) pw.print(", "); 12711 pw.print(mUserLru.get(i)); 12712 } 12713 pw.println("]"); 12714 if (dumpAll) { 12715 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray)); 12716 } 12717 synchronized (mUserProfileGroupIdsSelfLocked) { 12718 if (mUserProfileGroupIdsSelfLocked.size() > 0) { 12719 pw.println(" mUserProfileGroupIds:"); 12720 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) { 12721 pw.print(" User #"); 12722 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i)); 12723 pw.print(" -> profile #"); 12724 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i)); 12725 } 12726 } 12727 } 12728 } 12729 if (mHomeProcess != null && (dumpPackage == null 12730 || mHomeProcess.pkgList.containsKey(dumpPackage))) { 12731 if (needSep) { 12732 pw.println(); 12733 needSep = false; 12734 } 12735 pw.println(" mHomeProcess: " + mHomeProcess); 12736 } 12737 if (mPreviousProcess != null && (dumpPackage == null 12738 || mPreviousProcess.pkgList.containsKey(dumpPackage))) { 12739 if (needSep) { 12740 pw.println(); 12741 needSep = false; 12742 } 12743 pw.println(" mPreviousProcess: " + mPreviousProcess); 12744 } 12745 if (dumpAll) { 12746 StringBuilder sb = new StringBuilder(128); 12747 sb.append(" mPreviousProcessVisibleTime: "); 12748 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb); 12749 pw.println(sb); 12750 } 12751 if (mHeavyWeightProcess != null && (dumpPackage == null 12752 || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) { 12753 if (needSep) { 12754 pw.println(); 12755 needSep = false; 12756 } 12757 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 12758 } 12759 if (dumpPackage == null) { 12760 pw.println(" mConfiguration: " + mConfiguration); 12761 } 12762 if (dumpAll) { 12763 pw.println(" mConfigWillChange: " + getFocusedStack().mConfigWillChange); 12764 if (mCompatModePackages.getPackages().size() > 0) { 12765 boolean printed = false; 12766 for (Map.Entry<String, Integer> entry 12767 : mCompatModePackages.getPackages().entrySet()) { 12768 String pkg = entry.getKey(); 12769 int mode = entry.getValue(); 12770 if (dumpPackage != null && !dumpPackage.equals(pkg)) { 12771 continue; 12772 } 12773 if (!printed) { 12774 pw.println(" mScreenCompatPackages:"); 12775 printed = true; 12776 } 12777 pw.print(" "); pw.print(pkg); pw.print(": "); 12778 pw.print(mode); pw.println(); 12779 } 12780 } 12781 } 12782 if (dumpPackage == null) { 12783 if (mSleeping || mWentToSleep || mLockScreenShown) { 12784 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep 12785 + " mLockScreenShown " + mLockScreenShown); 12786 } 12787 if (mShuttingDown || mRunningVoice) { 12788 pw.print(" mShuttingDown=" + mShuttingDown + " mRunningVoice=" + mRunningVoice); 12789 } 12790 } 12791 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 12792 || mOrigWaitForDebugger) { 12793 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 12794 || dumpPackage.equals(mOrigDebugApp)) { 12795 if (needSep) { 12796 pw.println(); 12797 needSep = false; 12798 } 12799 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 12800 + " mDebugTransient=" + mDebugTransient 12801 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 12802 } 12803 } 12804 if (mOpenGlTraceApp != null) { 12805 if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) { 12806 if (needSep) { 12807 pw.println(); 12808 needSep = false; 12809 } 12810 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp); 12811 } 12812 } 12813 if (mProfileApp != null || mProfileProc != null || mProfileFile != null 12814 || mProfileFd != null) { 12815 if (dumpPackage == null || dumpPackage.equals(mProfileApp)) { 12816 if (needSep) { 12817 pw.println(); 12818 needSep = false; 12819 } 12820 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc); 12821 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd); 12822 pw.println(" mSamplingInterval=" + mSamplingInterval + " mAutoStopProfiler=" 12823 + mAutoStopProfiler); 12824 pw.println(" mProfileType=" + mProfileType); 12825 } 12826 } 12827 if (dumpPackage == null) { 12828 if (mAlwaysFinishActivities || mController != null) { 12829 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities 12830 + " mController=" + mController); 12831 } 12832 if (dumpAll) { 12833 pw.println(" Total persistent processes: " + numPers); 12834 pw.println(" mProcessesReady=" + mProcessesReady 12835 + " mSystemReady=" + mSystemReady); 12836 pw.println(" mBooting=" + mBooting 12837 + " mBooted=" + mBooted 12838 + " mFactoryTest=" + mFactoryTest); 12839 pw.print(" mLastPowerCheckRealtime="); 12840 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw); 12841 pw.println(""); 12842 pw.print(" mLastPowerCheckUptime="); 12843 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 12844 pw.println(""); 12845 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep); 12846 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity); 12847 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq); 12848 pw.println(" mNumNonCachedProcs=" + mNumNonCachedProcs 12849 + " (" + mLruProcesses.size() + " total)" 12850 + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs 12851 + " mNumServiceProcs=" + mNumServiceProcs 12852 + " mNewNumServiceProcs=" + mNewNumServiceProcs); 12853 pw.println(" mAllowLowerMemLevel=" + mAllowLowerMemLevel 12854 + " mLastMemoryLevel" + mLastMemoryLevel 12855 + " mLastNumProcesses" + mLastNumProcesses); 12856 long now = SystemClock.uptimeMillis(); 12857 pw.print(" mLastIdleTime="); 12858 TimeUtils.formatDuration(now, mLastIdleTime, pw); 12859 pw.print(" mLowRamSinceLastIdle="); 12860 TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw); 12861 pw.println(); 12862 } 12863 } 12864 12865 if (!printedAnything) { 12866 pw.println(" (nothing)"); 12867 } 12868 } 12869 12870 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args, 12871 int opti, boolean needSep, boolean dumpAll, String dumpPackage) { 12872 if (mProcessesToGc.size() > 0) { 12873 boolean printed = false; 12874 long now = SystemClock.uptimeMillis(); 12875 for (int i=0; i<mProcessesToGc.size(); i++) { 12876 ProcessRecord proc = mProcessesToGc.get(i); 12877 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) { 12878 continue; 12879 } 12880 if (!printed) { 12881 if (needSep) pw.println(); 12882 needSep = true; 12883 pw.println(" Processes that are waiting to GC:"); 12884 printed = true; 12885 } 12886 pw.print(" Process "); pw.println(proc); 12887 pw.print(" lowMem="); pw.print(proc.reportLowMemory); 12888 pw.print(", last gced="); 12889 pw.print(now-proc.lastRequestedGc); 12890 pw.print(" ms ago, last lowMem="); 12891 pw.print(now-proc.lastLowMemory); 12892 pw.println(" ms ago"); 12893 12894 } 12895 } 12896 return needSep; 12897 } 12898 12899 void printOomLevel(PrintWriter pw, String name, int adj) { 12900 pw.print(" "); 12901 if (adj >= 0) { 12902 pw.print(' '); 12903 if (adj < 10) pw.print(' '); 12904 } else { 12905 if (adj > -10) pw.print(' '); 12906 } 12907 pw.print(adj); 12908 pw.print(": "); 12909 pw.print(name); 12910 pw.print(" ("); 12911 pw.print(mProcessList.getMemLevel(adj)/1024); 12912 pw.println(" kB)"); 12913 } 12914 12915 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12916 int opti, boolean dumpAll) { 12917 boolean needSep = false; 12918 12919 if (mLruProcesses.size() > 0) { 12920 if (needSep) pw.println(); 12921 needSep = true; 12922 pw.println(" OOM levels:"); 12923 printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ); 12924 printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ); 12925 printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ); 12926 printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ); 12927 printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ); 12928 printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ); 12929 printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ); 12930 printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ); 12931 printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ); 12932 printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ); 12933 printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ); 12934 printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ); 12935 printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ); 12936 12937 if (needSep) pw.println(); 12938 pw.print(" Process OOM control ("); pw.print(mLruProcesses.size()); 12939 pw.print(" total, non-act at "); 12940 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 12941 pw.print(", non-svc at "); 12942 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 12943 pw.println("):"); 12944 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", true, null); 12945 needSep = true; 12946 } 12947 12948 dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null); 12949 12950 pw.println(); 12951 pw.println(" mHomeProcess: " + mHomeProcess); 12952 pw.println(" mPreviousProcess: " + mPreviousProcess); 12953 if (mHeavyWeightProcess != null) { 12954 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 12955 } 12956 12957 return true; 12958 } 12959 12960 /** 12961 * There are three ways to call this: 12962 * - no provider specified: dump all the providers 12963 * - a flattened component name that matched an existing provider was specified as the 12964 * first arg: dump that one provider 12965 * - the first arg isn't the flattened component name of an existing provider: 12966 * dump all providers whose component contains the first arg as a substring 12967 */ 12968 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 12969 int opti, boolean dumpAll) { 12970 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 12971 } 12972 12973 static class ItemMatcher { 12974 ArrayList<ComponentName> components; 12975 ArrayList<String> strings; 12976 ArrayList<Integer> objects; 12977 boolean all; 12978 12979 ItemMatcher() { 12980 all = true; 12981 } 12982 12983 void build(String name) { 12984 ComponentName componentName = ComponentName.unflattenFromString(name); 12985 if (componentName != null) { 12986 if (components == null) { 12987 components = new ArrayList<ComponentName>(); 12988 } 12989 components.add(componentName); 12990 all = false; 12991 } else { 12992 int objectId = 0; 12993 // Not a '/' separated full component name; maybe an object ID? 12994 try { 12995 objectId = Integer.parseInt(name, 16); 12996 if (objects == null) { 12997 objects = new ArrayList<Integer>(); 12998 } 12999 objects.add(objectId); 13000 all = false; 13001 } catch (RuntimeException e) { 13002 // Not an integer; just do string match. 13003 if (strings == null) { 13004 strings = new ArrayList<String>(); 13005 } 13006 strings.add(name); 13007 all = false; 13008 } 13009 } 13010 } 13011 13012 int build(String[] args, int opti) { 13013 for (; opti<args.length; opti++) { 13014 String name = args[opti]; 13015 if ("--".equals(name)) { 13016 return opti+1; 13017 } 13018 build(name); 13019 } 13020 return opti; 13021 } 13022 13023 boolean match(Object object, ComponentName comp) { 13024 if (all) { 13025 return true; 13026 } 13027 if (components != null) { 13028 for (int i=0; i<components.size(); i++) { 13029 if (components.get(i).equals(comp)) { 13030 return true; 13031 } 13032 } 13033 } 13034 if (objects != null) { 13035 for (int i=0; i<objects.size(); i++) { 13036 if (System.identityHashCode(object) == objects.get(i)) { 13037 return true; 13038 } 13039 } 13040 } 13041 if (strings != null) { 13042 String flat = comp.flattenToString(); 13043 for (int i=0; i<strings.size(); i++) { 13044 if (flat.contains(strings.get(i))) { 13045 return true; 13046 } 13047 } 13048 } 13049 return false; 13050 } 13051 } 13052 13053 /** 13054 * There are three things that cmd can be: 13055 * - a flattened component name that matches an existing activity 13056 * - the cmd arg isn't the flattened component name of an existing activity: 13057 * dump all activity whose component contains the cmd as a substring 13058 * - A hex number of the ActivityRecord object instance. 13059 */ 13060 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, 13061 int opti, boolean dumpAll) { 13062 ArrayList<ActivityRecord> activities; 13063 13064 synchronized (this) { 13065 activities = mStackSupervisor.getDumpActivitiesLocked(name); 13066 } 13067 13068 if (activities.size() <= 0) { 13069 return false; 13070 } 13071 13072 String[] newArgs = new String[args.length - opti]; 13073 System.arraycopy(args, opti, newArgs, 0, args.length - opti); 13074 13075 TaskRecord lastTask = null; 13076 boolean needSep = false; 13077 for (int i=activities.size()-1; i>=0; i--) { 13078 ActivityRecord r = activities.get(i); 13079 if (needSep) { 13080 pw.println(); 13081 } 13082 needSep = true; 13083 synchronized (this) { 13084 if (lastTask != r.task) { 13085 lastTask = r.task; 13086 pw.print("TASK "); pw.print(lastTask.affinity); 13087 pw.print(" id="); pw.println(lastTask.taskId); 13088 if (dumpAll) { 13089 lastTask.dump(pw, " "); 13090 } 13091 } 13092 } 13093 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll); 13094 } 13095 return true; 13096 } 13097 13098 /** 13099 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if 13100 * there is a thread associated with the activity. 13101 */ 13102 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, 13103 final ActivityRecord r, String[] args, boolean dumpAll) { 13104 String innerPrefix = prefix + " "; 13105 synchronized (this) { 13106 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName); 13107 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r))); 13108 pw.print(" pid="); 13109 if (r.app != null) pw.println(r.app.pid); 13110 else pw.println("(not running)"); 13111 if (dumpAll) { 13112 r.dump(pw, innerPrefix); 13113 } 13114 } 13115 if (r.app != null && r.app.thread != null) { 13116 // flush anything that is already in the PrintWriter since the thread is going 13117 // to write to the file descriptor directly 13118 pw.flush(); 13119 try { 13120 TransferPipe tp = new TransferPipe(); 13121 try { 13122 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), 13123 r.appToken, innerPrefix, args); 13124 tp.go(fd); 13125 } finally { 13126 tp.kill(); 13127 } 13128 } catch (IOException e) { 13129 pw.println(innerPrefix + "Failure while dumping the activity: " + e); 13130 } catch (RemoteException e) { 13131 pw.println(innerPrefix + "Got a RemoteException while dumping the activity"); 13132 } 13133 } 13134 } 13135 13136 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13137 int opti, boolean dumpAll, String dumpPackage) { 13138 boolean needSep = false; 13139 boolean onlyHistory = false; 13140 boolean printedAnything = false; 13141 13142 if ("history".equals(dumpPackage)) { 13143 if (opti < args.length && "-s".equals(args[opti])) { 13144 dumpAll = false; 13145 } 13146 onlyHistory = true; 13147 dumpPackage = null; 13148 } 13149 13150 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 13151 if (!onlyHistory && dumpAll) { 13152 if (mRegisteredReceivers.size() > 0) { 13153 boolean printed = false; 13154 Iterator it = mRegisteredReceivers.values().iterator(); 13155 while (it.hasNext()) { 13156 ReceiverList r = (ReceiverList)it.next(); 13157 if (dumpPackage != null && (r.app == null || 13158 !dumpPackage.equals(r.app.info.packageName))) { 13159 continue; 13160 } 13161 if (!printed) { 13162 pw.println(" Registered Receivers:"); 13163 needSep = true; 13164 printed = true; 13165 printedAnything = true; 13166 } 13167 pw.print(" * "); pw.println(r); 13168 r.dump(pw, " "); 13169 } 13170 } 13171 13172 if (mReceiverResolver.dump(pw, needSep ? 13173 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 13174 " ", dumpPackage, false)) { 13175 needSep = true; 13176 printedAnything = true; 13177 } 13178 } 13179 13180 for (BroadcastQueue q : mBroadcastQueues) { 13181 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 13182 printedAnything |= needSep; 13183 } 13184 13185 needSep = true; 13186 13187 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 13188 for (int user=0; user<mStickyBroadcasts.size(); user++) { 13189 if (needSep) { 13190 pw.println(); 13191 } 13192 needSep = true; 13193 printedAnything = true; 13194 pw.print(" Sticky broadcasts for user "); 13195 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 13196 StringBuilder sb = new StringBuilder(128); 13197 for (Map.Entry<String, ArrayList<Intent>> ent 13198 : mStickyBroadcasts.valueAt(user).entrySet()) { 13199 pw.print(" * Sticky action "); pw.print(ent.getKey()); 13200 if (dumpAll) { 13201 pw.println(":"); 13202 ArrayList<Intent> intents = ent.getValue(); 13203 final int N = intents.size(); 13204 for (int i=0; i<N; i++) { 13205 sb.setLength(0); 13206 sb.append(" Intent: "); 13207 intents.get(i).toShortString(sb, false, true, false, false); 13208 pw.println(sb.toString()); 13209 Bundle bundle = intents.get(i).getExtras(); 13210 if (bundle != null) { 13211 pw.print(" "); 13212 pw.println(bundle.toString()); 13213 } 13214 } 13215 } else { 13216 pw.println(""); 13217 } 13218 } 13219 } 13220 } 13221 13222 if (!onlyHistory && dumpAll) { 13223 pw.println(); 13224 for (BroadcastQueue queue : mBroadcastQueues) { 13225 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 13226 + queue.mBroadcastsScheduled); 13227 } 13228 pw.println(" mHandler:"); 13229 mHandler.dump(new PrintWriterPrinter(pw), " "); 13230 needSep = true; 13231 printedAnything = true; 13232 } 13233 13234 if (!printedAnything) { 13235 pw.println(" (nothing)"); 13236 } 13237 } 13238 13239 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13240 int opti, boolean dumpAll, String dumpPackage) { 13241 boolean needSep; 13242 boolean printedAnything = false; 13243 13244 ItemMatcher matcher = new ItemMatcher(); 13245 matcher.build(args, opti); 13246 13247 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 13248 13249 needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 13250 printedAnything |= needSep; 13251 13252 if (mLaunchingProviders.size() > 0) { 13253 boolean printed = false; 13254 for (int i=mLaunchingProviders.size()-1; i>=0; i--) { 13255 ContentProviderRecord r = mLaunchingProviders.get(i); 13256 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 13257 continue; 13258 } 13259 if (!printed) { 13260 if (needSep) pw.println(); 13261 needSep = true; 13262 pw.println(" Launching content providers:"); 13263 printed = true; 13264 printedAnything = true; 13265 } 13266 pw.print(" Launching #"); pw.print(i); pw.print(": "); 13267 pw.println(r); 13268 } 13269 } 13270 13271 if (mGrantedUriPermissions.size() > 0) { 13272 boolean printed = false; 13273 int dumpUid = -2; 13274 if (dumpPackage != null) { 13275 try { 13276 dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0); 13277 } catch (NameNotFoundException e) { 13278 dumpUid = -1; 13279 } 13280 } 13281 for (int i=0; i<mGrantedUriPermissions.size(); i++) { 13282 int uid = mGrantedUriPermissions.keyAt(i); 13283 if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) { 13284 continue; 13285 } 13286 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 13287 if (!printed) { 13288 if (needSep) pw.println(); 13289 needSep = true; 13290 pw.println(" Granted Uri Permissions:"); 13291 printed = true; 13292 printedAnything = true; 13293 } 13294 pw.print(" * UID "); pw.print(uid); pw.println(" holds:"); 13295 for (UriPermission perm : perms.values()) { 13296 pw.print(" "); pw.println(perm); 13297 if (dumpAll) { 13298 perm.dump(pw, " "); 13299 } 13300 } 13301 } 13302 } 13303 13304 if (!printedAnything) { 13305 pw.println(" (nothing)"); 13306 } 13307 } 13308 13309 void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13310 int opti, boolean dumpAll, String dumpPackage) { 13311 boolean printed = false; 13312 13313 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)"); 13314 13315 if (mIntentSenderRecords.size() > 0) { 13316 Iterator<WeakReference<PendingIntentRecord>> it 13317 = mIntentSenderRecords.values().iterator(); 13318 while (it.hasNext()) { 13319 WeakReference<PendingIntentRecord> ref = it.next(); 13320 PendingIntentRecord rec = ref != null ? ref.get(): null; 13321 if (dumpPackage != null && (rec == null 13322 || !dumpPackage.equals(rec.key.packageName))) { 13323 continue; 13324 } 13325 printed = true; 13326 if (rec != null) { 13327 pw.print(" * "); pw.println(rec); 13328 if (dumpAll) { 13329 rec.dump(pw, " "); 13330 } 13331 } else { 13332 pw.print(" * "); pw.println(ref); 13333 } 13334 } 13335 } 13336 13337 if (!printed) { 13338 pw.println(" (nothing)"); 13339 } 13340 } 13341 13342 private static final int dumpProcessList(PrintWriter pw, 13343 ActivityManagerService service, List list, 13344 String prefix, String normalLabel, String persistentLabel, 13345 String dumpPackage) { 13346 int numPers = 0; 13347 final int N = list.size()-1; 13348 for (int i=N; i>=0; i--) { 13349 ProcessRecord r = (ProcessRecord)list.get(i); 13350 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 13351 continue; 13352 } 13353 pw.println(String.format("%s%s #%2d: %s", 13354 prefix, (r.persistent ? persistentLabel : normalLabel), 13355 i, r.toString())); 13356 if (r.persistent) { 13357 numPers++; 13358 } 13359 } 13360 return numPers; 13361 } 13362 13363 private static final boolean dumpProcessOomList(PrintWriter pw, 13364 ActivityManagerService service, List<ProcessRecord> origList, 13365 String prefix, String normalLabel, String persistentLabel, 13366 boolean inclDetails, String dumpPackage) { 13367 13368 ArrayList<Pair<ProcessRecord, Integer>> list 13369 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size()); 13370 for (int i=0; i<origList.size(); i++) { 13371 ProcessRecord r = origList.get(i); 13372 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 13373 continue; 13374 } 13375 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i)); 13376 } 13377 13378 if (list.size() <= 0) { 13379 return false; 13380 } 13381 13382 Comparator<Pair<ProcessRecord, Integer>> comparator 13383 = new Comparator<Pair<ProcessRecord, Integer>>() { 13384 @Override 13385 public int compare(Pair<ProcessRecord, Integer> object1, 13386 Pair<ProcessRecord, Integer> object2) { 13387 if (object1.first.setAdj != object2.first.setAdj) { 13388 return object1.first.setAdj > object2.first.setAdj ? -1 : 1; 13389 } 13390 if (object1.second.intValue() != object2.second.intValue()) { 13391 return object1.second.intValue() > object2.second.intValue() ? -1 : 1; 13392 } 13393 return 0; 13394 } 13395 }; 13396 13397 Collections.sort(list, comparator); 13398 13399 final long curRealtime = SystemClock.elapsedRealtime(); 13400 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime; 13401 final long curUptime = SystemClock.uptimeMillis(); 13402 final long uptimeSince = curUptime - service.mLastPowerCheckUptime; 13403 13404 for (int i=list.size()-1; i>=0; i--) { 13405 ProcessRecord r = list.get(i).first; 13406 String oomAdj = ProcessList.makeOomAdjString(r.setAdj); 13407 char schedGroup; 13408 switch (r.setSchedGroup) { 13409 case Process.THREAD_GROUP_BG_NONINTERACTIVE: 13410 schedGroup = 'B'; 13411 break; 13412 case Process.THREAD_GROUP_DEFAULT: 13413 schedGroup = 'F'; 13414 break; 13415 default: 13416 schedGroup = '?'; 13417 break; 13418 } 13419 char foreground; 13420 if (r.foregroundActivities) { 13421 foreground = 'A'; 13422 } else if (r.foregroundServices) { 13423 foreground = 'S'; 13424 } else { 13425 foreground = ' '; 13426 } 13427 String procState = ProcessList.makeProcStateString(r.curProcState); 13428 pw.print(prefix); 13429 pw.print(r.persistent ? persistentLabel : normalLabel); 13430 pw.print(" #"); 13431 int num = (origList.size()-1)-list.get(i).second; 13432 if (num < 10) pw.print(' '); 13433 pw.print(num); 13434 pw.print(": "); 13435 pw.print(oomAdj); 13436 pw.print(' '); 13437 pw.print(schedGroup); 13438 pw.print('/'); 13439 pw.print(foreground); 13440 pw.print('/'); 13441 pw.print(procState); 13442 pw.print(" trm:"); 13443 if (r.trimMemoryLevel < 10) pw.print(' '); 13444 pw.print(r.trimMemoryLevel); 13445 pw.print(' '); 13446 pw.print(r.toShortString()); 13447 pw.print(" ("); 13448 pw.print(r.adjType); 13449 pw.println(')'); 13450 if (r.adjSource != null || r.adjTarget != null) { 13451 pw.print(prefix); 13452 pw.print(" "); 13453 if (r.adjTarget instanceof ComponentName) { 13454 pw.print(((ComponentName)r.adjTarget).flattenToShortString()); 13455 } else if (r.adjTarget != null) { 13456 pw.print(r.adjTarget.toString()); 13457 } else { 13458 pw.print("{null}"); 13459 } 13460 pw.print("<="); 13461 if (r.adjSource instanceof ProcessRecord) { 13462 pw.print("Proc{"); 13463 pw.print(((ProcessRecord)r.adjSource).toShortString()); 13464 pw.println("}"); 13465 } else if (r.adjSource != null) { 13466 pw.println(r.adjSource.toString()); 13467 } else { 13468 pw.println("{null}"); 13469 } 13470 } 13471 if (inclDetails) { 13472 pw.print(prefix); 13473 pw.print(" "); 13474 pw.print("oom: max="); pw.print(r.maxAdj); 13475 pw.print(" curRaw="); pw.print(r.curRawAdj); 13476 pw.print(" setRaw="); pw.print(r.setRawAdj); 13477 pw.print(" cur="); pw.print(r.curAdj); 13478 pw.print(" set="); pw.println(r.setAdj); 13479 pw.print(prefix); 13480 pw.print(" "); 13481 pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState)); 13482 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState)); 13483 pw.print(" lastPss="); pw.print(r.lastPss); 13484 pw.print(" lastCachedPss="); pw.println(r.lastCachedPss); 13485 pw.print(prefix); 13486 pw.print(" "); 13487 pw.print("cached="); pw.print(r.cached); 13488 pw.print(" empty="); pw.print(r.empty); 13489 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient); 13490 13491 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 13492 if (r.lastWakeTime != 0) { 13493 long wtime; 13494 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics(); 13495 synchronized (stats) { 13496 wtime = stats.getProcessWakeTime(r.info.uid, 13497 r.pid, curRealtime); 13498 } 13499 long timeUsed = wtime - r.lastWakeTime; 13500 pw.print(prefix); 13501 pw.print(" "); 13502 pw.print("keep awake over "); 13503 TimeUtils.formatDuration(realtimeSince, pw); 13504 pw.print(" used "); 13505 TimeUtils.formatDuration(timeUsed, pw); 13506 pw.print(" ("); 13507 pw.print((timeUsed*100)/realtimeSince); 13508 pw.println("%)"); 13509 } 13510 if (r.lastCpuTime != 0) { 13511 long timeUsed = r.curCpuTime - r.lastCpuTime; 13512 pw.print(prefix); 13513 pw.print(" "); 13514 pw.print("run cpu over "); 13515 TimeUtils.formatDuration(uptimeSince, pw); 13516 pw.print(" used "); 13517 TimeUtils.formatDuration(timeUsed, pw); 13518 pw.print(" ("); 13519 pw.print((timeUsed*100)/uptimeSince); 13520 pw.println("%)"); 13521 } 13522 } 13523 } 13524 } 13525 return true; 13526 } 13527 13528 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) { 13529 ArrayList<ProcessRecord> procs; 13530 synchronized (this) { 13531 if (args != null && args.length > start 13532 && args[start].charAt(0) != '-') { 13533 procs = new ArrayList<ProcessRecord>(); 13534 int pid = -1; 13535 try { 13536 pid = Integer.parseInt(args[start]); 13537 } catch (NumberFormatException e) { 13538 } 13539 for (int i=mLruProcesses.size()-1; i>=0; i--) { 13540 ProcessRecord proc = mLruProcesses.get(i); 13541 if (proc.pid == pid) { 13542 procs.add(proc); 13543 } else if (proc.processName.equals(args[start])) { 13544 procs.add(proc); 13545 } 13546 } 13547 if (procs.size() <= 0) { 13548 return null; 13549 } 13550 } else { 13551 procs = new ArrayList<ProcessRecord>(mLruProcesses); 13552 } 13553 } 13554 return procs; 13555 } 13556 13557 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 13558 PrintWriter pw, String[] args) { 13559 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 13560 if (procs == null) { 13561 pw.println("No process found for: " + args[0]); 13562 return; 13563 } 13564 13565 long uptime = SystemClock.uptimeMillis(); 13566 long realtime = SystemClock.elapsedRealtime(); 13567 pw.println("Applications Graphics Acceleration Info:"); 13568 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 13569 13570 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13571 ProcessRecord r = procs.get(i); 13572 if (r.thread != null) { 13573 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **"); 13574 pw.flush(); 13575 try { 13576 TransferPipe tp = new TransferPipe(); 13577 try { 13578 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args); 13579 tp.go(fd); 13580 } finally { 13581 tp.kill(); 13582 } 13583 } catch (IOException e) { 13584 pw.println("Failure while dumping the app: " + r); 13585 pw.flush(); 13586 } catch (RemoteException e) { 13587 pw.println("Got a RemoteException while dumping the app " + r); 13588 pw.flush(); 13589 } 13590 } 13591 } 13592 } 13593 13594 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 13595 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 13596 if (procs == null) { 13597 pw.println("No process found for: " + args[0]); 13598 return; 13599 } 13600 13601 pw.println("Applications Database Info:"); 13602 13603 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13604 ProcessRecord r = procs.get(i); 13605 if (r.thread != null) { 13606 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **"); 13607 pw.flush(); 13608 try { 13609 TransferPipe tp = new TransferPipe(); 13610 try { 13611 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args); 13612 tp.go(fd); 13613 } finally { 13614 tp.kill(); 13615 } 13616 } catch (IOException e) { 13617 pw.println("Failure while dumping the app: " + r); 13618 pw.flush(); 13619 } catch (RemoteException e) { 13620 pw.println("Got a RemoteException while dumping the app " + r); 13621 pw.flush(); 13622 } 13623 } 13624 } 13625 } 13626 13627 final static class MemItem { 13628 final boolean isProc; 13629 final String label; 13630 final String shortLabel; 13631 final long pss; 13632 final int id; 13633 final boolean hasActivities; 13634 ArrayList<MemItem> subitems; 13635 13636 public MemItem(String _label, String _shortLabel, long _pss, int _id, 13637 boolean _hasActivities) { 13638 isProc = true; 13639 label = _label; 13640 shortLabel = _shortLabel; 13641 pss = _pss; 13642 id = _id; 13643 hasActivities = _hasActivities; 13644 } 13645 13646 public MemItem(String _label, String _shortLabel, long _pss, int _id) { 13647 isProc = false; 13648 label = _label; 13649 shortLabel = _shortLabel; 13650 pss = _pss; 13651 id = _id; 13652 hasActivities = false; 13653 } 13654 } 13655 13656 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 13657 ArrayList<MemItem> items, boolean sort, boolean isCompact) { 13658 if (sort && !isCompact) { 13659 Collections.sort(items, new Comparator<MemItem>() { 13660 @Override 13661 public int compare(MemItem lhs, MemItem rhs) { 13662 if (lhs.pss < rhs.pss) { 13663 return 1; 13664 } else if (lhs.pss > rhs.pss) { 13665 return -1; 13666 } 13667 return 0; 13668 } 13669 }); 13670 } 13671 13672 for (int i=0; i<items.size(); i++) { 13673 MemItem mi = items.get(i); 13674 if (!isCompact) { 13675 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label); 13676 } else if (mi.isProc) { 13677 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 13678 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); 13679 pw.println(mi.hasActivities ? ",a" : ",e"); 13680 } else { 13681 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 13682 pw.println(mi.pss); 13683 } 13684 if (mi.subitems != null) { 13685 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 13686 true, isCompact); 13687 } 13688 } 13689 } 13690 13691 // These are in KB. 13692 static final long[] DUMP_MEM_BUCKETS = new long[] { 13693 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 13694 120*1024, 160*1024, 200*1024, 13695 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 13696 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 13697 }; 13698 13699 static final void appendMemBucket(StringBuilder out, long memKB, String label, 13700 boolean stackLike) { 13701 int start = label.lastIndexOf('.'); 13702 if (start >= 0) start++; 13703 else start = 0; 13704 int end = label.length(); 13705 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 13706 if (DUMP_MEM_BUCKETS[i] >= memKB) { 13707 long bucket = DUMP_MEM_BUCKETS[i]/1024; 13708 out.append(bucket); 13709 out.append(stackLike ? "MB." : "MB "); 13710 out.append(label, start, end); 13711 return; 13712 } 13713 } 13714 out.append(memKB/1024); 13715 out.append(stackLike ? "MB." : "MB "); 13716 out.append(label, start, end); 13717 } 13718 13719 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 13720 ProcessList.NATIVE_ADJ, 13721 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ, 13722 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, 13723 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 13724 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 13725 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ 13726 }; 13727 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 13728 "Native", 13729 "System", "Persistent", "Foreground", 13730 "Visible", "Perceptible", 13731 "Heavy Weight", "Backup", 13732 "A Services", "Home", 13733 "Previous", "B Services", "Cached" 13734 }; 13735 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 13736 "native", 13737 "sys", "pers", "fore", 13738 "vis", "percept", 13739 "heavy", "backup", 13740 "servicea", "home", 13741 "prev", "serviceb", "cached" 13742 }; 13743 13744 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 13745 long realtime, boolean isCheckinRequest, boolean isCompact) { 13746 if (isCheckinRequest || isCompact) { 13747 // short checkin version 13748 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 13749 } else { 13750 pw.println("Applications Memory Usage (kB):"); 13751 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 13752 } 13753 } 13754 13755 final void dumpApplicationMemoryUsage(FileDescriptor fd, 13756 PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) { 13757 boolean dumpDetails = false; 13758 boolean dumpFullDetails = false; 13759 boolean dumpDalvik = false; 13760 boolean oomOnly = false; 13761 boolean isCompact = false; 13762 boolean localOnly = false; 13763 13764 int opti = 0; 13765 while (opti < args.length) { 13766 String opt = args[opti]; 13767 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13768 break; 13769 } 13770 opti++; 13771 if ("-a".equals(opt)) { 13772 dumpDetails = true; 13773 dumpFullDetails = true; 13774 dumpDalvik = true; 13775 } else if ("-d".equals(opt)) { 13776 dumpDalvik = true; 13777 } else if ("-c".equals(opt)) { 13778 isCompact = true; 13779 } else if ("--oom".equals(opt)) { 13780 oomOnly = true; 13781 } else if ("--local".equals(opt)) { 13782 localOnly = true; 13783 } else if ("-h".equals(opt)) { 13784 pw.println("meminfo dump options: [-a] [-d] [-c] [--oom] [process]"); 13785 pw.println(" -a: include all available information for each process."); 13786 pw.println(" -d: include dalvik details when dumping process details."); 13787 pw.println(" -c: dump in a compact machine-parseable representation."); 13788 pw.println(" --oom: only show processes organized by oom adj."); 13789 pw.println(" --local: only collect details locally, don't call process."); 13790 pw.println("If [process] is specified it can be the name or "); 13791 pw.println("pid of a specific process to dump."); 13792 return; 13793 } else { 13794 pw.println("Unknown argument: " + opt + "; use -h for help"); 13795 } 13796 } 13797 13798 final boolean isCheckinRequest = scanArgs(args, "--checkin"); 13799 long uptime = SystemClock.uptimeMillis(); 13800 long realtime = SystemClock.elapsedRealtime(); 13801 final long[] tmpLong = new long[1]; 13802 13803 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args); 13804 if (procs == null) { 13805 // No Java processes. Maybe they want to print a native process. 13806 if (args != null && args.length > opti 13807 && args[opti].charAt(0) != '-') { 13808 ArrayList<ProcessCpuTracker.Stats> nativeProcs 13809 = new ArrayList<ProcessCpuTracker.Stats>(); 13810 updateCpuStatsNow(); 13811 int findPid = -1; 13812 try { 13813 findPid = Integer.parseInt(args[opti]); 13814 } catch (NumberFormatException e) { 13815 } 13816 synchronized (mProcessCpuTracker) { 13817 final int N = mProcessCpuTracker.countStats(); 13818 for (int i=0; i<N; i++) { 13819 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13820 if (st.pid == findPid || (st.baseName != null 13821 && st.baseName.equals(args[opti]))) { 13822 nativeProcs.add(st); 13823 } 13824 } 13825 } 13826 if (nativeProcs.size() > 0) { 13827 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, 13828 isCompact); 13829 Debug.MemoryInfo mi = null; 13830 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 13831 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 13832 final int pid = r.pid; 13833 if (!isCheckinRequest && dumpDetails) { 13834 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **"); 13835 } 13836 if (mi == null) { 13837 mi = new Debug.MemoryInfo(); 13838 } 13839 if (dumpDetails || (!brief && !oomOnly)) { 13840 Debug.getMemoryInfo(pid, mi); 13841 } else { 13842 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 13843 mi.dalvikPrivateDirty = (int)tmpLong[0]; 13844 } 13845 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 13846 dumpDalvik, pid, r.baseName, 0, 0, 0, 0, 0, 0); 13847 if (isCheckinRequest) { 13848 pw.println(); 13849 } 13850 } 13851 return; 13852 } 13853 } 13854 pw.println("No process found for: " + args[opti]); 13855 return; 13856 } 13857 13858 if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest)) { 13859 dumpDetails = true; 13860 } 13861 13862 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact); 13863 13864 String[] innerArgs = new String[args.length-opti]; 13865 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 13866 13867 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 13868 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 13869 long nativePss=0, dalvikPss=0, otherPss=0; 13870 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13871 13872 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 13873 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 13874 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 13875 13876 long totalPss = 0; 13877 long cachedPss = 0; 13878 13879 Debug.MemoryInfo mi = null; 13880 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13881 final ProcessRecord r = procs.get(i); 13882 final IApplicationThread thread; 13883 final int pid; 13884 final int oomAdj; 13885 final boolean hasActivities; 13886 synchronized (this) { 13887 thread = r.thread; 13888 pid = r.pid; 13889 oomAdj = r.getSetAdjWithServices(); 13890 hasActivities = r.activities.size() > 0; 13891 } 13892 if (thread != null) { 13893 if (!isCheckinRequest && dumpDetails) { 13894 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 13895 } 13896 if (mi == null) { 13897 mi = new Debug.MemoryInfo(); 13898 } 13899 if (dumpDetails || (!brief && !oomOnly)) { 13900 Debug.getMemoryInfo(pid, mi); 13901 } else { 13902 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 13903 mi.dalvikPrivateDirty = (int)tmpLong[0]; 13904 } 13905 if (dumpDetails) { 13906 if (localOnly) { 13907 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 13908 dumpDalvik, pid, r.processName, 0, 0, 0, 0, 0, 0); 13909 if (isCheckinRequest) { 13910 pw.println(); 13911 } 13912 } else { 13913 try { 13914 pw.flush(); 13915 thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails, 13916 dumpDalvik, innerArgs); 13917 } catch (RemoteException e) { 13918 if (!isCheckinRequest) { 13919 pw.println("Got RemoteException!"); 13920 pw.flush(); 13921 } 13922 } 13923 } 13924 } 13925 13926 final long myTotalPss = mi.getTotalPss(); 13927 final long myTotalUss = mi.getTotalUss(); 13928 13929 synchronized (this) { 13930 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 13931 // Record this for posterity if the process has been stable. 13932 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList); 13933 } 13934 } 13935 13936 if (!isCheckinRequest && mi != null) { 13937 totalPss += myTotalPss; 13938 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13939 (hasActivities ? " / activities)" : ")"), 13940 r.processName, myTotalPss, pid, hasActivities); 13941 procMems.add(pssItem); 13942 procMemsMap.put(pid, pssItem); 13943 13944 nativePss += mi.nativePss; 13945 dalvikPss += mi.dalvikPss; 13946 otherPss += mi.otherPss; 13947 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13948 long mem = mi.getOtherPss(j); 13949 miscPss[j] += mem; 13950 otherPss -= mem; 13951 } 13952 13953 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13954 cachedPss += myTotalPss; 13955 } 13956 13957 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13958 if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex] 13959 || oomIndex == (oomPss.length-1)) { 13960 oomPss[oomIndex] += myTotalPss; 13961 if (oomProcs[oomIndex] == null) { 13962 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13963 } 13964 oomProcs[oomIndex].add(pssItem); 13965 break; 13966 } 13967 } 13968 } 13969 } 13970 } 13971 13972 long nativeProcTotalPss = 0; 13973 13974 if (!isCheckinRequest && procs.size() > 1) { 13975 // If we are showing aggregations, also look for native processes to 13976 // include so that our aggregations are more accurate. 13977 updateCpuStatsNow(); 13978 synchronized (mProcessCpuTracker) { 13979 final int N = mProcessCpuTracker.countStats(); 13980 for (int i=0; i<N; i++) { 13981 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13982 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13983 if (mi == null) { 13984 mi = new Debug.MemoryInfo(); 13985 } 13986 if (!brief && !oomOnly) { 13987 Debug.getMemoryInfo(st.pid, mi); 13988 } else { 13989 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong); 13990 mi.nativePrivateDirty = (int)tmpLong[0]; 13991 } 13992 13993 final long myTotalPss = mi.getTotalPss(); 13994 totalPss += myTotalPss; 13995 nativeProcTotalPss += myTotalPss; 13996 13997 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 13998 st.name, myTotalPss, st.pid, false); 13999 procMems.add(pssItem); 14000 14001 nativePss += mi.nativePss; 14002 dalvikPss += mi.dalvikPss; 14003 otherPss += mi.otherPss; 14004 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14005 long mem = mi.getOtherPss(j); 14006 miscPss[j] += mem; 14007 otherPss -= mem; 14008 } 14009 oomPss[0] += myTotalPss; 14010 if (oomProcs[0] == null) { 14011 oomProcs[0] = new ArrayList<MemItem>(); 14012 } 14013 oomProcs[0].add(pssItem); 14014 } 14015 } 14016 } 14017 14018 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 14019 14020 catMems.add(new MemItem("Native", "Native", nativePss, -1)); 14021 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2)); 14022 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3)); 14023 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14024 String label = Debug.MemoryInfo.getOtherLabel(j); 14025 catMems.add(new MemItem(label, label, miscPss[j], j)); 14026 } 14027 14028 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 14029 for (int j=0; j<oomPss.length; j++) { 14030 if (oomPss[j] != 0) { 14031 String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 14032 : DUMP_MEM_OOM_LABEL[j]; 14033 MemItem item = new MemItem(label, label, oomPss[j], 14034 DUMP_MEM_OOM_ADJ[j]); 14035 item.subitems = oomProcs[j]; 14036 oomMems.add(item); 14037 } 14038 } 14039 14040 if (!brief && !oomOnly && !isCompact) { 14041 pw.println(); 14042 pw.println("Total PSS by process:"); 14043 dumpMemItems(pw, " ", "proc", procMems, true, isCompact); 14044 pw.println(); 14045 } 14046 if (!isCompact) { 14047 pw.println("Total PSS by OOM adjustment:"); 14048 } 14049 dumpMemItems(pw, " ", "oom", oomMems, false, isCompact); 14050 if (!brief && !oomOnly) { 14051 PrintWriter out = categoryPw != null ? categoryPw : pw; 14052 if (!isCompact) { 14053 out.println(); 14054 out.println("Total PSS by category:"); 14055 } 14056 dumpMemItems(out, " ", "cat", catMems, true, isCompact); 14057 } 14058 if (!isCompact) { 14059 pw.println(); 14060 } 14061 MemInfoReader memInfo = new MemInfoReader(); 14062 memInfo.readMemInfo(); 14063 if (nativeProcTotalPss > 0) { 14064 synchronized (this) { 14065 mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(), 14066 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(), 14067 memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()+memInfo.getSlabSizeKb(), 14068 nativeProcTotalPss); 14069 } 14070 } 14071 if (!brief) { 14072 if (!isCompact) { 14073 pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb()); 14074 pw.print(" kB (status "); 14075 switch (mLastMemoryLevel) { 14076 case ProcessStats.ADJ_MEM_FACTOR_NORMAL: 14077 pw.println("normal)"); 14078 break; 14079 case ProcessStats.ADJ_MEM_FACTOR_MODERATE: 14080 pw.println("moderate)"); 14081 break; 14082 case ProcessStats.ADJ_MEM_FACTOR_LOW: 14083 pw.println("low)"); 14084 break; 14085 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 14086 pw.println("critical)"); 14087 break; 14088 default: 14089 pw.print(mLastMemoryLevel); 14090 pw.println(")"); 14091 break; 14092 } 14093 pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb() 14094 + memInfo.getFreeSizeKb()); pw.print(" kB ("); 14095 pw.print(cachedPss); pw.print(" cached pss + "); 14096 pw.print(memInfo.getCachedSizeKb()); pw.print(" cached + "); 14097 pw.print(memInfo.getFreeSizeKb()); pw.println(" free)"); 14098 } else { 14099 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 14100 pw.print(cachedPss + memInfo.getCachedSizeKb() 14101 + memInfo.getFreeSizeKb()); pw.print(","); 14102 pw.println(totalPss - cachedPss); 14103 } 14104 } 14105 if (!isCompact) { 14106 pw.print(" Used RAM: "); pw.print(totalPss - cachedPss 14107 + memInfo.getBuffersSizeKb() + memInfo.getShmemSizeKb() 14108 + memInfo.getSlabSizeKb()); pw.print(" kB ("); 14109 pw.print(totalPss - cachedPss); pw.print(" used pss + "); 14110 pw.print(memInfo.getBuffersSizeKb()); pw.print(" buffers + "); 14111 pw.print(memInfo.getShmemSizeKb()); pw.print(" shmem + "); 14112 pw.print(memInfo.getSlabSizeKb()); pw.println(" slab)"); 14113 pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb() 14114 - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 14115 - memInfo.getBuffersSizeKb() - memInfo.getShmemSizeKb() 14116 - memInfo.getSlabSizeKb()); pw.println(" kB"); 14117 } 14118 if (!brief) { 14119 if (memInfo.getZramTotalSizeKb() != 0) { 14120 if (!isCompact) { 14121 pw.print(" ZRAM: "); pw.print(memInfo.getZramTotalSizeKb()); 14122 pw.print(" kB physical used for "); 14123 pw.print(memInfo.getSwapTotalSizeKb() 14124 - memInfo.getSwapFreeSizeKb()); 14125 pw.print(" kB in swap ("); 14126 pw.print(memInfo.getSwapTotalSizeKb()); 14127 pw.println(" kB total swap)"); 14128 } else { 14129 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 14130 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 14131 pw.println(memInfo.getSwapFreeSizeKb()); 14132 } 14133 } 14134 final int[] SINGLE_LONG_FORMAT = new int[] { 14135 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG 14136 }; 14137 long[] longOut = new long[1]; 14138 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared", 14139 SINGLE_LONG_FORMAT, null, longOut, null); 14140 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14141 longOut[0] = 0; 14142 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing", 14143 SINGLE_LONG_FORMAT, null, longOut, null); 14144 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14145 longOut[0] = 0; 14146 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared", 14147 SINGLE_LONG_FORMAT, null, longOut, null); 14148 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14149 longOut[0] = 0; 14150 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile", 14151 SINGLE_LONG_FORMAT, null, longOut, null); 14152 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14153 if (!isCompact) { 14154 if (sharing != 0 || shared != 0 || unshared != 0 || voltile != 0) { 14155 pw.print(" KSM: "); pw.print(sharing); 14156 pw.print(" kB saved from shared "); 14157 pw.print(shared); pw.println(" kB"); 14158 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; "); 14159 pw.print(voltile); pw.println(" kB volatile"); 14160 } 14161 pw.print(" Tuning: "); 14162 pw.print(ActivityManager.staticGetMemoryClass()); 14163 pw.print(" (large "); 14164 pw.print(ActivityManager.staticGetLargeMemoryClass()); 14165 pw.print("), oom "); 14166 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 14167 pw.print(" kB"); 14168 pw.print(", restore limit "); 14169 pw.print(mProcessList.getCachedRestoreThresholdKb()); 14170 pw.print(" kB"); 14171 if (ActivityManager.isLowRamDeviceStatic()) { 14172 pw.print(" (low-ram)"); 14173 } 14174 if (ActivityManager.isHighEndGfx()) { 14175 pw.print(" (high-end-gfx)"); 14176 } 14177 pw.println(); 14178 } else { 14179 pw.print("ksm,"); pw.print(sharing); pw.print(","); 14180 pw.print(shared); pw.print(","); pw.print(unshared); pw.print(","); 14181 pw.println(voltile); 14182 pw.print("tuning,"); 14183 pw.print(ActivityManager.staticGetMemoryClass()); 14184 pw.print(','); 14185 pw.print(ActivityManager.staticGetLargeMemoryClass()); 14186 pw.print(','); 14187 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 14188 if (ActivityManager.isLowRamDeviceStatic()) { 14189 pw.print(",low-ram"); 14190 } 14191 if (ActivityManager.isHighEndGfx()) { 14192 pw.print(",high-end-gfx"); 14193 } 14194 pw.println(); 14195 } 14196 } 14197 } 14198 } 14199 14200 /** 14201 * Searches array of arguments for the specified string 14202 * @param args array of argument strings 14203 * @param value value to search for 14204 * @return true if the value is contained in the array 14205 */ 14206 private static boolean scanArgs(String[] args, String value) { 14207 if (args != null) { 14208 for (String arg : args) { 14209 if (value.equals(arg)) { 14210 return true; 14211 } 14212 } 14213 } 14214 return false; 14215 } 14216 14217 private final boolean removeDyingProviderLocked(ProcessRecord proc, 14218 ContentProviderRecord cpr, boolean always) { 14219 final boolean inLaunching = mLaunchingProviders.contains(cpr); 14220 14221 if (!inLaunching || always) { 14222 synchronized (cpr) { 14223 cpr.launchingApp = null; 14224 cpr.notifyAll(); 14225 } 14226 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid)); 14227 String names[] = cpr.info.authority.split(";"); 14228 for (int j = 0; j < names.length; j++) { 14229 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid)); 14230 } 14231 } 14232 14233 for (int i=0; i<cpr.connections.size(); i++) { 14234 ContentProviderConnection conn = cpr.connections.get(i); 14235 if (conn.waiting) { 14236 // If this connection is waiting for the provider, then we don't 14237 // need to mess with its process unless we are always removing 14238 // or for some reason the provider is not currently launching. 14239 if (inLaunching && !always) { 14240 continue; 14241 } 14242 } 14243 ProcessRecord capp = conn.client; 14244 conn.dead = true; 14245 if (conn.stableCount > 0) { 14246 if (!capp.persistent && capp.thread != null 14247 && capp.pid != 0 14248 && capp.pid != MY_PID) { 14249 capp.kill("depends on provider " 14250 + cpr.name.flattenToShortString() 14251 + " in dying proc " + (proc != null ? proc.processName : "??"), true); 14252 } 14253 } else if (capp.thread != null && conn.provider.provider != null) { 14254 try { 14255 capp.thread.unstableProviderDied(conn.provider.provider.asBinder()); 14256 } catch (RemoteException e) { 14257 } 14258 // In the protocol here, we don't expect the client to correctly 14259 // clean up this connection, we'll just remove it. 14260 cpr.connections.remove(i); 14261 conn.client.conProviders.remove(conn); 14262 } 14263 } 14264 14265 if (inLaunching && always) { 14266 mLaunchingProviders.remove(cpr); 14267 } 14268 return inLaunching; 14269 } 14270 14271 /** 14272 * Main code for cleaning up a process when it has gone away. This is 14273 * called both as a result of the process dying, or directly when stopping 14274 * a process when running in single process mode. 14275 */ 14276 private final void cleanUpApplicationRecordLocked(ProcessRecord app, 14277 boolean restarting, boolean allowRestart, int index) { 14278 if (index >= 0) { 14279 removeLruProcessLocked(app); 14280 ProcessList.remove(app.pid); 14281 } 14282 14283 mProcessesToGc.remove(app); 14284 mPendingPssProcesses.remove(app); 14285 14286 // Dismiss any open dialogs. 14287 if (app.crashDialog != null && !app.forceCrashReport) { 14288 app.crashDialog.dismiss(); 14289 app.crashDialog = null; 14290 } 14291 if (app.anrDialog != null) { 14292 app.anrDialog.dismiss(); 14293 app.anrDialog = null; 14294 } 14295 if (app.waitDialog != null) { 14296 app.waitDialog.dismiss(); 14297 app.waitDialog = null; 14298 } 14299 14300 app.crashing = false; 14301 app.notResponding = false; 14302 14303 app.resetPackageList(mProcessStats); 14304 app.unlinkDeathRecipient(); 14305 app.makeInactive(mProcessStats); 14306 app.waitingToKill = null; 14307 app.forcingToForeground = null; 14308 updateProcessForegroundLocked(app, false, false); 14309 app.foregroundActivities = false; 14310 app.hasShownUi = false; 14311 app.treatLikeActivity = false; 14312 app.hasAboveClient = false; 14313 app.hasClientActivities = false; 14314 14315 mServices.killServicesLocked(app, allowRestart); 14316 14317 boolean restart = false; 14318 14319 // Remove published content providers. 14320 for (int i=app.pubProviders.size()-1; i>=0; i--) { 14321 ContentProviderRecord cpr = app.pubProviders.valueAt(i); 14322 final boolean always = app.bad || !allowRestart; 14323 if (removeDyingProviderLocked(app, cpr, always) || always) { 14324 // We left the provider in the launching list, need to 14325 // restart it. 14326 restart = true; 14327 } 14328 14329 cpr.provider = null; 14330 cpr.proc = null; 14331 } 14332 app.pubProviders.clear(); 14333 14334 // Take care of any launching providers waiting for this process. 14335 if (checkAppInLaunchingProvidersLocked(app, false)) { 14336 restart = true; 14337 } 14338 14339 // Unregister from connected content providers. 14340 if (!app.conProviders.isEmpty()) { 14341 for (int i=0; i<app.conProviders.size(); i++) { 14342 ContentProviderConnection conn = app.conProviders.get(i); 14343 conn.provider.connections.remove(conn); 14344 } 14345 app.conProviders.clear(); 14346 } 14347 14348 // At this point there may be remaining entries in mLaunchingProviders 14349 // where we were the only one waiting, so they are no longer of use. 14350 // Look for these and clean up if found. 14351 // XXX Commented out for now. Trying to figure out a way to reproduce 14352 // the actual situation to identify what is actually going on. 14353 if (false) { 14354 for (int i=0; i<mLaunchingProviders.size(); i++) { 14355 ContentProviderRecord cpr = (ContentProviderRecord) 14356 mLaunchingProviders.get(i); 14357 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 14358 synchronized (cpr) { 14359 cpr.launchingApp = null; 14360 cpr.notifyAll(); 14361 } 14362 } 14363 } 14364 } 14365 14366 skipCurrentReceiverLocked(app); 14367 14368 // Unregister any receivers. 14369 for (int i=app.receivers.size()-1; i>=0; i--) { 14370 removeReceiverLocked(app.receivers.valueAt(i)); 14371 } 14372 app.receivers.clear(); 14373 14374 // If the app is undergoing backup, tell the backup manager about it 14375 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) { 14376 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App " 14377 + mBackupTarget.appInfo + " died during backup"); 14378 try { 14379 IBackupManager bm = IBackupManager.Stub.asInterface( 14380 ServiceManager.getService(Context.BACKUP_SERVICE)); 14381 bm.agentDisconnected(app.info.packageName); 14382 } catch (RemoteException e) { 14383 // can't happen; backup manager is local 14384 } 14385 } 14386 14387 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) { 14388 ProcessChangeItem item = mPendingProcessChanges.get(i); 14389 if (item.pid == app.pid) { 14390 mPendingProcessChanges.remove(i); 14391 mAvailProcessChanges.add(item); 14392 } 14393 } 14394 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget(); 14395 14396 // If the caller is restarting this app, then leave it in its 14397 // current lists and let the caller take care of it. 14398 if (restarting) { 14399 return; 14400 } 14401 14402 if (!app.persistent || app.isolated) { 14403 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, 14404 "Removing non-persistent process during cleanup: " + app); 14405 mProcessNames.remove(app.processName, app.uid); 14406 mIsolatedProcesses.remove(app.uid); 14407 if (mHeavyWeightProcess == app) { 14408 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 14409 mHeavyWeightProcess.userId, 0)); 14410 mHeavyWeightProcess = null; 14411 } 14412 } else if (!app.removed) { 14413 // This app is persistent, so we need to keep its record around. 14414 // If it is not already on the pending app list, add it there 14415 // and start a new process for it. 14416 if (mPersistentStartingProcesses.indexOf(app) < 0) { 14417 mPersistentStartingProcesses.add(app); 14418 restart = true; 14419 } 14420 } 14421 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG, 14422 "Clean-up removing on hold: " + app); 14423 mProcessesOnHold.remove(app); 14424 14425 if (app == mHomeProcess) { 14426 mHomeProcess = null; 14427 } 14428 if (app == mPreviousProcess) { 14429 mPreviousProcess = null; 14430 } 14431 14432 if (restart && !app.isolated) { 14433 // We have components that still need to be running in the 14434 // process, so re-launch it. 14435 mProcessNames.put(app.processName, app.uid, app); 14436 startProcessLocked(app, "restart", app.processName); 14437 } else if (app.pid > 0 && app.pid != MY_PID) { 14438 // Goodbye! 14439 boolean removed; 14440 synchronized (mPidsSelfLocked) { 14441 mPidsSelfLocked.remove(app.pid); 14442 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 14443 } 14444 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 14445 if (app.isolated) { 14446 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 14447 } 14448 app.setPid(0); 14449 } 14450 } 14451 14452 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 14453 // Look through the content providers we are waiting to have launched, 14454 // and if any run in this process then either schedule a restart of 14455 // the process or kill the client waiting for it if this process has 14456 // gone bad. 14457 int NL = mLaunchingProviders.size(); 14458 boolean restart = false; 14459 for (int i=0; i<NL; i++) { 14460 ContentProviderRecord cpr = mLaunchingProviders.get(i); 14461 if (cpr.launchingApp == app) { 14462 if (!alwaysBad && !app.bad) { 14463 restart = true; 14464 } else { 14465 removeDyingProviderLocked(app, cpr, true); 14466 // cpr should have been removed from mLaunchingProviders 14467 NL = mLaunchingProviders.size(); 14468 i--; 14469 } 14470 } 14471 } 14472 return restart; 14473 } 14474 14475 // ========================================================= 14476 // SERVICES 14477 // ========================================================= 14478 14479 @Override 14480 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, 14481 int flags) { 14482 enforceNotIsolatedCaller("getServices"); 14483 synchronized (this) { 14484 return mServices.getRunningServiceInfoLocked(maxNum, flags); 14485 } 14486 } 14487 14488 @Override 14489 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 14490 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 14491 synchronized (this) { 14492 return mServices.getRunningServiceControlPanelLocked(name); 14493 } 14494 } 14495 14496 @Override 14497 public ComponentName startService(IApplicationThread caller, Intent service, 14498 String resolvedType, int userId) { 14499 enforceNotIsolatedCaller("startService"); 14500 // Refuse possible leaked file descriptors 14501 if (service != null && service.hasFileDescriptors() == true) { 14502 throw new IllegalArgumentException("File descriptors passed in Intent"); 14503 } 14504 14505 if (DEBUG_SERVICE) 14506 Slog.v(TAG, "startService: " + service + " type=" + resolvedType); 14507 synchronized(this) { 14508 final int callingPid = Binder.getCallingPid(); 14509 final int callingUid = Binder.getCallingUid(); 14510 final long origId = Binder.clearCallingIdentity(); 14511 ComponentName res = mServices.startServiceLocked(caller, service, 14512 resolvedType, callingPid, callingUid, userId); 14513 Binder.restoreCallingIdentity(origId); 14514 return res; 14515 } 14516 } 14517 14518 ComponentName startServiceInPackage(int uid, 14519 Intent service, String resolvedType, int userId) { 14520 synchronized(this) { 14521 if (DEBUG_SERVICE) 14522 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType); 14523 final long origId = Binder.clearCallingIdentity(); 14524 ComponentName res = mServices.startServiceLocked(null, service, 14525 resolvedType, -1, uid, userId); 14526 Binder.restoreCallingIdentity(origId); 14527 return res; 14528 } 14529 } 14530 14531 @Override 14532 public int stopService(IApplicationThread caller, Intent service, 14533 String resolvedType, int userId) { 14534 enforceNotIsolatedCaller("stopService"); 14535 // Refuse possible leaked file descriptors 14536 if (service != null && service.hasFileDescriptors() == true) { 14537 throw new IllegalArgumentException("File descriptors passed in Intent"); 14538 } 14539 14540 synchronized(this) { 14541 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 14542 } 14543 } 14544 14545 @Override 14546 public IBinder peekService(Intent service, String resolvedType) { 14547 enforceNotIsolatedCaller("peekService"); 14548 // Refuse possible leaked file descriptors 14549 if (service != null && service.hasFileDescriptors() == true) { 14550 throw new IllegalArgumentException("File descriptors passed in Intent"); 14551 } 14552 synchronized(this) { 14553 return mServices.peekServiceLocked(service, resolvedType); 14554 } 14555 } 14556 14557 @Override 14558 public boolean stopServiceToken(ComponentName className, IBinder token, 14559 int startId) { 14560 synchronized(this) { 14561 return mServices.stopServiceTokenLocked(className, token, startId); 14562 } 14563 } 14564 14565 @Override 14566 public void setServiceForeground(ComponentName className, IBinder token, 14567 int id, Notification notification, boolean removeNotification) { 14568 synchronized(this) { 14569 mServices.setServiceForegroundLocked(className, token, id, notification, 14570 removeNotification); 14571 } 14572 } 14573 14574 @Override 14575 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 14576 boolean requireFull, String name, String callerPackage) { 14577 return handleIncomingUser(callingPid, callingUid, userId, allowAll, 14578 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 14579 } 14580 14581 int unsafeConvertIncomingUser(int userId) { 14582 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) 14583 ? mCurrentUserId : userId; 14584 } 14585 14586 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 14587 int allowMode, String name, String callerPackage) { 14588 final int callingUserId = UserHandle.getUserId(callingUid); 14589 if (callingUserId == userId) { 14590 return userId; 14591 } 14592 14593 // Note that we may be accessing mCurrentUserId outside of a lock... 14594 // shouldn't be a big deal, if this is being called outside 14595 // of a locked context there is intrinsically a race with 14596 // the value the caller will receive and someone else changing it. 14597 // We assume that USER_CURRENT_OR_SELF will use the current user; later 14598 // we will switch to the calling user if access to the current user fails. 14599 int targetUserId = unsafeConvertIncomingUser(userId); 14600 14601 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14602 final boolean allow; 14603 if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 14604 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 14605 // If the caller has this permission, they always pass go. And collect $200. 14606 allow = true; 14607 } else if (allowMode == ALLOW_FULL_ONLY) { 14608 // We require full access, sucks to be you. 14609 allow = false; 14610 } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 14611 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { 14612 // If the caller does not have either permission, they are always doomed. 14613 allow = false; 14614 } else if (allowMode == ALLOW_NON_FULL) { 14615 // We are blanket allowing non-full access, you lucky caller! 14616 allow = true; 14617 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) { 14618 // We may or may not allow this depending on whether the two users are 14619 // in the same profile. 14620 synchronized (mUserProfileGroupIdsSelfLocked) { 14621 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId, 14622 UserInfo.NO_PROFILE_GROUP_ID); 14623 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId, 14624 UserInfo.NO_PROFILE_GROUP_ID); 14625 allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID 14626 && callingProfile == targetProfile; 14627 } 14628 } else { 14629 throw new IllegalArgumentException("Unknown mode: " + allowMode); 14630 } 14631 if (!allow) { 14632 if (userId == UserHandle.USER_CURRENT_OR_SELF) { 14633 // In this case, they would like to just execute as their 14634 // owner user instead of failing. 14635 targetUserId = callingUserId; 14636 } else { 14637 StringBuilder builder = new StringBuilder(128); 14638 builder.append("Permission Denial: "); 14639 builder.append(name); 14640 if (callerPackage != null) { 14641 builder.append(" from "); 14642 builder.append(callerPackage); 14643 } 14644 builder.append(" asks to run as user "); 14645 builder.append(userId); 14646 builder.append(" but is calling from user "); 14647 builder.append(UserHandle.getUserId(callingUid)); 14648 builder.append("; this requires "); 14649 builder.append(INTERACT_ACROSS_USERS_FULL); 14650 if (allowMode != ALLOW_FULL_ONLY) { 14651 builder.append(" or "); 14652 builder.append(INTERACT_ACROSS_USERS); 14653 } 14654 String msg = builder.toString(); 14655 Slog.w(TAG, msg); 14656 throw new SecurityException(msg); 14657 } 14658 } 14659 } 14660 if (!allowAll && targetUserId < 0) { 14661 throw new IllegalArgumentException( 14662 "Call does not support special user #" + targetUserId); 14663 } 14664 // Check shell permission 14665 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_OWNER) { 14666 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, 14667 targetUserId)) { 14668 throw new SecurityException("Shell does not have permission to access user " 14669 + targetUserId + "\n " + Debug.getCallers(3)); 14670 } 14671 } 14672 return targetUserId; 14673 } 14674 14675 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 14676 String className, int flags) { 14677 boolean result = false; 14678 // For apps that don't have pre-defined UIDs, check for permission 14679 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) { 14680 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14681 if (ActivityManager.checkUidPermission( 14682 INTERACT_ACROSS_USERS, 14683 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 14684 ComponentName comp = new ComponentName(aInfo.packageName, className); 14685 String msg = "Permission Denial: Component " + comp.flattenToShortString() 14686 + " requests FLAG_SINGLE_USER, but app does not hold " 14687 + INTERACT_ACROSS_USERS; 14688 Slog.w(TAG, msg); 14689 throw new SecurityException(msg); 14690 } 14691 // Permission passed 14692 result = true; 14693 } 14694 } else if ("system".equals(componentProcessName)) { 14695 result = true; 14696 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14697 // Phone app and persistent apps are allowed to export singleuser providers. 14698 result = UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID) 14699 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 14700 } 14701 if (DEBUG_MU) { 14702 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo 14703 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result); 14704 } 14705 return result; 14706 } 14707 14708 /** 14709 * Checks to see if the caller is in the same app as the singleton 14710 * component, or the component is in a special app. It allows special apps 14711 * to export singleton components but prevents exporting singleton 14712 * components for regular apps. 14713 */ 14714 boolean isValidSingletonCall(int callingUid, int componentUid) { 14715 int componentAppId = UserHandle.getAppId(componentUid); 14716 return UserHandle.isSameApp(callingUid, componentUid) 14717 || componentAppId == Process.SYSTEM_UID 14718 || componentAppId == Process.PHONE_UID 14719 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 14720 == PackageManager.PERMISSION_GRANTED; 14721 } 14722 14723 public int bindService(IApplicationThread caller, IBinder token, 14724 Intent service, String resolvedType, 14725 IServiceConnection connection, int flags, int userId) { 14726 enforceNotIsolatedCaller("bindService"); 14727 14728 // Refuse possible leaked file descriptors 14729 if (service != null && service.hasFileDescriptors() == true) { 14730 throw new IllegalArgumentException("File descriptors passed in Intent"); 14731 } 14732 14733 synchronized(this) { 14734 return mServices.bindServiceLocked(caller, token, service, resolvedType, 14735 connection, flags, userId); 14736 } 14737 } 14738 14739 public boolean unbindService(IServiceConnection connection) { 14740 synchronized (this) { 14741 return mServices.unbindServiceLocked(connection); 14742 } 14743 } 14744 14745 public void publishService(IBinder token, Intent intent, IBinder service) { 14746 // Refuse possible leaked file descriptors 14747 if (intent != null && intent.hasFileDescriptors() == true) { 14748 throw new IllegalArgumentException("File descriptors passed in Intent"); 14749 } 14750 14751 synchronized(this) { 14752 if (!(token instanceof ServiceRecord)) { 14753 throw new IllegalArgumentException("Invalid service token"); 14754 } 14755 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 14756 } 14757 } 14758 14759 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 14760 // Refuse possible leaked file descriptors 14761 if (intent != null && intent.hasFileDescriptors() == true) { 14762 throw new IllegalArgumentException("File descriptors passed in Intent"); 14763 } 14764 14765 synchronized(this) { 14766 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 14767 } 14768 } 14769 14770 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 14771 synchronized(this) { 14772 if (!(token instanceof ServiceRecord)) { 14773 throw new IllegalArgumentException("Invalid service token"); 14774 } 14775 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); 14776 } 14777 } 14778 14779 // ========================================================= 14780 // BACKUP AND RESTORE 14781 // ========================================================= 14782 14783 // Cause the target app to be launched if necessary and its backup agent 14784 // instantiated. The backup agent will invoke backupAgentCreated() on the 14785 // activity manager to announce its creation. 14786 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) { 14787 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode); 14788 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 14789 14790 synchronized(this) { 14791 // !!! TODO: currently no check here that we're already bound 14792 BatteryStatsImpl.Uid.Pkg.Serv ss = null; 14793 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 14794 synchronized (stats) { 14795 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name); 14796 } 14797 14798 // Backup agent is now in use, its package can't be stopped. 14799 try { 14800 AppGlobals.getPackageManager().setPackageStoppedState( 14801 app.packageName, false, UserHandle.getUserId(app.uid)); 14802 } catch (RemoteException e) { 14803 } catch (IllegalArgumentException e) { 14804 Slog.w(TAG, "Failed trying to unstop package " 14805 + app.packageName + ": " + e); 14806 } 14807 14808 BackupRecord r = new BackupRecord(ss, app, backupMode); 14809 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) 14810 ? new ComponentName(app.packageName, app.backupAgentName) 14811 : new ComponentName("android", "FullBackupAgent"); 14812 // startProcessLocked() returns existing proc's record if it's already running 14813 ProcessRecord proc = startProcessLocked(app.processName, app, 14814 false, 0, "backup", hostingName, false, false, false); 14815 if (proc == null) { 14816 Slog.e(TAG, "Unable to start backup agent process " + r); 14817 return false; 14818 } 14819 14820 r.app = proc; 14821 mBackupTarget = r; 14822 mBackupAppName = app.packageName; 14823 14824 // Try not to kill the process during backup 14825 updateOomAdjLocked(proc); 14826 14827 // If the process is already attached, schedule the creation of the backup agent now. 14828 // If it is not yet live, this will be done when it attaches to the framework. 14829 if (proc.thread != null) { 14830 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc); 14831 try { 14832 proc.thread.scheduleCreateBackupAgent(app, 14833 compatibilityInfoForPackageLocked(app), backupMode); 14834 } catch (RemoteException e) { 14835 // Will time out on the backup manager side 14836 } 14837 } else { 14838 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach"); 14839 } 14840 // Invariants: at this point, the target app process exists and the application 14841 // is either already running or in the process of coming up. mBackupTarget and 14842 // mBackupAppName describe the app, so that when it binds back to the AM we 14843 // know that it's scheduled for a backup-agent operation. 14844 } 14845 14846 return true; 14847 } 14848 14849 @Override 14850 public void clearPendingBackup() { 14851 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup"); 14852 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup"); 14853 14854 synchronized (this) { 14855 mBackupTarget = null; 14856 mBackupAppName = null; 14857 } 14858 } 14859 14860 // A backup agent has just come up 14861 public void backupAgentCreated(String agentPackageName, IBinder agent) { 14862 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName 14863 + " = " + agent); 14864 14865 synchronized(this) { 14866 if (!agentPackageName.equals(mBackupAppName)) { 14867 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14868 return; 14869 } 14870 } 14871 14872 long oldIdent = Binder.clearCallingIdentity(); 14873 try { 14874 IBackupManager bm = IBackupManager.Stub.asInterface( 14875 ServiceManager.getService(Context.BACKUP_SERVICE)); 14876 bm.agentConnected(agentPackageName, agent); 14877 } catch (RemoteException e) { 14878 // can't happen; the backup manager service is local 14879 } catch (Exception e) { 14880 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14881 e.printStackTrace(); 14882 } finally { 14883 Binder.restoreCallingIdentity(oldIdent); 14884 } 14885 } 14886 14887 // done with this agent 14888 public void unbindBackupAgent(ApplicationInfo appInfo) { 14889 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo); 14890 if (appInfo == null) { 14891 Slog.w(TAG, "unbind backup agent for null app"); 14892 return; 14893 } 14894 14895 synchronized(this) { 14896 try { 14897 if (mBackupAppName == null) { 14898 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14899 return; 14900 } 14901 14902 if (!mBackupAppName.equals(appInfo.packageName)) { 14903 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14904 return; 14905 } 14906 14907 // Not backing this app up any more; reset its OOM adjustment 14908 final ProcessRecord proc = mBackupTarget.app; 14909 updateOomAdjLocked(proc); 14910 14911 // If the app crashed during backup, 'thread' will be null here 14912 if (proc.thread != null) { 14913 try { 14914 proc.thread.scheduleDestroyBackupAgent(appInfo, 14915 compatibilityInfoForPackageLocked(appInfo)); 14916 } catch (Exception e) { 14917 Slog.e(TAG, "Exception when unbinding backup agent:"); 14918 e.printStackTrace(); 14919 } 14920 } 14921 } finally { 14922 mBackupTarget = null; 14923 mBackupAppName = null; 14924 } 14925 } 14926 } 14927 // ========================================================= 14928 // BROADCASTS 14929 // ========================================================= 14930 14931 private final List getStickiesLocked(String action, IntentFilter filter, 14932 List cur, int userId) { 14933 final ContentResolver resolver = mContext.getContentResolver(); 14934 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14935 if (stickies == null) { 14936 return cur; 14937 } 14938 final ArrayList<Intent> list = stickies.get(action); 14939 if (list == null) { 14940 return cur; 14941 } 14942 int N = list.size(); 14943 for (int i=0; i<N; i++) { 14944 Intent intent = list.get(i); 14945 if (filter.match(resolver, intent, true, TAG) >= 0) { 14946 if (cur == null) { 14947 cur = new ArrayList<Intent>(); 14948 } 14949 cur.add(intent); 14950 } 14951 } 14952 return cur; 14953 } 14954 14955 boolean isPendingBroadcastProcessLocked(int pid) { 14956 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 14957 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid); 14958 } 14959 14960 void skipPendingBroadcastLocked(int pid) { 14961 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 14962 for (BroadcastQueue queue : mBroadcastQueues) { 14963 queue.skipPendingBroadcastLocked(pid); 14964 } 14965 } 14966 14967 // The app just attached; send any pending broadcasts that it should receive 14968 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 14969 boolean didSomething = false; 14970 for (BroadcastQueue queue : mBroadcastQueues) { 14971 didSomething |= queue.sendPendingBroadcastsLocked(app); 14972 } 14973 return didSomething; 14974 } 14975 14976 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14977 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) { 14978 enforceNotIsolatedCaller("registerReceiver"); 14979 int callingUid; 14980 int callingPid; 14981 synchronized(this) { 14982 ProcessRecord callerApp = null; 14983 if (caller != null) { 14984 callerApp = getRecordForAppLocked(caller); 14985 if (callerApp == null) { 14986 throw new SecurityException( 14987 "Unable to find app for caller " + caller 14988 + " (pid=" + Binder.getCallingPid() 14989 + ") when registering receiver " + receiver); 14990 } 14991 if (callerApp.info.uid != Process.SYSTEM_UID && 14992 !callerApp.pkgList.containsKey(callerPackage) && 14993 !"android".equals(callerPackage)) { 14994 throw new SecurityException("Given caller package " + callerPackage 14995 + " is not running in process " + callerApp); 14996 } 14997 callingUid = callerApp.info.uid; 14998 callingPid = callerApp.pid; 14999 } else { 15000 callerPackage = null; 15001 callingUid = Binder.getCallingUid(); 15002 callingPid = Binder.getCallingPid(); 15003 } 15004 15005 userId = this.handleIncomingUser(callingPid, callingUid, userId, 15006 true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 15007 15008 List allSticky = null; 15009 15010 // Look for any matching sticky broadcasts... 15011 Iterator actions = filter.actionsIterator(); 15012 if (actions != null) { 15013 while (actions.hasNext()) { 15014 String action = (String)actions.next(); 15015 allSticky = getStickiesLocked(action, filter, allSticky, 15016 UserHandle.USER_ALL); 15017 allSticky = getStickiesLocked(action, filter, allSticky, 15018 UserHandle.getUserId(callingUid)); 15019 } 15020 } else { 15021 allSticky = getStickiesLocked(null, filter, allSticky, 15022 UserHandle.USER_ALL); 15023 allSticky = getStickiesLocked(null, filter, allSticky, 15024 UserHandle.getUserId(callingUid)); 15025 } 15026 15027 // The first sticky in the list is returned directly back to 15028 // the client. 15029 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null; 15030 15031 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter 15032 + ": " + sticky); 15033 15034 if (receiver == null) { 15035 return sticky; 15036 } 15037 15038 ReceiverList rl 15039 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder()); 15040 if (rl == null) { 15041 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 15042 userId, receiver); 15043 if (rl.app != null) { 15044 rl.app.receivers.add(rl); 15045 } else { 15046 try { 15047 receiver.asBinder().linkToDeath(rl, 0); 15048 } catch (RemoteException e) { 15049 return sticky; 15050 } 15051 rl.linkedToDeath = true; 15052 } 15053 mRegisteredReceivers.put(receiver.asBinder(), rl); 15054 } else if (rl.uid != callingUid) { 15055 throw new IllegalArgumentException( 15056 "Receiver requested to register for uid " + callingUid 15057 + " was previously registered for uid " + rl.uid); 15058 } else if (rl.pid != callingPid) { 15059 throw new IllegalArgumentException( 15060 "Receiver requested to register for pid " + callingPid 15061 + " was previously registered for pid " + rl.pid); 15062 } else if (rl.userId != userId) { 15063 throw new IllegalArgumentException( 15064 "Receiver requested to register for user " + userId 15065 + " was previously registered for user " + rl.userId); 15066 } 15067 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, 15068 permission, callingUid, userId); 15069 rl.add(bf); 15070 if (!bf.debugCheck()) { 15071 Slog.w(TAG, "==> For Dynamic broadast"); 15072 } 15073 mReceiverResolver.addFilter(bf); 15074 15075 // Enqueue broadcasts for all existing stickies that match 15076 // this filter. 15077 if (allSticky != null) { 15078 ArrayList receivers = new ArrayList(); 15079 receivers.add(bf); 15080 15081 int N = allSticky.size(); 15082 for (int i=0; i<N; i++) { 15083 Intent intent = (Intent)allSticky.get(i); 15084 BroadcastQueue queue = broadcastQueueForIntent(intent); 15085 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 15086 null, -1, -1, null, null, AppOpsManager.OP_NONE, receivers, null, 0, 15087 null, null, false, true, true, -1); 15088 queue.enqueueParallelBroadcastLocked(r); 15089 queue.scheduleBroadcastsLocked(); 15090 } 15091 } 15092 15093 return sticky; 15094 } 15095 } 15096 15097 public void unregisterReceiver(IIntentReceiver receiver) { 15098 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver); 15099 15100 final long origId = Binder.clearCallingIdentity(); 15101 try { 15102 boolean doTrim = false; 15103 15104 synchronized(this) { 15105 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 15106 if (rl != null) { 15107 if (rl.curBroadcast != null) { 15108 BroadcastRecord r = rl.curBroadcast; 15109 final boolean doNext = finishReceiverLocked( 15110 receiver.asBinder(), r.resultCode, r.resultData, 15111 r.resultExtras, r.resultAbort); 15112 if (doNext) { 15113 doTrim = true; 15114 r.queue.processNextBroadcast(false); 15115 } 15116 } 15117 15118 if (rl.app != null) { 15119 rl.app.receivers.remove(rl); 15120 } 15121 removeReceiverLocked(rl); 15122 if (rl.linkedToDeath) { 15123 rl.linkedToDeath = false; 15124 rl.receiver.asBinder().unlinkToDeath(rl, 0); 15125 } 15126 } 15127 } 15128 15129 // If we actually concluded any broadcasts, we might now be able 15130 // to trim the recipients' apps from our working set 15131 if (doTrim) { 15132 trimApplications(); 15133 return; 15134 } 15135 15136 } finally { 15137 Binder.restoreCallingIdentity(origId); 15138 } 15139 } 15140 15141 void removeReceiverLocked(ReceiverList rl) { 15142 mRegisteredReceivers.remove(rl.receiver.asBinder()); 15143 int N = rl.size(); 15144 for (int i=0; i<N; i++) { 15145 mReceiverResolver.removeFilter(rl.get(i)); 15146 } 15147 } 15148 15149 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 15150 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 15151 ProcessRecord r = mLruProcesses.get(i); 15152 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) { 15153 try { 15154 r.thread.dispatchPackageBroadcast(cmd, packages); 15155 } catch (RemoteException ex) { 15156 } 15157 } 15158 } 15159 } 15160 15161 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 15162 int callingUid, int[] users) { 15163 List<ResolveInfo> receivers = null; 15164 try { 15165 HashSet<ComponentName> singleUserReceivers = null; 15166 boolean scannedFirstReceivers = false; 15167 for (int user : users) { 15168 // Skip users that have Shell restrictions 15169 if (callingUid == Process.SHELL_UID 15170 && getUserManagerLocked().hasUserRestriction( 15171 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 15172 continue; 15173 } 15174 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 15175 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user); 15176 if (user != 0 && newReceivers != null) { 15177 // If this is not the primary user, we need to check for 15178 // any receivers that should be filtered out. 15179 for (int i=0; i<newReceivers.size(); i++) { 15180 ResolveInfo ri = newReceivers.get(i); 15181 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 15182 newReceivers.remove(i); 15183 i--; 15184 } 15185 } 15186 } 15187 if (newReceivers != null && newReceivers.size() == 0) { 15188 newReceivers = null; 15189 } 15190 if (receivers == null) { 15191 receivers = newReceivers; 15192 } else if (newReceivers != null) { 15193 // We need to concatenate the additional receivers 15194 // found with what we have do far. This would be easy, 15195 // but we also need to de-dup any receivers that are 15196 // singleUser. 15197 if (!scannedFirstReceivers) { 15198 // Collect any single user receivers we had already retrieved. 15199 scannedFirstReceivers = true; 15200 for (int i=0; i<receivers.size(); i++) { 15201 ResolveInfo ri = receivers.get(i); 15202 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 15203 ComponentName cn = new ComponentName( 15204 ri.activityInfo.packageName, ri.activityInfo.name); 15205 if (singleUserReceivers == null) { 15206 singleUserReceivers = new HashSet<ComponentName>(); 15207 } 15208 singleUserReceivers.add(cn); 15209 } 15210 } 15211 } 15212 // Add the new results to the existing results, tracking 15213 // and de-dupping single user receivers. 15214 for (int i=0; i<newReceivers.size(); i++) { 15215 ResolveInfo ri = newReceivers.get(i); 15216 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 15217 ComponentName cn = new ComponentName( 15218 ri.activityInfo.packageName, ri.activityInfo.name); 15219 if (singleUserReceivers == null) { 15220 singleUserReceivers = new HashSet<ComponentName>(); 15221 } 15222 if (!singleUserReceivers.contains(cn)) { 15223 singleUserReceivers.add(cn); 15224 receivers.add(ri); 15225 } 15226 } else { 15227 receivers.add(ri); 15228 } 15229 } 15230 } 15231 } 15232 } catch (RemoteException ex) { 15233 // pm is in same process, this will never happen. 15234 } 15235 return receivers; 15236 } 15237 15238 private final int broadcastIntentLocked(ProcessRecord callerApp, 15239 String callerPackage, Intent intent, String resolvedType, 15240 IIntentReceiver resultTo, int resultCode, String resultData, 15241 Bundle map, String requiredPermission, int appOp, 15242 boolean ordered, boolean sticky, int callingPid, int callingUid, 15243 int userId) { 15244 intent = new Intent(intent); 15245 15246 // By default broadcasts do not go to stopped apps. 15247 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 15248 15249 if (DEBUG_BROADCAST_LIGHT) Slog.v( 15250 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 15251 + " ordered=" + ordered + " userid=" + userId); 15252 if ((resultTo != null) && !ordered) { 15253 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 15254 } 15255 15256 userId = handleIncomingUser(callingPid, callingUid, userId, 15257 true, ALLOW_NON_FULL, "broadcast", callerPackage); 15258 15259 // Make sure that the user who is receiving this broadcast is started. 15260 // If not, we will just skip it. 15261 15262 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) { 15263 if (callingUid != Process.SYSTEM_UID || (intent.getFlags() 15264 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 15265 Slog.w(TAG, "Skipping broadcast of " + intent 15266 + ": user " + userId + " is stopped"); 15267 return ActivityManager.BROADCAST_SUCCESS; 15268 } 15269 } 15270 15271 /* 15272 * Prevent non-system code (defined here to be non-persistent 15273 * processes) from sending protected broadcasts. 15274 */ 15275 int callingAppId = UserHandle.getAppId(callingUid); 15276 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID 15277 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID 15278 || callingAppId == Process.NFC_UID || callingUid == 0) { 15279 // Always okay. 15280 } else if (callerApp == null || !callerApp.persistent) { 15281 try { 15282 if (AppGlobals.getPackageManager().isProtectedBroadcast( 15283 intent.getAction())) { 15284 String msg = "Permission Denial: not allowed to send broadcast " 15285 + intent.getAction() + " from pid=" 15286 + callingPid + ", uid=" + callingUid; 15287 Slog.w(TAG, msg); 15288 throw new SecurityException(msg); 15289 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) { 15290 // Special case for compatibility: we don't want apps to send this, 15291 // but historically it has not been protected and apps may be using it 15292 // to poke their own app widget. So, instead of making it protected, 15293 // just limit it to the caller. 15294 if (callerApp == null) { 15295 String msg = "Permission Denial: not allowed to send broadcast " 15296 + intent.getAction() + " from unknown caller."; 15297 Slog.w(TAG, msg); 15298 throw new SecurityException(msg); 15299 } else if (intent.getComponent() != null) { 15300 // They are good enough to send to an explicit component... verify 15301 // it is being sent to the calling app. 15302 if (!intent.getComponent().getPackageName().equals( 15303 callerApp.info.packageName)) { 15304 String msg = "Permission Denial: not allowed to send broadcast " 15305 + intent.getAction() + " to " 15306 + intent.getComponent().getPackageName() + " from " 15307 + callerApp.info.packageName; 15308 Slog.w(TAG, msg); 15309 throw new SecurityException(msg); 15310 } 15311 } else { 15312 // Limit broadcast to their own package. 15313 intent.setPackage(callerApp.info.packageName); 15314 } 15315 } 15316 } catch (RemoteException e) { 15317 Slog.w(TAG, "Remote exception", e); 15318 return ActivityManager.BROADCAST_SUCCESS; 15319 } 15320 } 15321 15322 // Handle special intents: if this broadcast is from the package 15323 // manager about a package being removed, we need to remove all of 15324 // its activities from the history stack. 15325 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals( 15326 intent.getAction()); 15327 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) 15328 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction()) 15329 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction()) 15330 || Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction()) 15331 || uidRemoved) { 15332 if (checkComponentPermission( 15333 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 15334 callingPid, callingUid, -1, true) 15335 == PackageManager.PERMISSION_GRANTED) { 15336 if (uidRemoved) { 15337 final Bundle intentExtras = intent.getExtras(); 15338 final int uid = intentExtras != null 15339 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 15340 if (uid >= 0) { 15341 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics(); 15342 synchronized (bs) { 15343 bs.removeUidStatsLocked(uid); 15344 } 15345 mAppOpsService.uidRemoved(uid); 15346 } 15347 } else { 15348 // If resources are unavailable just force stop all 15349 // those packages and flush the attribute cache as well. 15350 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) { 15351 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15352 if (list != null && (list.length > 0)) { 15353 for (String pkg : list) { 15354 forceStopPackageLocked(pkg, -1, false, true, true, false, false, userId, 15355 "storage unmount"); 15356 } 15357 cleanupRecentTasksLocked(UserHandle.USER_ALL); 15358 sendPackageBroadcastLocked( 15359 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId); 15360 } 15361 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals( 15362 intent.getAction())) { 15363 cleanupRecentTasksLocked(UserHandle.USER_ALL); 15364 } else { 15365 Uri data = intent.getData(); 15366 String ssp; 15367 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15368 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals( 15369 intent.getAction()); 15370 boolean fullUninstall = removed && 15371 !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15372 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) { 15373 forceStopPackageLocked(ssp, UserHandle.getAppId( 15374 intent.getIntExtra(Intent.EXTRA_UID, -1)), false, true, true, 15375 false, fullUninstall, userId, 15376 removed ? "pkg removed" : "pkg changed"); 15377 } 15378 if (removed) { 15379 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED, 15380 new String[] {ssp}, userId); 15381 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 15382 mAppOpsService.packageRemoved( 15383 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 15384 15385 // Remove all permissions granted from/to this package 15386 removeUriPermissionsForPackageLocked(ssp, userId, true); 15387 } 15388 } 15389 } 15390 } 15391 } 15392 } else { 15393 String msg = "Permission Denial: " + intent.getAction() 15394 + " broadcast from " + callerPackage + " (pid=" + callingPid 15395 + ", uid=" + callingUid + ")" 15396 + " requires " 15397 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 15398 Slog.w(TAG, msg); 15399 throw new SecurityException(msg); 15400 } 15401 15402 // Special case for adding a package: by default turn on compatibility 15403 // mode. 15404 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) { 15405 Uri data = intent.getData(); 15406 String ssp; 15407 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15408 mCompatModePackages.handlePackageAddedLocked(ssp, 15409 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)); 15410 } 15411 } 15412 15413 /* 15414 * If this is the time zone changed action, queue up a message that will reset the timezone 15415 * of all currently running processes. This message will get queued up before the broadcast 15416 * happens. 15417 */ 15418 if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) { 15419 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 15420 } 15421 15422 /* 15423 * If the user set the time, let all running processes know. 15424 */ 15425 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) { 15426 final int is24Hour = intent.getBooleanExtra( 15427 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 : 0; 15428 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0)); 15429 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 15430 synchronized (stats) { 15431 stats.noteCurrentTimeChangedLocked(); 15432 } 15433 } 15434 15435 if (Intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) { 15436 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 15437 } 15438 15439 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) { 15440 ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO); 15441 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy)); 15442 } 15443 15444 // Add to the sticky list if requested. 15445 if (sticky) { 15446 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 15447 callingPid, callingUid) 15448 != PackageManager.PERMISSION_GRANTED) { 15449 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 15450 + callingPid + ", uid=" + callingUid 15451 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15452 Slog.w(TAG, msg); 15453 throw new SecurityException(msg); 15454 } 15455 if (requiredPermission != null) { 15456 Slog.w(TAG, "Can't broadcast sticky intent " + intent 15457 + " and enforce permission " + requiredPermission); 15458 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 15459 } 15460 if (intent.getComponent() != null) { 15461 throw new SecurityException( 15462 "Sticky broadcasts can't target a specific component"); 15463 } 15464 // We use userId directly here, since the "all" target is maintained 15465 // as a separate set of sticky broadcasts. 15466 if (userId != UserHandle.USER_ALL) { 15467 // But first, if this is not a broadcast to all users, then 15468 // make sure it doesn't conflict with an existing broadcast to 15469 // all users. 15470 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 15471 UserHandle.USER_ALL); 15472 if (stickies != null) { 15473 ArrayList<Intent> list = stickies.get(intent.getAction()); 15474 if (list != null) { 15475 int N = list.size(); 15476 int i; 15477 for (i=0; i<N; i++) { 15478 if (intent.filterEquals(list.get(i))) { 15479 throw new IllegalArgumentException( 15480 "Sticky broadcast " + intent + " for user " 15481 + userId + " conflicts with existing global broadcast"); 15482 } 15483 } 15484 } 15485 } 15486 } 15487 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15488 if (stickies == null) { 15489 stickies = new ArrayMap<String, ArrayList<Intent>>(); 15490 mStickyBroadcasts.put(userId, stickies); 15491 } 15492 ArrayList<Intent> list = stickies.get(intent.getAction()); 15493 if (list == null) { 15494 list = new ArrayList<Intent>(); 15495 stickies.put(intent.getAction(), list); 15496 } 15497 int N = list.size(); 15498 int i; 15499 for (i=0; i<N; i++) { 15500 if (intent.filterEquals(list.get(i))) { 15501 // This sticky already exists, replace it. 15502 list.set(i, new Intent(intent)); 15503 break; 15504 } 15505 } 15506 if (i >= N) { 15507 list.add(new Intent(intent)); 15508 } 15509 } 15510 15511 int[] users; 15512 if (userId == UserHandle.USER_ALL) { 15513 // Caller wants broadcast to go to all started users. 15514 users = mStartedUserArray; 15515 } else { 15516 // Caller wants broadcast to go to one specific user. 15517 users = new int[] {userId}; 15518 } 15519 15520 // Figure out who all will receive this broadcast. 15521 List receivers = null; 15522 List<BroadcastFilter> registeredReceivers = null; 15523 // Need to resolve the intent to interested receivers... 15524 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 15525 == 0) { 15526 receivers = collectReceiverComponents(intent, resolvedType, callingUid, users); 15527 } 15528 if (intent.getComponent() == null) { 15529 if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) { 15530 // Query one target user at a time, excluding shell-restricted users 15531 UserManagerService ums = getUserManagerLocked(); 15532 for (int i = 0; i < users.length; i++) { 15533 if (ums.hasUserRestriction( 15534 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 15535 continue; 15536 } 15537 List<BroadcastFilter> registeredReceiversForUser = 15538 mReceiverResolver.queryIntent(intent, 15539 resolvedType, false, users[i]); 15540 if (registeredReceivers == null) { 15541 registeredReceivers = registeredReceiversForUser; 15542 } else if (registeredReceiversForUser != null) { 15543 registeredReceivers.addAll(registeredReceiversForUser); 15544 } 15545 } 15546 } else { 15547 registeredReceivers = mReceiverResolver.queryIntent(intent, 15548 resolvedType, false, userId); 15549 } 15550 } 15551 15552 final boolean replacePending = 15553 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 15554 15555 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction() 15556 + " replacePending=" + replacePending); 15557 15558 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 15559 if (!ordered && NR > 0) { 15560 // If we are not serializing this broadcast, then send the 15561 // registered receivers separately so they don't wait for the 15562 // components to be launched. 15563 final BroadcastQueue queue = broadcastQueueForIntent(intent); 15564 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15565 callerPackage, callingPid, callingUid, resolvedType, requiredPermission, 15566 appOp, registeredReceivers, resultTo, resultCode, resultData, map, 15567 ordered, sticky, false, userId); 15568 if (DEBUG_BROADCAST) Slog.v( 15569 TAG, "Enqueueing parallel broadcast " + r); 15570 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r); 15571 if (!replaced) { 15572 queue.enqueueParallelBroadcastLocked(r); 15573 queue.scheduleBroadcastsLocked(); 15574 } 15575 registeredReceivers = null; 15576 NR = 0; 15577 } 15578 15579 // Merge into one list. 15580 int ir = 0; 15581 if (receivers != null) { 15582 // A special case for PACKAGE_ADDED: do not allow the package 15583 // being added to see this broadcast. This prevents them from 15584 // using this as a back door to get run as soon as they are 15585 // installed. Maybe in the future we want to have a special install 15586 // broadcast or such for apps, but we'd like to deliberately make 15587 // this decision. 15588 String skipPackages[] = null; 15589 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 15590 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 15591 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 15592 Uri data = intent.getData(); 15593 if (data != null) { 15594 String pkgName = data.getSchemeSpecificPart(); 15595 if (pkgName != null) { 15596 skipPackages = new String[] { pkgName }; 15597 } 15598 } 15599 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 15600 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15601 } 15602 if (skipPackages != null && (skipPackages.length > 0)) { 15603 for (String skipPackage : skipPackages) { 15604 if (skipPackage != null) { 15605 int NT = receivers.size(); 15606 for (int it=0; it<NT; it++) { 15607 ResolveInfo curt = (ResolveInfo)receivers.get(it); 15608 if (curt.activityInfo.packageName.equals(skipPackage)) { 15609 receivers.remove(it); 15610 it--; 15611 NT--; 15612 } 15613 } 15614 } 15615 } 15616 } 15617 15618 int NT = receivers != null ? receivers.size() : 0; 15619 int it = 0; 15620 ResolveInfo curt = null; 15621 BroadcastFilter curr = null; 15622 while (it < NT && ir < NR) { 15623 if (curt == null) { 15624 curt = (ResolveInfo)receivers.get(it); 15625 } 15626 if (curr == null) { 15627 curr = registeredReceivers.get(ir); 15628 } 15629 if (curr.getPriority() >= curt.priority) { 15630 // Insert this broadcast record into the final list. 15631 receivers.add(it, curr); 15632 ir++; 15633 curr = null; 15634 it++; 15635 NT++; 15636 } else { 15637 // Skip to the next ResolveInfo in the final list. 15638 it++; 15639 curt = null; 15640 } 15641 } 15642 } 15643 while (ir < NR) { 15644 if (receivers == null) { 15645 receivers = new ArrayList(); 15646 } 15647 receivers.add(registeredReceivers.get(ir)); 15648 ir++; 15649 } 15650 15651 if ((receivers != null && receivers.size() > 0) 15652 || resultTo != null) { 15653 BroadcastQueue queue = broadcastQueueForIntent(intent); 15654 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15655 callerPackage, callingPid, callingUid, resolvedType, 15656 requiredPermission, appOp, receivers, resultTo, resultCode, 15657 resultData, map, ordered, sticky, false, userId); 15658 if (DEBUG_BROADCAST) Slog.v( 15659 TAG, "Enqueueing ordered broadcast " + r 15660 + ": prev had " + queue.mOrderedBroadcasts.size()); 15661 if (DEBUG_BROADCAST) { 15662 int seq = r.intent.getIntExtra("seq", -1); 15663 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq); 15664 } 15665 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r); 15666 if (!replaced) { 15667 queue.enqueueOrderedBroadcastLocked(r); 15668 queue.scheduleBroadcastsLocked(); 15669 } 15670 } 15671 15672 return ActivityManager.BROADCAST_SUCCESS; 15673 } 15674 15675 final Intent verifyBroadcastLocked(Intent intent) { 15676 // Refuse possible leaked file descriptors 15677 if (intent != null && intent.hasFileDescriptors() == true) { 15678 throw new IllegalArgumentException("File descriptors passed in Intent"); 15679 } 15680 15681 int flags = intent.getFlags(); 15682 15683 if (!mProcessesReady) { 15684 // if the caller really truly claims to know what they're doing, go 15685 // ahead and allow the broadcast without launching any receivers 15686 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 15687 intent = new Intent(intent); 15688 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15689 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 15690 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 15691 + " before boot completion"); 15692 throw new IllegalStateException("Cannot broadcast before boot completed"); 15693 } 15694 } 15695 15696 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 15697 throw new IllegalArgumentException( 15698 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 15699 } 15700 15701 return intent; 15702 } 15703 15704 public final int broadcastIntent(IApplicationThread caller, 15705 Intent intent, String resolvedType, IIntentReceiver resultTo, 15706 int resultCode, String resultData, Bundle map, 15707 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) { 15708 enforceNotIsolatedCaller("broadcastIntent"); 15709 synchronized(this) { 15710 intent = verifyBroadcastLocked(intent); 15711 15712 final ProcessRecord callerApp = getRecordForAppLocked(caller); 15713 final int callingPid = Binder.getCallingPid(); 15714 final int callingUid = Binder.getCallingUid(); 15715 final long origId = Binder.clearCallingIdentity(); 15716 int res = broadcastIntentLocked(callerApp, 15717 callerApp != null ? callerApp.info.packageName : null, 15718 intent, resolvedType, resultTo, 15719 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky, 15720 callingPid, callingUid, userId); 15721 Binder.restoreCallingIdentity(origId); 15722 return res; 15723 } 15724 } 15725 15726 int broadcastIntentInPackage(String packageName, int uid, 15727 Intent intent, String resolvedType, IIntentReceiver resultTo, 15728 int resultCode, String resultData, Bundle map, 15729 String requiredPermission, boolean serialized, boolean sticky, int userId) { 15730 synchronized(this) { 15731 intent = verifyBroadcastLocked(intent); 15732 15733 final long origId = Binder.clearCallingIdentity(); 15734 int res = broadcastIntentLocked(null, packageName, intent, resolvedType, 15735 resultTo, resultCode, resultData, map, requiredPermission, 15736 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId); 15737 Binder.restoreCallingIdentity(origId); 15738 return res; 15739 } 15740 } 15741 15742 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 15743 // Refuse possible leaked file descriptors 15744 if (intent != null && intent.hasFileDescriptors() == true) { 15745 throw new IllegalArgumentException("File descriptors passed in Intent"); 15746 } 15747 15748 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15749 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 15750 15751 synchronized(this) { 15752 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 15753 != PackageManager.PERMISSION_GRANTED) { 15754 String msg = "Permission Denial: unbroadcastIntent() from pid=" 15755 + Binder.getCallingPid() 15756 + ", uid=" + Binder.getCallingUid() 15757 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15758 Slog.w(TAG, msg); 15759 throw new SecurityException(msg); 15760 } 15761 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15762 if (stickies != null) { 15763 ArrayList<Intent> list = stickies.get(intent.getAction()); 15764 if (list != null) { 15765 int N = list.size(); 15766 int i; 15767 for (i=0; i<N; i++) { 15768 if (intent.filterEquals(list.get(i))) { 15769 list.remove(i); 15770 break; 15771 } 15772 } 15773 if (list.size() <= 0) { 15774 stickies.remove(intent.getAction()); 15775 } 15776 } 15777 if (stickies.size() <= 0) { 15778 mStickyBroadcasts.remove(userId); 15779 } 15780 } 15781 } 15782 } 15783 15784 private final boolean finishReceiverLocked(IBinder receiver, int resultCode, 15785 String resultData, Bundle resultExtras, boolean resultAbort) { 15786 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver); 15787 if (r == null) { 15788 Slog.w(TAG, "finishReceiver called but not found on queue"); 15789 return false; 15790 } 15791 15792 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort, false); 15793 } 15794 15795 void backgroundServicesFinishedLocked(int userId) { 15796 for (BroadcastQueue queue : mBroadcastQueues) { 15797 queue.backgroundServicesFinishedLocked(userId); 15798 } 15799 } 15800 15801 public void finishReceiver(IBinder who, int resultCode, String resultData, 15802 Bundle resultExtras, boolean resultAbort) { 15803 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who); 15804 15805 // Refuse possible leaked file descriptors 15806 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 15807 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15808 } 15809 15810 final long origId = Binder.clearCallingIdentity(); 15811 try { 15812 boolean doNext = false; 15813 BroadcastRecord r; 15814 15815 synchronized(this) { 15816 r = broadcastRecordForReceiverLocked(who); 15817 if (r != null) { 15818 doNext = r.queue.finishReceiverLocked(r, resultCode, 15819 resultData, resultExtras, resultAbort, true); 15820 } 15821 } 15822 15823 if (doNext) { 15824 r.queue.processNextBroadcast(false); 15825 } 15826 trimApplications(); 15827 } finally { 15828 Binder.restoreCallingIdentity(origId); 15829 } 15830 } 15831 15832 // ========================================================= 15833 // INSTRUMENTATION 15834 // ========================================================= 15835 15836 public boolean startInstrumentation(ComponentName className, 15837 String profileFile, int flags, Bundle arguments, 15838 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 15839 int userId, String abiOverride) { 15840 enforceNotIsolatedCaller("startInstrumentation"); 15841 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15842 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 15843 // Refuse possible leaked file descriptors 15844 if (arguments != null && arguments.hasFileDescriptors()) { 15845 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15846 } 15847 15848 synchronized(this) { 15849 InstrumentationInfo ii = null; 15850 ApplicationInfo ai = null; 15851 try { 15852 ii = mContext.getPackageManager().getInstrumentationInfo( 15853 className, STOCK_PM_FLAGS); 15854 ai = AppGlobals.getPackageManager().getApplicationInfo( 15855 ii.targetPackage, STOCK_PM_FLAGS, userId); 15856 } catch (PackageManager.NameNotFoundException e) { 15857 } catch (RemoteException e) { 15858 } 15859 if (ii == null) { 15860 reportStartInstrumentationFailure(watcher, className, 15861 "Unable to find instrumentation info for: " + className); 15862 return false; 15863 } 15864 if (ai == null) { 15865 reportStartInstrumentationFailure(watcher, className, 15866 "Unable to find instrumentation target package: " + ii.targetPackage); 15867 return false; 15868 } 15869 15870 int match = mContext.getPackageManager().checkSignatures( 15871 ii.targetPackage, ii.packageName); 15872 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 15873 String msg = "Permission Denial: starting instrumentation " 15874 + className + " from pid=" 15875 + Binder.getCallingPid() 15876 + ", uid=" + Binder.getCallingPid() 15877 + " not allowed because package " + ii.packageName 15878 + " does not have a signature matching the target " 15879 + ii.targetPackage; 15880 reportStartInstrumentationFailure(watcher, className, msg); 15881 throw new SecurityException(msg); 15882 } 15883 15884 final long origId = Binder.clearCallingIdentity(); 15885 // Instrumentation can kill and relaunch even persistent processes 15886 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, 15887 "start instr"); 15888 ProcessRecord app = addAppLocked(ai, false, abiOverride); 15889 app.instrumentationClass = className; 15890 app.instrumentationInfo = ai; 15891 app.instrumentationProfileFile = profileFile; 15892 app.instrumentationArguments = arguments; 15893 app.instrumentationWatcher = watcher; 15894 app.instrumentationUiAutomationConnection = uiAutomationConnection; 15895 app.instrumentationResultClass = className; 15896 Binder.restoreCallingIdentity(origId); 15897 } 15898 15899 return true; 15900 } 15901 15902 /** 15903 * Report errors that occur while attempting to start Instrumentation. Always writes the 15904 * error to the logs, but if somebody is watching, send the report there too. This enables 15905 * the "am" command to report errors with more information. 15906 * 15907 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 15908 * @param cn The component name of the instrumentation. 15909 * @param report The error report. 15910 */ 15911 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher, 15912 ComponentName cn, String report) { 15913 Slog.w(TAG, report); 15914 try { 15915 if (watcher != null) { 15916 Bundle results = new Bundle(); 15917 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 15918 results.putString("Error", report); 15919 watcher.instrumentationStatus(cn, -1, results); 15920 } 15921 } catch (RemoteException e) { 15922 Slog.w(TAG, e); 15923 } 15924 } 15925 15926 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 15927 if (app.instrumentationWatcher != null) { 15928 try { 15929 // NOTE: IInstrumentationWatcher *must* be oneway here 15930 app.instrumentationWatcher.instrumentationFinished( 15931 app.instrumentationClass, 15932 resultCode, 15933 results); 15934 } catch (RemoteException e) { 15935 } 15936 } 15937 if (app.instrumentationUiAutomationConnection != null) { 15938 try { 15939 app.instrumentationUiAutomationConnection.shutdown(); 15940 } catch (RemoteException re) { 15941 /* ignore */ 15942 } 15943 // Only a UiAutomation can set this flag and now that 15944 // it is finished we make sure it is reset to its default. 15945 mUserIsMonkey = false; 15946 } 15947 app.instrumentationWatcher = null; 15948 app.instrumentationUiAutomationConnection = null; 15949 app.instrumentationClass = null; 15950 app.instrumentationInfo = null; 15951 app.instrumentationProfileFile = null; 15952 app.instrumentationArguments = null; 15953 15954 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId, 15955 "finished inst"); 15956 } 15957 15958 public void finishInstrumentation(IApplicationThread target, 15959 int resultCode, Bundle results) { 15960 int userId = UserHandle.getCallingUserId(); 15961 // Refuse possible leaked file descriptors 15962 if (results != null && results.hasFileDescriptors()) { 15963 throw new IllegalArgumentException("File descriptors passed in Intent"); 15964 } 15965 15966 synchronized(this) { 15967 ProcessRecord app = getRecordForAppLocked(target); 15968 if (app == null) { 15969 Slog.w(TAG, "finishInstrumentation: no app for " + target); 15970 return; 15971 } 15972 final long origId = Binder.clearCallingIdentity(); 15973 finishInstrumentationLocked(app, resultCode, results); 15974 Binder.restoreCallingIdentity(origId); 15975 } 15976 } 15977 15978 // ========================================================= 15979 // CONFIGURATION 15980 // ========================================================= 15981 15982 public ConfigurationInfo getDeviceConfigurationInfo() { 15983 ConfigurationInfo config = new ConfigurationInfo(); 15984 synchronized (this) { 15985 config.reqTouchScreen = mConfiguration.touchscreen; 15986 config.reqKeyboardType = mConfiguration.keyboard; 15987 config.reqNavigation = mConfiguration.navigation; 15988 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD 15989 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) { 15990 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV; 15991 } 15992 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED 15993 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) { 15994 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD; 15995 } 15996 config.reqGlEsVersion = GL_ES_VERSION; 15997 } 15998 return config; 15999 } 16000 16001 ActivityStack getFocusedStack() { 16002 return mStackSupervisor.getFocusedStack(); 16003 } 16004 16005 public Configuration getConfiguration() { 16006 Configuration ci; 16007 synchronized(this) { 16008 ci = new Configuration(mConfiguration); 16009 } 16010 return ci; 16011 } 16012 16013 public void updatePersistentConfiguration(Configuration values) { 16014 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 16015 "updateConfiguration()"); 16016 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS, 16017 "updateConfiguration()"); 16018 if (values == null) { 16019 throw new NullPointerException("Configuration must not be null"); 16020 } 16021 16022 synchronized(this) { 16023 final long origId = Binder.clearCallingIdentity(); 16024 updateConfigurationLocked(values, null, true, false); 16025 Binder.restoreCallingIdentity(origId); 16026 } 16027 } 16028 16029 public void updateConfiguration(Configuration values) { 16030 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 16031 "updateConfiguration()"); 16032 16033 synchronized(this) { 16034 if (values == null && mWindowManager != null) { 16035 // sentinel: fetch the current configuration from the window manager 16036 values = mWindowManager.computeNewConfiguration(); 16037 } 16038 16039 if (mWindowManager != null) { 16040 mProcessList.applyDisplaySize(mWindowManager); 16041 } 16042 16043 final long origId = Binder.clearCallingIdentity(); 16044 if (values != null) { 16045 Settings.System.clearConfiguration(values); 16046 } 16047 updateConfigurationLocked(values, null, false, false); 16048 Binder.restoreCallingIdentity(origId); 16049 } 16050 } 16051 16052 /** 16053 * Do either or both things: (1) change the current configuration, and (2) 16054 * make sure the given activity is running with the (now) current 16055 * configuration. Returns true if the activity has been left running, or 16056 * false if <var>starting</var> is being destroyed to match the new 16057 * configuration. 16058 * @param persistent TODO 16059 */ 16060 boolean updateConfigurationLocked(Configuration values, 16061 ActivityRecord starting, boolean persistent, boolean initLocale) { 16062 int changes = 0; 16063 16064 if (values != null) { 16065 Configuration newConfig = new Configuration(mConfiguration); 16066 changes = newConfig.updateFrom(values); 16067 if (changes != 0) { 16068 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 16069 Slog.i(TAG, "Updating configuration to: " + values); 16070 } 16071 16072 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes); 16073 16074 if (values.locale != null && !initLocale) { 16075 saveLocaleLocked(values.locale, 16076 !values.locale.equals(mConfiguration.locale), 16077 values.userSetLocale); 16078 } 16079 16080 mConfigurationSeq++; 16081 if (mConfigurationSeq <= 0) { 16082 mConfigurationSeq = 1; 16083 } 16084 newConfig.seq = mConfigurationSeq; 16085 mConfiguration = newConfig; 16086 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig); 16087 mUsageStatsService.reportConfigurationChange(newConfig, mCurrentUserId); 16088 //mUsageStatsService.noteStartConfig(newConfig); 16089 16090 final Configuration configCopy = new Configuration(mConfiguration); 16091 16092 // TODO: If our config changes, should we auto dismiss any currently 16093 // showing dialogs? 16094 mShowDialogs = shouldShowDialogs(newConfig); 16095 16096 AttributeCache ac = AttributeCache.instance(); 16097 if (ac != null) { 16098 ac.updateConfiguration(configCopy); 16099 } 16100 16101 // Make sure all resources in our process are updated 16102 // right now, so that anyone who is going to retrieve 16103 // resource values after we return will be sure to get 16104 // the new ones. This is especially important during 16105 // boot, where the first config change needs to guarantee 16106 // all resources have that config before following boot 16107 // code is executed. 16108 mSystemThread.applyConfigurationToResources(configCopy); 16109 16110 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) { 16111 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG); 16112 msg.obj = new Configuration(configCopy); 16113 mHandler.sendMessage(msg); 16114 } 16115 16116 for (int i=mLruProcesses.size()-1; i>=0; i--) { 16117 ProcessRecord app = mLruProcesses.get(i); 16118 try { 16119 if (app.thread != null) { 16120 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc " 16121 + app.processName + " new config " + mConfiguration); 16122 app.thread.scheduleConfigurationChanged(configCopy); 16123 } 16124 } catch (Exception e) { 16125 } 16126 } 16127 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 16128 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 16129 | Intent.FLAG_RECEIVER_REPLACE_PENDING 16130 | Intent.FLAG_RECEIVER_FOREGROUND); 16131 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, 16132 null, AppOpsManager.OP_NONE, false, false, MY_PID, 16133 Process.SYSTEM_UID, UserHandle.USER_ALL); 16134 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) { 16135 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 16136 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 16137 broadcastIntentLocked(null, null, intent, 16138 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 16139 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 16140 } 16141 } 16142 } 16143 16144 boolean kept = true; 16145 final ActivityStack mainStack = mStackSupervisor.getFocusedStack(); 16146 // mainStack is null during startup. 16147 if (mainStack != null) { 16148 if (changes != 0 && starting == null) { 16149 // If the configuration changed, and the caller is not already 16150 // in the process of starting an activity, then find the top 16151 // activity to check if its configuration needs to change. 16152 starting = mainStack.topRunningActivityLocked(null); 16153 } 16154 16155 if (starting != null) { 16156 kept = mainStack.ensureActivityConfigurationLocked(starting, changes); 16157 // And we need to make sure at this point that all other activities 16158 // are made visible with the correct configuration. 16159 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes); 16160 } 16161 } 16162 16163 if (values != null && mWindowManager != null) { 16164 mWindowManager.setNewConfiguration(mConfiguration); 16165 } 16166 16167 return kept; 16168 } 16169 16170 /** 16171 * Decide based on the configuration whether we should shouw the ANR, 16172 * crash, etc dialogs. The idea is that if there is no affordnace to 16173 * press the on-screen buttons, we shouldn't show the dialog. 16174 * 16175 * A thought: SystemUI might also want to get told about this, the Power 16176 * dialog / global actions also might want different behaviors. 16177 */ 16178 private static final boolean shouldShowDialogs(Configuration config) { 16179 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS 16180 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH); 16181 } 16182 16183 /** 16184 * Save the locale. You must be inside a synchronized (this) block. 16185 */ 16186 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) { 16187 if(isDiff) { 16188 SystemProperties.set("user.language", l.getLanguage()); 16189 SystemProperties.set("user.region", l.getCountry()); 16190 } 16191 16192 if(isPersist) { 16193 SystemProperties.set("persist.sys.language", l.getLanguage()); 16194 SystemProperties.set("persist.sys.country", l.getCountry()); 16195 SystemProperties.set("persist.sys.localevar", l.getVariant()); 16196 } 16197 } 16198 16199 @Override 16200 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) { 16201 synchronized (this) { 16202 ActivityRecord srec = ActivityRecord.forToken(token); 16203 if (srec.task != null && srec.task.stack != null) { 16204 return srec.task.stack.shouldUpRecreateTaskLocked(srec, destAffinity); 16205 } 16206 } 16207 return false; 16208 } 16209 16210 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode, 16211 Intent resultData) { 16212 16213 synchronized (this) { 16214 final ActivityStack stack = ActivityRecord.getStackLocked(token); 16215 if (stack != null) { 16216 return stack.navigateUpToLocked(token, destIntent, resultCode, resultData); 16217 } 16218 return false; 16219 } 16220 } 16221 16222 public int getLaunchedFromUid(IBinder activityToken) { 16223 ActivityRecord srec = ActivityRecord.forToken(activityToken); 16224 if (srec == null) { 16225 return -1; 16226 } 16227 return srec.launchedFromUid; 16228 } 16229 16230 public String getLaunchedFromPackage(IBinder activityToken) { 16231 ActivityRecord srec = ActivityRecord.forToken(activityToken); 16232 if (srec == null) { 16233 return null; 16234 } 16235 return srec.launchedFromPackage; 16236 } 16237 16238 // ========================================================= 16239 // LIFETIME MANAGEMENT 16240 // ========================================================= 16241 16242 // Returns which broadcast queue the app is the current [or imminent] receiver 16243 // on, or 'null' if the app is not an active broadcast recipient. 16244 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) { 16245 BroadcastRecord r = app.curReceiver; 16246 if (r != null) { 16247 return r.queue; 16248 } 16249 16250 // It's not the current receiver, but it might be starting up to become one 16251 synchronized (this) { 16252 for (BroadcastQueue queue : mBroadcastQueues) { 16253 r = queue.mPendingBroadcast; 16254 if (r != null && r.curApp == app) { 16255 // found it; report which queue it's in 16256 return queue; 16257 } 16258 } 16259 } 16260 16261 return null; 16262 } 16263 16264 private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, 16265 boolean doingAll, long now) { 16266 if (mAdjSeq == app.adjSeq) { 16267 // This adjustment has already been computed. 16268 return app.curRawAdj; 16269 } 16270 16271 if (app.thread == null) { 16272 app.adjSeq = mAdjSeq; 16273 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16274 app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16275 return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ); 16276 } 16277 16278 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN; 16279 app.adjSource = null; 16280 app.adjTarget = null; 16281 app.empty = false; 16282 app.cached = false; 16283 16284 final int activitiesSize = app.activities.size(); 16285 16286 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) { 16287 // The max adjustment doesn't allow this app to be anything 16288 // below foreground, so it is not worth doing work for it. 16289 app.adjType = "fixed"; 16290 app.adjSeq = mAdjSeq; 16291 app.curRawAdj = app.maxAdj; 16292 app.foregroundActivities = false; 16293 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 16294 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT; 16295 // System processes can do UI, and when they do we want to have 16296 // them trim their memory after the user leaves the UI. To 16297 // facilitate this, here we need to determine whether or not it 16298 // is currently showing UI. 16299 app.systemNoUi = true; 16300 if (app == TOP_APP) { 16301 app.systemNoUi = false; 16302 } else if (activitiesSize > 0) { 16303 for (int j = 0; j < activitiesSize; j++) { 16304 final ActivityRecord r = app.activities.get(j); 16305 if (r.visible) { 16306 app.systemNoUi = false; 16307 } 16308 } 16309 } 16310 if (!app.systemNoUi) { 16311 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI; 16312 } 16313 return (app.curAdj=app.maxAdj); 16314 } 16315 16316 app.systemNoUi = false; 16317 16318 // Determine the importance of the process, starting with most 16319 // important to least, and assign an appropriate OOM adjustment. 16320 int adj; 16321 int schedGroup; 16322 int procState; 16323 boolean foregroundActivities = false; 16324 BroadcastQueue queue; 16325 if (app == TOP_APP) { 16326 // The last app on the list is the foreground app. 16327 adj = ProcessList.FOREGROUND_APP_ADJ; 16328 schedGroup = Process.THREAD_GROUP_DEFAULT; 16329 app.adjType = "top-activity"; 16330 foregroundActivities = true; 16331 procState = ActivityManager.PROCESS_STATE_TOP; 16332 } else if (app.instrumentationClass != null) { 16333 // Don't want to kill running instrumentation. 16334 adj = ProcessList.FOREGROUND_APP_ADJ; 16335 schedGroup = Process.THREAD_GROUP_DEFAULT; 16336 app.adjType = "instrumentation"; 16337 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16338 } else if ((queue = isReceivingBroadcast(app)) != null) { 16339 // An app that is currently receiving a broadcast also 16340 // counts as being in the foreground for OOM killer purposes. 16341 // It's placed in a sched group based on the nature of the 16342 // broadcast as reflected by which queue it's active in. 16343 adj = ProcessList.FOREGROUND_APP_ADJ; 16344 schedGroup = (queue == mFgBroadcastQueue) 16345 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 16346 app.adjType = "broadcast"; 16347 procState = ActivityManager.PROCESS_STATE_RECEIVER; 16348 } else if (app.executingServices.size() > 0) { 16349 // An app that is currently executing a service callback also 16350 // counts as being in the foreground. 16351 adj = ProcessList.FOREGROUND_APP_ADJ; 16352 schedGroup = app.execServicesFg ? 16353 Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 16354 app.adjType = "exec-service"; 16355 procState = ActivityManager.PROCESS_STATE_SERVICE; 16356 //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app); 16357 } else { 16358 // As far as we know the process is empty. We may change our mind later. 16359 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16360 // At this point we don't actually know the adjustment. Use the cached adj 16361 // value that the caller wants us to. 16362 adj = cachedAdj; 16363 procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16364 app.cached = true; 16365 app.empty = true; 16366 app.adjType = "cch-empty"; 16367 } 16368 16369 // Examine all activities if not already foreground. 16370 if (!foregroundActivities && activitiesSize > 0) { 16371 for (int j = 0; j < activitiesSize; j++) { 16372 final ActivityRecord r = app.activities.get(j); 16373 if (r.app != app) { 16374 Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc " 16375 + app + "?!?"); 16376 continue; 16377 } 16378 if (r.visible) { 16379 // App has a visible activity; only upgrade adjustment. 16380 if (adj > ProcessList.VISIBLE_APP_ADJ) { 16381 adj = ProcessList.VISIBLE_APP_ADJ; 16382 app.adjType = "visible"; 16383 } 16384 if (procState > ActivityManager.PROCESS_STATE_TOP) { 16385 procState = ActivityManager.PROCESS_STATE_TOP; 16386 } 16387 schedGroup = Process.THREAD_GROUP_DEFAULT; 16388 app.cached = false; 16389 app.empty = false; 16390 foregroundActivities = true; 16391 break; 16392 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) { 16393 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16394 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16395 app.adjType = "pausing"; 16396 } 16397 if (procState > ActivityManager.PROCESS_STATE_TOP) { 16398 procState = ActivityManager.PROCESS_STATE_TOP; 16399 } 16400 schedGroup = Process.THREAD_GROUP_DEFAULT; 16401 app.cached = false; 16402 app.empty = false; 16403 foregroundActivities = true; 16404 } else if (r.state == ActivityState.STOPPING) { 16405 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16406 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16407 app.adjType = "stopping"; 16408 } 16409 // For the process state, we will at this point consider the 16410 // process to be cached. It will be cached either as an activity 16411 // or empty depending on whether the activity is finishing. We do 16412 // this so that we can treat the process as cached for purposes of 16413 // memory trimming (determing current memory level, trim command to 16414 // send to process) since there can be an arbitrary number of stopping 16415 // processes and they should soon all go into the cached state. 16416 if (!r.finishing) { 16417 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16418 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 16419 } 16420 } 16421 app.cached = false; 16422 app.empty = false; 16423 foregroundActivities = true; 16424 } else { 16425 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16426 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 16427 app.adjType = "cch-act"; 16428 } 16429 } 16430 } 16431 } 16432 16433 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16434 if (app.foregroundServices) { 16435 // The user is aware of this app, so make it visible. 16436 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16437 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16438 app.cached = false; 16439 app.adjType = "fg-service"; 16440 schedGroup = Process.THREAD_GROUP_DEFAULT; 16441 } else if (app.forcingToForeground != null) { 16442 // The user is aware of this app, so make it visible. 16443 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16444 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16445 app.cached = false; 16446 app.adjType = "force-fg"; 16447 app.adjSource = app.forcingToForeground; 16448 schedGroup = Process.THREAD_GROUP_DEFAULT; 16449 } 16450 } 16451 16452 if (app == mHeavyWeightProcess) { 16453 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) { 16454 // We don't want to kill the current heavy-weight process. 16455 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ; 16456 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16457 app.cached = false; 16458 app.adjType = "heavy"; 16459 } 16460 if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 16461 procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT; 16462 } 16463 } 16464 16465 if (app == mHomeProcess) { 16466 if (adj > ProcessList.HOME_APP_ADJ) { 16467 // This process is hosting what we currently consider to be the 16468 // home app, so we don't want to let it go into the background. 16469 adj = ProcessList.HOME_APP_ADJ; 16470 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16471 app.cached = false; 16472 app.adjType = "home"; 16473 } 16474 if (procState > ActivityManager.PROCESS_STATE_HOME) { 16475 procState = ActivityManager.PROCESS_STATE_HOME; 16476 } 16477 } 16478 16479 if (app == mPreviousProcess && app.activities.size() > 0) { 16480 if (adj > ProcessList.PREVIOUS_APP_ADJ) { 16481 // This was the previous process that showed UI to the user. 16482 // We want to try to keep it around more aggressively, to give 16483 // a good experience around switching between two apps. 16484 adj = ProcessList.PREVIOUS_APP_ADJ; 16485 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16486 app.cached = false; 16487 app.adjType = "previous"; 16488 } 16489 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 16490 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 16491 } 16492 } 16493 16494 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj 16495 + " reason=" + app.adjType); 16496 16497 // By default, we use the computed adjustment. It may be changed if 16498 // there are applications dependent on our services or providers, but 16499 // this gives us a baseline and makes sure we don't get into an 16500 // infinite recursion. 16501 app.adjSeq = mAdjSeq; 16502 app.curRawAdj = adj; 16503 app.hasStartedServices = false; 16504 16505 if (mBackupTarget != null && app == mBackupTarget.app) { 16506 // If possible we want to avoid killing apps while they're being backed up 16507 if (adj > ProcessList.BACKUP_APP_ADJ) { 16508 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app); 16509 adj = ProcessList.BACKUP_APP_ADJ; 16510 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 16511 procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 16512 } 16513 app.adjType = "backup"; 16514 app.cached = false; 16515 } 16516 if (procState > ActivityManager.PROCESS_STATE_BACKUP) { 16517 procState = ActivityManager.PROCESS_STATE_BACKUP; 16518 } 16519 } 16520 16521 boolean mayBeTop = false; 16522 16523 for (int is = app.services.size()-1; 16524 is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16525 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16526 || procState > ActivityManager.PROCESS_STATE_TOP); 16527 is--) { 16528 ServiceRecord s = app.services.valueAt(is); 16529 if (s.startRequested) { 16530 app.hasStartedServices = true; 16531 if (procState > ActivityManager.PROCESS_STATE_SERVICE) { 16532 procState = ActivityManager.PROCESS_STATE_SERVICE; 16533 } 16534 if (app.hasShownUi && app != mHomeProcess) { 16535 // If this process has shown some UI, let it immediately 16536 // go to the LRU list because it may be pretty heavy with 16537 // UI stuff. We'll tag it with a label just to help 16538 // debug and understand what is going on. 16539 if (adj > ProcessList.SERVICE_ADJ) { 16540 app.adjType = "cch-started-ui-services"; 16541 } 16542 } else { 16543 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) { 16544 // This service has seen some activity within 16545 // recent memory, so we will keep its process ahead 16546 // of the background processes. 16547 if (adj > ProcessList.SERVICE_ADJ) { 16548 adj = ProcessList.SERVICE_ADJ; 16549 app.adjType = "started-services"; 16550 app.cached = false; 16551 } 16552 } 16553 // If we have let the service slide into the background 16554 // state, still have some text describing what it is doing 16555 // even though the service no longer has an impact. 16556 if (adj > ProcessList.SERVICE_ADJ) { 16557 app.adjType = "cch-started-services"; 16558 } 16559 } 16560 } 16561 for (int conni = s.connections.size()-1; 16562 conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16563 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16564 || procState > ActivityManager.PROCESS_STATE_TOP); 16565 conni--) { 16566 ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni); 16567 for (int i = 0; 16568 i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ 16569 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16570 || procState > ActivityManager.PROCESS_STATE_TOP); 16571 i++) { 16572 // XXX should compute this based on the max of 16573 // all connected clients. 16574 ConnectionRecord cr = clist.get(i); 16575 if (cr.binding.client == app) { 16576 // Binding to ourself is not interesting. 16577 continue; 16578 } 16579 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) { 16580 ProcessRecord client = cr.binding.client; 16581 int clientAdj = computeOomAdjLocked(client, cachedAdj, 16582 TOP_APP, doingAll, now); 16583 int clientProcState = client.curProcState; 16584 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16585 // If the other app is cached for any reason, for purposes here 16586 // we are going to consider it empty. The specific cached state 16587 // doesn't propagate except under certain conditions. 16588 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16589 } 16590 String adjType = null; 16591 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) { 16592 // Not doing bind OOM management, so treat 16593 // this guy more like a started service. 16594 if (app.hasShownUi && app != mHomeProcess) { 16595 // If this process has shown some UI, let it immediately 16596 // go to the LRU list because it may be pretty heavy with 16597 // UI stuff. We'll tag it with a label just to help 16598 // debug and understand what is going on. 16599 if (adj > clientAdj) { 16600 adjType = "cch-bound-ui-services"; 16601 } 16602 app.cached = false; 16603 clientAdj = adj; 16604 clientProcState = procState; 16605 } else { 16606 if (now >= (s.lastActivity 16607 + ActiveServices.MAX_SERVICE_INACTIVITY)) { 16608 // This service has not seen activity within 16609 // recent memory, so allow it to drop to the 16610 // LRU list if there is no other reason to keep 16611 // it around. We'll also tag it with a label just 16612 // to help debug and undertand what is going on. 16613 if (adj > clientAdj) { 16614 adjType = "cch-bound-services"; 16615 } 16616 clientAdj = adj; 16617 } 16618 } 16619 } 16620 if (adj > clientAdj) { 16621 // If this process has recently shown UI, and 16622 // the process that is binding to it is less 16623 // important than being visible, then we don't 16624 // care about the binding as much as we care 16625 // about letting this process get into the LRU 16626 // list to be killed and restarted if needed for 16627 // memory. 16628 if (app.hasShownUi && app != mHomeProcess 16629 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16630 adjType = "cch-bound-ui-services"; 16631 } else { 16632 if ((cr.flags&(Context.BIND_ABOVE_CLIENT 16633 |Context.BIND_IMPORTANT)) != 0) { 16634 adj = clientAdj; 16635 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0 16636 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ 16637 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16638 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16639 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) { 16640 adj = clientAdj; 16641 } else { 16642 if (adj > ProcessList.VISIBLE_APP_ADJ) { 16643 adj = ProcessList.VISIBLE_APP_ADJ; 16644 } 16645 } 16646 if (!client.cached) { 16647 app.cached = false; 16648 } 16649 adjType = "service"; 16650 } 16651 } 16652 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 16653 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 16654 schedGroup = Process.THREAD_GROUP_DEFAULT; 16655 } 16656 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 16657 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 16658 // Special handling of clients who are in the top state. 16659 // We *may* want to consider this process to be in the 16660 // top state as well, but only if there is not another 16661 // reason for it to be running. Being on the top is a 16662 // special state, meaning you are specifically running 16663 // for the current top app. If the process is already 16664 // running in the background for some other reason, it 16665 // is more important to continue considering it to be 16666 // in the background state. 16667 mayBeTop = true; 16668 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16669 } else { 16670 // Special handling for above-top states (persistent 16671 // processes). These should not bring the current process 16672 // into the top state, since they are not on top. Instead 16673 // give them the best state after that. 16674 clientProcState = 16675 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16676 } 16677 } 16678 } else { 16679 if (clientProcState < 16680 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 16681 clientProcState = 16682 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 16683 } 16684 } 16685 if (procState > clientProcState) { 16686 procState = clientProcState; 16687 } 16688 if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16689 && (cr.flags&Context.BIND_SHOWING_UI) != 0) { 16690 app.pendingUiClean = true; 16691 } 16692 if (adjType != null) { 16693 app.adjType = adjType; 16694 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16695 .REASON_SERVICE_IN_USE; 16696 app.adjSource = cr.binding.client; 16697 app.adjSourceProcState = clientProcState; 16698 app.adjTarget = s.name; 16699 } 16700 } 16701 if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 16702 app.treatLikeActivity = true; 16703 } 16704 final ActivityRecord a = cr.activity; 16705 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) { 16706 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ && 16707 (a.visible || a.state == ActivityState.RESUMED 16708 || a.state == ActivityState.PAUSING)) { 16709 adj = ProcessList.FOREGROUND_APP_ADJ; 16710 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 16711 schedGroup = Process.THREAD_GROUP_DEFAULT; 16712 } 16713 app.cached = false; 16714 app.adjType = "service"; 16715 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16716 .REASON_SERVICE_IN_USE; 16717 app.adjSource = a; 16718 app.adjSourceProcState = procState; 16719 app.adjTarget = s.name; 16720 } 16721 } 16722 } 16723 } 16724 } 16725 16726 for (int provi = app.pubProviders.size()-1; 16727 provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16728 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16729 || procState > ActivityManager.PROCESS_STATE_TOP); 16730 provi--) { 16731 ContentProviderRecord cpr = app.pubProviders.valueAt(provi); 16732 for (int i = cpr.connections.size()-1; 16733 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16734 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16735 || procState > ActivityManager.PROCESS_STATE_TOP); 16736 i--) { 16737 ContentProviderConnection conn = cpr.connections.get(i); 16738 ProcessRecord client = conn.client; 16739 if (client == app) { 16740 // Being our own client is not interesting. 16741 continue; 16742 } 16743 int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now); 16744 int clientProcState = client.curProcState; 16745 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16746 // If the other app is cached for any reason, for purposes here 16747 // we are going to consider it empty. 16748 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16749 } 16750 if (adj > clientAdj) { 16751 if (app.hasShownUi && app != mHomeProcess 16752 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16753 app.adjType = "cch-ui-provider"; 16754 } else { 16755 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ 16756 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ; 16757 app.adjType = "provider"; 16758 } 16759 app.cached &= client.cached; 16760 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16761 .REASON_PROVIDER_IN_USE; 16762 app.adjSource = client; 16763 app.adjSourceProcState = clientProcState; 16764 app.adjTarget = cpr.name; 16765 } 16766 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 16767 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 16768 // Special handling of clients who are in the top state. 16769 // We *may* want to consider this process to be in the 16770 // top state as well, but only if there is not another 16771 // reason for it to be running. Being on the top is a 16772 // special state, meaning you are specifically running 16773 // for the current top app. If the process is already 16774 // running in the background for some other reason, it 16775 // is more important to continue considering it to be 16776 // in the background state. 16777 mayBeTop = true; 16778 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16779 } else { 16780 // Special handling for above-top states (persistent 16781 // processes). These should not bring the current process 16782 // into the top state, since they are not on top. Instead 16783 // give them the best state after that. 16784 clientProcState = 16785 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16786 } 16787 } 16788 if (procState > clientProcState) { 16789 procState = clientProcState; 16790 } 16791 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 16792 schedGroup = Process.THREAD_GROUP_DEFAULT; 16793 } 16794 } 16795 // If the provider has external (non-framework) process 16796 // dependencies, ensure that its adjustment is at least 16797 // FOREGROUND_APP_ADJ. 16798 if (cpr.hasExternalProcessHandles()) { 16799 if (adj > ProcessList.FOREGROUND_APP_ADJ) { 16800 adj = ProcessList.FOREGROUND_APP_ADJ; 16801 schedGroup = Process.THREAD_GROUP_DEFAULT; 16802 app.cached = false; 16803 app.adjType = "provider"; 16804 app.adjTarget = cpr.name; 16805 } 16806 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 16807 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16808 } 16809 } 16810 } 16811 16812 if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) { 16813 // A client of one of our services or providers is in the top state. We 16814 // *may* want to be in the top state, but not if we are already running in 16815 // the background for some other reason. For the decision here, we are going 16816 // to pick out a few specific states that we want to remain in when a client 16817 // is top (states that tend to be longer-term) and otherwise allow it to go 16818 // to the top state. 16819 switch (procState) { 16820 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 16821 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 16822 case ActivityManager.PROCESS_STATE_SERVICE: 16823 // These all are longer-term states, so pull them up to the top 16824 // of the background states, but not all the way to the top state. 16825 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16826 break; 16827 default: 16828 // Otherwise, top is a better choice, so take it. 16829 procState = ActivityManager.PROCESS_STATE_TOP; 16830 break; 16831 } 16832 } 16833 16834 if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 16835 if (app.hasClientActivities) { 16836 // This is a cached process, but with client activities. Mark it so. 16837 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT; 16838 app.adjType = "cch-client-act"; 16839 } else if (app.treatLikeActivity) { 16840 // This is a cached process, but somebody wants us to treat it like it has 16841 // an activity, okay! 16842 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 16843 app.adjType = "cch-as-act"; 16844 } 16845 } 16846 16847 if (adj == ProcessList.SERVICE_ADJ) { 16848 if (doingAll) { 16849 app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3); 16850 mNewNumServiceProcs++; 16851 //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb); 16852 if (!app.serviceb) { 16853 // This service isn't far enough down on the LRU list to 16854 // normally be a B service, but if we are low on RAM and it 16855 // is large we want to force it down since we would prefer to 16856 // keep launcher over it. 16857 if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 16858 && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) { 16859 app.serviceHighRam = true; 16860 app.serviceb = true; 16861 //Slog.i(TAG, "ADJ " + app + " high ram!"); 16862 } else { 16863 mNewNumAServiceProcs++; 16864 //Slog.i(TAG, "ADJ " + app + " not high ram!"); 16865 } 16866 } else { 16867 app.serviceHighRam = false; 16868 } 16869 } 16870 if (app.serviceb) { 16871 adj = ProcessList.SERVICE_B_ADJ; 16872 } 16873 } 16874 16875 app.curRawAdj = adj; 16876 16877 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid + 16878 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj); 16879 if (adj > app.maxAdj) { 16880 adj = app.maxAdj; 16881 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 16882 schedGroup = Process.THREAD_GROUP_DEFAULT; 16883 } 16884 } 16885 16886 // Do final modification to adj. Everything we do between here and applying 16887 // the final setAdj must be done in this function, because we will also use 16888 // it when computing the final cached adj later. Note that we don't need to 16889 // worry about this for max adj above, since max adj will always be used to 16890 // keep it out of the cached vaues. 16891 app.curAdj = app.modifyRawOomAdj(adj); 16892 app.curSchedGroup = schedGroup; 16893 app.curProcState = procState; 16894 app.foregroundActivities = foregroundActivities; 16895 16896 return app.curRawAdj; 16897 } 16898 16899 /** 16900 * Schedule PSS collection of a process. 16901 */ 16902 void requestPssLocked(ProcessRecord proc, int procState) { 16903 if (mPendingPssProcesses.contains(proc)) { 16904 return; 16905 } 16906 if (mPendingPssProcesses.size() == 0) { 16907 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16908 } 16909 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of: " + proc); 16910 proc.pssProcState = procState; 16911 mPendingPssProcesses.add(proc); 16912 } 16913 16914 /** 16915 * Schedule PSS collection of all processes. 16916 */ 16917 void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) { 16918 if (!always) { 16919 if (now < (mLastFullPssTime + 16920 (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) { 16921 return; 16922 } 16923 } 16924 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of all procs! memLowered=" + memLowered); 16925 mLastFullPssTime = now; 16926 mFullPssPending = true; 16927 mPendingPssProcesses.ensureCapacity(mLruProcesses.size()); 16928 mPendingPssProcesses.clear(); 16929 for (int i=mLruProcesses.size()-1; i>=0; i--) { 16930 ProcessRecord app = mLruProcesses.get(i); 16931 if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) { 16932 app.pssProcState = app.setProcState; 16933 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 16934 isSleeping(), now); 16935 mPendingPssProcesses.add(app); 16936 } 16937 } 16938 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16939 } 16940 16941 /** 16942 * Ask a given process to GC right now. 16943 */ 16944 final void performAppGcLocked(ProcessRecord app) { 16945 try { 16946 app.lastRequestedGc = SystemClock.uptimeMillis(); 16947 if (app.thread != null) { 16948 if (app.reportLowMemory) { 16949 app.reportLowMemory = false; 16950 app.thread.scheduleLowMemory(); 16951 } else { 16952 app.thread.processInBackground(); 16953 } 16954 } 16955 } catch (Exception e) { 16956 // whatever. 16957 } 16958 } 16959 16960 /** 16961 * Returns true if things are idle enough to perform GCs. 16962 */ 16963 private final boolean canGcNowLocked() { 16964 boolean processingBroadcasts = false; 16965 for (BroadcastQueue q : mBroadcastQueues) { 16966 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) { 16967 processingBroadcasts = true; 16968 } 16969 } 16970 return !processingBroadcasts 16971 && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle()); 16972 } 16973 16974 /** 16975 * Perform GCs on all processes that are waiting for it, but only 16976 * if things are idle. 16977 */ 16978 final void performAppGcsLocked() { 16979 final int N = mProcessesToGc.size(); 16980 if (N <= 0) { 16981 return; 16982 } 16983 if (canGcNowLocked()) { 16984 while (mProcessesToGc.size() > 0) { 16985 ProcessRecord proc = mProcessesToGc.remove(0); 16986 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) { 16987 if ((proc.lastRequestedGc+GC_MIN_INTERVAL) 16988 <= SystemClock.uptimeMillis()) { 16989 // To avoid spamming the system, we will GC processes one 16990 // at a time, waiting a few seconds between each. 16991 performAppGcLocked(proc); 16992 scheduleAppGcsLocked(); 16993 return; 16994 } else { 16995 // It hasn't been long enough since we last GCed this 16996 // process... put it in the list to wait for its time. 16997 addProcessToGcListLocked(proc); 16998 break; 16999 } 17000 } 17001 } 17002 17003 scheduleAppGcsLocked(); 17004 } 17005 } 17006 17007 /** 17008 * If all looks good, perform GCs on all processes waiting for them. 17009 */ 17010 final void performAppGcsIfAppropriateLocked() { 17011 if (canGcNowLocked()) { 17012 performAppGcsLocked(); 17013 return; 17014 } 17015 // Still not idle, wait some more. 17016 scheduleAppGcsLocked(); 17017 } 17018 17019 /** 17020 * Schedule the execution of all pending app GCs. 17021 */ 17022 final void scheduleAppGcsLocked() { 17023 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG); 17024 17025 if (mProcessesToGc.size() > 0) { 17026 // Schedule a GC for the time to the next process. 17027 ProcessRecord proc = mProcessesToGc.get(0); 17028 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG); 17029 17030 long when = proc.lastRequestedGc + GC_MIN_INTERVAL; 17031 long now = SystemClock.uptimeMillis(); 17032 if (when < (now+GC_TIMEOUT)) { 17033 when = now + GC_TIMEOUT; 17034 } 17035 mHandler.sendMessageAtTime(msg, when); 17036 } 17037 } 17038 17039 /** 17040 * Add a process to the array of processes waiting to be GCed. Keeps the 17041 * list in sorted order by the last GC time. The process can't already be 17042 * on the list. 17043 */ 17044 final void addProcessToGcListLocked(ProcessRecord proc) { 17045 boolean added = false; 17046 for (int i=mProcessesToGc.size()-1; i>=0; i--) { 17047 if (mProcessesToGc.get(i).lastRequestedGc < 17048 proc.lastRequestedGc) { 17049 added = true; 17050 mProcessesToGc.add(i+1, proc); 17051 break; 17052 } 17053 } 17054 if (!added) { 17055 mProcessesToGc.add(0, proc); 17056 } 17057 } 17058 17059 /** 17060 * Set up to ask a process to GC itself. This will either do it 17061 * immediately, or put it on the list of processes to gc the next 17062 * time things are idle. 17063 */ 17064 final void scheduleAppGcLocked(ProcessRecord app) { 17065 long now = SystemClock.uptimeMillis(); 17066 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) { 17067 return; 17068 } 17069 if (!mProcessesToGc.contains(app)) { 17070 addProcessToGcListLocked(app); 17071 scheduleAppGcsLocked(); 17072 } 17073 } 17074 17075 final void checkExcessivePowerUsageLocked(boolean doKills) { 17076 updateCpuStatsNow(); 17077 17078 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 17079 boolean doWakeKills = doKills; 17080 boolean doCpuKills = doKills; 17081 if (mLastPowerCheckRealtime == 0) { 17082 doWakeKills = false; 17083 } 17084 if (mLastPowerCheckUptime == 0) { 17085 doCpuKills = false; 17086 } 17087 if (stats.isScreenOn()) { 17088 doWakeKills = false; 17089 } 17090 final long curRealtime = SystemClock.elapsedRealtime(); 17091 final long realtimeSince = curRealtime - mLastPowerCheckRealtime; 17092 final long curUptime = SystemClock.uptimeMillis(); 17093 final long uptimeSince = curUptime - mLastPowerCheckUptime; 17094 mLastPowerCheckRealtime = curRealtime; 17095 mLastPowerCheckUptime = curUptime; 17096 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) { 17097 doWakeKills = false; 17098 } 17099 if (uptimeSince < CPU_MIN_CHECK_DURATION) { 17100 doCpuKills = false; 17101 } 17102 int i = mLruProcesses.size(); 17103 while (i > 0) { 17104 i--; 17105 ProcessRecord app = mLruProcesses.get(i); 17106 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 17107 long wtime; 17108 synchronized (stats) { 17109 wtime = stats.getProcessWakeTime(app.info.uid, 17110 app.pid, curRealtime); 17111 } 17112 long wtimeUsed = wtime - app.lastWakeTime; 17113 long cputimeUsed = app.curCpuTime - app.lastCpuTime; 17114 if (DEBUG_POWER) { 17115 StringBuilder sb = new StringBuilder(128); 17116 sb.append("Wake for "); 17117 app.toShortString(sb); 17118 sb.append(": over "); 17119 TimeUtils.formatDuration(realtimeSince, sb); 17120 sb.append(" used "); 17121 TimeUtils.formatDuration(wtimeUsed, sb); 17122 sb.append(" ("); 17123 sb.append((wtimeUsed*100)/realtimeSince); 17124 sb.append("%)"); 17125 Slog.i(TAG, sb.toString()); 17126 sb.setLength(0); 17127 sb.append("CPU for "); 17128 app.toShortString(sb); 17129 sb.append(": over "); 17130 TimeUtils.formatDuration(uptimeSince, sb); 17131 sb.append(" used "); 17132 TimeUtils.formatDuration(cputimeUsed, sb); 17133 sb.append(" ("); 17134 sb.append((cputimeUsed*100)/uptimeSince); 17135 sb.append("%)"); 17136 Slog.i(TAG, sb.toString()); 17137 } 17138 // If a process has held a wake lock for more 17139 // than 50% of the time during this period, 17140 // that sounds bad. Kill! 17141 if (doWakeKills && realtimeSince > 0 17142 && ((wtimeUsed*100)/realtimeSince) >= 50) { 17143 synchronized (stats) { 17144 stats.reportExcessiveWakeLocked(app.info.uid, app.processName, 17145 realtimeSince, wtimeUsed); 17146 } 17147 app.kill("excessive wake held " + wtimeUsed + " during " + realtimeSince, true); 17148 app.baseProcessTracker.reportExcessiveWake(app.pkgList); 17149 } else if (doCpuKills && uptimeSince > 0 17150 && ((cputimeUsed*100)/uptimeSince) >= 25) { 17151 synchronized (stats) { 17152 stats.reportExcessiveCpuLocked(app.info.uid, app.processName, 17153 uptimeSince, cputimeUsed); 17154 } 17155 app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince, true); 17156 app.baseProcessTracker.reportExcessiveCpu(app.pkgList); 17157 } else { 17158 app.lastWakeTime = wtime; 17159 app.lastCpuTime = app.curCpuTime; 17160 } 17161 } 17162 } 17163 } 17164 17165 private final boolean applyOomAdjLocked(ProcessRecord app, 17166 ProcessRecord TOP_APP, boolean doingAll, long now) { 17167 boolean success = true; 17168 17169 if (app.curRawAdj != app.setRawAdj) { 17170 app.setRawAdj = app.curRawAdj; 17171 } 17172 17173 int changes = 0; 17174 17175 if (app.curAdj != app.setAdj) { 17176 ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj); 17177 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v( 17178 TAG, "Set " + app.pid + " " + app.processName + 17179 " adj " + app.curAdj + ": " + app.adjType); 17180 app.setAdj = app.curAdj; 17181 } 17182 17183 if (app.setSchedGroup != app.curSchedGroup) { 17184 app.setSchedGroup = app.curSchedGroup; 17185 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17186 "Setting process group of " + app.processName 17187 + " to " + app.curSchedGroup); 17188 if (app.waitingToKill != null && 17189 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 17190 app.kill(app.waitingToKill, true); 17191 success = false; 17192 } else { 17193 if (true) { 17194 long oldId = Binder.clearCallingIdentity(); 17195 try { 17196 Process.setProcessGroup(app.pid, app.curSchedGroup); 17197 } catch (Exception e) { 17198 Slog.w(TAG, "Failed setting process group of " + app.pid 17199 + " to " + app.curSchedGroup); 17200 e.printStackTrace(); 17201 } finally { 17202 Binder.restoreCallingIdentity(oldId); 17203 } 17204 } else { 17205 if (app.thread != null) { 17206 try { 17207 app.thread.setSchedulingGroup(app.curSchedGroup); 17208 } catch (RemoteException e) { 17209 } 17210 } 17211 } 17212 Process.setSwappiness(app.pid, 17213 app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE); 17214 } 17215 } 17216 if (app.repForegroundActivities != app.foregroundActivities) { 17217 app.repForegroundActivities = app.foregroundActivities; 17218 changes |= ProcessChangeItem.CHANGE_ACTIVITIES; 17219 } 17220 if (app.repProcState != app.curProcState) { 17221 app.repProcState = app.curProcState; 17222 changes |= ProcessChangeItem.CHANGE_PROCESS_STATE; 17223 if (app.thread != null) { 17224 try { 17225 if (false) { 17226 //RuntimeException h = new RuntimeException("here"); 17227 Slog.i(TAG, "Sending new process state " + app.repProcState 17228 + " to " + app /*, h*/); 17229 } 17230 app.thread.setProcessState(app.repProcState); 17231 } catch (RemoteException e) { 17232 } 17233 } 17234 } 17235 if (app.setProcState < 0 || ProcessList.procStatesDifferForMem(app.curProcState, 17236 app.setProcState)) { 17237 app.lastStateTime = now; 17238 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 17239 isSleeping(), now); 17240 if (DEBUG_PSS) Slog.d(TAG, "Process state change from " 17241 + ProcessList.makeProcStateString(app.setProcState) + " to " 17242 + ProcessList.makeProcStateString(app.curProcState) + " next pss in " 17243 + (app.nextPssTime-now) + ": " + app); 17244 } else { 17245 if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL) 17246 && now > (app.lastStateTime+ProcessList.PSS_MIN_TIME_FROM_STATE_CHANGE))) { 17247 requestPssLocked(app, app.setProcState); 17248 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false, 17249 isSleeping(), now); 17250 } else if (false && DEBUG_PSS) { 17251 Slog.d(TAG, "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now)); 17252 } 17253 } 17254 if (app.setProcState != app.curProcState) { 17255 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17256 "Proc state change of " + app.processName 17257 + " to " + app.curProcState); 17258 boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE; 17259 boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE; 17260 if (setImportant && !curImportant) { 17261 // This app is no longer something we consider important enough to allow to 17262 // use arbitrary amounts of battery power. Note 17263 // its current wake lock time to later know to kill it if 17264 // it is not behaving well. 17265 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 17266 synchronized (stats) { 17267 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid, 17268 app.pid, SystemClock.elapsedRealtime()); 17269 } 17270 app.lastCpuTime = app.curCpuTime; 17271 17272 } 17273 app.setProcState = app.curProcState; 17274 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 17275 app.notCachedSinceIdle = false; 17276 } 17277 if (!doingAll) { 17278 setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now); 17279 } else { 17280 app.procStateChanged = true; 17281 } 17282 } 17283 17284 if (changes != 0) { 17285 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes); 17286 int i = mPendingProcessChanges.size()-1; 17287 ProcessChangeItem item = null; 17288 while (i >= 0) { 17289 item = mPendingProcessChanges.get(i); 17290 if (item.pid == app.pid) { 17291 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item); 17292 break; 17293 } 17294 i--; 17295 } 17296 if (i < 0) { 17297 // No existing item in pending changes; need a new one. 17298 final int NA = mAvailProcessChanges.size(); 17299 if (NA > 0) { 17300 item = mAvailProcessChanges.remove(NA-1); 17301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item); 17302 } else { 17303 item = new ProcessChangeItem(); 17304 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item); 17305 } 17306 item.changes = 0; 17307 item.pid = app.pid; 17308 item.uid = app.info.uid; 17309 if (mPendingProcessChanges.size() == 0) { 17310 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, 17311 "*** Enqueueing dispatch processes changed!"); 17312 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget(); 17313 } 17314 mPendingProcessChanges.add(item); 17315 } 17316 item.changes |= changes; 17317 item.processState = app.repProcState; 17318 item.foregroundActivities = app.repForegroundActivities; 17319 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item " 17320 + Integer.toHexString(System.identityHashCode(item)) 17321 + " " + app.toShortString() + ": changes=" + item.changes 17322 + " procState=" + item.processState 17323 + " foreground=" + item.foregroundActivities 17324 + " type=" + app.adjType + " source=" + app.adjSource 17325 + " target=" + app.adjTarget); 17326 } 17327 17328 return success; 17329 } 17330 17331 private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) { 17332 if (proc.thread != null) { 17333 if (proc.baseProcessTracker != null) { 17334 proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList); 17335 } 17336 if (proc.repProcState >= 0) { 17337 mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid, 17338 proc.repProcState); 17339 } 17340 } 17341 } 17342 17343 private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj, 17344 ProcessRecord TOP_APP, boolean doingAll, long now) { 17345 if (app.thread == null) { 17346 return false; 17347 } 17348 17349 computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now); 17350 17351 return applyOomAdjLocked(app, TOP_APP, doingAll, now); 17352 } 17353 17354 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 17355 boolean oomAdj) { 17356 if (isForeground != proc.foregroundServices) { 17357 proc.foregroundServices = isForeground; 17358 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 17359 proc.info.uid); 17360 if (isForeground) { 17361 if (curProcs == null) { 17362 curProcs = new ArrayList<ProcessRecord>(); 17363 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 17364 } 17365 if (!curProcs.contains(proc)) { 17366 curProcs.add(proc); 17367 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 17368 proc.info.packageName, proc.info.uid); 17369 } 17370 } else { 17371 if (curProcs != null) { 17372 if (curProcs.remove(proc)) { 17373 mBatteryStatsService.noteEvent( 17374 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 17375 proc.info.packageName, proc.info.uid); 17376 if (curProcs.size() <= 0) { 17377 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 17378 } 17379 } 17380 } 17381 } 17382 if (oomAdj) { 17383 updateOomAdjLocked(); 17384 } 17385 } 17386 } 17387 17388 private final ActivityRecord resumedAppLocked() { 17389 ActivityRecord act = mStackSupervisor.resumedAppLocked(); 17390 String pkg; 17391 int uid; 17392 if (act != null) { 17393 pkg = act.packageName; 17394 uid = act.info.applicationInfo.uid; 17395 } else { 17396 pkg = null; 17397 uid = -1; 17398 } 17399 // Has the UID or resumed package name changed? 17400 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 17401 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 17402 if (mCurResumedPackage != null) { 17403 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 17404 mCurResumedPackage, mCurResumedUid); 17405 } 17406 mCurResumedPackage = pkg; 17407 mCurResumedUid = uid; 17408 if (mCurResumedPackage != null) { 17409 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 17410 mCurResumedPackage, mCurResumedUid); 17411 } 17412 } 17413 return act; 17414 } 17415 17416 final boolean updateOomAdjLocked(ProcessRecord app) { 17417 final ActivityRecord TOP_ACT = resumedAppLocked(); 17418 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 17419 final boolean wasCached = app.cached; 17420 17421 mAdjSeq++; 17422 17423 // This is the desired cached adjusment we want to tell it to use. 17424 // If our app is currently cached, we know it, and that is it. Otherwise, 17425 // we don't know it yet, and it needs to now be cached we will then 17426 // need to do a complete oom adj. 17427 final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ 17428 ? app.curRawAdj : ProcessList.UNKNOWN_ADJ; 17429 boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false, 17430 SystemClock.uptimeMillis()); 17431 if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) { 17432 // Changed to/from cached state, so apps after it in the LRU 17433 // list may also be changed. 17434 updateOomAdjLocked(); 17435 } 17436 return success; 17437 } 17438 17439 final void updateOomAdjLocked() { 17440 final ActivityRecord TOP_ACT = resumedAppLocked(); 17441 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 17442 final long now = SystemClock.uptimeMillis(); 17443 final long oldTime = now - ProcessList.MAX_EMPTY_TIME; 17444 final int N = mLruProcesses.size(); 17445 17446 if (false) { 17447 RuntimeException e = new RuntimeException(); 17448 e.fillInStackTrace(); 17449 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e); 17450 } 17451 17452 mAdjSeq++; 17453 mNewNumServiceProcs = 0; 17454 mNewNumAServiceProcs = 0; 17455 17456 final int emptyProcessLimit; 17457 final int cachedProcessLimit; 17458 if (mProcessLimit <= 0) { 17459 emptyProcessLimit = cachedProcessLimit = 0; 17460 } else if (mProcessLimit == 1) { 17461 emptyProcessLimit = 1; 17462 cachedProcessLimit = 0; 17463 } else { 17464 emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit); 17465 cachedProcessLimit = mProcessLimit - emptyProcessLimit; 17466 } 17467 17468 // Let's determine how many processes we have running vs. 17469 // how many slots we have for background processes; we may want 17470 // to put multiple processes in a slot of there are enough of 17471 // them. 17472 int numSlots = (ProcessList.CACHED_APP_MAX_ADJ 17473 - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2; 17474 int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs; 17475 if (numEmptyProcs > cachedProcessLimit) { 17476 // If there are more empty processes than our limit on cached 17477 // processes, then use the cached process limit for the factor. 17478 // This ensures that the really old empty processes get pushed 17479 // down to the bottom, so if we are running low on memory we will 17480 // have a better chance at keeping around more cached processes 17481 // instead of a gazillion empty processes. 17482 numEmptyProcs = cachedProcessLimit; 17483 } 17484 int emptyFactor = numEmptyProcs/numSlots; 17485 if (emptyFactor < 1) emptyFactor = 1; 17486 int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots; 17487 if (cachedFactor < 1) cachedFactor = 1; 17488 int stepCached = 0; 17489 int stepEmpty = 0; 17490 int numCached = 0; 17491 int numEmpty = 0; 17492 int numTrimming = 0; 17493 17494 mNumNonCachedProcs = 0; 17495 mNumCachedHiddenProcs = 0; 17496 17497 // First update the OOM adjustment for each of the 17498 // application processes based on their current state. 17499 int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ; 17500 int nextCachedAdj = curCachedAdj+1; 17501 int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ; 17502 int nextEmptyAdj = curEmptyAdj+2; 17503 for (int i=N-1; i>=0; i--) { 17504 ProcessRecord app = mLruProcesses.get(i); 17505 if (!app.killedByAm && app.thread != null) { 17506 app.procStateChanged = false; 17507 computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now); 17508 17509 // If we haven't yet assigned the final cached adj 17510 // to the process, do that now. 17511 if (app.curAdj >= ProcessList.UNKNOWN_ADJ) { 17512 switch (app.curProcState) { 17513 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 17514 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 17515 // This process is a cached process holding activities... 17516 // assign it the next cached value for that type, and then 17517 // step that cached level. 17518 app.curRawAdj = curCachedAdj; 17519 app.curAdj = app.modifyRawOomAdj(curCachedAdj); 17520 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning activity LRU #" + i 17521 + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj 17522 + ")"); 17523 if (curCachedAdj != nextCachedAdj) { 17524 stepCached++; 17525 if (stepCached >= cachedFactor) { 17526 stepCached = 0; 17527 curCachedAdj = nextCachedAdj; 17528 nextCachedAdj += 2; 17529 if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) { 17530 nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ; 17531 } 17532 } 17533 } 17534 break; 17535 default: 17536 // For everything else, assign next empty cached process 17537 // level and bump that up. Note that this means that 17538 // long-running services that have dropped down to the 17539 // cached level will be treated as empty (since their process 17540 // state is still as a service), which is what we want. 17541 app.curRawAdj = curEmptyAdj; 17542 app.curAdj = app.modifyRawOomAdj(curEmptyAdj); 17543 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning empty LRU #" + i 17544 + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj 17545 + ")"); 17546 if (curEmptyAdj != nextEmptyAdj) { 17547 stepEmpty++; 17548 if (stepEmpty >= emptyFactor) { 17549 stepEmpty = 0; 17550 curEmptyAdj = nextEmptyAdj; 17551 nextEmptyAdj += 2; 17552 if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) { 17553 nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ; 17554 } 17555 } 17556 } 17557 break; 17558 } 17559 } 17560 17561 applyOomAdjLocked(app, TOP_APP, true, now); 17562 17563 // Count the number of process types. 17564 switch (app.curProcState) { 17565 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 17566 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 17567 mNumCachedHiddenProcs++; 17568 numCached++; 17569 if (numCached > cachedProcessLimit) { 17570 app.kill("cached #" + numCached, true); 17571 } 17572 break; 17573 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 17574 if (numEmpty > ProcessList.TRIM_EMPTY_APPS 17575 && app.lastActivityTime < oldTime) { 17576 app.kill("empty for " 17577 + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime) 17578 / 1000) + "s", true); 17579 } else { 17580 numEmpty++; 17581 if (numEmpty > emptyProcessLimit) { 17582 app.kill("empty #" + numEmpty, true); 17583 } 17584 } 17585 break; 17586 default: 17587 mNumNonCachedProcs++; 17588 break; 17589 } 17590 17591 if (app.isolated && app.services.size() <= 0) { 17592 // If this is an isolated process, and there are no 17593 // services running in it, then the process is no longer 17594 // needed. We agressively kill these because we can by 17595 // definition not re-use the same process again, and it is 17596 // good to avoid having whatever code was running in them 17597 // left sitting around after no longer needed. 17598 app.kill("isolated not needed", true); 17599 } 17600 17601 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 17602 && !app.killedByAm) { 17603 numTrimming++; 17604 } 17605 } 17606 } 17607 17608 mNumServiceProcs = mNewNumServiceProcs; 17609 17610 // Now determine the memory trimming level of background processes. 17611 // Unfortunately we need to start at the back of the list to do this 17612 // properly. We only do this if the number of background apps we 17613 // are managing to keep around is less than half the maximum we desire; 17614 // if we are keeping a good number around, we'll let them use whatever 17615 // memory they want. 17616 final int numCachedAndEmpty = numCached + numEmpty; 17617 int memFactor; 17618 if (numCached <= ProcessList.TRIM_CACHED_APPS 17619 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) { 17620 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) { 17621 memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL; 17622 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) { 17623 memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW; 17624 } else { 17625 memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE; 17626 } 17627 } else { 17628 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 17629 } 17630 // We always allow the memory level to go up (better). We only allow it to go 17631 // down if we are in a state where that is allowed, *and* the total number of processes 17632 // has gone down since last time. 17633 if (DEBUG_OOM_ADJ) Slog.d(TAG, "oom: memFactor=" + memFactor + " last=" + mLastMemoryLevel 17634 + " allowLow=" + mAllowLowerMemLevel + " numProcs=" + mLruProcesses.size() 17635 + " last=" + mLastNumProcesses); 17636 if (memFactor > mLastMemoryLevel) { 17637 if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) { 17638 memFactor = mLastMemoryLevel; 17639 if (DEBUG_OOM_ADJ) Slog.d(TAG, "Keeping last mem factor!"); 17640 } 17641 } 17642 mLastMemoryLevel = memFactor; 17643 mLastNumProcesses = mLruProcesses.size(); 17644 boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now); 17645 final int trackerMemFactor = mProcessStats.getMemFactorLocked(); 17646 if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) { 17647 if (mLowRamStartTime == 0) { 17648 mLowRamStartTime = now; 17649 } 17650 int step = 0; 17651 int fgTrimLevel; 17652 switch (memFactor) { 17653 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 17654 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 17655 break; 17656 case ProcessStats.ADJ_MEM_FACTOR_LOW: 17657 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 17658 break; 17659 default: 17660 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 17661 break; 17662 } 17663 int factor = numTrimming/3; 17664 int minFactor = 2; 17665 if (mHomeProcess != null) minFactor++; 17666 if (mPreviousProcess != null) minFactor++; 17667 if (factor < minFactor) factor = minFactor; 17668 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 17669 for (int i=N-1; i>=0; i--) { 17670 ProcessRecord app = mLruProcesses.get(i); 17671 if (allChanged || app.procStateChanged) { 17672 setProcessTrackerStateLocked(app, trackerMemFactor, now); 17673 app.procStateChanged = false; 17674 } 17675 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 17676 && !app.killedByAm) { 17677 if (app.trimMemoryLevel < curLevel && app.thread != null) { 17678 try { 17679 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17680 "Trimming memory of " + app.processName 17681 + " to " + curLevel); 17682 app.thread.scheduleTrimMemory(curLevel); 17683 } catch (RemoteException e) { 17684 } 17685 if (false) { 17686 // For now we won't do this; our memory trimming seems 17687 // to be good enough at this point that destroying 17688 // activities causes more harm than good. 17689 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE 17690 && app != mHomeProcess && app != mPreviousProcess) { 17691 // Need to do this on its own message because the stack may not 17692 // be in a consistent state at this point. 17693 // For these apps we will also finish their activities 17694 // to help them free memory. 17695 mStackSupervisor.scheduleDestroyAllActivities(app, "trim"); 17696 } 17697 } 17698 } 17699 app.trimMemoryLevel = curLevel; 17700 step++; 17701 if (step >= factor) { 17702 step = 0; 17703 switch (curLevel) { 17704 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: 17705 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 17706 break; 17707 case ComponentCallbacks2.TRIM_MEMORY_MODERATE: 17708 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 17709 break; 17710 } 17711 } 17712 } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 17713 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND 17714 && app.thread != null) { 17715 try { 17716 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17717 "Trimming memory of heavy-weight " + app.processName 17718 + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 17719 app.thread.scheduleTrimMemory( 17720 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 17721 } catch (RemoteException e) { 17722 } 17723 } 17724 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 17725 } else { 17726 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 17727 || app.systemNoUi) && app.pendingUiClean) { 17728 // If this application is now in the background and it 17729 // had done UI, then give it the special trim level to 17730 // have it free UI resources. 17731 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 17732 if (app.trimMemoryLevel < level && app.thread != null) { 17733 try { 17734 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17735 "Trimming memory of bg-ui " + app.processName 17736 + " to " + level); 17737 app.thread.scheduleTrimMemory(level); 17738 } catch (RemoteException e) { 17739 } 17740 } 17741 app.pendingUiClean = false; 17742 } 17743 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) { 17744 try { 17745 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17746 "Trimming memory of fg " + app.processName 17747 + " to " + fgTrimLevel); 17748 app.thread.scheduleTrimMemory(fgTrimLevel); 17749 } catch (RemoteException e) { 17750 } 17751 } 17752 app.trimMemoryLevel = fgTrimLevel; 17753 } 17754 } 17755 } else { 17756 if (mLowRamStartTime != 0) { 17757 mLowRamTimeSinceLastIdle += now - mLowRamStartTime; 17758 mLowRamStartTime = 0; 17759 } 17760 for (int i=N-1; i>=0; i--) { 17761 ProcessRecord app = mLruProcesses.get(i); 17762 if (allChanged || app.procStateChanged) { 17763 setProcessTrackerStateLocked(app, trackerMemFactor, now); 17764 app.procStateChanged = false; 17765 } 17766 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 17767 || app.systemNoUi) && app.pendingUiClean) { 17768 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN 17769 && app.thread != null) { 17770 try { 17771 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17772 "Trimming memory of ui hidden " + app.processName 17773 + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 17774 app.thread.scheduleTrimMemory( 17775 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 17776 } catch (RemoteException e) { 17777 } 17778 } 17779 app.pendingUiClean = false; 17780 } 17781 app.trimMemoryLevel = 0; 17782 } 17783 } 17784 17785 if (mAlwaysFinishActivities) { 17786 // Need to do this on its own message because the stack may not 17787 // be in a consistent state at this point. 17788 mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish"); 17789 } 17790 17791 if (allChanged) { 17792 requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered()); 17793 } 17794 17795 if (mProcessStats.shouldWriteNowLocked(now)) { 17796 mHandler.post(new Runnable() { 17797 @Override public void run() { 17798 synchronized (ActivityManagerService.this) { 17799 mProcessStats.writeStateAsyncLocked(); 17800 } 17801 } 17802 }); 17803 } 17804 17805 if (DEBUG_OOM_ADJ) { 17806 Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms"); 17807 } 17808 } 17809 17810 final void trimApplications() { 17811 synchronized (this) { 17812 int i; 17813 17814 // First remove any unused application processes whose package 17815 // has been removed. 17816 for (i=mRemovedProcesses.size()-1; i>=0; i--) { 17817 final ProcessRecord app = mRemovedProcesses.get(i); 17818 if (app.activities.size() == 0 17819 && app.curReceiver == null && app.services.size() == 0) { 17820 Slog.i( 17821 TAG, "Exiting empty application process " 17822 + app.processName + " (" 17823 + (app.thread != null ? app.thread.asBinder() : null) 17824 + ")\n"); 17825 if (app.pid > 0 && app.pid != MY_PID) { 17826 app.kill("empty", false); 17827 } else { 17828 try { 17829 app.thread.scheduleExit(); 17830 } catch (Exception e) { 17831 // Ignore exceptions. 17832 } 17833 } 17834 cleanUpApplicationRecordLocked(app, false, true, -1); 17835 mRemovedProcesses.remove(i); 17836 17837 if (app.persistent) { 17838 addAppLocked(app.info, false, null /* ABI override */); 17839 } 17840 } 17841 } 17842 17843 // Now update the oom adj for all processes. 17844 updateOomAdjLocked(); 17845 } 17846 } 17847 17848 /** This method sends the specified signal to each of the persistent apps */ 17849 public void signalPersistentProcesses(int sig) throws RemoteException { 17850 if (sig != Process.SIGNAL_USR1) { 17851 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 17852 } 17853 17854 synchronized (this) { 17855 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 17856 != PackageManager.PERMISSION_GRANTED) { 17857 throw new SecurityException("Requires permission " 17858 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 17859 } 17860 17861 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 17862 ProcessRecord r = mLruProcesses.get(i); 17863 if (r.thread != null && r.persistent) { 17864 Process.sendSignal(r.pid, sig); 17865 } 17866 } 17867 } 17868 } 17869 17870 private void stopProfilerLocked(ProcessRecord proc, int profileType) { 17871 if (proc == null || proc == mProfileProc) { 17872 proc = mProfileProc; 17873 profileType = mProfileType; 17874 clearProfilerLocked(); 17875 } 17876 if (proc == null) { 17877 return; 17878 } 17879 try { 17880 proc.thread.profilerControl(false, null, profileType); 17881 } catch (RemoteException e) { 17882 throw new IllegalStateException("Process disappeared"); 17883 } 17884 } 17885 17886 private void clearProfilerLocked() { 17887 if (mProfileFd != null) { 17888 try { 17889 mProfileFd.close(); 17890 } catch (IOException e) { 17891 } 17892 } 17893 mProfileApp = null; 17894 mProfileProc = null; 17895 mProfileFile = null; 17896 mProfileType = 0; 17897 mAutoStopProfiler = false; 17898 mSamplingInterval = 0; 17899 } 17900 17901 public boolean profileControl(String process, int userId, boolean start, 17902 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 17903 17904 try { 17905 synchronized (this) { 17906 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17907 // its own permission. 17908 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17909 != PackageManager.PERMISSION_GRANTED) { 17910 throw new SecurityException("Requires permission " 17911 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17912 } 17913 17914 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 17915 throw new IllegalArgumentException("null profile info or fd"); 17916 } 17917 17918 ProcessRecord proc = null; 17919 if (process != null) { 17920 proc = findProcessLocked(process, userId, "profileControl"); 17921 } 17922 17923 if (start && (proc == null || proc.thread == null)) { 17924 throw new IllegalArgumentException("Unknown process: " + process); 17925 } 17926 17927 if (start) { 17928 stopProfilerLocked(null, 0); 17929 setProfileApp(proc.info, proc.processName, profilerInfo); 17930 mProfileProc = proc; 17931 mProfileType = profileType; 17932 ParcelFileDescriptor fd = profilerInfo.profileFd; 17933 try { 17934 fd = fd.dup(); 17935 } catch (IOException e) { 17936 fd = null; 17937 } 17938 profilerInfo.profileFd = fd; 17939 proc.thread.profilerControl(start, profilerInfo, profileType); 17940 fd = null; 17941 mProfileFd = null; 17942 } else { 17943 stopProfilerLocked(proc, profileType); 17944 if (profilerInfo != null && profilerInfo.profileFd != null) { 17945 try { 17946 profilerInfo.profileFd.close(); 17947 } catch (IOException e) { 17948 } 17949 } 17950 } 17951 17952 return true; 17953 } 17954 } catch (RemoteException e) { 17955 throw new IllegalStateException("Process disappeared"); 17956 } finally { 17957 if (profilerInfo != null && profilerInfo.profileFd != null) { 17958 try { 17959 profilerInfo.profileFd.close(); 17960 } catch (IOException e) { 17961 } 17962 } 17963 } 17964 } 17965 17966 private ProcessRecord findProcessLocked(String process, int userId, String callName) { 17967 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17968 userId, true, ALLOW_FULL_ONLY, callName, null); 17969 ProcessRecord proc = null; 17970 try { 17971 int pid = Integer.parseInt(process); 17972 synchronized (mPidsSelfLocked) { 17973 proc = mPidsSelfLocked.get(pid); 17974 } 17975 } catch (NumberFormatException e) { 17976 } 17977 17978 if (proc == null) { 17979 ArrayMap<String, SparseArray<ProcessRecord>> all 17980 = mProcessNames.getMap(); 17981 SparseArray<ProcessRecord> procs = all.get(process); 17982 if (procs != null && procs.size() > 0) { 17983 proc = procs.valueAt(0); 17984 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 17985 for (int i=1; i<procs.size(); i++) { 17986 ProcessRecord thisProc = procs.valueAt(i); 17987 if (thisProc.userId == userId) { 17988 proc = thisProc; 17989 break; 17990 } 17991 } 17992 } 17993 } 17994 } 17995 17996 return proc; 17997 } 17998 17999 public boolean dumpHeap(String process, int userId, boolean managed, 18000 String path, ParcelFileDescriptor fd) throws RemoteException { 18001 18002 try { 18003 synchronized (this) { 18004 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 18005 // its own permission (same as profileControl). 18006 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 18007 != PackageManager.PERMISSION_GRANTED) { 18008 throw new SecurityException("Requires permission " 18009 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 18010 } 18011 18012 if (fd == null) { 18013 throw new IllegalArgumentException("null fd"); 18014 } 18015 18016 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap"); 18017 if (proc == null || proc.thread == null) { 18018 throw new IllegalArgumentException("Unknown process: " + process); 18019 } 18020 18021 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 18022 if (!isDebuggable) { 18023 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 18024 throw new SecurityException("Process not debuggable: " + proc); 18025 } 18026 } 18027 18028 proc.thread.dumpHeap(managed, path, fd); 18029 fd = null; 18030 return true; 18031 } 18032 } catch (RemoteException e) { 18033 throw new IllegalStateException("Process disappeared"); 18034 } finally { 18035 if (fd != null) { 18036 try { 18037 fd.close(); 18038 } catch (IOException e) { 18039 } 18040 } 18041 } 18042 } 18043 18044 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ 18045 public void monitor() { 18046 synchronized (this) { } 18047 } 18048 18049 void onCoreSettingsChange(Bundle settings) { 18050 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 18051 ProcessRecord processRecord = mLruProcesses.get(i); 18052 try { 18053 if (processRecord.thread != null) { 18054 processRecord.thread.setCoreSettings(settings); 18055 } 18056 } catch (RemoteException re) { 18057 /* ignore */ 18058 } 18059 } 18060 } 18061 18062 // Multi-user methods 18063 18064 /** 18065 * Start user, if its not already running, but don't bring it to foreground. 18066 */ 18067 @Override 18068 public boolean startUserInBackground(final int userId) { 18069 return startUser(userId, /* foreground */ false); 18070 } 18071 18072 /** 18073 * Start user, if its not already running, and bring it to foreground. 18074 */ 18075 boolean startUserInForeground(final int userId, Dialog dlg) { 18076 boolean result = startUser(userId, /* foreground */ true); 18077 dlg.dismiss(); 18078 return result; 18079 } 18080 18081 /** 18082 * Refreshes the list of users related to the current user when either a 18083 * user switch happens or when a new related user is started in the 18084 * background. 18085 */ 18086 private void updateCurrentProfileIdsLocked() { 18087 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18088 mCurrentUserId, false /* enabledOnly */); 18089 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null 18090 for (int i = 0; i < currentProfileIds.length; i++) { 18091 currentProfileIds[i] = profiles.get(i).id; 18092 } 18093 mCurrentProfileIds = currentProfileIds; 18094 18095 synchronized (mUserProfileGroupIdsSelfLocked) { 18096 mUserProfileGroupIdsSelfLocked.clear(); 18097 final List<UserInfo> users = getUserManagerLocked().getUsers(false); 18098 for (int i = 0; i < users.size(); i++) { 18099 UserInfo user = users.get(i); 18100 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 18101 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId); 18102 } 18103 } 18104 } 18105 } 18106 18107 private Set getProfileIdsLocked(int userId) { 18108 Set userIds = new HashSet<Integer>(); 18109 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18110 userId, false /* enabledOnly */); 18111 for (UserInfo user : profiles) { 18112 userIds.add(Integer.valueOf(user.id)); 18113 } 18114 return userIds; 18115 } 18116 18117 @Override 18118 public boolean switchUser(final int userId) { 18119 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 18120 String userName; 18121 synchronized (this) { 18122 UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 18123 if (userInfo == null) { 18124 Slog.w(TAG, "No user info for user #" + userId); 18125 return false; 18126 } 18127 if (userInfo.isManagedProfile()) { 18128 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 18129 return false; 18130 } 18131 userName = userInfo.name; 18132 mTargetUserId = userId; 18133 } 18134 mHandler.removeMessages(START_USER_SWITCH_MSG); 18135 mHandler.sendMessage(mHandler.obtainMessage(START_USER_SWITCH_MSG, userId, 0, userName)); 18136 return true; 18137 } 18138 18139 private void showUserSwitchDialog(int userId, String userName) { 18140 // The dialog will show and then initiate the user switch by calling startUserInForeground 18141 Dialog d = new UserSwitchingDialog(this, mContext, userId, userName, 18142 true /* above system */); 18143 d.show(); 18144 } 18145 18146 private boolean startUser(final int userId, final boolean foreground) { 18147 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18148 != PackageManager.PERMISSION_GRANTED) { 18149 String msg = "Permission Denial: switchUser() from pid=" 18150 + Binder.getCallingPid() 18151 + ", uid=" + Binder.getCallingUid() 18152 + " requires " + INTERACT_ACROSS_USERS_FULL; 18153 Slog.w(TAG, msg); 18154 throw new SecurityException(msg); 18155 } 18156 18157 if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground); 18158 18159 final long ident = Binder.clearCallingIdentity(); 18160 try { 18161 synchronized (this) { 18162 final int oldUserId = mCurrentUserId; 18163 if (oldUserId == userId) { 18164 return true; 18165 } 18166 18167 mStackSupervisor.setLockTaskModeLocked(null, false); 18168 18169 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 18170 if (userInfo == null) { 18171 Slog.w(TAG, "No user info for user #" + userId); 18172 return false; 18173 } 18174 if (foreground && userInfo.isManagedProfile()) { 18175 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 18176 return false; 18177 } 18178 18179 if (foreground) { 18180 mWindowManager.startFreezingScreen(R.anim.screen_user_exit, 18181 R.anim.screen_user_enter); 18182 } 18183 18184 boolean needStart = false; 18185 18186 // If the user we are switching to is not currently started, then 18187 // we need to start it now. 18188 if (mStartedUsers.get(userId) == null) { 18189 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false)); 18190 updateStartedUserArrayLocked(); 18191 needStart = true; 18192 } 18193 18194 final Integer userIdInt = Integer.valueOf(userId); 18195 mUserLru.remove(userIdInt); 18196 mUserLru.add(userIdInt); 18197 18198 if (foreground) { 18199 mCurrentUserId = userId; 18200 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up 18201 updateCurrentProfileIdsLocked(); 18202 mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 18203 // Once the internal notion of the active user has switched, we lock the device 18204 // with the option to show the user switcher on the keyguard. 18205 mWindowManager.lockNow(null); 18206 } else { 18207 final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId); 18208 updateCurrentProfileIdsLocked(); 18209 mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 18210 mUserLru.remove(currentUserIdInt); 18211 mUserLru.add(currentUserIdInt); 18212 } 18213 18214 final UserStartedState uss = mStartedUsers.get(userId); 18215 18216 // Make sure user is in the started state. If it is currently 18217 // stopping, we need to knock that off. 18218 if (uss.mState == UserStartedState.STATE_STOPPING) { 18219 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 18220 // so we can just fairly silently bring the user back from 18221 // the almost-dead. 18222 uss.mState = UserStartedState.STATE_RUNNING; 18223 updateStartedUserArrayLocked(); 18224 needStart = true; 18225 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) { 18226 // This means ACTION_SHUTDOWN has been sent, so we will 18227 // need to treat this as a new boot of the user. 18228 uss.mState = UserStartedState.STATE_BOOTING; 18229 updateStartedUserArrayLocked(); 18230 needStart = true; 18231 } 18232 18233 if (uss.mState == UserStartedState.STATE_BOOTING) { 18234 // Booting up a new user, need to tell system services about it. 18235 // Note that this is on the same handler as scheduling of broadcasts, 18236 // which is important because it needs to go first. 18237 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0)); 18238 } 18239 18240 if (foreground) { 18241 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 18242 oldUserId)); 18243 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 18244 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 18245 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 18246 oldUserId, userId, uss)); 18247 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 18248 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 18249 } 18250 18251 if (needStart) { 18252 // Send USER_STARTED broadcast 18253 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 18254 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18255 | Intent.FLAG_RECEIVER_FOREGROUND); 18256 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18257 broadcastIntentLocked(null, null, intent, 18258 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18259 false, false, MY_PID, Process.SYSTEM_UID, userId); 18260 } 18261 18262 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) { 18263 if (userId != UserHandle.USER_OWNER) { 18264 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); 18265 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 18266 broadcastIntentLocked(null, null, intent, null, 18267 new IIntentReceiver.Stub() { 18268 public void performReceive(Intent intent, int resultCode, 18269 String data, Bundle extras, boolean ordered, 18270 boolean sticky, int sendingUser) { 18271 onUserInitialized(uss, foreground, oldUserId, userId); 18272 } 18273 }, 0, null, null, null, AppOpsManager.OP_NONE, 18274 true, false, MY_PID, Process.SYSTEM_UID, 18275 userId); 18276 uss.initializing = true; 18277 } else { 18278 getUserManagerLocked().makeInitialized(userInfo.id); 18279 } 18280 } 18281 18282 if (foreground) { 18283 if (!uss.initializing) { 18284 moveUserToForeground(uss, oldUserId, userId); 18285 } 18286 } else { 18287 mStackSupervisor.startBackgroundUserLocked(userId, uss); 18288 } 18289 18290 if (needStart) { 18291 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 18292 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18293 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18294 broadcastIntentLocked(null, null, intent, 18295 null, new IIntentReceiver.Stub() { 18296 @Override 18297 public void performReceive(Intent intent, int resultCode, String data, 18298 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 18299 throws RemoteException { 18300 } 18301 }, 0, null, null, 18302 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 18303 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18304 } 18305 } 18306 } finally { 18307 Binder.restoreCallingIdentity(ident); 18308 } 18309 18310 return true; 18311 } 18312 18313 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) { 18314 long ident = Binder.clearCallingIdentity(); 18315 try { 18316 Intent intent; 18317 if (oldUserId >= 0) { 18318 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user 18319 List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false); 18320 int count = profiles.size(); 18321 for (int i = 0; i < count; i++) { 18322 int profileUserId = profiles.get(i).id; 18323 intent = new Intent(Intent.ACTION_USER_BACKGROUND); 18324 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18325 | Intent.FLAG_RECEIVER_FOREGROUND); 18326 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 18327 broadcastIntentLocked(null, null, intent, 18328 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18329 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 18330 } 18331 } 18332 if (newUserId >= 0) { 18333 // Send USER_FOREGROUND broadcast to all profiles of the incoming user 18334 List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false); 18335 int count = profiles.size(); 18336 for (int i = 0; i < count; i++) { 18337 int profileUserId = profiles.get(i).id; 18338 intent = new Intent(Intent.ACTION_USER_FOREGROUND); 18339 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18340 | Intent.FLAG_RECEIVER_FOREGROUND); 18341 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 18342 broadcastIntentLocked(null, null, intent, 18343 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18344 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 18345 } 18346 intent = new Intent(Intent.ACTION_USER_SWITCHED); 18347 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18348 | Intent.FLAG_RECEIVER_FOREGROUND); 18349 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId); 18350 broadcastIntentLocked(null, null, intent, 18351 null, null, 0, null, null, 18352 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE, 18353 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18354 } 18355 } finally { 18356 Binder.restoreCallingIdentity(ident); 18357 } 18358 } 18359 18360 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId, 18361 final int newUserId) { 18362 final int N = mUserSwitchObservers.beginBroadcast(); 18363 if (N > 0) { 18364 final IRemoteCallback callback = new IRemoteCallback.Stub() { 18365 int mCount = 0; 18366 @Override 18367 public void sendResult(Bundle data) throws RemoteException { 18368 synchronized (ActivityManagerService.this) { 18369 if (mCurUserSwitchCallback == this) { 18370 mCount++; 18371 if (mCount == N) { 18372 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18373 } 18374 } 18375 } 18376 } 18377 }; 18378 synchronized (this) { 18379 uss.switching = true; 18380 mCurUserSwitchCallback = callback; 18381 } 18382 for (int i=0; i<N; i++) { 18383 try { 18384 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching( 18385 newUserId, callback); 18386 } catch (RemoteException e) { 18387 } 18388 } 18389 } else { 18390 synchronized (this) { 18391 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18392 } 18393 } 18394 mUserSwitchObservers.finishBroadcast(); 18395 } 18396 18397 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 18398 synchronized (this) { 18399 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId); 18400 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18401 } 18402 } 18403 18404 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) { 18405 mCurUserSwitchCallback = null; 18406 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 18407 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG, 18408 oldUserId, newUserId, uss)); 18409 } 18410 18411 void onUserInitialized(UserStartedState uss, boolean foreground, int oldUserId, int newUserId) { 18412 synchronized (this) { 18413 if (foreground) { 18414 moveUserToForeground(uss, oldUserId, newUserId); 18415 } 18416 } 18417 18418 completeSwitchAndInitalize(uss, newUserId, true, false); 18419 } 18420 18421 void moveUserToForeground(UserStartedState uss, int oldUserId, int newUserId) { 18422 boolean homeInFront = mStackSupervisor.switchUserLocked(newUserId, uss); 18423 if (homeInFront) { 18424 startHomeActivityLocked(newUserId); 18425 } else { 18426 mStackSupervisor.resumeTopActivitiesLocked(); 18427 } 18428 EventLogTags.writeAmSwitchUser(newUserId); 18429 getUserManagerLocked().userForeground(newUserId); 18430 sendUserSwitchBroadcastsLocked(oldUserId, newUserId); 18431 } 18432 18433 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 18434 completeSwitchAndInitalize(uss, newUserId, false, true); 18435 } 18436 18437 void completeSwitchAndInitalize(UserStartedState uss, int newUserId, 18438 boolean clearInitializing, boolean clearSwitching) { 18439 boolean unfrozen = false; 18440 synchronized (this) { 18441 if (clearInitializing) { 18442 uss.initializing = false; 18443 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier()); 18444 } 18445 if (clearSwitching) { 18446 uss.switching = false; 18447 } 18448 if (!uss.switching && !uss.initializing) { 18449 mWindowManager.stopFreezingScreen(); 18450 unfrozen = true; 18451 } 18452 } 18453 if (unfrozen) { 18454 final int N = mUserSwitchObservers.beginBroadcast(); 18455 for (int i=0; i<N; i++) { 18456 try { 18457 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId); 18458 } catch (RemoteException e) { 18459 } 18460 } 18461 mUserSwitchObservers.finishBroadcast(); 18462 } 18463 } 18464 18465 void scheduleStartProfilesLocked() { 18466 if (!mHandler.hasMessages(START_PROFILES_MSG)) { 18467 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG), 18468 DateUtils.SECOND_IN_MILLIS); 18469 } 18470 } 18471 18472 void startProfilesLocked() { 18473 if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked"); 18474 List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18475 mCurrentUserId, false /* enabledOnly */); 18476 List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size()); 18477 for (UserInfo user : profiles) { 18478 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 18479 && user.id != mCurrentUserId) { 18480 toStart.add(user); 18481 } 18482 } 18483 final int n = toStart.size(); 18484 int i = 0; 18485 for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) { 18486 startUserInBackground(toStart.get(i).id); 18487 } 18488 if (i < n) { 18489 Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS"); 18490 } 18491 } 18492 18493 void finishUserBoot(UserStartedState uss) { 18494 synchronized (this) { 18495 if (uss.mState == UserStartedState.STATE_BOOTING 18496 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) { 18497 uss.mState = UserStartedState.STATE_RUNNING; 18498 final int userId = uss.mHandle.getIdentifier(); 18499 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 18500 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18501 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 18502 broadcastIntentLocked(null, null, intent, 18503 null, null, 0, null, null, 18504 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE, 18505 true, false, MY_PID, Process.SYSTEM_UID, userId); 18506 } 18507 } 18508 } 18509 18510 void finishUserSwitch(UserStartedState uss) { 18511 synchronized (this) { 18512 finishUserBoot(uss); 18513 18514 startProfilesLocked(); 18515 18516 int num = mUserLru.size(); 18517 int i = 0; 18518 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) { 18519 Integer oldUserId = mUserLru.get(i); 18520 UserStartedState oldUss = mStartedUsers.get(oldUserId); 18521 if (oldUss == null) { 18522 // Shouldn't happen, but be sane if it does. 18523 mUserLru.remove(i); 18524 num--; 18525 continue; 18526 } 18527 if (oldUss.mState == UserStartedState.STATE_STOPPING 18528 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) { 18529 // This user is already stopping, doesn't count. 18530 num--; 18531 i++; 18532 continue; 18533 } 18534 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) { 18535 // Owner and current can't be stopped, but count as running. 18536 i++; 18537 continue; 18538 } 18539 // This is a user to be stopped. 18540 stopUserLocked(oldUserId, null); 18541 num--; 18542 i++; 18543 } 18544 } 18545 } 18546 18547 @Override 18548 public int stopUser(final int userId, final IStopUserCallback callback) { 18549 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18550 != PackageManager.PERMISSION_GRANTED) { 18551 String msg = "Permission Denial: switchUser() from pid=" 18552 + Binder.getCallingPid() 18553 + ", uid=" + Binder.getCallingUid() 18554 + " requires " + INTERACT_ACROSS_USERS_FULL; 18555 Slog.w(TAG, msg); 18556 throw new SecurityException(msg); 18557 } 18558 if (userId <= 0) { 18559 throw new IllegalArgumentException("Can't stop primary user " + userId); 18560 } 18561 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 18562 synchronized (this) { 18563 return stopUserLocked(userId, callback); 18564 } 18565 } 18566 18567 private int stopUserLocked(final int userId, final IStopUserCallback callback) { 18568 if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId); 18569 if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) { 18570 return ActivityManager.USER_OP_IS_CURRENT; 18571 } 18572 18573 final UserStartedState uss = mStartedUsers.get(userId); 18574 if (uss == null) { 18575 // User is not started, nothing to do... but we do need to 18576 // callback if requested. 18577 if (callback != null) { 18578 mHandler.post(new Runnable() { 18579 @Override 18580 public void run() { 18581 try { 18582 callback.userStopped(userId); 18583 } catch (RemoteException e) { 18584 } 18585 } 18586 }); 18587 } 18588 return ActivityManager.USER_OP_SUCCESS; 18589 } 18590 18591 if (callback != null) { 18592 uss.mStopCallbacks.add(callback); 18593 } 18594 18595 if (uss.mState != UserStartedState.STATE_STOPPING 18596 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18597 uss.mState = UserStartedState.STATE_STOPPING; 18598 updateStartedUserArrayLocked(); 18599 18600 long ident = Binder.clearCallingIdentity(); 18601 try { 18602 // We are going to broadcast ACTION_USER_STOPPING and then 18603 // once that is done send a final ACTION_SHUTDOWN and then 18604 // stop the user. 18605 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING); 18606 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18607 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18608 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 18609 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 18610 // This is the result receiver for the final shutdown broadcast. 18611 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 18612 @Override 18613 public void performReceive(Intent intent, int resultCode, String data, 18614 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 18615 finishUserStop(uss); 18616 } 18617 }; 18618 // This is the result receiver for the initial stopping broadcast. 18619 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() { 18620 @Override 18621 public void performReceive(Intent intent, int resultCode, String data, 18622 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 18623 // On to the next. 18624 synchronized (ActivityManagerService.this) { 18625 if (uss.mState != UserStartedState.STATE_STOPPING) { 18626 // Whoops, we are being started back up. Abort, abort! 18627 return; 18628 } 18629 uss.mState = UserStartedState.STATE_SHUTDOWN; 18630 } 18631 mBatteryStatsService.noteEvent( 18632 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 18633 Integer.toString(userId), userId); 18634 mSystemServiceManager.stopUser(userId); 18635 broadcastIntentLocked(null, null, shutdownIntent, 18636 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE, 18637 true, false, MY_PID, Process.SYSTEM_UID, userId); 18638 } 18639 }; 18640 // Kick things off. 18641 broadcastIntentLocked(null, null, stoppingIntent, 18642 null, stoppingReceiver, 0, null, null, 18643 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 18644 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18645 } finally { 18646 Binder.restoreCallingIdentity(ident); 18647 } 18648 } 18649 18650 return ActivityManager.USER_OP_SUCCESS; 18651 } 18652 18653 void finishUserStop(UserStartedState uss) { 18654 final int userId = uss.mHandle.getIdentifier(); 18655 boolean stopped; 18656 ArrayList<IStopUserCallback> callbacks; 18657 synchronized (this) { 18658 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks); 18659 if (mStartedUsers.get(userId) != uss) { 18660 stopped = false; 18661 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) { 18662 stopped = false; 18663 } else { 18664 stopped = true; 18665 // User can no longer run. 18666 mStartedUsers.remove(userId); 18667 mUserLru.remove(Integer.valueOf(userId)); 18668 updateStartedUserArrayLocked(); 18669 18670 // Clean up all state and processes associated with the user. 18671 // Kill all the processes for the user. 18672 forceStopUserLocked(userId, "finish user"); 18673 } 18674 18675 // Explicitly remove the old information in mRecentTasks. 18676 removeRecentTasksForUserLocked(userId); 18677 } 18678 18679 for (int i=0; i<callbacks.size(); i++) { 18680 try { 18681 if (stopped) callbacks.get(i).userStopped(userId); 18682 else callbacks.get(i).userStopAborted(userId); 18683 } catch (RemoteException e) { 18684 } 18685 } 18686 18687 if (stopped) { 18688 mSystemServiceManager.cleanupUser(userId); 18689 synchronized (this) { 18690 mStackSupervisor.removeUserLocked(userId); 18691 } 18692 } 18693 } 18694 18695 @Override 18696 public UserInfo getCurrentUser() { 18697 if ((checkCallingPermission(INTERACT_ACROSS_USERS) 18698 != PackageManager.PERMISSION_GRANTED) && ( 18699 checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18700 != PackageManager.PERMISSION_GRANTED)) { 18701 String msg = "Permission Denial: getCurrentUser() from pid=" 18702 + Binder.getCallingPid() 18703 + ", uid=" + Binder.getCallingUid() 18704 + " requires " + INTERACT_ACROSS_USERS; 18705 Slog.w(TAG, msg); 18706 throw new SecurityException(msg); 18707 } 18708 synchronized (this) { 18709 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 18710 return getUserManagerLocked().getUserInfo(userId); 18711 } 18712 } 18713 18714 int getCurrentUserIdLocked() { 18715 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 18716 } 18717 18718 @Override 18719 public boolean isUserRunning(int userId, boolean orStopped) { 18720 if (checkCallingPermission(INTERACT_ACROSS_USERS) 18721 != PackageManager.PERMISSION_GRANTED) { 18722 String msg = "Permission Denial: isUserRunning() from pid=" 18723 + Binder.getCallingPid() 18724 + ", uid=" + Binder.getCallingUid() 18725 + " requires " + INTERACT_ACROSS_USERS; 18726 Slog.w(TAG, msg); 18727 throw new SecurityException(msg); 18728 } 18729 synchronized (this) { 18730 return isUserRunningLocked(userId, orStopped); 18731 } 18732 } 18733 18734 boolean isUserRunningLocked(int userId, boolean orStopped) { 18735 UserStartedState state = mStartedUsers.get(userId); 18736 if (state == null) { 18737 return false; 18738 } 18739 if (orStopped) { 18740 return true; 18741 } 18742 return state.mState != UserStartedState.STATE_STOPPING 18743 && state.mState != UserStartedState.STATE_SHUTDOWN; 18744 } 18745 18746 @Override 18747 public int[] getRunningUserIds() { 18748 if (checkCallingPermission(INTERACT_ACROSS_USERS) 18749 != PackageManager.PERMISSION_GRANTED) { 18750 String msg = "Permission Denial: isUserRunning() from pid=" 18751 + Binder.getCallingPid() 18752 + ", uid=" + Binder.getCallingUid() 18753 + " requires " + INTERACT_ACROSS_USERS; 18754 Slog.w(TAG, msg); 18755 throw new SecurityException(msg); 18756 } 18757 synchronized (this) { 18758 return mStartedUserArray; 18759 } 18760 } 18761 18762 private void updateStartedUserArrayLocked() { 18763 int num = 0; 18764 for (int i=0; i<mStartedUsers.size(); i++) { 18765 UserStartedState uss = mStartedUsers.valueAt(i); 18766 // This list does not include stopping users. 18767 if (uss.mState != UserStartedState.STATE_STOPPING 18768 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18769 num++; 18770 } 18771 } 18772 mStartedUserArray = new int[num]; 18773 num = 0; 18774 for (int i=0; i<mStartedUsers.size(); i++) { 18775 UserStartedState uss = mStartedUsers.valueAt(i); 18776 if (uss.mState != UserStartedState.STATE_STOPPING 18777 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18778 mStartedUserArray[num] = mStartedUsers.keyAt(i); 18779 num++; 18780 } 18781 } 18782 } 18783 18784 @Override 18785 public void registerUserSwitchObserver(IUserSwitchObserver observer) { 18786 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18787 != PackageManager.PERMISSION_GRANTED) { 18788 String msg = "Permission Denial: registerUserSwitchObserver() from pid=" 18789 + Binder.getCallingPid() 18790 + ", uid=" + Binder.getCallingUid() 18791 + " requires " + INTERACT_ACROSS_USERS_FULL; 18792 Slog.w(TAG, msg); 18793 throw new SecurityException(msg); 18794 } 18795 18796 mUserSwitchObservers.register(observer); 18797 } 18798 18799 @Override 18800 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 18801 mUserSwitchObservers.unregister(observer); 18802 } 18803 18804 private boolean userExists(int userId) { 18805 if (userId == 0) { 18806 return true; 18807 } 18808 UserManagerService ums = getUserManagerLocked(); 18809 return ums != null ? (ums.getUserInfo(userId) != null) : false; 18810 } 18811 18812 int[] getUsersLocked() { 18813 UserManagerService ums = getUserManagerLocked(); 18814 return ums != null ? ums.getUserIds() : new int[] { 0 }; 18815 } 18816 18817 UserManagerService getUserManagerLocked() { 18818 if (mUserManager == null) { 18819 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 18820 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b); 18821 } 18822 return mUserManager; 18823 } 18824 18825 private int applyUserId(int uid, int userId) { 18826 return UserHandle.getUid(userId, uid); 18827 } 18828 18829 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 18830 if (info == null) return null; 18831 ApplicationInfo newInfo = new ApplicationInfo(info); 18832 newInfo.uid = applyUserId(info.uid, userId); 18833 newInfo.dataDir = USER_DATA_DIR + userId + "/" 18834 + info.packageName; 18835 return newInfo; 18836 } 18837 18838 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 18839 if (aInfo == null 18840 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 18841 return aInfo; 18842 } 18843 18844 ActivityInfo info = new ActivityInfo(aInfo); 18845 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 18846 return info; 18847 } 18848 18849 private final class LocalService extends ActivityManagerInternal { 18850 @Override 18851 public void goingToSleep() { 18852 ActivityManagerService.this.goingToSleep(); 18853 } 18854 18855 @Override 18856 public void wakingUp() { 18857 ActivityManagerService.this.wakingUp(); 18858 } 18859 18860 @Override 18861 public int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 18862 String processName, String abiOverride, int uid, Runnable crashHandler) { 18863 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 18864 processName, abiOverride, uid, crashHandler); 18865 } 18866 } 18867 18868 /** 18869 * An implementation of IAppTask, that allows an app to manage its own tasks via 18870 * {@link android.app.ActivityManager.AppTask}. We keep track of the callingUid to ensure that 18871 * only the process that calls getAppTasks() can call the AppTask methods. 18872 */ 18873 class AppTaskImpl extends IAppTask.Stub { 18874 private int mTaskId; 18875 private int mCallingUid; 18876 18877 public AppTaskImpl(int taskId, int callingUid) { 18878 mTaskId = taskId; 18879 mCallingUid = callingUid; 18880 } 18881 18882 private void checkCaller() { 18883 if (mCallingUid != Binder.getCallingUid()) { 18884 throw new SecurityException("Caller " + mCallingUid 18885 + " does not match caller of getAppTasks(): " + Binder.getCallingUid()); 18886 } 18887 } 18888 18889 @Override 18890 public void finishAndRemoveTask() { 18891 checkCaller(); 18892 18893 synchronized (ActivityManagerService.this) { 18894 long origId = Binder.clearCallingIdentity(); 18895 try { 18896 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18897 if (tr == null) { 18898 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18899 } 18900 // Only kill the process if we are not a new document 18901 int flags = tr.getBaseIntent().getFlags(); 18902 boolean isDocument = (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) == 18903 Intent.FLAG_ACTIVITY_NEW_DOCUMENT; 18904 removeTaskByIdLocked(mTaskId, 18905 !isDocument ? ActivityManager.REMOVE_TASK_KILL_PROCESS : 0); 18906 } finally { 18907 Binder.restoreCallingIdentity(origId); 18908 } 18909 } 18910 } 18911 18912 @Override 18913 public ActivityManager.RecentTaskInfo getTaskInfo() { 18914 checkCaller(); 18915 18916 synchronized (ActivityManagerService.this) { 18917 long origId = Binder.clearCallingIdentity(); 18918 try { 18919 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18920 if (tr == null) { 18921 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18922 } 18923 return createRecentTaskInfoFromTaskRecord(tr); 18924 } finally { 18925 Binder.restoreCallingIdentity(origId); 18926 } 18927 } 18928 } 18929 18930 @Override 18931 public void moveToFront() { 18932 checkCaller(); 18933 18934 final TaskRecord tr; 18935 synchronized (ActivityManagerService.this) { 18936 tr = recentTaskForIdLocked(mTaskId); 18937 if (tr == null) { 18938 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18939 } 18940 if (tr.getRootActivity() != null) { 18941 long origId = Binder.clearCallingIdentity(); 18942 try { 18943 moveTaskToFrontLocked(tr.taskId, 0, null); 18944 return; 18945 } finally { 18946 Binder.restoreCallingIdentity(origId); 18947 } 18948 } 18949 } 18950 18951 startActivityFromRecentsInner(tr.taskId, null); 18952 } 18953 18954 @Override 18955 public int startActivity(IBinder whoThread, String callingPackage, 18956 Intent intent, String resolvedType, Bundle options) { 18957 checkCaller(); 18958 18959 int callingUser = UserHandle.getCallingUserId(); 18960 TaskRecord tr; 18961 IApplicationThread appThread; 18962 synchronized (ActivityManagerService.this) { 18963 tr = recentTaskForIdLocked(mTaskId); 18964 if (tr == null) { 18965 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18966 } 18967 appThread = ApplicationThreadNative.asInterface(whoThread); 18968 if (appThread == null) { 18969 throw new IllegalArgumentException("Bad app thread " + appThread); 18970 } 18971 } 18972 return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent, 18973 resolvedType, null, null, null, null, 0, 0, null, null, 18974 null, options, callingUser, null, tr); 18975 } 18976 18977 @Override 18978 public void setExcludeFromRecents(boolean exclude) { 18979 checkCaller(); 18980 18981 synchronized (ActivityManagerService.this) { 18982 long origId = Binder.clearCallingIdentity(); 18983 try { 18984 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18985 if (tr == null) { 18986 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18987 } 18988 Intent intent = tr.getBaseIntent(); 18989 if (exclude) { 18990 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 18991 } else { 18992 intent.setFlags(intent.getFlags() 18993 & ~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 18994 } 18995 } finally { 18996 Binder.restoreCallingIdentity(origId); 18997 } 18998 } 18999 } 19000 } 19001} 19002