ActivityManagerService.java revision 36c4db8bd3bd7dad4b6cb8abd9cdc1a627fe3bbc
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, 0, 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, 3763 -1, r.launchedFromUid, 0, 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 // If they don't have direct access to the URI, then revoke any 7532 // ownerless URI 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, "Revoking non-owned " + perm.targetUid + 7542 " permission to " + perm.uri); 7543 persistChanged |= perm.revokeModes( 7544 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, false); 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, true); 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(persistable 7665 ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true); 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.setTaskDescription(td); 8379 r.task.updateTaskDescription(); 8380 } 8381 } 8382 } 8383 8384 @Override 8385 public Bitmap getTaskDescriptionIcon(String filename) { 8386 return mTaskPersister.getTaskDescriptionIcon(filename); 8387 } 8388 8389 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) { 8390 mRecentTasks.remove(tr); 8391 tr.removedFromRecents(mTaskPersister); 8392 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0; 8393 Intent baseIntent = new Intent( 8394 tr.intent != null ? tr.intent : tr.affinityIntent); 8395 ComponentName component = baseIntent.getComponent(); 8396 if (component == null) { 8397 Slog.w(TAG, "Now component for base intent of task: " + tr); 8398 return; 8399 } 8400 8401 // Find any running services associated with this app. 8402 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent); 8403 8404 if (killProcesses) { 8405 // Find any running processes associated with this app. 8406 final String pkg = component.getPackageName(); 8407 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 8408 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 8409 for (int i=0; i<pmap.size(); i++) { 8410 SparseArray<ProcessRecord> uids = pmap.valueAt(i); 8411 for (int j=0; j<uids.size(); j++) { 8412 ProcessRecord proc = uids.valueAt(j); 8413 if (proc.userId != tr.userId) { 8414 continue; 8415 } 8416 if (!proc.pkgList.containsKey(pkg)) { 8417 continue; 8418 } 8419 procs.add(proc); 8420 } 8421 } 8422 8423 // Kill the running processes. 8424 for (int i=0; i<procs.size(); i++) { 8425 ProcessRecord pr = procs.get(i); 8426 if (pr == mHomeProcess) { 8427 // Don't kill the home process along with tasks from the same package. 8428 continue; 8429 } 8430 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 8431 pr.kill("remove task", true); 8432 } else { 8433 pr.waitingToKill = "remove task"; 8434 } 8435 } 8436 } 8437 } 8438 8439 /** 8440 * Removes the task with the specified task id. 8441 * 8442 * @param taskId Identifier of the task to be removed. 8443 * @param flags Additional operational flags. May be 0 or 8444 * {@link ActivityManager#REMOVE_TASK_KILL_PROCESS}. 8445 * @return Returns true if the given task was found and removed. 8446 */ 8447 private boolean removeTaskByIdLocked(int taskId, int flags) { 8448 TaskRecord tr = recentTaskForIdLocked(taskId); 8449 if (tr != null) { 8450 tr.removeTaskActivitiesLocked(); 8451 cleanUpRemovedTaskLocked(tr, flags); 8452 if (tr.isPersistable) { 8453 notifyTaskPersisterLocked(null, true); 8454 } 8455 return true; 8456 } 8457 return false; 8458 } 8459 8460 @Override 8461 public boolean removeTask(int taskId, int flags) { 8462 synchronized (this) { 8463 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 8464 "removeTask()"); 8465 long ident = Binder.clearCallingIdentity(); 8466 try { 8467 return removeTaskByIdLocked(taskId, flags); 8468 } finally { 8469 Binder.restoreCallingIdentity(ident); 8470 } 8471 } 8472 } 8473 8474 /** 8475 * TODO: Add mController hook 8476 */ 8477 @Override 8478 public void moveTaskToFront(int taskId, int flags, Bundle options) { 8479 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8480 "moveTaskToFront()"); 8481 8482 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToFront: moving taskId=" + taskId); 8483 synchronized(this) { 8484 moveTaskToFrontLocked(taskId, flags, options); 8485 } 8486 } 8487 8488 void moveTaskToFrontLocked(int taskId, int flags, Bundle options) { 8489 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8490 Binder.getCallingUid(), -1, -1, "Task to front")) { 8491 ActivityOptions.abort(options); 8492 return; 8493 } 8494 final long origId = Binder.clearCallingIdentity(); 8495 try { 8496 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 8497 if (task == null) { 8498 return; 8499 } 8500 if (mStackSupervisor.isLockTaskModeViolation(task)) { 8501 mStackSupervisor.showLockTaskToast(); 8502 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode"); 8503 return; 8504 } 8505 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked(); 8506 if (prev != null && prev.isRecentsActivity()) { 8507 task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE); 8508 } 8509 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options); 8510 } finally { 8511 Binder.restoreCallingIdentity(origId); 8512 } 8513 ActivityOptions.abort(options); 8514 } 8515 8516 @Override 8517 public void moveTaskToBack(int taskId) { 8518 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8519 "moveTaskToBack()"); 8520 8521 synchronized(this) { 8522 TaskRecord tr = recentTaskForIdLocked(taskId); 8523 if (tr != null) { 8524 if (tr == mStackSupervisor.mLockTaskModeTask) { 8525 mStackSupervisor.showLockTaskToast(); 8526 return; 8527 } 8528 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToBack: moving task=" + tr); 8529 ActivityStack stack = tr.stack; 8530 if (stack.mResumedActivity != null && stack.mResumedActivity.task == tr) { 8531 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8532 Binder.getCallingUid(), -1, -1, "Task to back")) { 8533 return; 8534 } 8535 } 8536 final long origId = Binder.clearCallingIdentity(); 8537 try { 8538 stack.moveTaskToBackLocked(taskId, null); 8539 } finally { 8540 Binder.restoreCallingIdentity(origId); 8541 } 8542 } 8543 } 8544 } 8545 8546 /** 8547 * Moves an activity, and all of the other activities within the same task, to the bottom 8548 * of the history stack. The activity's order within the task is unchanged. 8549 * 8550 * @param token A reference to the activity we wish to move 8551 * @param nonRoot If false then this only works if the activity is the root 8552 * of a task; if true it will work for any activity in a task. 8553 * @return Returns true if the move completed, false if not. 8554 */ 8555 @Override 8556 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 8557 enforceNotIsolatedCaller("moveActivityTaskToBack"); 8558 synchronized(this) { 8559 final long origId = Binder.clearCallingIdentity(); 8560 try { 8561 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); 8562 if (taskId >= 0) { 8563 if ((mStackSupervisor.mLockTaskModeTask != null) 8564 && (mStackSupervisor.mLockTaskModeTask.taskId == taskId)) { 8565 mStackSupervisor.showLockTaskToast(); 8566 return false; 8567 } 8568 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId, null); 8569 } 8570 } finally { 8571 Binder.restoreCallingIdentity(origId); 8572 } 8573 } 8574 return false; 8575 } 8576 8577 @Override 8578 public void moveTaskBackwards(int task) { 8579 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8580 "moveTaskBackwards()"); 8581 8582 synchronized(this) { 8583 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8584 Binder.getCallingUid(), -1, -1, "Task backwards")) { 8585 return; 8586 } 8587 final long origId = Binder.clearCallingIdentity(); 8588 moveTaskBackwardsLocked(task); 8589 Binder.restoreCallingIdentity(origId); 8590 } 8591 } 8592 8593 private final void moveTaskBackwardsLocked(int task) { 8594 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 8595 } 8596 8597 @Override 8598 public IBinder getHomeActivityToken() throws RemoteException { 8599 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8600 "getHomeActivityToken()"); 8601 synchronized (this) { 8602 return mStackSupervisor.getHomeActivityToken(); 8603 } 8604 } 8605 8606 @Override 8607 public IActivityContainer createActivityContainer(IBinder parentActivityToken, 8608 IActivityContainerCallback callback) throws RemoteException { 8609 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8610 "createActivityContainer()"); 8611 synchronized (this) { 8612 if (parentActivityToken == null) { 8613 throw new IllegalArgumentException("parent token must not be null"); 8614 } 8615 ActivityRecord r = ActivityRecord.forToken(parentActivityToken); 8616 if (r == null) { 8617 return null; 8618 } 8619 if (callback == null) { 8620 throw new IllegalArgumentException("callback must not be null"); 8621 } 8622 return mStackSupervisor.createActivityContainer(r, callback); 8623 } 8624 } 8625 8626 @Override 8627 public void deleteActivityContainer(IActivityContainer container) throws RemoteException { 8628 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8629 "deleteActivityContainer()"); 8630 synchronized (this) { 8631 mStackSupervisor.deleteActivityContainer(container); 8632 } 8633 } 8634 8635 @Override 8636 public IActivityContainer getEnclosingActivityContainer(IBinder activityToken) 8637 throws RemoteException { 8638 synchronized (this) { 8639 ActivityStack stack = ActivityRecord.getStackLocked(activityToken); 8640 if (stack != null) { 8641 return stack.mActivityContainer; 8642 } 8643 return null; 8644 } 8645 } 8646 8647 @Override 8648 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 8649 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8650 "moveTaskToStack()"); 8651 if (stackId == HOME_STACK_ID) { 8652 Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack", 8653 new RuntimeException("here").fillInStackTrace()); 8654 } 8655 synchronized (this) { 8656 long ident = Binder.clearCallingIdentity(); 8657 try { 8658 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToStack: moving task=" + taskId + " to stackId=" 8659 + stackId + " toTop=" + toTop); 8660 mStackSupervisor.moveTaskToStack(taskId, stackId, toTop); 8661 } finally { 8662 Binder.restoreCallingIdentity(ident); 8663 } 8664 } 8665 } 8666 8667 @Override 8668 public void resizeStack(int stackBoxId, Rect bounds) { 8669 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8670 "resizeStackBox()"); 8671 long ident = Binder.clearCallingIdentity(); 8672 try { 8673 mWindowManager.resizeStack(stackBoxId, bounds); 8674 } finally { 8675 Binder.restoreCallingIdentity(ident); 8676 } 8677 } 8678 8679 @Override 8680 public List<StackInfo> getAllStackInfos() { 8681 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8682 "getAllStackInfos()"); 8683 long ident = Binder.clearCallingIdentity(); 8684 try { 8685 synchronized (this) { 8686 return mStackSupervisor.getAllStackInfosLocked(); 8687 } 8688 } finally { 8689 Binder.restoreCallingIdentity(ident); 8690 } 8691 } 8692 8693 @Override 8694 public StackInfo getStackInfo(int stackId) { 8695 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8696 "getStackInfo()"); 8697 long ident = Binder.clearCallingIdentity(); 8698 try { 8699 synchronized (this) { 8700 return mStackSupervisor.getStackInfoLocked(stackId); 8701 } 8702 } finally { 8703 Binder.restoreCallingIdentity(ident); 8704 } 8705 } 8706 8707 @Override 8708 public boolean isInHomeStack(int taskId) { 8709 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8710 "getStackInfo()"); 8711 long ident = Binder.clearCallingIdentity(); 8712 try { 8713 synchronized (this) { 8714 TaskRecord tr = recentTaskForIdLocked(taskId); 8715 return tr != null && tr.stack != null && tr.stack.isHomeStack(); 8716 } 8717 } finally { 8718 Binder.restoreCallingIdentity(ident); 8719 } 8720 } 8721 8722 @Override 8723 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 8724 synchronized(this) { 8725 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot); 8726 } 8727 } 8728 8729 private boolean isLockTaskAuthorized(String pkg) { 8730 final DevicePolicyManager dpm = (DevicePolicyManager) 8731 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 8732 try { 8733 int uid = mContext.getPackageManager().getPackageUid(pkg, 8734 Binder.getCallingUserHandle().getIdentifier()); 8735 return (uid == Binder.getCallingUid()) && dpm != null && dpm.isLockTaskPermitted(pkg); 8736 } catch (NameNotFoundException e) { 8737 return false; 8738 } 8739 } 8740 8741 void startLockTaskMode(TaskRecord task) { 8742 final String pkg; 8743 synchronized (this) { 8744 pkg = task.intent.getComponent().getPackageName(); 8745 } 8746 boolean isSystemInitiated = Binder.getCallingUid() == Process.SYSTEM_UID; 8747 if (!isSystemInitiated && !isLockTaskAuthorized(pkg)) { 8748 final TaskRecord taskRecord = task; 8749 mHandler.post(new Runnable() { 8750 @Override 8751 public void run() { 8752 mLockToAppRequest.showLockTaskPrompt(taskRecord); 8753 } 8754 }); 8755 return; 8756 } 8757 long ident = Binder.clearCallingIdentity(); 8758 try { 8759 synchronized (this) { 8760 // Since we lost lock on task, make sure it is still there. 8761 task = mStackSupervisor.anyTaskForIdLocked(task.taskId); 8762 if (task != null) { 8763 if (!isSystemInitiated 8764 && ((mFocusedActivity == null) || (task != mFocusedActivity.task))) { 8765 throw new IllegalArgumentException("Invalid task, not in foreground"); 8766 } 8767 mStackSupervisor.setLockTaskModeLocked(task, !isSystemInitiated); 8768 } 8769 } 8770 } finally { 8771 Binder.restoreCallingIdentity(ident); 8772 } 8773 } 8774 8775 @Override 8776 public void startLockTaskMode(int taskId) { 8777 final TaskRecord task; 8778 long ident = Binder.clearCallingIdentity(); 8779 try { 8780 synchronized (this) { 8781 task = mStackSupervisor.anyTaskForIdLocked(taskId); 8782 } 8783 } finally { 8784 Binder.restoreCallingIdentity(ident); 8785 } 8786 if (task != null) { 8787 startLockTaskMode(task); 8788 } 8789 } 8790 8791 @Override 8792 public void startLockTaskMode(IBinder token) { 8793 final TaskRecord task; 8794 long ident = Binder.clearCallingIdentity(); 8795 try { 8796 synchronized (this) { 8797 final ActivityRecord r = ActivityRecord.forToken(token); 8798 if (r == null) { 8799 return; 8800 } 8801 task = r.task; 8802 } 8803 } finally { 8804 Binder.restoreCallingIdentity(ident); 8805 } 8806 if (task != null) { 8807 startLockTaskMode(task); 8808 } 8809 } 8810 8811 @Override 8812 public void startLockTaskModeOnCurrent() throws RemoteException { 8813 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8814 "startLockTaskModeOnCurrent"); 8815 ActivityRecord r = null; 8816 synchronized (this) { 8817 r = mStackSupervisor.topRunningActivityLocked(); 8818 } 8819 startLockTaskMode(r.task); 8820 } 8821 8822 @Override 8823 public void stopLockTaskMode() { 8824 // Verify that the user matches the package of the intent for the TaskRecord 8825 // we are locked to or systtem. This will ensure the same caller for startLockTaskMode 8826 // and stopLockTaskMode. 8827 final int callingUid = Binder.getCallingUid(); 8828 if (callingUid != Process.SYSTEM_UID) { 8829 try { 8830 String pkg = 8831 mStackSupervisor.mLockTaskModeTask.intent.getComponent().getPackageName(); 8832 int uid = mContext.getPackageManager().getPackageUid(pkg, 8833 Binder.getCallingUserHandle().getIdentifier()); 8834 if (uid != callingUid) { 8835 throw new SecurityException("Invalid uid, expected " + uid); 8836 } 8837 } catch (NameNotFoundException e) { 8838 Log.d(TAG, "stopLockTaskMode " + e); 8839 return; 8840 } 8841 } 8842 long ident = Binder.clearCallingIdentity(); 8843 try { 8844 Log.d(TAG, "stopLockTaskMode"); 8845 // Stop lock task 8846 synchronized (this) { 8847 mStackSupervisor.setLockTaskModeLocked(null, false); 8848 } 8849 } finally { 8850 Binder.restoreCallingIdentity(ident); 8851 } 8852 } 8853 8854 @Override 8855 public void stopLockTaskModeOnCurrent() throws RemoteException { 8856 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8857 "stopLockTaskModeOnCurrent"); 8858 long ident = Binder.clearCallingIdentity(); 8859 try { 8860 stopLockTaskMode(); 8861 } finally { 8862 Binder.restoreCallingIdentity(ident); 8863 } 8864 } 8865 8866 @Override 8867 public boolean isInLockTaskMode() { 8868 synchronized (this) { 8869 return mStackSupervisor.isInLockTaskMode(); 8870 } 8871 } 8872 8873 // ========================================================= 8874 // CONTENT PROVIDERS 8875 // ========================================================= 8876 8877 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 8878 List<ProviderInfo> providers = null; 8879 try { 8880 providers = AppGlobals.getPackageManager(). 8881 queryContentProviders(app.processName, app.uid, 8882 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS); 8883 } catch (RemoteException ex) { 8884 } 8885 if (DEBUG_MU) 8886 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 8887 int userId = app.userId; 8888 if (providers != null) { 8889 int N = providers.size(); 8890 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 8891 for (int i=0; i<N; i++) { 8892 ProviderInfo cpi = 8893 (ProviderInfo)providers.get(i); 8894 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 8895 cpi.name, cpi.flags); 8896 if (singleton && UserHandle.getUserId(app.uid) != 0) { 8897 // This is a singleton provider, but a user besides the 8898 // default user is asking to initialize a process it runs 8899 // in... well, no, it doesn't actually run in this process, 8900 // it runs in the process of the default user. Get rid of it. 8901 providers.remove(i); 8902 N--; 8903 i--; 8904 continue; 8905 } 8906 8907 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 8908 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 8909 if (cpr == null) { 8910 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 8911 mProviderMap.putProviderByClass(comp, cpr); 8912 } 8913 if (DEBUG_MU) 8914 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 8915 app.pubProviders.put(cpi.name, cpr); 8916 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 8917 // Don't add this if it is a platform component that is marked 8918 // to run in multiple processes, because this is actually 8919 // part of the framework so doesn't make sense to track as a 8920 // separate apk in the process. 8921 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode, 8922 mProcessStats); 8923 } 8924 ensurePackageDexOpt(cpi.applicationInfo.packageName); 8925 } 8926 } 8927 return providers; 8928 } 8929 8930 /** 8931 * Check if {@link ProcessRecord} has a possible chance at accessing the 8932 * given {@link ProviderInfo}. Final permission checking is always done 8933 * in {@link ContentProvider}. 8934 */ 8935 private final String checkContentProviderPermissionLocked( 8936 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 8937 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 8938 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 8939 boolean checkedGrants = false; 8940 if (checkUser) { 8941 // Looking for cross-user grants before enforcing the typical cross-users permissions 8942 int tmpTargetUserId = unsafeConvertIncomingUser(userId); 8943 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 8944 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) { 8945 return null; 8946 } 8947 checkedGrants = true; 8948 } 8949 userId = handleIncomingUser(callingPid, callingUid, userId, 8950 false, ALLOW_NON_FULL, 8951 "checkContentProviderPermissionLocked " + cpi.authority, null); 8952 if (userId != tmpTargetUserId) { 8953 // When we actually went to determine the final targer user ID, this ended 8954 // up different than our initial check for the authority. This is because 8955 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 8956 // SELF. So we need to re-check the grants again. 8957 checkedGrants = false; 8958 } 8959 } 8960 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 8961 cpi.applicationInfo.uid, cpi.exported) 8962 == PackageManager.PERMISSION_GRANTED) { 8963 return null; 8964 } 8965 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 8966 cpi.applicationInfo.uid, cpi.exported) 8967 == PackageManager.PERMISSION_GRANTED) { 8968 return null; 8969 } 8970 8971 PathPermission[] pps = cpi.pathPermissions; 8972 if (pps != null) { 8973 int i = pps.length; 8974 while (i > 0) { 8975 i--; 8976 PathPermission pp = pps[i]; 8977 String pprperm = pp.getReadPermission(); 8978 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 8979 cpi.applicationInfo.uid, cpi.exported) 8980 == PackageManager.PERMISSION_GRANTED) { 8981 return null; 8982 } 8983 String ppwperm = pp.getWritePermission(); 8984 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 8985 cpi.applicationInfo.uid, cpi.exported) 8986 == PackageManager.PERMISSION_GRANTED) { 8987 return null; 8988 } 8989 } 8990 } 8991 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 8992 return null; 8993 } 8994 8995 String msg; 8996 if (!cpi.exported) { 8997 msg = "Permission Denial: opening provider " + cpi.name 8998 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 8999 + ", uid=" + callingUid + ") that is not exported from uid " 9000 + cpi.applicationInfo.uid; 9001 } else { 9002 msg = "Permission Denial: opening provider " + cpi.name 9003 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 9004 + ", uid=" + callingUid + ") requires " 9005 + cpi.readPermission + " or " + cpi.writePermission; 9006 } 9007 Slog.w(TAG, msg); 9008 return msg; 9009 } 9010 9011 /** 9012 * Returns if the ContentProvider has granted a uri to callingUid 9013 */ 9014 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) { 9015 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 9016 if (perms != null) { 9017 for (int i=perms.size()-1; i>=0; i--) { 9018 GrantUri grantUri = perms.keyAt(i); 9019 if (grantUri.sourceUserId == userId || !checkUser) { 9020 if (matchesProvider(grantUri.uri, cpi)) { 9021 return true; 9022 } 9023 } 9024 } 9025 } 9026 return false; 9027 } 9028 9029 /** 9030 * Returns true if the uri authority is one of the authorities specified in the provider. 9031 */ 9032 boolean matchesProvider(Uri uri, ProviderInfo cpi) { 9033 String uriAuth = uri.getAuthority(); 9034 String cpiAuth = cpi.authority; 9035 if (cpiAuth.indexOf(';') == -1) { 9036 return cpiAuth.equals(uriAuth); 9037 } 9038 String[] cpiAuths = cpiAuth.split(";"); 9039 int length = cpiAuths.length; 9040 for (int i = 0; i < length; i++) { 9041 if (cpiAuths[i].equals(uriAuth)) return true; 9042 } 9043 return false; 9044 } 9045 9046 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 9047 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9048 if (r != null) { 9049 for (int i=0; i<r.conProviders.size(); i++) { 9050 ContentProviderConnection conn = r.conProviders.get(i); 9051 if (conn.provider == cpr) { 9052 if (DEBUG_PROVIDER) Slog.v(TAG, 9053 "Adding provider requested by " 9054 + r.processName + " from process " 9055 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9056 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9057 if (stable) { 9058 conn.stableCount++; 9059 conn.numStableIncs++; 9060 } else { 9061 conn.unstableCount++; 9062 conn.numUnstableIncs++; 9063 } 9064 return conn; 9065 } 9066 } 9067 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 9068 if (stable) { 9069 conn.stableCount = 1; 9070 conn.numStableIncs = 1; 9071 } else { 9072 conn.unstableCount = 1; 9073 conn.numUnstableIncs = 1; 9074 } 9075 cpr.connections.add(conn); 9076 r.conProviders.add(conn); 9077 return conn; 9078 } 9079 cpr.addExternalProcessHandleLocked(externalProcessToken); 9080 return null; 9081 } 9082 9083 boolean decProviderCountLocked(ContentProviderConnection conn, 9084 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9085 if (conn != null) { 9086 cpr = conn.provider; 9087 if (DEBUG_PROVIDER) Slog.v(TAG, 9088 "Removing provider requested by " 9089 + conn.client.processName + " from process " 9090 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9091 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9092 if (stable) { 9093 conn.stableCount--; 9094 } else { 9095 conn.unstableCount--; 9096 } 9097 if (conn.stableCount == 0 && conn.unstableCount == 0) { 9098 cpr.connections.remove(conn); 9099 conn.client.conProviders.remove(conn); 9100 return true; 9101 } 9102 return false; 9103 } 9104 cpr.removeExternalProcessHandleLocked(externalProcessToken); 9105 return false; 9106 } 9107 9108 private void checkTime(long startTime, String where) { 9109 long now = SystemClock.elapsedRealtime(); 9110 if ((now-startTime) > 1000) { 9111 // If we are taking more than a second, log about it. 9112 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where); 9113 } 9114 } 9115 9116 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 9117 String name, IBinder token, boolean stable, int userId) { 9118 ContentProviderRecord cpr; 9119 ContentProviderConnection conn = null; 9120 ProviderInfo cpi = null; 9121 9122 synchronized(this) { 9123 long startTime = SystemClock.elapsedRealtime(); 9124 9125 ProcessRecord r = null; 9126 if (caller != null) { 9127 r = getRecordForAppLocked(caller); 9128 if (r == null) { 9129 throw new SecurityException( 9130 "Unable to find app for caller " + caller 9131 + " (pid=" + Binder.getCallingPid() 9132 + ") when getting content provider " + name); 9133 } 9134 } 9135 9136 boolean checkCrossUser = true; 9137 9138 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 9139 9140 // First check if this content provider has been published... 9141 cpr = mProviderMap.getProviderByName(name, userId); 9142 // If that didn't work, check if it exists for user 0 and then 9143 // verify that it's a singleton provider before using it. 9144 if (cpr == null && userId != UserHandle.USER_OWNER) { 9145 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER); 9146 if (cpr != null) { 9147 cpi = cpr.info; 9148 if (isSingleton(cpi.processName, cpi.applicationInfo, 9149 cpi.name, cpi.flags) 9150 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 9151 userId = UserHandle.USER_OWNER; 9152 checkCrossUser = false; 9153 } else { 9154 cpr = null; 9155 cpi = null; 9156 } 9157 } 9158 } 9159 9160 boolean providerRunning = cpr != null; 9161 if (providerRunning) { 9162 cpi = cpr.info; 9163 String msg; 9164 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9165 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 9166 != null) { 9167 throw new SecurityException(msg); 9168 } 9169 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9170 9171 if (r != null && cpr.canRunHere(r)) { 9172 // This provider has been published or is in the process 9173 // of being published... but it is also allowed to run 9174 // in the caller's process, so don't make a connection 9175 // and just let the caller instantiate its own instance. 9176 ContentProviderHolder holder = cpr.newHolder(null); 9177 // don't give caller the provider object, it needs 9178 // to make its own. 9179 holder.provider = null; 9180 return holder; 9181 } 9182 9183 final long origId = Binder.clearCallingIdentity(); 9184 9185 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 9186 9187 // In this case the provider instance already exists, so we can 9188 // return it right away. 9189 conn = incProviderCountLocked(r, cpr, token, stable); 9190 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 9191 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 9192 // If this is a perceptible app accessing the provider, 9193 // make sure to count it as being accessed and thus 9194 // back up on the LRU list. This is good because 9195 // content providers are often expensive to start. 9196 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 9197 updateLruProcessLocked(cpr.proc, false, null); 9198 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 9199 } 9200 } 9201 9202 if (cpr.proc != null) { 9203 if (false) { 9204 if (cpr.name.flattenToShortString().equals( 9205 "com.android.providers.calendar/.CalendarProvider2")) { 9206 Slog.v(TAG, "****************** KILLING " 9207 + cpr.name.flattenToShortString()); 9208 Process.killProcess(cpr.proc.pid); 9209 } 9210 } 9211 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 9212 boolean success = updateOomAdjLocked(cpr.proc); 9213 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 9214 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success); 9215 // NOTE: there is still a race here where a signal could be 9216 // pending on the process even though we managed to update its 9217 // adj level. Not sure what to do about this, but at least 9218 // the race is now smaller. 9219 if (!success) { 9220 // Uh oh... it looks like the provider's process 9221 // has been killed on us. We need to wait for a new 9222 // process to be started, and make sure its death 9223 // doesn't kill our process. 9224 Slog.i(TAG, 9225 "Existing provider " + cpr.name.flattenToShortString() 9226 + " is crashing; detaching " + r); 9227 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 9228 checkTime(startTime, "getContentProviderImpl: before appDied"); 9229 appDiedLocked(cpr.proc); 9230 checkTime(startTime, "getContentProviderImpl: after appDied"); 9231 if (!lastRef) { 9232 // This wasn't the last ref our process had on 9233 // the provider... we have now been killed, bail. 9234 return null; 9235 } 9236 providerRunning = false; 9237 conn = null; 9238 } 9239 } 9240 9241 Binder.restoreCallingIdentity(origId); 9242 } 9243 9244 boolean singleton; 9245 if (!providerRunning) { 9246 try { 9247 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 9248 cpi = AppGlobals.getPackageManager(). 9249 resolveContentProvider(name, 9250 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 9251 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 9252 } catch (RemoteException ex) { 9253 } 9254 if (cpi == null) { 9255 return null; 9256 } 9257 // If the provider is a singleton AND 9258 // (it's a call within the same user || the provider is a 9259 // privileged app) 9260 // Then allow connecting to the singleton provider 9261 singleton = isSingleton(cpi.processName, cpi.applicationInfo, 9262 cpi.name, cpi.flags) 9263 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 9264 if (singleton) { 9265 userId = UserHandle.USER_OWNER; 9266 } 9267 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 9268 checkTime(startTime, "getContentProviderImpl: got app info for user"); 9269 9270 String msg; 9271 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9272 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 9273 != null) { 9274 throw new SecurityException(msg); 9275 } 9276 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9277 9278 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate 9279 && !cpi.processName.equals("system")) { 9280 // If this content provider does not run in the system 9281 // process, and the system is not yet ready to run other 9282 // processes, then fail fast instead of hanging. 9283 throw new IllegalArgumentException( 9284 "Attempt to launch content provider before system ready"); 9285 } 9286 9287 // Make sure that the user who owns this provider is started. If not, 9288 // we don't want to allow it to run. 9289 if (mStartedUsers.get(userId) == null) { 9290 Slog.w(TAG, "Unable to launch app " 9291 + cpi.applicationInfo.packageName + "/" 9292 + cpi.applicationInfo.uid + " for provider " 9293 + name + ": user " + userId + " is stopped"); 9294 return null; 9295 } 9296 9297 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 9298 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 9299 cpr = mProviderMap.getProviderByClass(comp, userId); 9300 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 9301 final boolean firstClass = cpr == null; 9302 if (firstClass) { 9303 try { 9304 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 9305 ApplicationInfo ai = 9306 AppGlobals.getPackageManager(). 9307 getApplicationInfo( 9308 cpi.applicationInfo.packageName, 9309 STOCK_PM_FLAGS, userId); 9310 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 9311 if (ai == null) { 9312 Slog.w(TAG, "No package info for content provider " 9313 + cpi.name); 9314 return null; 9315 } 9316 ai = getAppInfoForUser(ai, userId); 9317 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 9318 } catch (RemoteException ex) { 9319 // pm is in same process, this will never happen. 9320 } 9321 } 9322 9323 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 9324 9325 if (r != null && cpr.canRunHere(r)) { 9326 // If this is a multiprocess provider, then just return its 9327 // info and allow the caller to instantiate it. Only do 9328 // this if the provider is the same user as the caller's 9329 // process, or can run as root (so can be in any process). 9330 return cpr.newHolder(null); 9331 } 9332 9333 if (DEBUG_PROVIDER) { 9334 RuntimeException e = new RuntimeException("here"); 9335 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null) 9336 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e); 9337 } 9338 9339 // This is single process, and our app is now connecting to it. 9340 // See if we are already in the process of launching this 9341 // provider. 9342 final int N = mLaunchingProviders.size(); 9343 int i; 9344 for (i=0; i<N; i++) { 9345 if (mLaunchingProviders.get(i) == cpr) { 9346 break; 9347 } 9348 } 9349 9350 // If the provider is not already being launched, then get it 9351 // started. 9352 if (i >= N) { 9353 final long origId = Binder.clearCallingIdentity(); 9354 9355 try { 9356 // Content provider is now in use, its package can't be stopped. 9357 try { 9358 checkTime(startTime, "getContentProviderImpl: before set stopped state"); 9359 AppGlobals.getPackageManager().setPackageStoppedState( 9360 cpr.appInfo.packageName, false, userId); 9361 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 9362 } catch (RemoteException e) { 9363 } catch (IllegalArgumentException e) { 9364 Slog.w(TAG, "Failed trying to unstop package " 9365 + cpr.appInfo.packageName + ": " + e); 9366 } 9367 9368 // Use existing process if already started 9369 checkTime(startTime, "getContentProviderImpl: looking for process record"); 9370 ProcessRecord proc = getProcessRecordLocked( 9371 cpi.processName, cpr.appInfo.uid, false); 9372 if (proc != null && proc.thread != null) { 9373 if (DEBUG_PROVIDER) { 9374 Slog.d(TAG, "Installing in existing process " + proc); 9375 } 9376 checkTime(startTime, "getContentProviderImpl: scheduling install"); 9377 proc.pubProviders.put(cpi.name, cpr); 9378 try { 9379 proc.thread.scheduleInstallProvider(cpi); 9380 } catch (RemoteException e) { 9381 } 9382 } else { 9383 checkTime(startTime, "getContentProviderImpl: before start process"); 9384 proc = startProcessLocked(cpi.processName, 9385 cpr.appInfo, false, 0, "content provider", 9386 new ComponentName(cpi.applicationInfo.packageName, 9387 cpi.name), false, false, false); 9388 checkTime(startTime, "getContentProviderImpl: after start process"); 9389 if (proc == null) { 9390 Slog.w(TAG, "Unable to launch app " 9391 + cpi.applicationInfo.packageName + "/" 9392 + cpi.applicationInfo.uid + " for provider " 9393 + name + ": process is bad"); 9394 return null; 9395 } 9396 } 9397 cpr.launchingApp = proc; 9398 mLaunchingProviders.add(cpr); 9399 } finally { 9400 Binder.restoreCallingIdentity(origId); 9401 } 9402 } 9403 9404 checkTime(startTime, "getContentProviderImpl: updating data structures"); 9405 9406 // Make sure the provider is published (the same provider class 9407 // may be published under multiple names). 9408 if (firstClass) { 9409 mProviderMap.putProviderByClass(comp, cpr); 9410 } 9411 9412 mProviderMap.putProviderByName(name, cpr); 9413 conn = incProviderCountLocked(r, cpr, token, stable); 9414 if (conn != null) { 9415 conn.waiting = true; 9416 } 9417 } 9418 checkTime(startTime, "getContentProviderImpl: done!"); 9419 } 9420 9421 // Wait for the provider to be published... 9422 synchronized (cpr) { 9423 while (cpr.provider == null) { 9424 if (cpr.launchingApp == null) { 9425 Slog.w(TAG, "Unable to launch app " 9426 + cpi.applicationInfo.packageName + "/" 9427 + cpi.applicationInfo.uid + " for provider " 9428 + name + ": launching app became null"); 9429 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 9430 UserHandle.getUserId(cpi.applicationInfo.uid), 9431 cpi.applicationInfo.packageName, 9432 cpi.applicationInfo.uid, name); 9433 return null; 9434 } 9435 try { 9436 if (DEBUG_MU) { 9437 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp=" 9438 + cpr.launchingApp); 9439 } 9440 if (conn != null) { 9441 conn.waiting = true; 9442 } 9443 cpr.wait(); 9444 } catch (InterruptedException ex) { 9445 } finally { 9446 if (conn != null) { 9447 conn.waiting = false; 9448 } 9449 } 9450 } 9451 } 9452 return cpr != null ? cpr.newHolder(conn) : null; 9453 } 9454 9455 @Override 9456 public final ContentProviderHolder getContentProvider( 9457 IApplicationThread caller, String name, int userId, boolean stable) { 9458 enforceNotIsolatedCaller("getContentProvider"); 9459 if (caller == null) { 9460 String msg = "null IApplicationThread when getting content provider " 9461 + name; 9462 Slog.w(TAG, msg); 9463 throw new SecurityException(msg); 9464 } 9465 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 9466 // with cross-user grant. 9467 return getContentProviderImpl(caller, name, null, stable, userId); 9468 } 9469 9470 public ContentProviderHolder getContentProviderExternal( 9471 String name, int userId, IBinder token) { 9472 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9473 "Do not have permission in call getContentProviderExternal()"); 9474 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 9475 false, ALLOW_FULL_ONLY, "getContentProvider", null); 9476 return getContentProviderExternalUnchecked(name, token, userId); 9477 } 9478 9479 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 9480 IBinder token, int userId) { 9481 return getContentProviderImpl(null, name, token, true, userId); 9482 } 9483 9484 /** 9485 * Drop a content provider from a ProcessRecord's bookkeeping 9486 */ 9487 public void removeContentProvider(IBinder connection, boolean stable) { 9488 enforceNotIsolatedCaller("removeContentProvider"); 9489 long ident = Binder.clearCallingIdentity(); 9490 try { 9491 synchronized (this) { 9492 ContentProviderConnection conn; 9493 try { 9494 conn = (ContentProviderConnection)connection; 9495 } catch (ClassCastException e) { 9496 String msg ="removeContentProvider: " + connection 9497 + " not a ContentProviderConnection"; 9498 Slog.w(TAG, msg); 9499 throw new IllegalArgumentException(msg); 9500 } 9501 if (conn == null) { 9502 throw new NullPointerException("connection is null"); 9503 } 9504 if (decProviderCountLocked(conn, null, null, stable)) { 9505 updateOomAdjLocked(); 9506 } 9507 } 9508 } finally { 9509 Binder.restoreCallingIdentity(ident); 9510 } 9511 } 9512 9513 public void removeContentProviderExternal(String name, IBinder token) { 9514 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9515 "Do not have permission in call removeContentProviderExternal()"); 9516 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId()); 9517 } 9518 9519 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 9520 synchronized (this) { 9521 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 9522 if(cpr == null) { 9523 //remove from mProvidersByClass 9524 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list"); 9525 return; 9526 } 9527 9528 //update content provider record entry info 9529 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 9530 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 9531 if (localCpr.hasExternalProcessHandles()) { 9532 if (localCpr.removeExternalProcessHandleLocked(token)) { 9533 updateOomAdjLocked(); 9534 } else { 9535 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 9536 + " with no external reference for token: " 9537 + token + "."); 9538 } 9539 } else { 9540 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 9541 + " with no external references."); 9542 } 9543 } 9544 } 9545 9546 public final void publishContentProviders(IApplicationThread caller, 9547 List<ContentProviderHolder> providers) { 9548 if (providers == null) { 9549 return; 9550 } 9551 9552 enforceNotIsolatedCaller("publishContentProviders"); 9553 synchronized (this) { 9554 final ProcessRecord r = getRecordForAppLocked(caller); 9555 if (DEBUG_MU) 9556 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 9557 if (r == null) { 9558 throw new SecurityException( 9559 "Unable to find app for caller " + caller 9560 + " (pid=" + Binder.getCallingPid() 9561 + ") when publishing content providers"); 9562 } 9563 9564 final long origId = Binder.clearCallingIdentity(); 9565 9566 final int N = providers.size(); 9567 for (int i=0; i<N; i++) { 9568 ContentProviderHolder src = providers.get(i); 9569 if (src == null || src.info == null || src.provider == null) { 9570 continue; 9571 } 9572 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 9573 if (DEBUG_MU) 9574 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 9575 if (dst != null) { 9576 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 9577 mProviderMap.putProviderByClass(comp, dst); 9578 String names[] = dst.info.authority.split(";"); 9579 for (int j = 0; j < names.length; j++) { 9580 mProviderMap.putProviderByName(names[j], dst); 9581 } 9582 9583 int NL = mLaunchingProviders.size(); 9584 int j; 9585 for (j=0; j<NL; j++) { 9586 if (mLaunchingProviders.get(j) == dst) { 9587 mLaunchingProviders.remove(j); 9588 j--; 9589 NL--; 9590 } 9591 } 9592 synchronized (dst) { 9593 dst.provider = src.provider; 9594 dst.proc = r; 9595 dst.notifyAll(); 9596 } 9597 updateOomAdjLocked(r); 9598 } 9599 } 9600 9601 Binder.restoreCallingIdentity(origId); 9602 } 9603 } 9604 9605 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 9606 ContentProviderConnection conn; 9607 try { 9608 conn = (ContentProviderConnection)connection; 9609 } catch (ClassCastException e) { 9610 String msg ="refContentProvider: " + connection 9611 + " not a ContentProviderConnection"; 9612 Slog.w(TAG, msg); 9613 throw new IllegalArgumentException(msg); 9614 } 9615 if (conn == null) { 9616 throw new NullPointerException("connection is null"); 9617 } 9618 9619 synchronized (this) { 9620 if (stable > 0) { 9621 conn.numStableIncs += stable; 9622 } 9623 stable = conn.stableCount + stable; 9624 if (stable < 0) { 9625 throw new IllegalStateException("stableCount < 0: " + stable); 9626 } 9627 9628 if (unstable > 0) { 9629 conn.numUnstableIncs += unstable; 9630 } 9631 unstable = conn.unstableCount + unstable; 9632 if (unstable < 0) { 9633 throw new IllegalStateException("unstableCount < 0: " + unstable); 9634 } 9635 9636 if ((stable+unstable) <= 0) { 9637 throw new IllegalStateException("ref counts can't go to zero here: stable=" 9638 + stable + " unstable=" + unstable); 9639 } 9640 conn.stableCount = stable; 9641 conn.unstableCount = unstable; 9642 return !conn.dead; 9643 } 9644 } 9645 9646 public void unstableProviderDied(IBinder connection) { 9647 ContentProviderConnection conn; 9648 try { 9649 conn = (ContentProviderConnection)connection; 9650 } catch (ClassCastException e) { 9651 String msg ="refContentProvider: " + connection 9652 + " not a ContentProviderConnection"; 9653 Slog.w(TAG, msg); 9654 throw new IllegalArgumentException(msg); 9655 } 9656 if (conn == null) { 9657 throw new NullPointerException("connection is null"); 9658 } 9659 9660 // Safely retrieve the content provider associated with the connection. 9661 IContentProvider provider; 9662 synchronized (this) { 9663 provider = conn.provider.provider; 9664 } 9665 9666 if (provider == null) { 9667 // Um, yeah, we're way ahead of you. 9668 return; 9669 } 9670 9671 // Make sure the caller is being honest with us. 9672 if (provider.asBinder().pingBinder()) { 9673 // Er, no, still looks good to us. 9674 synchronized (this) { 9675 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 9676 + " says " + conn + " died, but we don't agree"); 9677 return; 9678 } 9679 } 9680 9681 // Well look at that! It's dead! 9682 synchronized (this) { 9683 if (conn.provider.provider != provider) { 9684 // But something changed... good enough. 9685 return; 9686 } 9687 9688 ProcessRecord proc = conn.provider.proc; 9689 if (proc == null || proc.thread == null) { 9690 // Seems like the process is already cleaned up. 9691 return; 9692 } 9693 9694 // As far as we're concerned, this is just like receiving a 9695 // death notification... just a bit prematurely. 9696 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid 9697 + ") early provider death"); 9698 final long ident = Binder.clearCallingIdentity(); 9699 try { 9700 appDiedLocked(proc); 9701 } finally { 9702 Binder.restoreCallingIdentity(ident); 9703 } 9704 } 9705 } 9706 9707 @Override 9708 public void appNotRespondingViaProvider(IBinder connection) { 9709 enforceCallingPermission( 9710 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()"); 9711 9712 final ContentProviderConnection conn = (ContentProviderConnection) connection; 9713 if (conn == null) { 9714 Slog.w(TAG, "ContentProviderConnection is null"); 9715 return; 9716 } 9717 9718 final ProcessRecord host = conn.provider.proc; 9719 if (host == null) { 9720 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 9721 return; 9722 } 9723 9724 final long token = Binder.clearCallingIdentity(); 9725 try { 9726 appNotResponding(host, null, null, false, "ContentProvider not responding"); 9727 } finally { 9728 Binder.restoreCallingIdentity(token); 9729 } 9730 } 9731 9732 public final void installSystemProviders() { 9733 List<ProviderInfo> providers; 9734 synchronized (this) { 9735 ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID); 9736 providers = generateApplicationProvidersLocked(app); 9737 if (providers != null) { 9738 for (int i=providers.size()-1; i>=0; i--) { 9739 ProviderInfo pi = (ProviderInfo)providers.get(i); 9740 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9741 Slog.w(TAG, "Not installing system proc provider " + pi.name 9742 + ": not system .apk"); 9743 providers.remove(i); 9744 } 9745 } 9746 } 9747 } 9748 if (providers != null) { 9749 mSystemThread.installSystemProviders(providers); 9750 } 9751 9752 mCoreSettingsObserver = new CoreSettingsObserver(this); 9753 9754 //mUsageStatsService.monitorPackages(); 9755 } 9756 9757 /** 9758 * Allows apps to retrieve the MIME type of a URI. 9759 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 9760 * users, then it does not need permission to access the ContentProvider. 9761 * Either, it needs cross-user uri grants. 9762 * 9763 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 9764 * 9765 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 9766 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 9767 */ 9768 public String getProviderMimeType(Uri uri, int userId) { 9769 enforceNotIsolatedCaller("getProviderMimeType"); 9770 final String name = uri.getAuthority(); 9771 int callingUid = Binder.getCallingUid(); 9772 int callingPid = Binder.getCallingPid(); 9773 long ident = 0; 9774 boolean clearedIdentity = false; 9775 userId = unsafeConvertIncomingUser(userId); 9776 if (canClearIdentity(callingPid, callingUid, userId)) { 9777 clearedIdentity = true; 9778 ident = Binder.clearCallingIdentity(); 9779 } 9780 ContentProviderHolder holder = null; 9781 try { 9782 holder = getContentProviderExternalUnchecked(name, null, userId); 9783 if (holder != null) { 9784 return holder.provider.getType(uri); 9785 } 9786 } catch (RemoteException e) { 9787 Log.w(TAG, "Content provider dead retrieving " + uri, e); 9788 return null; 9789 } finally { 9790 // We need to clear the identity to call removeContentProviderExternalUnchecked 9791 if (!clearedIdentity) { 9792 ident = Binder.clearCallingIdentity(); 9793 } 9794 try { 9795 if (holder != null) { 9796 removeContentProviderExternalUnchecked(name, null, userId); 9797 } 9798 } finally { 9799 Binder.restoreCallingIdentity(ident); 9800 } 9801 } 9802 9803 return null; 9804 } 9805 9806 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 9807 if (UserHandle.getUserId(callingUid) == userId) { 9808 return true; 9809 } 9810 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 9811 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 9812 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 9813 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 9814 return true; 9815 } 9816 return false; 9817 } 9818 9819 // ========================================================= 9820 // GLOBAL MANAGEMENT 9821 // ========================================================= 9822 9823 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 9824 boolean isolated, int isolatedUid) { 9825 String proc = customProcess != null ? customProcess : info.processName; 9826 BatteryStatsImpl.Uid.Proc ps = null; 9827 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 9828 int uid = info.uid; 9829 if (isolated) { 9830 if (isolatedUid == 0) { 9831 int userId = UserHandle.getUserId(uid); 9832 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1; 9833 while (true) { 9834 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID 9835 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) { 9836 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID; 9837 } 9838 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid); 9839 mNextIsolatedProcessUid++; 9840 if (mIsolatedProcesses.indexOfKey(uid) < 0) { 9841 // No process for this uid, use it. 9842 break; 9843 } 9844 stepsLeft--; 9845 if (stepsLeft <= 0) { 9846 return null; 9847 } 9848 } 9849 } else { 9850 // Special case for startIsolatedProcess (internal only), where 9851 // the uid of the isolated process is specified by the caller. 9852 uid = isolatedUid; 9853 } 9854 } 9855 return new ProcessRecord(stats, info, proc, uid); 9856 } 9857 9858 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated, 9859 String abiOverride) { 9860 ProcessRecord app; 9861 if (!isolated) { 9862 app = getProcessRecordLocked(info.processName, info.uid, true); 9863 } else { 9864 app = null; 9865 } 9866 9867 if (app == null) { 9868 app = newProcessRecordLocked(info, null, isolated, 0); 9869 mProcessNames.put(info.processName, app.uid, app); 9870 if (isolated) { 9871 mIsolatedProcesses.put(app.uid, app); 9872 } 9873 updateLruProcessLocked(app, false, null); 9874 updateOomAdjLocked(); 9875 } 9876 9877 // This package really, really can not be stopped. 9878 try { 9879 AppGlobals.getPackageManager().setPackageStoppedState( 9880 info.packageName, false, UserHandle.getUserId(app.uid)); 9881 } catch (RemoteException e) { 9882 } catch (IllegalArgumentException e) { 9883 Slog.w(TAG, "Failed trying to unstop package " 9884 + info.packageName + ": " + e); 9885 } 9886 9887 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) 9888 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) { 9889 app.persistent = true; 9890 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 9891 } 9892 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 9893 mPersistentStartingProcesses.add(app); 9894 startProcessLocked(app, "added application", app.processName, abiOverride, 9895 null /* entryPoint */, null /* entryPointArgs */); 9896 } 9897 9898 return app; 9899 } 9900 9901 public void unhandledBack() { 9902 enforceCallingPermission(android.Manifest.permission.FORCE_BACK, 9903 "unhandledBack()"); 9904 9905 synchronized(this) { 9906 final long origId = Binder.clearCallingIdentity(); 9907 try { 9908 getFocusedStack().unhandledBackLocked(); 9909 } finally { 9910 Binder.restoreCallingIdentity(origId); 9911 } 9912 } 9913 } 9914 9915 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException { 9916 enforceNotIsolatedCaller("openContentUri"); 9917 final int userId = UserHandle.getCallingUserId(); 9918 String name = uri.getAuthority(); 9919 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId); 9920 ParcelFileDescriptor pfd = null; 9921 if (cph != null) { 9922 // We record the binder invoker's uid in thread-local storage before 9923 // going to the content provider to open the file. Later, in the code 9924 // that handles all permissions checks, we look for this uid and use 9925 // that rather than the Activity Manager's own uid. The effect is that 9926 // we do the check against the caller's permissions even though it looks 9927 // to the content provider like the Activity Manager itself is making 9928 // the request. 9929 sCallerIdentity.set(new Identity( 9930 Binder.getCallingPid(), Binder.getCallingUid())); 9931 try { 9932 pfd = cph.provider.openFile(null, uri, "r", null); 9933 } catch (FileNotFoundException e) { 9934 // do nothing; pfd will be returned null 9935 } finally { 9936 // Ensure that whatever happens, we clean up the identity state 9937 sCallerIdentity.remove(); 9938 } 9939 9940 // We've got the fd now, so we're done with the provider. 9941 removeContentProviderExternalUnchecked(name, null, userId); 9942 } else { 9943 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 9944 } 9945 return pfd; 9946 } 9947 9948 // Actually is sleeping or shutting down or whatever else in the future 9949 // is an inactive state. 9950 public boolean isSleepingOrShuttingDown() { 9951 return isSleeping() || mShuttingDown; 9952 } 9953 9954 public boolean isSleeping() { 9955 return mSleeping && !mKeyguardWaitingForDraw; 9956 } 9957 9958 void goingToSleep() { 9959 synchronized(this) { 9960 mWentToSleep = true; 9961 goToSleepIfNeededLocked(); 9962 } 9963 } 9964 9965 void finishRunningVoiceLocked() { 9966 if (mRunningVoice) { 9967 mRunningVoice = false; 9968 goToSleepIfNeededLocked(); 9969 } 9970 } 9971 9972 void goToSleepIfNeededLocked() { 9973 if (mWentToSleep && !mRunningVoice) { 9974 if (!mSleeping) { 9975 mSleeping = true; 9976 mKeyguardWaitingForDraw = false; 9977 mStackSupervisor.goingToSleepLocked(); 9978 9979 // Initialize the wake times of all processes. 9980 checkExcessivePowerUsageLocked(false); 9981 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9982 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9983 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 9984 } 9985 } 9986 } 9987 9988 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { 9989 if (task != null && task.stack != null && task.stack.isHomeStack()) { 9990 // Never persist the home stack. 9991 return; 9992 } 9993 mTaskPersister.wakeup(task, flush); 9994 } 9995 9996 @Override 9997 public boolean shutdown(int timeout) { 9998 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 9999 != PackageManager.PERMISSION_GRANTED) { 10000 throw new SecurityException("Requires permission " 10001 + android.Manifest.permission.SHUTDOWN); 10002 } 10003 10004 boolean timedout = false; 10005 10006 synchronized(this) { 10007 mShuttingDown = true; 10008 updateEventDispatchingLocked(); 10009 timedout = mStackSupervisor.shutdownLocked(timeout); 10010 } 10011 10012 mAppOpsService.shutdown(); 10013 if (mUsageStatsService != null) { 10014 mUsageStatsService.prepareShutdown(); 10015 } 10016 mBatteryStatsService.shutdown(); 10017 synchronized (this) { 10018 mProcessStats.shutdownLocked(); 10019 } 10020 notifyTaskPersisterLocked(null, true); 10021 10022 return timedout; 10023 } 10024 10025 public final void activitySlept(IBinder token) { 10026 if (localLOGV) Slog.v(TAG, "Activity slept: token=" + token); 10027 10028 final long origId = Binder.clearCallingIdentity(); 10029 10030 synchronized (this) { 10031 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10032 if (r != null) { 10033 mStackSupervisor.activitySleptLocked(r); 10034 } 10035 } 10036 10037 Binder.restoreCallingIdentity(origId); 10038 } 10039 10040 void logLockScreen(String msg) { 10041 if (DEBUG_LOCKSCREEN) Slog.d(TAG, Debug.getCallers(2) + ":" + msg + 10042 " mLockScreenShown=" + mLockScreenShown + " mWentToSleep=" + 10043 mWentToSleep + " mSleeping=" + mSleeping); 10044 } 10045 10046 private void comeOutOfSleepIfNeededLocked() { 10047 if ((!mWentToSleep && !mLockScreenShown) || mRunningVoice) { 10048 if (mSleeping) { 10049 mSleeping = false; 10050 mStackSupervisor.comeOutOfSleepIfNeededLocked(); 10051 } 10052 } 10053 } 10054 10055 void wakingUp() { 10056 synchronized(this) { 10057 mWentToSleep = false; 10058 comeOutOfSleepIfNeededLocked(); 10059 } 10060 } 10061 10062 void startRunningVoiceLocked() { 10063 if (!mRunningVoice) { 10064 mRunningVoice = true; 10065 comeOutOfSleepIfNeededLocked(); 10066 } 10067 } 10068 10069 private void updateEventDispatchingLocked() { 10070 mWindowManager.setEventDispatching(mBooted && !mShuttingDown); 10071 } 10072 10073 public void setLockScreenShown(boolean shown) { 10074 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER) 10075 != PackageManager.PERMISSION_GRANTED) { 10076 throw new SecurityException("Requires permission " 10077 + android.Manifest.permission.DEVICE_POWER); 10078 } 10079 10080 synchronized(this) { 10081 long ident = Binder.clearCallingIdentity(); 10082 try { 10083 if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown); 10084 mLockScreenShown = shown; 10085 mKeyguardWaitingForDraw = false; 10086 comeOutOfSleepIfNeededLocked(); 10087 } finally { 10088 Binder.restoreCallingIdentity(ident); 10089 } 10090 } 10091 } 10092 10093 @Override 10094 public void stopAppSwitches() { 10095 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10096 != PackageManager.PERMISSION_GRANTED) { 10097 throw new SecurityException("Requires permission " 10098 + android.Manifest.permission.STOP_APP_SWITCHES); 10099 } 10100 10101 synchronized(this) { 10102 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() 10103 + APP_SWITCH_DELAY_TIME; 10104 mDidAppSwitch = false; 10105 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10106 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10107 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME); 10108 } 10109 } 10110 10111 public void resumeAppSwitches() { 10112 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10113 != PackageManager.PERMISSION_GRANTED) { 10114 throw new SecurityException("Requires permission " 10115 + android.Manifest.permission.STOP_APP_SWITCHES); 10116 } 10117 10118 synchronized(this) { 10119 // Note that we don't execute any pending app switches... we will 10120 // let those wait until either the timeout, or the next start 10121 // activity request. 10122 mAppSwitchesAllowedTime = 0; 10123 } 10124 } 10125 10126 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, 10127 int callingPid, int callingUid, String name) { 10128 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { 10129 return true; 10130 } 10131 10132 int perm = checkComponentPermission( 10133 android.Manifest.permission.STOP_APP_SWITCHES, sourcePid, 10134 sourceUid, -1, true); 10135 if (perm == PackageManager.PERMISSION_GRANTED) { 10136 return true; 10137 } 10138 10139 // If the actual IPC caller is different from the logical source, then 10140 // also see if they are allowed to control app switches. 10141 if (callingUid != -1 && callingUid != sourceUid) { 10142 perm = checkComponentPermission( 10143 android.Manifest.permission.STOP_APP_SWITCHES, callingPid, 10144 callingUid, -1, true); 10145 if (perm == PackageManager.PERMISSION_GRANTED) { 10146 return true; 10147 } 10148 } 10149 10150 Slog.w(TAG, name + " request from " + sourceUid + " stopped"); 10151 return false; 10152 } 10153 10154 public void setDebugApp(String packageName, boolean waitForDebugger, 10155 boolean persistent) { 10156 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 10157 "setDebugApp()"); 10158 10159 long ident = Binder.clearCallingIdentity(); 10160 try { 10161 // Note that this is not really thread safe if there are multiple 10162 // callers into it at the same time, but that's not a situation we 10163 // care about. 10164 if (persistent) { 10165 final ContentResolver resolver = mContext.getContentResolver(); 10166 Settings.Global.putString( 10167 resolver, Settings.Global.DEBUG_APP, 10168 packageName); 10169 Settings.Global.putInt( 10170 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 10171 waitForDebugger ? 1 : 0); 10172 } 10173 10174 synchronized (this) { 10175 if (!persistent) { 10176 mOrigDebugApp = mDebugApp; 10177 mOrigWaitForDebugger = mWaitForDebugger; 10178 } 10179 mDebugApp = packageName; 10180 mWaitForDebugger = waitForDebugger; 10181 mDebugTransient = !persistent; 10182 if (packageName != null) { 10183 forceStopPackageLocked(packageName, -1, false, false, true, true, 10184 false, UserHandle.USER_ALL, "set debug app"); 10185 } 10186 } 10187 } finally { 10188 Binder.restoreCallingIdentity(ident); 10189 } 10190 } 10191 10192 void setOpenGlTraceApp(ApplicationInfo app, String processName) { 10193 synchronized (this) { 10194 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10195 if (!isDebuggable) { 10196 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10197 throw new SecurityException("Process not debuggable: " + app.packageName); 10198 } 10199 } 10200 10201 mOpenGlTraceApp = processName; 10202 } 10203 } 10204 10205 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 10206 synchronized (this) { 10207 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10208 if (!isDebuggable) { 10209 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10210 throw new SecurityException("Process not debuggable: " + app.packageName); 10211 } 10212 } 10213 mProfileApp = processName; 10214 mProfileFile = profilerInfo.profileFile; 10215 if (mProfileFd != null) { 10216 try { 10217 mProfileFd.close(); 10218 } catch (IOException e) { 10219 } 10220 mProfileFd = null; 10221 } 10222 mProfileFd = profilerInfo.profileFd; 10223 mSamplingInterval = profilerInfo.samplingInterval; 10224 mAutoStopProfiler = profilerInfo.autoStopProfiler; 10225 mProfileType = 0; 10226 } 10227 } 10228 10229 @Override 10230 public void setAlwaysFinish(boolean enabled) { 10231 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 10232 "setAlwaysFinish()"); 10233 10234 Settings.Global.putInt( 10235 mContext.getContentResolver(), 10236 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 10237 10238 synchronized (this) { 10239 mAlwaysFinishActivities = enabled; 10240 } 10241 } 10242 10243 @Override 10244 public void setActivityController(IActivityController controller) { 10245 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10246 "setActivityController()"); 10247 synchronized (this) { 10248 mController = controller; 10249 Watchdog.getInstance().setActivityController(controller); 10250 } 10251 } 10252 10253 @Override 10254 public void setUserIsMonkey(boolean userIsMonkey) { 10255 synchronized (this) { 10256 synchronized (mPidsSelfLocked) { 10257 final int callingPid = Binder.getCallingPid(); 10258 ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid); 10259 if (precessRecord == null) { 10260 throw new SecurityException("Unknown process: " + callingPid); 10261 } 10262 if (precessRecord.instrumentationUiAutomationConnection == null) { 10263 throw new SecurityException("Only an instrumentation process " 10264 + "with a UiAutomation can call setUserIsMonkey"); 10265 } 10266 } 10267 mUserIsMonkey = userIsMonkey; 10268 } 10269 } 10270 10271 @Override 10272 public boolean isUserAMonkey() { 10273 synchronized (this) { 10274 // If there is a controller also implies the user is a monkey. 10275 return (mUserIsMonkey || mController != null); 10276 } 10277 } 10278 10279 public void requestBugReport() { 10280 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 10281 SystemProperties.set("ctl.start", "bugreport"); 10282 } 10283 10284 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) { 10285 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT; 10286 } 10287 10288 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) { 10289 if (r != null && (r.instrumentationClass != null || r.usingWrapper)) { 10290 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT; 10291 } 10292 return KEY_DISPATCHING_TIMEOUT; 10293 } 10294 10295 @Override 10296 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 10297 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10298 != PackageManager.PERMISSION_GRANTED) { 10299 throw new SecurityException("Requires permission " 10300 + android.Manifest.permission.FILTER_EVENTS); 10301 } 10302 ProcessRecord proc; 10303 long timeout; 10304 synchronized (this) { 10305 synchronized (mPidsSelfLocked) { 10306 proc = mPidsSelfLocked.get(pid); 10307 } 10308 timeout = getInputDispatchingTimeoutLocked(proc); 10309 } 10310 10311 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) { 10312 return -1; 10313 } 10314 10315 return timeout; 10316 } 10317 10318 /** 10319 * Handle input dispatching timeouts. 10320 * Returns whether input dispatching should be aborted or not. 10321 */ 10322 public boolean inputDispatchingTimedOut(final ProcessRecord proc, 10323 final ActivityRecord activity, final ActivityRecord parent, 10324 final boolean aboveSystem, String reason) { 10325 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10326 != PackageManager.PERMISSION_GRANTED) { 10327 throw new SecurityException("Requires permission " 10328 + android.Manifest.permission.FILTER_EVENTS); 10329 } 10330 10331 final String annotation; 10332 if (reason == null) { 10333 annotation = "Input dispatching timed out"; 10334 } else { 10335 annotation = "Input dispatching timed out (" + reason + ")"; 10336 } 10337 10338 if (proc != null) { 10339 synchronized (this) { 10340 if (proc.debugging) { 10341 return false; 10342 } 10343 10344 if (mDidDexOpt) { 10345 // Give more time since we were dexopting. 10346 mDidDexOpt = false; 10347 return false; 10348 } 10349 10350 if (proc.instrumentationClass != null) { 10351 Bundle info = new Bundle(); 10352 info.putString("shortMsg", "keyDispatchingTimedOut"); 10353 info.putString("longMsg", annotation); 10354 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 10355 return true; 10356 } 10357 } 10358 mHandler.post(new Runnable() { 10359 @Override 10360 public void run() { 10361 appNotResponding(proc, activity, parent, aboveSystem, annotation); 10362 } 10363 }); 10364 } 10365 10366 return true; 10367 } 10368 10369 public Bundle getAssistContextExtras(int requestType) { 10370 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO, 10371 "getAssistContextExtras()"); 10372 PendingAssistExtras pae; 10373 Bundle extras = new Bundle(); 10374 synchronized (this) { 10375 ActivityRecord activity = getFocusedStack().mResumedActivity; 10376 if (activity == null) { 10377 Slog.w(TAG, "getAssistContextExtras failed: no resumed activity"); 10378 return null; 10379 } 10380 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName); 10381 if (activity.app == null || activity.app.thread == null) { 10382 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity); 10383 return extras; 10384 } 10385 if (activity.app.pid == Binder.getCallingPid()) { 10386 Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity); 10387 return extras; 10388 } 10389 pae = new PendingAssistExtras(activity); 10390 try { 10391 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, 10392 requestType); 10393 mPendingAssistExtras.add(pae); 10394 mHandler.postDelayed(pae, PENDING_ASSIST_EXTRAS_TIMEOUT); 10395 } catch (RemoteException e) { 10396 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity); 10397 return extras; 10398 } 10399 } 10400 synchronized (pae) { 10401 while (!pae.haveResult) { 10402 try { 10403 pae.wait(); 10404 } catch (InterruptedException e) { 10405 } 10406 } 10407 if (pae.result != null) { 10408 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result); 10409 } 10410 } 10411 synchronized (this) { 10412 mPendingAssistExtras.remove(pae); 10413 mHandler.removeCallbacks(pae); 10414 } 10415 return extras; 10416 } 10417 10418 public void reportAssistContextExtras(IBinder token, Bundle extras) { 10419 PendingAssistExtras pae = (PendingAssistExtras)token; 10420 synchronized (pae) { 10421 pae.result = extras; 10422 pae.haveResult = true; 10423 pae.notifyAll(); 10424 } 10425 } 10426 10427 public void registerProcessObserver(IProcessObserver observer) { 10428 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10429 "registerProcessObserver()"); 10430 synchronized (this) { 10431 mProcessObservers.register(observer); 10432 } 10433 } 10434 10435 @Override 10436 public void unregisterProcessObserver(IProcessObserver observer) { 10437 synchronized (this) { 10438 mProcessObservers.unregister(observer); 10439 } 10440 } 10441 10442 @Override 10443 public boolean convertFromTranslucent(IBinder token) { 10444 final long origId = Binder.clearCallingIdentity(); 10445 try { 10446 synchronized (this) { 10447 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10448 if (r == null) { 10449 return false; 10450 } 10451 final boolean translucentChanged = r.changeWindowTranslucency(true); 10452 if (translucentChanged) { 10453 r.task.stack.releaseBackgroundResources(); 10454 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 10455 } 10456 mWindowManager.setAppFullscreen(token, true); 10457 return translucentChanged; 10458 } 10459 } finally { 10460 Binder.restoreCallingIdentity(origId); 10461 } 10462 } 10463 10464 @Override 10465 public boolean convertToTranslucent(IBinder token, ActivityOptions options) { 10466 final long origId = Binder.clearCallingIdentity(); 10467 try { 10468 synchronized (this) { 10469 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10470 if (r == null) { 10471 return false; 10472 } 10473 int index = r.task.mActivities.lastIndexOf(r); 10474 if (index > 0) { 10475 ActivityRecord under = r.task.mActivities.get(index - 1); 10476 under.returningOptions = options; 10477 } 10478 final boolean translucentChanged = r.changeWindowTranslucency(false); 10479 if (translucentChanged) { 10480 r.task.stack.convertToTranslucent(r); 10481 } 10482 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 10483 mWindowManager.setAppFullscreen(token, false); 10484 return translucentChanged; 10485 } 10486 } finally { 10487 Binder.restoreCallingIdentity(origId); 10488 } 10489 } 10490 10491 @Override 10492 public boolean requestVisibleBehind(IBinder token, boolean visible) { 10493 final long origId = Binder.clearCallingIdentity(); 10494 try { 10495 synchronized (this) { 10496 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10497 if (r != null) { 10498 return mStackSupervisor.requestVisibleBehindLocked(r, visible); 10499 } 10500 } 10501 return false; 10502 } finally { 10503 Binder.restoreCallingIdentity(origId); 10504 } 10505 } 10506 10507 @Override 10508 public boolean isBackgroundVisibleBehind(IBinder token) { 10509 final long origId = Binder.clearCallingIdentity(); 10510 try { 10511 synchronized (this) { 10512 final ActivityStack stack = ActivityRecord.getStackLocked(token); 10513 final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity(); 10514 if (ActivityStackSupervisor.DEBUG_VISIBLE_BEHIND) Slog.d(TAG, 10515 "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible); 10516 return visible; 10517 } 10518 } finally { 10519 Binder.restoreCallingIdentity(origId); 10520 } 10521 } 10522 10523 @Override 10524 public ActivityOptions getActivityOptions(IBinder token) { 10525 final long origId = Binder.clearCallingIdentity(); 10526 try { 10527 synchronized (this) { 10528 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10529 if (r != null) { 10530 final ActivityOptions activityOptions = r.pendingOptions; 10531 r.pendingOptions = null; 10532 return activityOptions; 10533 } 10534 return null; 10535 } 10536 } finally { 10537 Binder.restoreCallingIdentity(origId); 10538 } 10539 } 10540 10541 @Override 10542 public void setImmersive(IBinder token, boolean immersive) { 10543 synchronized(this) { 10544 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10545 if (r == null) { 10546 throw new IllegalArgumentException(); 10547 } 10548 r.immersive = immersive; 10549 10550 // update associated state if we're frontmost 10551 if (r == mFocusedActivity) { 10552 if (DEBUG_IMMERSIVE) { 10553 Slog.d(TAG, "Frontmost changed immersion: "+ r); 10554 } 10555 applyUpdateLockStateLocked(r); 10556 } 10557 } 10558 } 10559 10560 @Override 10561 public boolean isImmersive(IBinder token) { 10562 synchronized (this) { 10563 ActivityRecord r = ActivityRecord.isInStackLocked(token); 10564 if (r == null) { 10565 throw new IllegalArgumentException(); 10566 } 10567 return r.immersive; 10568 } 10569 } 10570 10571 public boolean isTopActivityImmersive() { 10572 enforceNotIsolatedCaller("startActivity"); 10573 synchronized (this) { 10574 ActivityRecord r = getFocusedStack().topRunningActivityLocked(null); 10575 return (r != null) ? r.immersive : false; 10576 } 10577 } 10578 10579 @Override 10580 public boolean isTopOfTask(IBinder token) { 10581 synchronized (this) { 10582 ActivityRecord r = ActivityRecord.isInStackLocked(token); 10583 if (r == null) { 10584 throw new IllegalArgumentException(); 10585 } 10586 return r.task.getTopActivity() == r; 10587 } 10588 } 10589 10590 public final void enterSafeMode() { 10591 synchronized(this) { 10592 // It only makes sense to do this before the system is ready 10593 // and started launching other packages. 10594 if (!mSystemReady) { 10595 try { 10596 AppGlobals.getPackageManager().enterSafeMode(); 10597 } catch (RemoteException e) { 10598 } 10599 } 10600 10601 mSafeMode = true; 10602 } 10603 } 10604 10605 public final void showSafeModeOverlay() { 10606 View v = LayoutInflater.from(mContext).inflate( 10607 com.android.internal.R.layout.safe_mode, null); 10608 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 10609 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 10610 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 10611 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 10612 lp.gravity = Gravity.BOTTOM | Gravity.START; 10613 lp.format = v.getBackground().getOpacity(); 10614 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 10615 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 10616 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 10617 ((WindowManager)mContext.getSystemService( 10618 Context.WINDOW_SERVICE)).addView(v, lp); 10619 } 10620 10621 public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg) { 10622 if (!(sender instanceof PendingIntentRecord)) { 10623 return; 10624 } 10625 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 10626 synchronized (stats) { 10627 if (mBatteryStatsService.isOnBattery()) { 10628 mBatteryStatsService.enforceCallingPermission(); 10629 PendingIntentRecord rec = (PendingIntentRecord)sender; 10630 int MY_UID = Binder.getCallingUid(); 10631 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 10632 BatteryStatsImpl.Uid.Pkg pkg = 10633 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid, 10634 sourcePkg != null ? sourcePkg : rec.key.packageName); 10635 pkg.incWakeupsLocked(); 10636 } 10637 } 10638 } 10639 10640 public boolean killPids(int[] pids, String pReason, boolean secure) { 10641 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10642 throw new SecurityException("killPids only available to the system"); 10643 } 10644 String reason = (pReason == null) ? "Unknown" : pReason; 10645 // XXX Note: don't acquire main activity lock here, because the window 10646 // manager calls in with its locks held. 10647 10648 boolean killed = false; 10649 synchronized (mPidsSelfLocked) { 10650 int[] types = new int[pids.length]; 10651 int worstType = 0; 10652 for (int i=0; i<pids.length; i++) { 10653 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 10654 if (proc != null) { 10655 int type = proc.setAdj; 10656 types[i] = type; 10657 if (type > worstType) { 10658 worstType = type; 10659 } 10660 } 10661 } 10662 10663 // If the worst oom_adj is somewhere in the cached proc LRU range, 10664 // then constrain it so we will kill all cached procs. 10665 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 10666 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 10667 worstType = ProcessList.CACHED_APP_MIN_ADJ; 10668 } 10669 10670 // If this is not a secure call, don't let it kill processes that 10671 // are important. 10672 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 10673 worstType = ProcessList.SERVICE_ADJ; 10674 } 10675 10676 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 10677 for (int i=0; i<pids.length; i++) { 10678 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 10679 if (proc == null) { 10680 continue; 10681 } 10682 int adj = proc.setAdj; 10683 if (adj >= worstType && !proc.killedByAm) { 10684 proc.kill(reason, true); 10685 killed = true; 10686 } 10687 } 10688 } 10689 return killed; 10690 } 10691 10692 @Override 10693 public void killUid(int uid, String reason) { 10694 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10695 throw new SecurityException("killUid only available to the system"); 10696 } 10697 synchronized (this) { 10698 killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid), 10699 ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false, 10700 reason != null ? reason : "kill uid"); 10701 } 10702 } 10703 10704 @Override 10705 public boolean killProcessesBelowForeground(String reason) { 10706 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10707 throw new SecurityException("killProcessesBelowForeground() only available to system"); 10708 } 10709 10710 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 10711 } 10712 10713 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 10714 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 10715 throw new SecurityException("killProcessesBelowAdj() only available to system"); 10716 } 10717 10718 boolean killed = false; 10719 synchronized (mPidsSelfLocked) { 10720 final int size = mPidsSelfLocked.size(); 10721 for (int i = 0; i < size; i++) { 10722 final int pid = mPidsSelfLocked.keyAt(i); 10723 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 10724 if (proc == null) continue; 10725 10726 final int adj = proc.setAdj; 10727 if (adj > belowAdj && !proc.killedByAm) { 10728 proc.kill(reason, true); 10729 killed = true; 10730 } 10731 } 10732 } 10733 return killed; 10734 } 10735 10736 @Override 10737 public void hang(final IBinder who, boolean allowRestart) { 10738 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10739 != PackageManager.PERMISSION_GRANTED) { 10740 throw new SecurityException("Requires permission " 10741 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10742 } 10743 10744 final IBinder.DeathRecipient death = new DeathRecipient() { 10745 @Override 10746 public void binderDied() { 10747 synchronized (this) { 10748 notifyAll(); 10749 } 10750 } 10751 }; 10752 10753 try { 10754 who.linkToDeath(death, 0); 10755 } catch (RemoteException e) { 10756 Slog.w(TAG, "hang: given caller IBinder is already dead."); 10757 return; 10758 } 10759 10760 synchronized (this) { 10761 Watchdog.getInstance().setAllowRestart(allowRestart); 10762 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 10763 synchronized (death) { 10764 while (who.isBinderAlive()) { 10765 try { 10766 death.wait(); 10767 } catch (InterruptedException e) { 10768 } 10769 } 10770 } 10771 Watchdog.getInstance().setAllowRestart(true); 10772 } 10773 } 10774 10775 @Override 10776 public void restart() { 10777 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10778 != PackageManager.PERMISSION_GRANTED) { 10779 throw new SecurityException("Requires permission " 10780 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10781 } 10782 10783 Log.i(TAG, "Sending shutdown broadcast..."); 10784 10785 BroadcastReceiver br = new BroadcastReceiver() { 10786 @Override public void onReceive(Context context, Intent intent) { 10787 // Now the broadcast is done, finish up the low-level shutdown. 10788 Log.i(TAG, "Shutting down activity manager..."); 10789 shutdown(10000); 10790 Log.i(TAG, "Shutdown complete, restarting!"); 10791 Process.killProcess(Process.myPid()); 10792 System.exit(10); 10793 } 10794 }; 10795 10796 // First send the high-level shut down broadcast. 10797 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 10798 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10799 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 10800 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 10801 mContext.sendOrderedBroadcastAsUser(intent, 10802 UserHandle.ALL, null, br, mHandler, 0, null, null); 10803 */ 10804 br.onReceive(mContext, intent); 10805 } 10806 10807 private long getLowRamTimeSinceIdle(long now) { 10808 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 10809 } 10810 10811 @Override 10812 public void performIdleMaintenance() { 10813 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 10814 != PackageManager.PERMISSION_GRANTED) { 10815 throw new SecurityException("Requires permission " 10816 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 10817 } 10818 10819 synchronized (this) { 10820 final long now = SystemClock.uptimeMillis(); 10821 final long timeSinceLastIdle = now - mLastIdleTime; 10822 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 10823 mLastIdleTime = now; 10824 mLowRamTimeSinceLastIdle = 0; 10825 if (mLowRamStartTime != 0) { 10826 mLowRamStartTime = now; 10827 } 10828 10829 StringBuilder sb = new StringBuilder(128); 10830 sb.append("Idle maintenance over "); 10831 TimeUtils.formatDuration(timeSinceLastIdle, sb); 10832 sb.append(" low RAM for "); 10833 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 10834 Slog.i(TAG, sb.toString()); 10835 10836 // If at least 1/3 of our time since the last idle period has been spent 10837 // with RAM low, then we want to kill processes. 10838 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 10839 10840 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 10841 ProcessRecord proc = mLruProcesses.get(i); 10842 if (proc.notCachedSinceIdle) { 10843 if (proc.setProcState > ActivityManager.PROCESS_STATE_TOP 10844 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 10845 if (doKilling && proc.initialIdlePss != 0 10846 && proc.lastPss > ((proc.initialIdlePss*3)/2)) { 10847 proc.kill("idle maint (pss " + proc.lastPss 10848 + " from " + proc.initialIdlePss + ")", true); 10849 } 10850 } 10851 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) { 10852 proc.notCachedSinceIdle = true; 10853 proc.initialIdlePss = 0; 10854 proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true, 10855 isSleeping(), now); 10856 } 10857 } 10858 10859 mHandler.removeMessages(REQUEST_ALL_PSS_MSG); 10860 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000); 10861 } 10862 } 10863 10864 private void retrieveSettings() { 10865 final ContentResolver resolver = mContext.getContentResolver(); 10866 String debugApp = Settings.Global.getString( 10867 resolver, Settings.Global.DEBUG_APP); 10868 boolean waitForDebugger = Settings.Global.getInt( 10869 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0; 10870 boolean alwaysFinishActivities = Settings.Global.getInt( 10871 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0; 10872 boolean forceRtl = Settings.Global.getInt( 10873 resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0; 10874 // Transfer any global setting for forcing RTL layout, into a System Property 10875 SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0"); 10876 10877 Configuration configuration = new Configuration(); 10878 Settings.System.getConfiguration(resolver, configuration); 10879 if (forceRtl) { 10880 // This will take care of setting the correct layout direction flags 10881 configuration.setLayoutDirection(configuration.locale); 10882 } 10883 10884 synchronized (this) { 10885 mDebugApp = mOrigDebugApp = debugApp; 10886 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 10887 mAlwaysFinishActivities = alwaysFinishActivities; 10888 // This happens before any activities are started, so we can 10889 // change mConfiguration in-place. 10890 updateConfigurationLocked(configuration, null, false, true); 10891 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration); 10892 } 10893 } 10894 10895 /** Loads resources after the current configuration has been set. */ 10896 private void loadResourcesOnSystemReady() { 10897 final Resources res = mContext.getResources(); 10898 mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents); 10899 mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 10900 mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 10901 } 10902 10903 public boolean testIsSystemReady() { 10904 // no need to synchronize(this) just to read & return the value 10905 return mSystemReady; 10906 } 10907 10908 private static File getCalledPreBootReceiversFile() { 10909 File dataDir = Environment.getDataDirectory(); 10910 File systemDir = new File(dataDir, "system"); 10911 File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME); 10912 return fname; 10913 } 10914 10915 private static ArrayList<ComponentName> readLastDonePreBootReceivers() { 10916 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>(); 10917 File file = getCalledPreBootReceiversFile(); 10918 FileInputStream fis = null; 10919 try { 10920 fis = new FileInputStream(file); 10921 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048)); 10922 int fvers = dis.readInt(); 10923 if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) { 10924 String vers = dis.readUTF(); 10925 String codename = dis.readUTF(); 10926 String build = dis.readUTF(); 10927 if (android.os.Build.VERSION.RELEASE.equals(vers) 10928 && android.os.Build.VERSION.CODENAME.equals(codename) 10929 && android.os.Build.VERSION.INCREMENTAL.equals(build)) { 10930 int num = dis.readInt(); 10931 while (num > 0) { 10932 num--; 10933 String pkg = dis.readUTF(); 10934 String cls = dis.readUTF(); 10935 lastDoneReceivers.add(new ComponentName(pkg, cls)); 10936 } 10937 } 10938 } 10939 } catch (FileNotFoundException e) { 10940 } catch (IOException e) { 10941 Slog.w(TAG, "Failure reading last done pre-boot receivers", e); 10942 } finally { 10943 if (fis != null) { 10944 try { 10945 fis.close(); 10946 } catch (IOException e) { 10947 } 10948 } 10949 } 10950 return lastDoneReceivers; 10951 } 10952 10953 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) { 10954 File file = getCalledPreBootReceiversFile(); 10955 FileOutputStream fos = null; 10956 DataOutputStream dos = null; 10957 try { 10958 fos = new FileOutputStream(file); 10959 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048)); 10960 dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION); 10961 dos.writeUTF(android.os.Build.VERSION.RELEASE); 10962 dos.writeUTF(android.os.Build.VERSION.CODENAME); 10963 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL); 10964 dos.writeInt(list.size()); 10965 for (int i=0; i<list.size(); i++) { 10966 dos.writeUTF(list.get(i).getPackageName()); 10967 dos.writeUTF(list.get(i).getClassName()); 10968 } 10969 } catch (IOException e) { 10970 Slog.w(TAG, "Failure writing last done pre-boot receivers", e); 10971 file.delete(); 10972 } finally { 10973 FileUtils.sync(fos); 10974 if (dos != null) { 10975 try { 10976 dos.close(); 10977 } catch (IOException e) { 10978 // TODO Auto-generated catch block 10979 e.printStackTrace(); 10980 } 10981 } 10982 } 10983 } 10984 10985 private boolean deliverPreBootCompleted(final Runnable onFinishCallback, 10986 ArrayList<ComponentName> doneReceivers, int userId) { 10987 boolean waitingUpdate = false; 10988 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 10989 List<ResolveInfo> ris = null; 10990 try { 10991 ris = AppGlobals.getPackageManager().queryIntentReceivers( 10992 intent, null, 0, userId); 10993 } catch (RemoteException e) { 10994 } 10995 if (ris != null) { 10996 for (int i=ris.size()-1; i>=0; i--) { 10997 if ((ris.get(i).activityInfo.applicationInfo.flags 10998 &ApplicationInfo.FLAG_SYSTEM) == 0) { 10999 ris.remove(i); 11000 } 11001 } 11002 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); 11003 11004 // For User 0, load the version number. When delivering to a new user, deliver 11005 // to all receivers. 11006 if (userId == UserHandle.USER_OWNER) { 11007 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers(); 11008 for (int i=0; i<ris.size(); i++) { 11009 ActivityInfo ai = ris.get(i).activityInfo; 11010 ComponentName comp = new ComponentName(ai.packageName, ai.name); 11011 if (lastDoneReceivers.contains(comp)) { 11012 // We already did the pre boot receiver for this app with the current 11013 // platform version, so don't do it again... 11014 ris.remove(i); 11015 i--; 11016 // ...however, do keep it as one that has been done, so we don't 11017 // forget about it when rewriting the file of last done receivers. 11018 doneReceivers.add(comp); 11019 } 11020 } 11021 } 11022 11023 // If primary user, send broadcast to all available users, else just to userId 11024 final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked() 11025 : new int[] { userId }; 11026 for (int i = 0; i < ris.size(); i++) { 11027 ActivityInfo ai = ris.get(i).activityInfo; 11028 ComponentName comp = new ComponentName(ai.packageName, ai.name); 11029 doneReceivers.add(comp); 11030 intent.setComponent(comp); 11031 for (int j=0; j<users.length; j++) { 11032 IIntentReceiver finisher = null; 11033 // On last receiver and user, set up a completion callback 11034 if (i == ris.size() - 1 && j == users.length - 1 && onFinishCallback != null) { 11035 finisher = new IIntentReceiver.Stub() { 11036 public void performReceive(Intent intent, int resultCode, 11037 String data, Bundle extras, boolean ordered, 11038 boolean sticky, int sendingUser) { 11039 // The raw IIntentReceiver interface is called 11040 // with the AM lock held, so redispatch to 11041 // execute our code without the lock. 11042 mHandler.post(onFinishCallback); 11043 } 11044 }; 11045 } 11046 Slog.i(TAG, "Sending system update to " + intent.getComponent() 11047 + " for user " + users[j]); 11048 broadcastIntentLocked(null, null, intent, null, finisher, 11049 0, null, null, null, AppOpsManager.OP_NONE, 11050 true, false, MY_PID, Process.SYSTEM_UID, 11051 users[j]); 11052 if (finisher != null) { 11053 waitingUpdate = true; 11054 } 11055 } 11056 } 11057 } 11058 11059 return waitingUpdate; 11060 } 11061 11062 public void systemReady(final Runnable goingCallback) { 11063 synchronized(this) { 11064 if (mSystemReady) { 11065 // If we're done calling all the receivers, run the next "boot phase" passed in 11066 // by the SystemServer 11067 if (goingCallback != null) { 11068 goingCallback.run(); 11069 } 11070 return; 11071 } 11072 11073 // Make sure we have the current profile info, since it is needed for 11074 // security checks. 11075 updateCurrentProfileIdsLocked(); 11076 11077 if (mRecentTasks == null) { 11078 mRecentTasks = mTaskPersister.restoreTasksLocked(); 11079 if (!mRecentTasks.isEmpty()) { 11080 mStackSupervisor.createStackForRestoredTaskHistory(mRecentTasks); 11081 } 11082 cleanupRecentTasksLocked(UserHandle.USER_ALL); 11083 mTaskPersister.startPersisting(); 11084 } 11085 11086 // Check to see if there are any update receivers to run. 11087 if (!mDidUpdate) { 11088 if (mWaitingUpdate) { 11089 return; 11090 } 11091 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); 11092 mWaitingUpdate = deliverPreBootCompleted(new Runnable() { 11093 public void run() { 11094 synchronized (ActivityManagerService.this) { 11095 mDidUpdate = true; 11096 } 11097 writeLastDonePreBootReceivers(doneReceivers); 11098 showBootMessage(mContext.getText( 11099 R.string.android_upgrading_complete), 11100 false); 11101 systemReady(goingCallback); 11102 } 11103 }, doneReceivers, UserHandle.USER_OWNER); 11104 11105 if (mWaitingUpdate) { 11106 return; 11107 } 11108 mDidUpdate = true; 11109 } 11110 11111 mAppOpsService.systemReady(); 11112 mSystemReady = true; 11113 } 11114 11115 ArrayList<ProcessRecord> procsToKill = null; 11116 synchronized(mPidsSelfLocked) { 11117 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 11118 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 11119 if (!isAllowedWhileBooting(proc.info)){ 11120 if (procsToKill == null) { 11121 procsToKill = new ArrayList<ProcessRecord>(); 11122 } 11123 procsToKill.add(proc); 11124 } 11125 } 11126 } 11127 11128 synchronized(this) { 11129 if (procsToKill != null) { 11130 for (int i=procsToKill.size()-1; i>=0; i--) { 11131 ProcessRecord proc = procsToKill.get(i); 11132 Slog.i(TAG, "Removing system update proc: " + proc); 11133 removeProcessLocked(proc, true, false, "system update done"); 11134 } 11135 } 11136 11137 // Now that we have cleaned up any update processes, we 11138 // are ready to start launching real processes and know that 11139 // we won't trample on them any more. 11140 mProcessesReady = true; 11141 } 11142 11143 Slog.i(TAG, "System now ready"); 11144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, 11145 SystemClock.uptimeMillis()); 11146 11147 synchronized(this) { 11148 // Make sure we have no pre-ready processes sitting around. 11149 11150 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11151 ResolveInfo ri = mContext.getPackageManager() 11152 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), 11153 STOCK_PM_FLAGS); 11154 CharSequence errorMsg = null; 11155 if (ri != null) { 11156 ActivityInfo ai = ri.activityInfo; 11157 ApplicationInfo app = ai.applicationInfo; 11158 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11159 mTopAction = Intent.ACTION_FACTORY_TEST; 11160 mTopData = null; 11161 mTopComponent = new ComponentName(app.packageName, 11162 ai.name); 11163 } else { 11164 errorMsg = mContext.getResources().getText( 11165 com.android.internal.R.string.factorytest_not_system); 11166 } 11167 } else { 11168 errorMsg = mContext.getResources().getText( 11169 com.android.internal.R.string.factorytest_no_action); 11170 } 11171 if (errorMsg != null) { 11172 mTopAction = null; 11173 mTopData = null; 11174 mTopComponent = null; 11175 Message msg = Message.obtain(); 11176 msg.what = SHOW_FACTORY_ERROR_MSG; 11177 msg.getData().putCharSequence("msg", errorMsg); 11178 mHandler.sendMessage(msg); 11179 } 11180 } 11181 } 11182 11183 retrieveSettings(); 11184 loadResourcesOnSystemReady(); 11185 11186 synchronized (this) { 11187 readGrantedUriPermissionsLocked(); 11188 } 11189 11190 if (goingCallback != null) goingCallback.run(); 11191 11192 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 11193 Integer.toString(mCurrentUserId), mCurrentUserId); 11194 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 11195 Integer.toString(mCurrentUserId), mCurrentUserId); 11196 mSystemServiceManager.startUser(mCurrentUserId); 11197 11198 synchronized (this) { 11199 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11200 try { 11201 List apps = AppGlobals.getPackageManager(). 11202 getPersistentApplications(STOCK_PM_FLAGS); 11203 if (apps != null) { 11204 int N = apps.size(); 11205 int i; 11206 for (i=0; i<N; i++) { 11207 ApplicationInfo info 11208 = (ApplicationInfo)apps.get(i); 11209 if (info != null && 11210 !info.packageName.equals("android")) { 11211 addAppLocked(info, false, null /* ABI override */); 11212 } 11213 } 11214 } 11215 } catch (RemoteException ex) { 11216 // pm is in same process, this will never happen. 11217 } 11218 } 11219 11220 // Start up initial activity. 11221 mBooting = true; 11222 11223 try { 11224 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { 11225 Message msg = Message.obtain(); 11226 msg.what = SHOW_UID_ERROR_MSG; 11227 mHandler.sendMessage(msg); 11228 } 11229 } catch (RemoteException e) { 11230 } 11231 11232 long ident = Binder.clearCallingIdentity(); 11233 try { 11234 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 11235 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 11236 | Intent.FLAG_RECEIVER_FOREGROUND); 11237 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11238 broadcastIntentLocked(null, null, intent, 11239 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 11240 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId); 11241 intent = new Intent(Intent.ACTION_USER_STARTING); 11242 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 11243 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11244 broadcastIntentLocked(null, null, intent, 11245 null, new IIntentReceiver.Stub() { 11246 @Override 11247 public void performReceive(Intent intent, int resultCode, String data, 11248 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 11249 throws RemoteException { 11250 } 11251 }, 0, null, null, 11252 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 11253 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 11254 } catch (Throwable t) { 11255 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 11256 } finally { 11257 Binder.restoreCallingIdentity(ident); 11258 } 11259 mStackSupervisor.resumeTopActivitiesLocked(); 11260 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId); 11261 } 11262 } 11263 11264 private boolean makeAppCrashingLocked(ProcessRecord app, 11265 String shortMsg, String longMsg, String stackTrace) { 11266 app.crashing = true; 11267 app.crashingReport = generateProcessError(app, 11268 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace); 11269 startAppProblemLocked(app); 11270 app.stopFreezingAllLocked(); 11271 return handleAppCrashLocked(app, shortMsg, longMsg, stackTrace); 11272 } 11273 11274 private void makeAppNotRespondingLocked(ProcessRecord app, 11275 String activity, String shortMsg, String longMsg) { 11276 app.notResponding = true; 11277 app.notRespondingReport = generateProcessError(app, 11278 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 11279 activity, shortMsg, longMsg, null); 11280 startAppProblemLocked(app); 11281 app.stopFreezingAllLocked(); 11282 } 11283 11284 /** 11285 * Generate a process error record, suitable for attachment to a ProcessRecord. 11286 * 11287 * @param app The ProcessRecord in which the error occurred. 11288 * @param condition Crashing, Application Not Responding, etc. Values are defined in 11289 * ActivityManager.AppErrorStateInfo 11290 * @param activity The activity associated with the crash, if known. 11291 * @param shortMsg Short message describing the crash. 11292 * @param longMsg Long message describing the crash. 11293 * @param stackTrace Full crash stack trace, may be null. 11294 * 11295 * @return Returns a fully-formed AppErrorStateInfo record. 11296 */ 11297 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app, 11298 int condition, String activity, String shortMsg, String longMsg, String stackTrace) { 11299 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo(); 11300 11301 report.condition = condition; 11302 report.processName = app.processName; 11303 report.pid = app.pid; 11304 report.uid = app.info.uid; 11305 report.tag = activity; 11306 report.shortMsg = shortMsg; 11307 report.longMsg = longMsg; 11308 report.stackTrace = stackTrace; 11309 11310 return report; 11311 } 11312 11313 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 11314 synchronized (this) { 11315 app.crashing = false; 11316 app.crashingReport = null; 11317 app.notResponding = false; 11318 app.notRespondingReport = null; 11319 if (app.anrDialog == fromDialog) { 11320 app.anrDialog = null; 11321 } 11322 if (app.waitDialog == fromDialog) { 11323 app.waitDialog = null; 11324 } 11325 if (app.pid > 0 && app.pid != MY_PID) { 11326 handleAppCrashLocked(app, null, null, null); 11327 app.kill("user request after error", true); 11328 } 11329 } 11330 } 11331 11332 private boolean handleAppCrashLocked(ProcessRecord app, String shortMsg, String longMsg, 11333 String stackTrace) { 11334 long now = SystemClock.uptimeMillis(); 11335 11336 Long crashTime; 11337 if (!app.isolated) { 11338 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid); 11339 } else { 11340 crashTime = null; 11341 } 11342 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) { 11343 // This process loses! 11344 Slog.w(TAG, "Process " + app.info.processName 11345 + " has crashed too many times: killing!"); 11346 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, 11347 app.userId, app.info.processName, app.uid); 11348 mStackSupervisor.handleAppCrashLocked(app); 11349 if (!app.persistent) { 11350 // We don't want to start this process again until the user 11351 // explicitly does so... but for persistent process, we really 11352 // need to keep it running. If a persistent process is actually 11353 // repeatedly crashing, then badness for everyone. 11354 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, 11355 app.info.processName); 11356 if (!app.isolated) { 11357 // XXX We don't have a way to mark isolated processes 11358 // as bad, since they don't have a peristent identity. 11359 mBadProcesses.put(app.info.processName, app.uid, 11360 new BadProcessInfo(now, shortMsg, longMsg, stackTrace)); 11361 mProcessCrashTimes.remove(app.info.processName, app.uid); 11362 } 11363 app.bad = true; 11364 app.removed = true; 11365 // Don't let services in this process be restarted and potentially 11366 // annoy the user repeatedly. Unless it is persistent, since those 11367 // processes run critical code. 11368 removeProcessLocked(app, false, false, "crash"); 11369 mStackSupervisor.resumeTopActivitiesLocked(); 11370 return false; 11371 } 11372 mStackSupervisor.resumeTopActivitiesLocked(); 11373 } else { 11374 mStackSupervisor.finishTopRunningActivityLocked(app); 11375 } 11376 11377 // Bump up the crash count of any services currently running in the proc. 11378 for (int i=app.services.size()-1; i>=0; i--) { 11379 // Any services running in the application need to be placed 11380 // back in the pending list. 11381 ServiceRecord sr = app.services.valueAt(i); 11382 sr.crashCount++; 11383 } 11384 11385 // If the crashing process is what we consider to be the "home process" and it has been 11386 // replaced by a third-party app, clear the package preferred activities from packages 11387 // with a home activity running in the process to prevent a repeatedly crashing app 11388 // from blocking the user to manually clear the list. 11389 final ArrayList<ActivityRecord> activities = app.activities; 11390 if (app == mHomeProcess && activities.size() > 0 11391 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 11392 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 11393 final ActivityRecord r = activities.get(activityNdx); 11394 if (r.isHomeActivity()) { 11395 Log.i(TAG, "Clearing package preferred activities from " + r.packageName); 11396 try { 11397 ActivityThread.getPackageManager() 11398 .clearPackagePreferredActivities(r.packageName); 11399 } catch (RemoteException c) { 11400 // pm is in same process, this will never happen. 11401 } 11402 } 11403 } 11404 } 11405 11406 if (!app.isolated) { 11407 // XXX Can't keep track of crash times for isolated processes, 11408 // because they don't have a perisistent identity. 11409 mProcessCrashTimes.put(app.info.processName, app.uid, now); 11410 } 11411 11412 if (app.crashHandler != null) mHandler.post(app.crashHandler); 11413 return true; 11414 } 11415 11416 void startAppProblemLocked(ProcessRecord app) { 11417 // If this app is not running under the current user, then we 11418 // can't give it a report button because that would require 11419 // launching the report UI under a different user. 11420 app.errorReportReceiver = null; 11421 11422 for (int userId : mCurrentProfileIds) { 11423 if (app.userId == userId) { 11424 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver( 11425 mContext, app.info.packageName, app.info.flags); 11426 } 11427 } 11428 skipCurrentReceiverLocked(app); 11429 } 11430 11431 void skipCurrentReceiverLocked(ProcessRecord app) { 11432 for (BroadcastQueue queue : mBroadcastQueues) { 11433 queue.skipCurrentReceiverLocked(app); 11434 } 11435 } 11436 11437 /** 11438 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 11439 * The application process will exit immediately after this call returns. 11440 * @param app object of the crashing app, null for the system server 11441 * @param crashInfo describing the exception 11442 */ 11443 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) { 11444 ProcessRecord r = findAppProcess(app, "Crash"); 11445 final String processName = app == null ? "system_server" 11446 : (r == null ? "unknown" : r.processName); 11447 11448 handleApplicationCrashInner("crash", r, processName, crashInfo); 11449 } 11450 11451 /* Native crash reporting uses this inner version because it needs to be somewhat 11452 * decoupled from the AM-managed cleanup lifecycle 11453 */ 11454 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 11455 ApplicationErrorReport.CrashInfo crashInfo) { 11456 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(), 11457 UserHandle.getUserId(Binder.getCallingUid()), processName, 11458 r == null ? -1 : r.info.flags, 11459 crashInfo.exceptionClassName, 11460 crashInfo.exceptionMessage, 11461 crashInfo.throwFileName, 11462 crashInfo.throwLineNumber); 11463 11464 addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo); 11465 11466 crashApplication(r, crashInfo); 11467 } 11468 11469 public void handleApplicationStrictModeViolation( 11470 IBinder app, 11471 int violationMask, 11472 StrictMode.ViolationInfo info) { 11473 ProcessRecord r = findAppProcess(app, "StrictMode"); 11474 if (r == null) { 11475 return; 11476 } 11477 11478 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) { 11479 Integer stackFingerprint = info.hashCode(); 11480 boolean logIt = true; 11481 synchronized (mAlreadyLoggedViolatedStacks) { 11482 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 11483 logIt = false; 11484 // TODO: sub-sample into EventLog for these, with 11485 // the info.durationMillis? Then we'd get 11486 // the relative pain numbers, without logging all 11487 // the stack traces repeatedly. We'd want to do 11488 // likewise in the client code, which also does 11489 // dup suppression, before the Binder call. 11490 } else { 11491 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 11492 mAlreadyLoggedViolatedStacks.clear(); 11493 } 11494 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 11495 } 11496 } 11497 if (logIt) { 11498 logStrictModeViolationToDropBox(r, info); 11499 } 11500 } 11501 11502 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) { 11503 AppErrorResult result = new AppErrorResult(); 11504 synchronized (this) { 11505 final long origId = Binder.clearCallingIdentity(); 11506 11507 Message msg = Message.obtain(); 11508 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG; 11509 HashMap<String, Object> data = new HashMap<String, Object>(); 11510 data.put("result", result); 11511 data.put("app", r); 11512 data.put("violationMask", violationMask); 11513 data.put("info", info); 11514 msg.obj = data; 11515 mHandler.sendMessage(msg); 11516 11517 Binder.restoreCallingIdentity(origId); 11518 } 11519 int res = result.get(); 11520 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 11521 } 11522 } 11523 11524 // Depending on the policy in effect, there could be a bunch of 11525 // these in quick succession so we try to batch these together to 11526 // minimize disk writes, number of dropbox entries, and maximize 11527 // compression, by having more fewer, larger records. 11528 private void logStrictModeViolationToDropBox( 11529 ProcessRecord process, 11530 StrictMode.ViolationInfo info) { 11531 if (info == null) { 11532 return; 11533 } 11534 final boolean isSystemApp = process == null || 11535 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 11536 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 11537 final String processName = process == null ? "unknown" : process.processName; 11538 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode"; 11539 final DropBoxManager dbox = (DropBoxManager) 11540 mContext.getSystemService(Context.DROPBOX_SERVICE); 11541 11542 // Exit early if the dropbox isn't configured to accept this report type. 11543 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 11544 11545 boolean bufferWasEmpty; 11546 boolean needsFlush; 11547 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024); 11548 synchronized (sb) { 11549 bufferWasEmpty = sb.length() == 0; 11550 appendDropBoxProcessHeaders(process, processName, sb); 11551 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 11552 sb.append("System-App: ").append(isSystemApp).append("\n"); 11553 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 11554 if (info.violationNumThisLoop != 0) { 11555 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 11556 } 11557 if (info.numAnimationsRunning != 0) { 11558 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 11559 } 11560 if (info.broadcastIntentAction != null) { 11561 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 11562 } 11563 if (info.durationMillis != -1) { 11564 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 11565 } 11566 if (info.numInstances != -1) { 11567 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 11568 } 11569 if (info.tags != null) { 11570 for (String tag : info.tags) { 11571 sb.append("Span-Tag: ").append(tag).append("\n"); 11572 } 11573 } 11574 sb.append("\n"); 11575 if (info.crashInfo != null && info.crashInfo.stackTrace != null) { 11576 sb.append(info.crashInfo.stackTrace); 11577 } 11578 sb.append("\n"); 11579 11580 // Only buffer up to ~64k. Various logging bits truncate 11581 // things at 128k. 11582 needsFlush = (sb.length() > 64 * 1024); 11583 } 11584 11585 // Flush immediately if the buffer's grown too large, or this 11586 // is a non-system app. Non-system apps are isolated with a 11587 // different tag & policy and not batched. 11588 // 11589 // Batching is useful during internal testing with 11590 // StrictMode settings turned up high. Without batching, 11591 // thousands of separate files could be created on boot. 11592 if (!isSystemApp || needsFlush) { 11593 new Thread("Error dump: " + dropboxTag) { 11594 @Override 11595 public void run() { 11596 String report; 11597 synchronized (sb) { 11598 report = sb.toString(); 11599 sb.delete(0, sb.length()); 11600 sb.trimToSize(); 11601 } 11602 if (report.length() != 0) { 11603 dbox.addText(dropboxTag, report); 11604 } 11605 } 11606 }.start(); 11607 return; 11608 } 11609 11610 // System app batching: 11611 if (!bufferWasEmpty) { 11612 // An existing dropbox-writing thread is outstanding, so 11613 // we don't need to start it up. The existing thread will 11614 // catch the buffer appends we just did. 11615 return; 11616 } 11617 11618 // Worker thread to both batch writes and to avoid blocking the caller on I/O. 11619 // (After this point, we shouldn't access AMS internal data structures.) 11620 new Thread("Error dump: " + dropboxTag) { 11621 @Override 11622 public void run() { 11623 // 5 second sleep to let stacks arrive and be batched together 11624 try { 11625 Thread.sleep(5000); // 5 seconds 11626 } catch (InterruptedException e) {} 11627 11628 String errorReport; 11629 synchronized (mStrictModeBuffer) { 11630 errorReport = mStrictModeBuffer.toString(); 11631 if (errorReport.length() == 0) { 11632 return; 11633 } 11634 mStrictModeBuffer.delete(0, mStrictModeBuffer.length()); 11635 mStrictModeBuffer.trimToSize(); 11636 } 11637 dbox.addText(dropboxTag, errorReport); 11638 } 11639 }.start(); 11640 } 11641 11642 /** 11643 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 11644 * @param app object of the crashing app, null for the system server 11645 * @param tag reported by the caller 11646 * @param system whether this wtf is coming from the system 11647 * @param crashInfo describing the context of the error 11648 * @return true if the process should exit immediately (WTF is fatal) 11649 */ 11650 public boolean handleApplicationWtf(IBinder app, final String tag, boolean system, 11651 final ApplicationErrorReport.CrashInfo crashInfo) { 11652 final ProcessRecord r = findAppProcess(app, "WTF"); 11653 final String processName = app == null ? "system_server" 11654 : (r == null ? "unknown" : r.processName); 11655 11656 EventLog.writeEvent(EventLogTags.AM_WTF, 11657 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(), 11658 processName, 11659 r == null ? -1 : r.info.flags, 11660 tag, crashInfo.exceptionMessage); 11661 11662 if (system) { 11663 // If this is coming from the system, we could very well have low-level 11664 // system locks held, so we want to do this all asynchronously. And we 11665 // never want this to become fatal, so there is that too. 11666 mHandler.post(new Runnable() { 11667 @Override public void run() { 11668 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, 11669 crashInfo); 11670 } 11671 }); 11672 return false; 11673 } 11674 11675 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo); 11676 11677 if (r != null && r.pid != Process.myPid() && 11678 Settings.Global.getInt(mContext.getContentResolver(), 11679 Settings.Global.WTF_IS_FATAL, 0) != 0) { 11680 crashApplication(r, crashInfo); 11681 return true; 11682 } else { 11683 return false; 11684 } 11685 } 11686 11687 /** 11688 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 11689 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 11690 */ 11691 private ProcessRecord findAppProcess(IBinder app, String reason) { 11692 if (app == null) { 11693 return null; 11694 } 11695 11696 synchronized (this) { 11697 final int NP = mProcessNames.getMap().size(); 11698 for (int ip=0; ip<NP; ip++) { 11699 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 11700 final int NA = apps.size(); 11701 for (int ia=0; ia<NA; ia++) { 11702 ProcessRecord p = apps.valueAt(ia); 11703 if (p.thread != null && p.thread.asBinder() == app) { 11704 return p; 11705 } 11706 } 11707 } 11708 11709 Slog.w(TAG, "Can't find mystery application for " + reason 11710 + " from pid=" + Binder.getCallingPid() 11711 + " uid=" + Binder.getCallingUid() + ": " + app); 11712 return null; 11713 } 11714 } 11715 11716 /** 11717 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 11718 * to append various headers to the dropbox log text. 11719 */ 11720 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 11721 StringBuilder sb) { 11722 // Watchdog thread ends up invoking this function (with 11723 // a null ProcessRecord) to add the stack file to dropbox. 11724 // Do not acquire a lock on this (am) in such cases, as it 11725 // could cause a potential deadlock, if and when watchdog 11726 // is invoked due to unavailability of lock on am and it 11727 // would prevent watchdog from killing system_server. 11728 if (process == null) { 11729 sb.append("Process: ").append(processName).append("\n"); 11730 return; 11731 } 11732 // Note: ProcessRecord 'process' is guarded by the service 11733 // instance. (notably process.pkgList, which could otherwise change 11734 // concurrently during execution of this method) 11735 synchronized (this) { 11736 sb.append("Process: ").append(processName).append("\n"); 11737 int flags = process.info.flags; 11738 IPackageManager pm = AppGlobals.getPackageManager(); 11739 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n"); 11740 for (int ip=0; ip<process.pkgList.size(); ip++) { 11741 String pkg = process.pkgList.keyAt(ip); 11742 sb.append("Package: ").append(pkg); 11743 try { 11744 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId()); 11745 if (pi != null) { 11746 sb.append(" v").append(pi.versionCode); 11747 if (pi.versionName != null) { 11748 sb.append(" (").append(pi.versionName).append(")"); 11749 } 11750 } 11751 } catch (RemoteException e) { 11752 Slog.e(TAG, "Error getting package info: " + pkg, e); 11753 } 11754 sb.append("\n"); 11755 } 11756 } 11757 } 11758 11759 private static String processClass(ProcessRecord process) { 11760 if (process == null || process.pid == MY_PID) { 11761 return "system_server"; 11762 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11763 return "system_app"; 11764 } else { 11765 return "data_app"; 11766 } 11767 } 11768 11769 /** 11770 * Write a description of an error (crash, WTF, ANR) to the drop box. 11771 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 11772 * @param process which caused the error, null means the system server 11773 * @param activity which triggered the error, null if unknown 11774 * @param parent activity related to the error, null if unknown 11775 * @param subject line related to the error, null if absent 11776 * @param report in long form describing the error, null if absent 11777 * @param logFile to include in the report, null if none 11778 * @param crashInfo giving an application stack trace, null if absent 11779 */ 11780 public void addErrorToDropBox(String eventType, 11781 ProcessRecord process, String processName, ActivityRecord activity, 11782 ActivityRecord parent, String subject, 11783 final String report, final File logFile, 11784 final ApplicationErrorReport.CrashInfo crashInfo) { 11785 // NOTE -- this must never acquire the ActivityManagerService lock, 11786 // otherwise the watchdog may be prevented from resetting the system. 11787 11788 final String dropboxTag = processClass(process) + "_" + eventType; 11789 final DropBoxManager dbox = (DropBoxManager) 11790 mContext.getSystemService(Context.DROPBOX_SERVICE); 11791 11792 // Exit early if the dropbox isn't configured to accept this report type. 11793 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 11794 11795 final StringBuilder sb = new StringBuilder(1024); 11796 appendDropBoxProcessHeaders(process, processName, sb); 11797 if (activity != null) { 11798 sb.append("Activity: ").append(activity.shortComponentName).append("\n"); 11799 } 11800 if (parent != null && parent.app != null && parent.app.pid != process.pid) { 11801 sb.append("Parent-Process: ").append(parent.app.processName).append("\n"); 11802 } 11803 if (parent != null && parent != activity) { 11804 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n"); 11805 } 11806 if (subject != null) { 11807 sb.append("Subject: ").append(subject).append("\n"); 11808 } 11809 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 11810 if (Debug.isDebuggerConnected()) { 11811 sb.append("Debugger: Connected\n"); 11812 } 11813 sb.append("\n"); 11814 11815 // Do the rest in a worker thread to avoid blocking the caller on I/O 11816 // (After this point, we shouldn't access AMS internal data structures.) 11817 Thread worker = new Thread("Error dump: " + dropboxTag) { 11818 @Override 11819 public void run() { 11820 if (report != null) { 11821 sb.append(report); 11822 } 11823 if (logFile != null) { 11824 try { 11825 sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE, 11826 "\n\n[[TRUNCATED]]")); 11827 } catch (IOException e) { 11828 Slog.e(TAG, "Error reading " + logFile, e); 11829 } 11830 } 11831 if (crashInfo != null && crashInfo.stackTrace != null) { 11832 sb.append(crashInfo.stackTrace); 11833 } 11834 11835 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 11836 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0); 11837 if (lines > 0) { 11838 sb.append("\n"); 11839 11840 // Merge several logcat streams, and take the last N lines 11841 InputStreamReader input = null; 11842 try { 11843 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat", 11844 "-v", "time", "-b", "events", "-b", "system", "-b", "main", 11845 "-b", "crash", 11846 "-t", String.valueOf(lines)).redirectErrorStream(true).start(); 11847 11848 try { logcat.getOutputStream().close(); } catch (IOException e) {} 11849 try { logcat.getErrorStream().close(); } catch (IOException e) {} 11850 input = new InputStreamReader(logcat.getInputStream()); 11851 11852 int num; 11853 char[] buf = new char[8192]; 11854 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 11855 } catch (IOException e) { 11856 Slog.e(TAG, "Error running logcat", e); 11857 } finally { 11858 if (input != null) try { input.close(); } catch (IOException e) {} 11859 } 11860 } 11861 11862 dbox.addText(dropboxTag, sb.toString()); 11863 } 11864 }; 11865 11866 if (process == null) { 11867 // If process is null, we are being called from some internal code 11868 // and may be about to die -- run this synchronously. 11869 worker.run(); 11870 } else { 11871 worker.start(); 11872 } 11873 } 11874 11875 /** 11876 * Bring up the "unexpected error" dialog box for a crashing app. 11877 * Deal with edge cases (intercepts from instrumented applications, 11878 * ActivityController, error intent receivers, that sort of thing). 11879 * @param r the application crashing 11880 * @param crashInfo describing the failure 11881 */ 11882 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) { 11883 long timeMillis = System.currentTimeMillis(); 11884 String shortMsg = crashInfo.exceptionClassName; 11885 String longMsg = crashInfo.exceptionMessage; 11886 String stackTrace = crashInfo.stackTrace; 11887 if (shortMsg != null && longMsg != null) { 11888 longMsg = shortMsg + ": " + longMsg; 11889 } else if (shortMsg != null) { 11890 longMsg = shortMsg; 11891 } 11892 11893 AppErrorResult result = new AppErrorResult(); 11894 synchronized (this) { 11895 if (mController != null) { 11896 try { 11897 String name = r != null ? r.processName : null; 11898 int pid = r != null ? r.pid : Binder.getCallingPid(); 11899 int uid = r != null ? r.info.uid : Binder.getCallingUid(); 11900 if (!mController.appCrashed(name, pid, 11901 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) { 11902 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")) 11903 && "Native crash".equals(crashInfo.exceptionClassName)) { 11904 Slog.w(TAG, "Skip killing native crashed app " + name 11905 + "(" + pid + ") during testing"); 11906 } else { 11907 Slog.w(TAG, "Force-killing crashed app " + name 11908 + " at watcher's request"); 11909 if (r != null) { 11910 r.kill("crash", true); 11911 } else { 11912 // Huh. 11913 Process.killProcess(pid); 11914 Process.killProcessGroup(uid, pid); 11915 } 11916 } 11917 return; 11918 } 11919 } catch (RemoteException e) { 11920 mController = null; 11921 Watchdog.getInstance().setActivityController(null); 11922 } 11923 } 11924 11925 final long origId = Binder.clearCallingIdentity(); 11926 11927 // If this process is running instrumentation, finish it. 11928 if (r != null && r.instrumentationClass != null) { 11929 Slog.w(TAG, "Error in app " + r.processName 11930 + " running instrumentation " + r.instrumentationClass + ":"); 11931 if (shortMsg != null) Slog.w(TAG, " " + shortMsg); 11932 if (longMsg != null) Slog.w(TAG, " " + longMsg); 11933 Bundle info = new Bundle(); 11934 info.putString("shortMsg", shortMsg); 11935 info.putString("longMsg", longMsg); 11936 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info); 11937 Binder.restoreCallingIdentity(origId); 11938 return; 11939 } 11940 11941 // If we can't identify the process or it's already exceeded its crash quota, 11942 // quit right away without showing a crash dialog. 11943 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) { 11944 Binder.restoreCallingIdentity(origId); 11945 return; 11946 } 11947 11948 Message msg = Message.obtain(); 11949 msg.what = SHOW_ERROR_MSG; 11950 HashMap data = new HashMap(); 11951 data.put("result", result); 11952 data.put("app", r); 11953 msg.obj = data; 11954 mHandler.sendMessage(msg); 11955 11956 Binder.restoreCallingIdentity(origId); 11957 } 11958 11959 int res = result.get(); 11960 11961 Intent appErrorIntent = null; 11962 synchronized (this) { 11963 if (r != null && !r.isolated) { 11964 // XXX Can't keep track of crash time for isolated processes, 11965 // since they don't have a persistent identity. 11966 mProcessCrashTimes.put(r.info.processName, r.uid, 11967 SystemClock.uptimeMillis()); 11968 } 11969 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) { 11970 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo); 11971 } 11972 } 11973 11974 if (appErrorIntent != null) { 11975 try { 11976 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId)); 11977 } catch (ActivityNotFoundException e) { 11978 Slog.w(TAG, "bug report receiver dissappeared", e); 11979 } 11980 } 11981 } 11982 11983 Intent createAppErrorIntentLocked(ProcessRecord r, 11984 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11985 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo); 11986 if (report == null) { 11987 return null; 11988 } 11989 Intent result = new Intent(Intent.ACTION_APP_ERROR); 11990 result.setComponent(r.errorReportReceiver); 11991 result.putExtra(Intent.EXTRA_BUG_REPORT, report); 11992 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11993 return result; 11994 } 11995 11996 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r, 11997 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11998 if (r.errorReportReceiver == null) { 11999 return null; 12000 } 12001 12002 if (!r.crashing && !r.notResponding && !r.forceCrashReport) { 12003 return null; 12004 } 12005 12006 ApplicationErrorReport report = new ApplicationErrorReport(); 12007 report.packageName = r.info.packageName; 12008 report.installerPackageName = r.errorReportReceiver.getPackageName(); 12009 report.processName = r.processName; 12010 report.time = timeMillis; 12011 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12012 12013 if (r.crashing || r.forceCrashReport) { 12014 report.type = ApplicationErrorReport.TYPE_CRASH; 12015 report.crashInfo = crashInfo; 12016 } else if (r.notResponding) { 12017 report.type = ApplicationErrorReport.TYPE_ANR; 12018 report.anrInfo = new ApplicationErrorReport.AnrInfo(); 12019 12020 report.anrInfo.activity = r.notRespondingReport.tag; 12021 report.anrInfo.cause = r.notRespondingReport.shortMsg; 12022 report.anrInfo.info = r.notRespondingReport.longMsg; 12023 } 12024 12025 return report; 12026 } 12027 12028 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 12029 enforceNotIsolatedCaller("getProcessesInErrorState"); 12030 // assume our apps are happy - lazy create the list 12031 List<ActivityManager.ProcessErrorStateInfo> errList = null; 12032 12033 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12034 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 12035 int userId = UserHandle.getUserId(Binder.getCallingUid()); 12036 12037 synchronized (this) { 12038 12039 // iterate across all processes 12040 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12041 ProcessRecord app = mLruProcesses.get(i); 12042 if (!allUsers && app.userId != userId) { 12043 continue; 12044 } 12045 if ((app.thread != null) && (app.crashing || app.notResponding)) { 12046 // This one's in trouble, so we'll generate a report for it 12047 // crashes are higher priority (in case there's a crash *and* an anr) 12048 ActivityManager.ProcessErrorStateInfo report = null; 12049 if (app.crashing) { 12050 report = app.crashingReport; 12051 } else if (app.notResponding) { 12052 report = app.notRespondingReport; 12053 } 12054 12055 if (report != null) { 12056 if (errList == null) { 12057 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1); 12058 } 12059 errList.add(report); 12060 } else { 12061 Slog.w(TAG, "Missing app error report, app = " + app.processName + 12062 " crashing = " + app.crashing + 12063 " notResponding = " + app.notResponding); 12064 } 12065 } 12066 } 12067 } 12068 12069 return errList; 12070 } 12071 12072 static int procStateToImportance(int procState, int memAdj, 12073 ActivityManager.RunningAppProcessInfo currApp) { 12074 int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState); 12075 if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { 12076 currApp.lru = memAdj; 12077 } else { 12078 currApp.lru = 0; 12079 } 12080 return imp; 12081 } 12082 12083 private void fillInProcMemInfo(ProcessRecord app, 12084 ActivityManager.RunningAppProcessInfo outInfo) { 12085 outInfo.pid = app.pid; 12086 outInfo.uid = app.info.uid; 12087 if (mHeavyWeightProcess == app) { 12088 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE; 12089 } 12090 if (app.persistent) { 12091 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT; 12092 } 12093 if (app.activities.size() > 0) { 12094 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES; 12095 } 12096 outInfo.lastTrimLevel = app.trimMemoryLevel; 12097 int adj = app.curAdj; 12098 int procState = app.curProcState; 12099 outInfo.importance = procStateToImportance(procState, adj, outInfo); 12100 outInfo.importanceReasonCode = app.adjTypeCode; 12101 outInfo.processState = app.curProcState; 12102 } 12103 12104 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 12105 enforceNotIsolatedCaller("getRunningAppProcesses"); 12106 // Lazy instantiation of list 12107 List<ActivityManager.RunningAppProcessInfo> runList = null; 12108 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12109 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 12110 int userId = UserHandle.getUserId(Binder.getCallingUid()); 12111 synchronized (this) { 12112 // Iterate across all processes 12113 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12114 ProcessRecord app = mLruProcesses.get(i); 12115 if (!allUsers && app.userId != userId) { 12116 continue; 12117 } 12118 if ((app.thread != null) && (!app.crashing && !app.notResponding)) { 12119 // Generate process state info for running application 12120 ActivityManager.RunningAppProcessInfo currApp = 12121 new ActivityManager.RunningAppProcessInfo(app.processName, 12122 app.pid, app.getPackageList()); 12123 fillInProcMemInfo(app, currApp); 12124 if (app.adjSource instanceof ProcessRecord) { 12125 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid; 12126 currApp.importanceReasonImportance = 12127 ActivityManager.RunningAppProcessInfo.procStateToImportance( 12128 app.adjSourceProcState); 12129 } else if (app.adjSource instanceof ActivityRecord) { 12130 ActivityRecord r = (ActivityRecord)app.adjSource; 12131 if (r.app != null) currApp.importanceReasonPid = r.app.pid; 12132 } 12133 if (app.adjTarget instanceof ComponentName) { 12134 currApp.importanceReasonComponent = (ComponentName)app.adjTarget; 12135 } 12136 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance 12137 // + " lru=" + currApp.lru); 12138 if (runList == null) { 12139 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>(); 12140 } 12141 runList.add(currApp); 12142 } 12143 } 12144 } 12145 return runList; 12146 } 12147 12148 public List<ApplicationInfo> getRunningExternalApplications() { 12149 enforceNotIsolatedCaller("getRunningExternalApplications"); 12150 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 12151 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 12152 if (runningApps != null && runningApps.size() > 0) { 12153 Set<String> extList = new HashSet<String>(); 12154 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 12155 if (app.pkgList != null) { 12156 for (String pkg : app.pkgList) { 12157 extList.add(pkg); 12158 } 12159 } 12160 } 12161 IPackageManager pm = AppGlobals.getPackageManager(); 12162 for (String pkg : extList) { 12163 try { 12164 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 12165 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 12166 retList.add(info); 12167 } 12168 } catch (RemoteException e) { 12169 } 12170 } 12171 } 12172 return retList; 12173 } 12174 12175 @Override 12176 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) { 12177 enforceNotIsolatedCaller("getMyMemoryState"); 12178 synchronized (this) { 12179 ProcessRecord proc; 12180 synchronized (mPidsSelfLocked) { 12181 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 12182 } 12183 fillInProcMemInfo(proc, outInfo); 12184 } 12185 } 12186 12187 @Override 12188 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12189 if (checkCallingPermission(android.Manifest.permission.DUMP) 12190 != PackageManager.PERMISSION_GRANTED) { 12191 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12192 + Binder.getCallingPid() 12193 + ", uid=" + Binder.getCallingUid() 12194 + " without permission " 12195 + android.Manifest.permission.DUMP); 12196 return; 12197 } 12198 12199 boolean dumpAll = false; 12200 boolean dumpClient = false; 12201 String dumpPackage = null; 12202 12203 int opti = 0; 12204 while (opti < args.length) { 12205 String opt = args[opti]; 12206 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12207 break; 12208 } 12209 opti++; 12210 if ("-a".equals(opt)) { 12211 dumpAll = true; 12212 } else if ("-c".equals(opt)) { 12213 dumpClient = true; 12214 } else if ("-h".equals(opt)) { 12215 pw.println("Activity manager dump options:"); 12216 pw.println(" [-a] [-c] [-h] [cmd] ..."); 12217 pw.println(" cmd may be one of:"); 12218 pw.println(" a[ctivities]: activity stack state"); 12219 pw.println(" r[recents]: recent activities state"); 12220 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state"); 12221 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state"); 12222 pw.println(" p[rocesses] [PACKAGE_NAME]: process state"); 12223 pw.println(" o[om]: out of memory management"); 12224 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state"); 12225 pw.println(" provider [COMP_SPEC]: provider client-side state"); 12226 pw.println(" s[ervices] [COMP_SPEC ...]: service state"); 12227 pw.println(" service [COMP_SPEC]: service client-side state"); 12228 pw.println(" package [PACKAGE_NAME]: all state related to given package"); 12229 pw.println(" all: dump all activities"); 12230 pw.println(" top: dump the top activity"); 12231 pw.println(" cmd may also be a COMP_SPEC to dump activities."); 12232 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),"); 12233 pw.println(" a partial substring in a component name, a"); 12234 pw.println(" hex object identifier."); 12235 pw.println(" -a: include all available server state."); 12236 pw.println(" -c: include client state."); 12237 return; 12238 } else { 12239 pw.println("Unknown argument: " + opt + "; use -h for help"); 12240 } 12241 } 12242 12243 long origId = Binder.clearCallingIdentity(); 12244 boolean more = false; 12245 // Is the caller requesting to dump a particular piece of data? 12246 if (opti < args.length) { 12247 String cmd = args[opti]; 12248 opti++; 12249 if ("activities".equals(cmd) || "a".equals(cmd)) { 12250 synchronized (this) { 12251 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null); 12252 } 12253 } else if ("recents".equals(cmd) || "r".equals(cmd)) { 12254 synchronized (this) { 12255 dumpRecentsLocked(fd, pw, args, opti, true, null); 12256 } 12257 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 12258 String[] newArgs; 12259 String name; 12260 if (opti >= args.length) { 12261 name = null; 12262 newArgs = EMPTY_STRING_ARRAY; 12263 } else { 12264 name = args[opti]; 12265 opti++; 12266 newArgs = new String[args.length - opti]; 12267 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12268 args.length - opti); 12269 } 12270 synchronized (this) { 12271 dumpBroadcastsLocked(fd, pw, args, opti, true, name); 12272 } 12273 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 12274 String[] newArgs; 12275 String name; 12276 if (opti >= args.length) { 12277 name = null; 12278 newArgs = EMPTY_STRING_ARRAY; 12279 } else { 12280 name = args[opti]; 12281 opti++; 12282 newArgs = new String[args.length - opti]; 12283 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12284 args.length - opti); 12285 } 12286 synchronized (this) { 12287 dumpPendingIntentsLocked(fd, pw, args, opti, true, name); 12288 } 12289 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 12290 String[] newArgs; 12291 String name; 12292 if (opti >= args.length) { 12293 name = null; 12294 newArgs = EMPTY_STRING_ARRAY; 12295 } else { 12296 name = args[opti]; 12297 opti++; 12298 newArgs = new String[args.length - opti]; 12299 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12300 args.length - opti); 12301 } 12302 synchronized (this) { 12303 dumpProcessesLocked(fd, pw, args, opti, true, name); 12304 } 12305 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 12306 synchronized (this) { 12307 dumpOomLocked(fd, pw, args, opti, true); 12308 } 12309 } else if ("provider".equals(cmd)) { 12310 String[] newArgs; 12311 String name; 12312 if (opti >= args.length) { 12313 name = null; 12314 newArgs = EMPTY_STRING_ARRAY; 12315 } else { 12316 name = args[opti]; 12317 opti++; 12318 newArgs = new String[args.length - opti]; 12319 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 12320 } 12321 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 12322 pw.println("No providers match: " + name); 12323 pw.println("Use -h for help."); 12324 } 12325 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 12326 synchronized (this) { 12327 dumpProvidersLocked(fd, pw, args, opti, true, null); 12328 } 12329 } else if ("service".equals(cmd)) { 12330 String[] newArgs; 12331 String name; 12332 if (opti >= args.length) { 12333 name = null; 12334 newArgs = EMPTY_STRING_ARRAY; 12335 } else { 12336 name = args[opti]; 12337 opti++; 12338 newArgs = new String[args.length - opti]; 12339 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12340 args.length - opti); 12341 } 12342 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) { 12343 pw.println("No services match: " + name); 12344 pw.println("Use -h for help."); 12345 } 12346 } else if ("package".equals(cmd)) { 12347 String[] newArgs; 12348 if (opti >= args.length) { 12349 pw.println("package: no package name specified"); 12350 pw.println("Use -h for help."); 12351 } else { 12352 dumpPackage = args[opti]; 12353 opti++; 12354 newArgs = new String[args.length - opti]; 12355 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12356 args.length - opti); 12357 args = newArgs; 12358 opti = 0; 12359 more = true; 12360 } 12361 } else if ("services".equals(cmd) || "s".equals(cmd)) { 12362 synchronized (this) { 12363 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null); 12364 } 12365 } else { 12366 // Dumping a single activity? 12367 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) { 12368 pw.println("Bad activity command, or no activities match: " + cmd); 12369 pw.println("Use -h for help."); 12370 } 12371 } 12372 if (!more) { 12373 Binder.restoreCallingIdentity(origId); 12374 return; 12375 } 12376 } 12377 12378 // No piece of data specified, dump everything. 12379 synchronized (this) { 12380 dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12381 pw.println(); 12382 if (dumpAll) { 12383 pw.println("-------------------------------------------------------------------------------"); 12384 } 12385 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12386 pw.println(); 12387 if (dumpAll) { 12388 pw.println("-------------------------------------------------------------------------------"); 12389 } 12390 dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12391 pw.println(); 12392 if (dumpAll) { 12393 pw.println("-------------------------------------------------------------------------------"); 12394 } 12395 mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 12396 pw.println(); 12397 if (dumpAll) { 12398 pw.println("-------------------------------------------------------------------------------"); 12399 } 12400 dumpRecentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12401 pw.println(); 12402 if (dumpAll) { 12403 pw.println("-------------------------------------------------------------------------------"); 12404 } 12405 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 12406 pw.println(); 12407 if (dumpAll) { 12408 pw.println("-------------------------------------------------------------------------------"); 12409 } 12410 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage); 12411 } 12412 Binder.restoreCallingIdentity(origId); 12413 } 12414 12415 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12416 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 12417 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)"); 12418 12419 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, 12420 dumpPackage); 12421 boolean needSep = printedAnything; 12422 12423 boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity, 12424 dumpPackage, needSep, " mFocusedActivity: "); 12425 if (printed) { 12426 printedAnything = true; 12427 needSep = false; 12428 } 12429 12430 if (dumpPackage == null) { 12431 if (needSep) { 12432 pw.println(); 12433 } 12434 needSep = true; 12435 printedAnything = true; 12436 mStackSupervisor.dump(pw, " "); 12437 } 12438 12439 if (!printedAnything) { 12440 pw.println(" (nothing)"); 12441 } 12442 } 12443 12444 void dumpRecentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12445 int opti, boolean dumpAll, String dumpPackage) { 12446 pw.println("ACTIVITY MANAGER RECENT ACTIVITIES (dumpsys activity recents)"); 12447 12448 boolean printedAnything = false; 12449 12450 if (mRecentTasks.size() > 0) { 12451 boolean printedHeader = false; 12452 12453 final int N = mRecentTasks.size(); 12454 for (int i=0; i<N; i++) { 12455 TaskRecord tr = mRecentTasks.get(i); 12456 if (dumpPackage != null) { 12457 if (tr.realActivity == null || 12458 !dumpPackage.equals(tr.realActivity)) { 12459 continue; 12460 } 12461 } 12462 if (!printedHeader) { 12463 pw.println(" Recent tasks:"); 12464 printedHeader = true; 12465 printedAnything = true; 12466 } 12467 pw.print(" * Recent #"); pw.print(i); pw.print(": "); 12468 pw.println(tr); 12469 if (dumpAll) { 12470 mRecentTasks.get(i).dump(pw, " "); 12471 } 12472 } 12473 } 12474 12475 if (!printedAnything) { 12476 pw.println(" (nothing)"); 12477 } 12478 } 12479 12480 void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12481 int opti, boolean dumpAll, String dumpPackage) { 12482 boolean needSep = false; 12483 boolean printedAnything = false; 12484 int numPers = 0; 12485 12486 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)"); 12487 12488 if (dumpAll) { 12489 final int NP = mProcessNames.getMap().size(); 12490 for (int ip=0; ip<NP; ip++) { 12491 SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip); 12492 final int NA = procs.size(); 12493 for (int ia=0; ia<NA; ia++) { 12494 ProcessRecord r = procs.valueAt(ia); 12495 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12496 continue; 12497 } 12498 if (!needSep) { 12499 pw.println(" All known processes:"); 12500 needSep = true; 12501 printedAnything = true; 12502 } 12503 pw.print(r.persistent ? " *PERS*" : " *APP*"); 12504 pw.print(" UID "); pw.print(procs.keyAt(ia)); 12505 pw.print(" "); pw.println(r); 12506 r.dump(pw, " "); 12507 if (r.persistent) { 12508 numPers++; 12509 } 12510 } 12511 } 12512 } 12513 12514 if (mIsolatedProcesses.size() > 0) { 12515 boolean printed = false; 12516 for (int i=0; i<mIsolatedProcesses.size(); i++) { 12517 ProcessRecord r = mIsolatedProcesses.valueAt(i); 12518 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12519 continue; 12520 } 12521 if (!printed) { 12522 if (needSep) { 12523 pw.println(); 12524 } 12525 pw.println(" Isolated process list (sorted by uid):"); 12526 printedAnything = true; 12527 printed = true; 12528 needSep = true; 12529 } 12530 pw.println(String.format("%sIsolated #%2d: %s", 12531 " ", i, r.toString())); 12532 } 12533 } 12534 12535 if (mLruProcesses.size() > 0) { 12536 if (needSep) { 12537 pw.println(); 12538 } 12539 pw.print(" Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size()); 12540 pw.print(" total, non-act at "); 12541 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 12542 pw.print(", non-svc at "); 12543 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 12544 pw.println("):"); 12545 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", false, dumpPackage); 12546 needSep = true; 12547 printedAnything = true; 12548 } 12549 12550 if (dumpAll || dumpPackage != null) { 12551 synchronized (mPidsSelfLocked) { 12552 boolean printed = false; 12553 for (int i=0; i<mPidsSelfLocked.size(); i++) { 12554 ProcessRecord r = mPidsSelfLocked.valueAt(i); 12555 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12556 continue; 12557 } 12558 if (!printed) { 12559 if (needSep) pw.println(); 12560 needSep = true; 12561 pw.println(" PID mappings:"); 12562 printed = true; 12563 printedAnything = true; 12564 } 12565 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 12566 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 12567 } 12568 } 12569 } 12570 12571 if (mForegroundProcesses.size() > 0) { 12572 synchronized (mPidsSelfLocked) { 12573 boolean printed = false; 12574 for (int i=0; i<mForegroundProcesses.size(); i++) { 12575 ProcessRecord r = mPidsSelfLocked.get( 12576 mForegroundProcesses.valueAt(i).pid); 12577 if (dumpPackage != null && (r == null 12578 || !r.pkgList.containsKey(dumpPackage))) { 12579 continue; 12580 } 12581 if (!printed) { 12582 if (needSep) pw.println(); 12583 needSep = true; 12584 pw.println(" Foreground Processes:"); 12585 printed = true; 12586 printedAnything = true; 12587 } 12588 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i)); 12589 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i)); 12590 } 12591 } 12592 } 12593 12594 if (mPersistentStartingProcesses.size() > 0) { 12595 if (needSep) pw.println(); 12596 needSep = true; 12597 printedAnything = true; 12598 pw.println(" Persisent processes that are starting:"); 12599 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 12600 "Starting Norm", "Restarting PERS", dumpPackage); 12601 } 12602 12603 if (mRemovedProcesses.size() > 0) { 12604 if (needSep) pw.println(); 12605 needSep = true; 12606 printedAnything = true; 12607 pw.println(" Processes that are being removed:"); 12608 dumpProcessList(pw, this, mRemovedProcesses, " ", 12609 "Removed Norm", "Removed PERS", dumpPackage); 12610 } 12611 12612 if (mProcessesOnHold.size() > 0) { 12613 if (needSep) pw.println(); 12614 needSep = true; 12615 printedAnything = true; 12616 pw.println(" Processes that are on old until the system is ready:"); 12617 dumpProcessList(pw, this, mProcessesOnHold, " ", 12618 "OnHold Norm", "OnHold PERS", dumpPackage); 12619 } 12620 12621 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage); 12622 12623 if (mProcessCrashTimes.getMap().size() > 0) { 12624 boolean printed = false; 12625 long now = SystemClock.uptimeMillis(); 12626 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 12627 final int NP = pmap.size(); 12628 for (int ip=0; ip<NP; ip++) { 12629 String pname = pmap.keyAt(ip); 12630 SparseArray<Long> uids = pmap.valueAt(ip); 12631 final int N = uids.size(); 12632 for (int i=0; i<N; i++) { 12633 int puid = uids.keyAt(i); 12634 ProcessRecord r = mProcessNames.get(pname, puid); 12635 if (dumpPackage != null && (r == null 12636 || !r.pkgList.containsKey(dumpPackage))) { 12637 continue; 12638 } 12639 if (!printed) { 12640 if (needSep) pw.println(); 12641 needSep = true; 12642 pw.println(" Time since processes crashed:"); 12643 printed = true; 12644 printedAnything = true; 12645 } 12646 pw.print(" Process "); pw.print(pname); 12647 pw.print(" uid "); pw.print(puid); 12648 pw.print(": last crashed "); 12649 TimeUtils.formatDuration(now-uids.valueAt(i), pw); 12650 pw.println(" ago"); 12651 } 12652 } 12653 } 12654 12655 if (mBadProcesses.getMap().size() > 0) { 12656 boolean printed = false; 12657 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap(); 12658 final int NP = pmap.size(); 12659 for (int ip=0; ip<NP; ip++) { 12660 String pname = pmap.keyAt(ip); 12661 SparseArray<BadProcessInfo> uids = pmap.valueAt(ip); 12662 final int N = uids.size(); 12663 for (int i=0; i<N; i++) { 12664 int puid = uids.keyAt(i); 12665 ProcessRecord r = mProcessNames.get(pname, puid); 12666 if (dumpPackage != null && (r == null 12667 || !r.pkgList.containsKey(dumpPackage))) { 12668 continue; 12669 } 12670 if (!printed) { 12671 if (needSep) pw.println(); 12672 needSep = true; 12673 pw.println(" Bad processes:"); 12674 printedAnything = true; 12675 } 12676 BadProcessInfo info = uids.valueAt(i); 12677 pw.print(" Bad process "); pw.print(pname); 12678 pw.print(" uid "); pw.print(puid); 12679 pw.print(": crashed at time "); pw.println(info.time); 12680 if (info.shortMsg != null) { 12681 pw.print(" Short msg: "); pw.println(info.shortMsg); 12682 } 12683 if (info.longMsg != null) { 12684 pw.print(" Long msg: "); pw.println(info.longMsg); 12685 } 12686 if (info.stack != null) { 12687 pw.println(" Stack:"); 12688 int lastPos = 0; 12689 for (int pos=0; pos<info.stack.length(); pos++) { 12690 if (info.stack.charAt(pos) == '\n') { 12691 pw.print(" "); 12692 pw.write(info.stack, lastPos, pos-lastPos); 12693 pw.println(); 12694 lastPos = pos+1; 12695 } 12696 } 12697 if (lastPos < info.stack.length()) { 12698 pw.print(" "); 12699 pw.write(info.stack, lastPos, info.stack.length()-lastPos); 12700 pw.println(); 12701 } 12702 } 12703 } 12704 } 12705 } 12706 12707 if (dumpPackage == null) { 12708 pw.println(); 12709 needSep = false; 12710 pw.println(" mStartedUsers:"); 12711 for (int i=0; i<mStartedUsers.size(); i++) { 12712 UserStartedState uss = mStartedUsers.valueAt(i); 12713 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier()); 12714 pw.print(": "); uss.dump("", pw); 12715 } 12716 pw.print(" mStartedUserArray: ["); 12717 for (int i=0; i<mStartedUserArray.length; i++) { 12718 if (i > 0) pw.print(", "); 12719 pw.print(mStartedUserArray[i]); 12720 } 12721 pw.println("]"); 12722 pw.print(" mUserLru: ["); 12723 for (int i=0; i<mUserLru.size(); i++) { 12724 if (i > 0) pw.print(", "); 12725 pw.print(mUserLru.get(i)); 12726 } 12727 pw.println("]"); 12728 if (dumpAll) { 12729 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray)); 12730 } 12731 synchronized (mUserProfileGroupIdsSelfLocked) { 12732 if (mUserProfileGroupIdsSelfLocked.size() > 0) { 12733 pw.println(" mUserProfileGroupIds:"); 12734 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) { 12735 pw.print(" User #"); 12736 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i)); 12737 pw.print(" -> profile #"); 12738 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i)); 12739 } 12740 } 12741 } 12742 } 12743 if (mHomeProcess != null && (dumpPackage == null 12744 || mHomeProcess.pkgList.containsKey(dumpPackage))) { 12745 if (needSep) { 12746 pw.println(); 12747 needSep = false; 12748 } 12749 pw.println(" mHomeProcess: " + mHomeProcess); 12750 } 12751 if (mPreviousProcess != null && (dumpPackage == null 12752 || mPreviousProcess.pkgList.containsKey(dumpPackage))) { 12753 if (needSep) { 12754 pw.println(); 12755 needSep = false; 12756 } 12757 pw.println(" mPreviousProcess: " + mPreviousProcess); 12758 } 12759 if (dumpAll) { 12760 StringBuilder sb = new StringBuilder(128); 12761 sb.append(" mPreviousProcessVisibleTime: "); 12762 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb); 12763 pw.println(sb); 12764 } 12765 if (mHeavyWeightProcess != null && (dumpPackage == null 12766 || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) { 12767 if (needSep) { 12768 pw.println(); 12769 needSep = false; 12770 } 12771 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 12772 } 12773 if (dumpPackage == null) { 12774 pw.println(" mConfiguration: " + mConfiguration); 12775 } 12776 if (dumpAll) { 12777 pw.println(" mConfigWillChange: " + getFocusedStack().mConfigWillChange); 12778 if (mCompatModePackages.getPackages().size() > 0) { 12779 boolean printed = false; 12780 for (Map.Entry<String, Integer> entry 12781 : mCompatModePackages.getPackages().entrySet()) { 12782 String pkg = entry.getKey(); 12783 int mode = entry.getValue(); 12784 if (dumpPackage != null && !dumpPackage.equals(pkg)) { 12785 continue; 12786 } 12787 if (!printed) { 12788 pw.println(" mScreenCompatPackages:"); 12789 printed = true; 12790 } 12791 pw.print(" "); pw.print(pkg); pw.print(": "); 12792 pw.print(mode); pw.println(); 12793 } 12794 } 12795 } 12796 if (dumpPackage == null) { 12797 if (mSleeping || mWentToSleep || mLockScreenShown) { 12798 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep 12799 + " mLockScreenShown " + mLockScreenShown); 12800 } 12801 if (mShuttingDown || mRunningVoice) { 12802 pw.print(" mShuttingDown=" + mShuttingDown + " mRunningVoice=" + mRunningVoice); 12803 } 12804 } 12805 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 12806 || mOrigWaitForDebugger) { 12807 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 12808 || dumpPackage.equals(mOrigDebugApp)) { 12809 if (needSep) { 12810 pw.println(); 12811 needSep = false; 12812 } 12813 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 12814 + " mDebugTransient=" + mDebugTransient 12815 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 12816 } 12817 } 12818 if (mOpenGlTraceApp != null) { 12819 if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) { 12820 if (needSep) { 12821 pw.println(); 12822 needSep = false; 12823 } 12824 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp); 12825 } 12826 } 12827 if (mProfileApp != null || mProfileProc != null || mProfileFile != null 12828 || mProfileFd != null) { 12829 if (dumpPackage == null || dumpPackage.equals(mProfileApp)) { 12830 if (needSep) { 12831 pw.println(); 12832 needSep = false; 12833 } 12834 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc); 12835 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd); 12836 pw.println(" mSamplingInterval=" + mSamplingInterval + " mAutoStopProfiler=" 12837 + mAutoStopProfiler); 12838 pw.println(" mProfileType=" + mProfileType); 12839 } 12840 } 12841 if (dumpPackage == null) { 12842 if (mAlwaysFinishActivities || mController != null) { 12843 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities 12844 + " mController=" + mController); 12845 } 12846 if (dumpAll) { 12847 pw.println(" Total persistent processes: " + numPers); 12848 pw.println(" mProcessesReady=" + mProcessesReady 12849 + " mSystemReady=" + mSystemReady); 12850 pw.println(" mBooting=" + mBooting 12851 + " mBooted=" + mBooted 12852 + " mFactoryTest=" + mFactoryTest); 12853 pw.print(" mLastPowerCheckRealtime="); 12854 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw); 12855 pw.println(""); 12856 pw.print(" mLastPowerCheckUptime="); 12857 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 12858 pw.println(""); 12859 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep); 12860 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity); 12861 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq); 12862 pw.println(" mNumNonCachedProcs=" + mNumNonCachedProcs 12863 + " (" + mLruProcesses.size() + " total)" 12864 + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs 12865 + " mNumServiceProcs=" + mNumServiceProcs 12866 + " mNewNumServiceProcs=" + mNewNumServiceProcs); 12867 pw.println(" mAllowLowerMemLevel=" + mAllowLowerMemLevel 12868 + " mLastMemoryLevel" + mLastMemoryLevel 12869 + " mLastNumProcesses" + mLastNumProcesses); 12870 long now = SystemClock.uptimeMillis(); 12871 pw.print(" mLastIdleTime="); 12872 TimeUtils.formatDuration(now, mLastIdleTime, pw); 12873 pw.print(" mLowRamSinceLastIdle="); 12874 TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw); 12875 pw.println(); 12876 } 12877 } 12878 12879 if (!printedAnything) { 12880 pw.println(" (nothing)"); 12881 } 12882 } 12883 12884 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args, 12885 int opti, boolean needSep, boolean dumpAll, String dumpPackage) { 12886 if (mProcessesToGc.size() > 0) { 12887 boolean printed = false; 12888 long now = SystemClock.uptimeMillis(); 12889 for (int i=0; i<mProcessesToGc.size(); i++) { 12890 ProcessRecord proc = mProcessesToGc.get(i); 12891 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) { 12892 continue; 12893 } 12894 if (!printed) { 12895 if (needSep) pw.println(); 12896 needSep = true; 12897 pw.println(" Processes that are waiting to GC:"); 12898 printed = true; 12899 } 12900 pw.print(" Process "); pw.println(proc); 12901 pw.print(" lowMem="); pw.print(proc.reportLowMemory); 12902 pw.print(", last gced="); 12903 pw.print(now-proc.lastRequestedGc); 12904 pw.print(" ms ago, last lowMem="); 12905 pw.print(now-proc.lastLowMemory); 12906 pw.println(" ms ago"); 12907 12908 } 12909 } 12910 return needSep; 12911 } 12912 12913 void printOomLevel(PrintWriter pw, String name, int adj) { 12914 pw.print(" "); 12915 if (adj >= 0) { 12916 pw.print(' '); 12917 if (adj < 10) pw.print(' '); 12918 } else { 12919 if (adj > -10) pw.print(' '); 12920 } 12921 pw.print(adj); 12922 pw.print(": "); 12923 pw.print(name); 12924 pw.print(" ("); 12925 pw.print(mProcessList.getMemLevel(adj)/1024); 12926 pw.println(" kB)"); 12927 } 12928 12929 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12930 int opti, boolean dumpAll) { 12931 boolean needSep = false; 12932 12933 if (mLruProcesses.size() > 0) { 12934 if (needSep) pw.println(); 12935 needSep = true; 12936 pw.println(" OOM levels:"); 12937 printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ); 12938 printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ); 12939 printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ); 12940 printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ); 12941 printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ); 12942 printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ); 12943 printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ); 12944 printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ); 12945 printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ); 12946 printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ); 12947 printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ); 12948 printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ); 12949 printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ); 12950 12951 if (needSep) pw.println(); 12952 pw.print(" Process OOM control ("); pw.print(mLruProcesses.size()); 12953 pw.print(" total, non-act at "); 12954 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 12955 pw.print(", non-svc at "); 12956 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 12957 pw.println("):"); 12958 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", true, null); 12959 needSep = true; 12960 } 12961 12962 dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null); 12963 12964 pw.println(); 12965 pw.println(" mHomeProcess: " + mHomeProcess); 12966 pw.println(" mPreviousProcess: " + mPreviousProcess); 12967 if (mHeavyWeightProcess != null) { 12968 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 12969 } 12970 12971 return true; 12972 } 12973 12974 /** 12975 * There are three ways to call this: 12976 * - no provider specified: dump all the providers 12977 * - a flattened component name that matched an existing provider was specified as the 12978 * first arg: dump that one provider 12979 * - the first arg isn't the flattened component name of an existing provider: 12980 * dump all providers whose component contains the first arg as a substring 12981 */ 12982 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 12983 int opti, boolean dumpAll) { 12984 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 12985 } 12986 12987 static class ItemMatcher { 12988 ArrayList<ComponentName> components; 12989 ArrayList<String> strings; 12990 ArrayList<Integer> objects; 12991 boolean all; 12992 12993 ItemMatcher() { 12994 all = true; 12995 } 12996 12997 void build(String name) { 12998 ComponentName componentName = ComponentName.unflattenFromString(name); 12999 if (componentName != null) { 13000 if (components == null) { 13001 components = new ArrayList<ComponentName>(); 13002 } 13003 components.add(componentName); 13004 all = false; 13005 } else { 13006 int objectId = 0; 13007 // Not a '/' separated full component name; maybe an object ID? 13008 try { 13009 objectId = Integer.parseInt(name, 16); 13010 if (objects == null) { 13011 objects = new ArrayList<Integer>(); 13012 } 13013 objects.add(objectId); 13014 all = false; 13015 } catch (RuntimeException e) { 13016 // Not an integer; just do string match. 13017 if (strings == null) { 13018 strings = new ArrayList<String>(); 13019 } 13020 strings.add(name); 13021 all = false; 13022 } 13023 } 13024 } 13025 13026 int build(String[] args, int opti) { 13027 for (; opti<args.length; opti++) { 13028 String name = args[opti]; 13029 if ("--".equals(name)) { 13030 return opti+1; 13031 } 13032 build(name); 13033 } 13034 return opti; 13035 } 13036 13037 boolean match(Object object, ComponentName comp) { 13038 if (all) { 13039 return true; 13040 } 13041 if (components != null) { 13042 for (int i=0; i<components.size(); i++) { 13043 if (components.get(i).equals(comp)) { 13044 return true; 13045 } 13046 } 13047 } 13048 if (objects != null) { 13049 for (int i=0; i<objects.size(); i++) { 13050 if (System.identityHashCode(object) == objects.get(i)) { 13051 return true; 13052 } 13053 } 13054 } 13055 if (strings != null) { 13056 String flat = comp.flattenToString(); 13057 for (int i=0; i<strings.size(); i++) { 13058 if (flat.contains(strings.get(i))) { 13059 return true; 13060 } 13061 } 13062 } 13063 return false; 13064 } 13065 } 13066 13067 /** 13068 * There are three things that cmd can be: 13069 * - a flattened component name that matches an existing activity 13070 * - the cmd arg isn't the flattened component name of an existing activity: 13071 * dump all activity whose component contains the cmd as a substring 13072 * - A hex number of the ActivityRecord object instance. 13073 */ 13074 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, 13075 int opti, boolean dumpAll) { 13076 ArrayList<ActivityRecord> activities; 13077 13078 synchronized (this) { 13079 activities = mStackSupervisor.getDumpActivitiesLocked(name); 13080 } 13081 13082 if (activities.size() <= 0) { 13083 return false; 13084 } 13085 13086 String[] newArgs = new String[args.length - opti]; 13087 System.arraycopy(args, opti, newArgs, 0, args.length - opti); 13088 13089 TaskRecord lastTask = null; 13090 boolean needSep = false; 13091 for (int i=activities.size()-1; i>=0; i--) { 13092 ActivityRecord r = activities.get(i); 13093 if (needSep) { 13094 pw.println(); 13095 } 13096 needSep = true; 13097 synchronized (this) { 13098 if (lastTask != r.task) { 13099 lastTask = r.task; 13100 pw.print("TASK "); pw.print(lastTask.affinity); 13101 pw.print(" id="); pw.println(lastTask.taskId); 13102 if (dumpAll) { 13103 lastTask.dump(pw, " "); 13104 } 13105 } 13106 } 13107 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll); 13108 } 13109 return true; 13110 } 13111 13112 /** 13113 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if 13114 * there is a thread associated with the activity. 13115 */ 13116 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, 13117 final ActivityRecord r, String[] args, boolean dumpAll) { 13118 String innerPrefix = prefix + " "; 13119 synchronized (this) { 13120 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName); 13121 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r))); 13122 pw.print(" pid="); 13123 if (r.app != null) pw.println(r.app.pid); 13124 else pw.println("(not running)"); 13125 if (dumpAll) { 13126 r.dump(pw, innerPrefix); 13127 } 13128 } 13129 if (r.app != null && r.app.thread != null) { 13130 // flush anything that is already in the PrintWriter since the thread is going 13131 // to write to the file descriptor directly 13132 pw.flush(); 13133 try { 13134 TransferPipe tp = new TransferPipe(); 13135 try { 13136 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), 13137 r.appToken, innerPrefix, args); 13138 tp.go(fd); 13139 } finally { 13140 tp.kill(); 13141 } 13142 } catch (IOException e) { 13143 pw.println(innerPrefix + "Failure while dumping the activity: " + e); 13144 } catch (RemoteException e) { 13145 pw.println(innerPrefix + "Got a RemoteException while dumping the activity"); 13146 } 13147 } 13148 } 13149 13150 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13151 int opti, boolean dumpAll, String dumpPackage) { 13152 boolean needSep = false; 13153 boolean onlyHistory = false; 13154 boolean printedAnything = false; 13155 13156 if ("history".equals(dumpPackage)) { 13157 if (opti < args.length && "-s".equals(args[opti])) { 13158 dumpAll = false; 13159 } 13160 onlyHistory = true; 13161 dumpPackage = null; 13162 } 13163 13164 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 13165 if (!onlyHistory && dumpAll) { 13166 if (mRegisteredReceivers.size() > 0) { 13167 boolean printed = false; 13168 Iterator it = mRegisteredReceivers.values().iterator(); 13169 while (it.hasNext()) { 13170 ReceiverList r = (ReceiverList)it.next(); 13171 if (dumpPackage != null && (r.app == null || 13172 !dumpPackage.equals(r.app.info.packageName))) { 13173 continue; 13174 } 13175 if (!printed) { 13176 pw.println(" Registered Receivers:"); 13177 needSep = true; 13178 printed = true; 13179 printedAnything = true; 13180 } 13181 pw.print(" * "); pw.println(r); 13182 r.dump(pw, " "); 13183 } 13184 } 13185 13186 if (mReceiverResolver.dump(pw, needSep ? 13187 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 13188 " ", dumpPackage, false)) { 13189 needSep = true; 13190 printedAnything = true; 13191 } 13192 } 13193 13194 for (BroadcastQueue q : mBroadcastQueues) { 13195 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 13196 printedAnything |= needSep; 13197 } 13198 13199 needSep = true; 13200 13201 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 13202 for (int user=0; user<mStickyBroadcasts.size(); user++) { 13203 if (needSep) { 13204 pw.println(); 13205 } 13206 needSep = true; 13207 printedAnything = true; 13208 pw.print(" Sticky broadcasts for user "); 13209 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 13210 StringBuilder sb = new StringBuilder(128); 13211 for (Map.Entry<String, ArrayList<Intent>> ent 13212 : mStickyBroadcasts.valueAt(user).entrySet()) { 13213 pw.print(" * Sticky action "); pw.print(ent.getKey()); 13214 if (dumpAll) { 13215 pw.println(":"); 13216 ArrayList<Intent> intents = ent.getValue(); 13217 final int N = intents.size(); 13218 for (int i=0; i<N; i++) { 13219 sb.setLength(0); 13220 sb.append(" Intent: "); 13221 intents.get(i).toShortString(sb, false, true, false, false); 13222 pw.println(sb.toString()); 13223 Bundle bundle = intents.get(i).getExtras(); 13224 if (bundle != null) { 13225 pw.print(" "); 13226 pw.println(bundle.toString()); 13227 } 13228 } 13229 } else { 13230 pw.println(""); 13231 } 13232 } 13233 } 13234 } 13235 13236 if (!onlyHistory && dumpAll) { 13237 pw.println(); 13238 for (BroadcastQueue queue : mBroadcastQueues) { 13239 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 13240 + queue.mBroadcastsScheduled); 13241 } 13242 pw.println(" mHandler:"); 13243 mHandler.dump(new PrintWriterPrinter(pw), " "); 13244 needSep = true; 13245 printedAnything = true; 13246 } 13247 13248 if (!printedAnything) { 13249 pw.println(" (nothing)"); 13250 } 13251 } 13252 13253 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13254 int opti, boolean dumpAll, String dumpPackage) { 13255 boolean needSep; 13256 boolean printedAnything = false; 13257 13258 ItemMatcher matcher = new ItemMatcher(); 13259 matcher.build(args, opti); 13260 13261 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 13262 13263 needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 13264 printedAnything |= needSep; 13265 13266 if (mLaunchingProviders.size() > 0) { 13267 boolean printed = false; 13268 for (int i=mLaunchingProviders.size()-1; i>=0; i--) { 13269 ContentProviderRecord r = mLaunchingProviders.get(i); 13270 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 13271 continue; 13272 } 13273 if (!printed) { 13274 if (needSep) pw.println(); 13275 needSep = true; 13276 pw.println(" Launching content providers:"); 13277 printed = true; 13278 printedAnything = true; 13279 } 13280 pw.print(" Launching #"); pw.print(i); pw.print(": "); 13281 pw.println(r); 13282 } 13283 } 13284 13285 if (mGrantedUriPermissions.size() > 0) { 13286 boolean printed = false; 13287 int dumpUid = -2; 13288 if (dumpPackage != null) { 13289 try { 13290 dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0); 13291 } catch (NameNotFoundException e) { 13292 dumpUid = -1; 13293 } 13294 } 13295 for (int i=0; i<mGrantedUriPermissions.size(); i++) { 13296 int uid = mGrantedUriPermissions.keyAt(i); 13297 if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) { 13298 continue; 13299 } 13300 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 13301 if (!printed) { 13302 if (needSep) pw.println(); 13303 needSep = true; 13304 pw.println(" Granted Uri Permissions:"); 13305 printed = true; 13306 printedAnything = true; 13307 } 13308 pw.print(" * UID "); pw.print(uid); pw.println(" holds:"); 13309 for (UriPermission perm : perms.values()) { 13310 pw.print(" "); pw.println(perm); 13311 if (dumpAll) { 13312 perm.dump(pw, " "); 13313 } 13314 } 13315 } 13316 } 13317 13318 if (!printedAnything) { 13319 pw.println(" (nothing)"); 13320 } 13321 } 13322 13323 void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13324 int opti, boolean dumpAll, String dumpPackage) { 13325 boolean printed = false; 13326 13327 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)"); 13328 13329 if (mIntentSenderRecords.size() > 0) { 13330 Iterator<WeakReference<PendingIntentRecord>> it 13331 = mIntentSenderRecords.values().iterator(); 13332 while (it.hasNext()) { 13333 WeakReference<PendingIntentRecord> ref = it.next(); 13334 PendingIntentRecord rec = ref != null ? ref.get(): null; 13335 if (dumpPackage != null && (rec == null 13336 || !dumpPackage.equals(rec.key.packageName))) { 13337 continue; 13338 } 13339 printed = true; 13340 if (rec != null) { 13341 pw.print(" * "); pw.println(rec); 13342 if (dumpAll) { 13343 rec.dump(pw, " "); 13344 } 13345 } else { 13346 pw.print(" * "); pw.println(ref); 13347 } 13348 } 13349 } 13350 13351 if (!printed) { 13352 pw.println(" (nothing)"); 13353 } 13354 } 13355 13356 private static final int dumpProcessList(PrintWriter pw, 13357 ActivityManagerService service, List list, 13358 String prefix, String normalLabel, String persistentLabel, 13359 String dumpPackage) { 13360 int numPers = 0; 13361 final int N = list.size()-1; 13362 for (int i=N; i>=0; i--) { 13363 ProcessRecord r = (ProcessRecord)list.get(i); 13364 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 13365 continue; 13366 } 13367 pw.println(String.format("%s%s #%2d: %s", 13368 prefix, (r.persistent ? persistentLabel : normalLabel), 13369 i, r.toString())); 13370 if (r.persistent) { 13371 numPers++; 13372 } 13373 } 13374 return numPers; 13375 } 13376 13377 private static final boolean dumpProcessOomList(PrintWriter pw, 13378 ActivityManagerService service, List<ProcessRecord> origList, 13379 String prefix, String normalLabel, String persistentLabel, 13380 boolean inclDetails, String dumpPackage) { 13381 13382 ArrayList<Pair<ProcessRecord, Integer>> list 13383 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size()); 13384 for (int i=0; i<origList.size(); i++) { 13385 ProcessRecord r = origList.get(i); 13386 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 13387 continue; 13388 } 13389 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i)); 13390 } 13391 13392 if (list.size() <= 0) { 13393 return false; 13394 } 13395 13396 Comparator<Pair<ProcessRecord, Integer>> comparator 13397 = new Comparator<Pair<ProcessRecord, Integer>>() { 13398 @Override 13399 public int compare(Pair<ProcessRecord, Integer> object1, 13400 Pair<ProcessRecord, Integer> object2) { 13401 if (object1.first.setAdj != object2.first.setAdj) { 13402 return object1.first.setAdj > object2.first.setAdj ? -1 : 1; 13403 } 13404 if (object1.second.intValue() != object2.second.intValue()) { 13405 return object1.second.intValue() > object2.second.intValue() ? -1 : 1; 13406 } 13407 return 0; 13408 } 13409 }; 13410 13411 Collections.sort(list, comparator); 13412 13413 final long curRealtime = SystemClock.elapsedRealtime(); 13414 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime; 13415 final long curUptime = SystemClock.uptimeMillis(); 13416 final long uptimeSince = curUptime - service.mLastPowerCheckUptime; 13417 13418 for (int i=list.size()-1; i>=0; i--) { 13419 ProcessRecord r = list.get(i).first; 13420 String oomAdj = ProcessList.makeOomAdjString(r.setAdj); 13421 char schedGroup; 13422 switch (r.setSchedGroup) { 13423 case Process.THREAD_GROUP_BG_NONINTERACTIVE: 13424 schedGroup = 'B'; 13425 break; 13426 case Process.THREAD_GROUP_DEFAULT: 13427 schedGroup = 'F'; 13428 break; 13429 default: 13430 schedGroup = '?'; 13431 break; 13432 } 13433 char foreground; 13434 if (r.foregroundActivities) { 13435 foreground = 'A'; 13436 } else if (r.foregroundServices) { 13437 foreground = 'S'; 13438 } else { 13439 foreground = ' '; 13440 } 13441 String procState = ProcessList.makeProcStateString(r.curProcState); 13442 pw.print(prefix); 13443 pw.print(r.persistent ? persistentLabel : normalLabel); 13444 pw.print(" #"); 13445 int num = (origList.size()-1)-list.get(i).second; 13446 if (num < 10) pw.print(' '); 13447 pw.print(num); 13448 pw.print(": "); 13449 pw.print(oomAdj); 13450 pw.print(' '); 13451 pw.print(schedGroup); 13452 pw.print('/'); 13453 pw.print(foreground); 13454 pw.print('/'); 13455 pw.print(procState); 13456 pw.print(" trm:"); 13457 if (r.trimMemoryLevel < 10) pw.print(' '); 13458 pw.print(r.trimMemoryLevel); 13459 pw.print(' '); 13460 pw.print(r.toShortString()); 13461 pw.print(" ("); 13462 pw.print(r.adjType); 13463 pw.println(')'); 13464 if (r.adjSource != null || r.adjTarget != null) { 13465 pw.print(prefix); 13466 pw.print(" "); 13467 if (r.adjTarget instanceof ComponentName) { 13468 pw.print(((ComponentName)r.adjTarget).flattenToShortString()); 13469 } else if (r.adjTarget != null) { 13470 pw.print(r.adjTarget.toString()); 13471 } else { 13472 pw.print("{null}"); 13473 } 13474 pw.print("<="); 13475 if (r.adjSource instanceof ProcessRecord) { 13476 pw.print("Proc{"); 13477 pw.print(((ProcessRecord)r.adjSource).toShortString()); 13478 pw.println("}"); 13479 } else if (r.adjSource != null) { 13480 pw.println(r.adjSource.toString()); 13481 } else { 13482 pw.println("{null}"); 13483 } 13484 } 13485 if (inclDetails) { 13486 pw.print(prefix); 13487 pw.print(" "); 13488 pw.print("oom: max="); pw.print(r.maxAdj); 13489 pw.print(" curRaw="); pw.print(r.curRawAdj); 13490 pw.print(" setRaw="); pw.print(r.setRawAdj); 13491 pw.print(" cur="); pw.print(r.curAdj); 13492 pw.print(" set="); pw.println(r.setAdj); 13493 pw.print(prefix); 13494 pw.print(" "); 13495 pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState)); 13496 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState)); 13497 pw.print(" lastPss="); pw.print(r.lastPss); 13498 pw.print(" lastCachedPss="); pw.println(r.lastCachedPss); 13499 pw.print(prefix); 13500 pw.print(" "); 13501 pw.print("cached="); pw.print(r.cached); 13502 pw.print(" empty="); pw.print(r.empty); 13503 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient); 13504 13505 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 13506 if (r.lastWakeTime != 0) { 13507 long wtime; 13508 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics(); 13509 synchronized (stats) { 13510 wtime = stats.getProcessWakeTime(r.info.uid, 13511 r.pid, curRealtime); 13512 } 13513 long timeUsed = wtime - r.lastWakeTime; 13514 pw.print(prefix); 13515 pw.print(" "); 13516 pw.print("keep awake over "); 13517 TimeUtils.formatDuration(realtimeSince, pw); 13518 pw.print(" used "); 13519 TimeUtils.formatDuration(timeUsed, pw); 13520 pw.print(" ("); 13521 pw.print((timeUsed*100)/realtimeSince); 13522 pw.println("%)"); 13523 } 13524 if (r.lastCpuTime != 0) { 13525 long timeUsed = r.curCpuTime - r.lastCpuTime; 13526 pw.print(prefix); 13527 pw.print(" "); 13528 pw.print("run cpu over "); 13529 TimeUtils.formatDuration(uptimeSince, pw); 13530 pw.print(" used "); 13531 TimeUtils.formatDuration(timeUsed, pw); 13532 pw.print(" ("); 13533 pw.print((timeUsed*100)/uptimeSince); 13534 pw.println("%)"); 13535 } 13536 } 13537 } 13538 } 13539 return true; 13540 } 13541 13542 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) { 13543 ArrayList<ProcessRecord> procs; 13544 synchronized (this) { 13545 if (args != null && args.length > start 13546 && args[start].charAt(0) != '-') { 13547 procs = new ArrayList<ProcessRecord>(); 13548 int pid = -1; 13549 try { 13550 pid = Integer.parseInt(args[start]); 13551 } catch (NumberFormatException e) { 13552 } 13553 for (int i=mLruProcesses.size()-1; i>=0; i--) { 13554 ProcessRecord proc = mLruProcesses.get(i); 13555 if (proc.pid == pid) { 13556 procs.add(proc); 13557 } else if (proc.processName.equals(args[start])) { 13558 procs.add(proc); 13559 } 13560 } 13561 if (procs.size() <= 0) { 13562 return null; 13563 } 13564 } else { 13565 procs = new ArrayList<ProcessRecord>(mLruProcesses); 13566 } 13567 } 13568 return procs; 13569 } 13570 13571 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 13572 PrintWriter pw, String[] args) { 13573 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 13574 if (procs == null) { 13575 pw.println("No process found for: " + args[0]); 13576 return; 13577 } 13578 13579 long uptime = SystemClock.uptimeMillis(); 13580 long realtime = SystemClock.elapsedRealtime(); 13581 pw.println("Applications Graphics Acceleration Info:"); 13582 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 13583 13584 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13585 ProcessRecord r = procs.get(i); 13586 if (r.thread != null) { 13587 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **"); 13588 pw.flush(); 13589 try { 13590 TransferPipe tp = new TransferPipe(); 13591 try { 13592 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args); 13593 tp.go(fd); 13594 } finally { 13595 tp.kill(); 13596 } 13597 } catch (IOException e) { 13598 pw.println("Failure while dumping the app: " + r); 13599 pw.flush(); 13600 } catch (RemoteException e) { 13601 pw.println("Got a RemoteException while dumping the app " + r); 13602 pw.flush(); 13603 } 13604 } 13605 } 13606 } 13607 13608 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 13609 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 13610 if (procs == null) { 13611 pw.println("No process found for: " + args[0]); 13612 return; 13613 } 13614 13615 pw.println("Applications Database Info:"); 13616 13617 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13618 ProcessRecord r = procs.get(i); 13619 if (r.thread != null) { 13620 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **"); 13621 pw.flush(); 13622 try { 13623 TransferPipe tp = new TransferPipe(); 13624 try { 13625 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args); 13626 tp.go(fd); 13627 } finally { 13628 tp.kill(); 13629 } 13630 } catch (IOException e) { 13631 pw.println("Failure while dumping the app: " + r); 13632 pw.flush(); 13633 } catch (RemoteException e) { 13634 pw.println("Got a RemoteException while dumping the app " + r); 13635 pw.flush(); 13636 } 13637 } 13638 } 13639 } 13640 13641 final static class MemItem { 13642 final boolean isProc; 13643 final String label; 13644 final String shortLabel; 13645 final long pss; 13646 final int id; 13647 final boolean hasActivities; 13648 ArrayList<MemItem> subitems; 13649 13650 public MemItem(String _label, String _shortLabel, long _pss, int _id, 13651 boolean _hasActivities) { 13652 isProc = true; 13653 label = _label; 13654 shortLabel = _shortLabel; 13655 pss = _pss; 13656 id = _id; 13657 hasActivities = _hasActivities; 13658 } 13659 13660 public MemItem(String _label, String _shortLabel, long _pss, int _id) { 13661 isProc = false; 13662 label = _label; 13663 shortLabel = _shortLabel; 13664 pss = _pss; 13665 id = _id; 13666 hasActivities = false; 13667 } 13668 } 13669 13670 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 13671 ArrayList<MemItem> items, boolean sort, boolean isCompact) { 13672 if (sort && !isCompact) { 13673 Collections.sort(items, new Comparator<MemItem>() { 13674 @Override 13675 public int compare(MemItem lhs, MemItem rhs) { 13676 if (lhs.pss < rhs.pss) { 13677 return 1; 13678 } else if (lhs.pss > rhs.pss) { 13679 return -1; 13680 } 13681 return 0; 13682 } 13683 }); 13684 } 13685 13686 for (int i=0; i<items.size(); i++) { 13687 MemItem mi = items.get(i); 13688 if (!isCompact) { 13689 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label); 13690 } else if (mi.isProc) { 13691 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 13692 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); 13693 pw.println(mi.hasActivities ? ",a" : ",e"); 13694 } else { 13695 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 13696 pw.println(mi.pss); 13697 } 13698 if (mi.subitems != null) { 13699 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 13700 true, isCompact); 13701 } 13702 } 13703 } 13704 13705 // These are in KB. 13706 static final long[] DUMP_MEM_BUCKETS = new long[] { 13707 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 13708 120*1024, 160*1024, 200*1024, 13709 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 13710 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 13711 }; 13712 13713 static final void appendMemBucket(StringBuilder out, long memKB, String label, 13714 boolean stackLike) { 13715 int start = label.lastIndexOf('.'); 13716 if (start >= 0) start++; 13717 else start = 0; 13718 int end = label.length(); 13719 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 13720 if (DUMP_MEM_BUCKETS[i] >= memKB) { 13721 long bucket = DUMP_MEM_BUCKETS[i]/1024; 13722 out.append(bucket); 13723 out.append(stackLike ? "MB." : "MB "); 13724 out.append(label, start, end); 13725 return; 13726 } 13727 } 13728 out.append(memKB/1024); 13729 out.append(stackLike ? "MB." : "MB "); 13730 out.append(label, start, end); 13731 } 13732 13733 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 13734 ProcessList.NATIVE_ADJ, 13735 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ, 13736 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, 13737 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 13738 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 13739 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ 13740 }; 13741 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 13742 "Native", 13743 "System", "Persistent", "Foreground", 13744 "Visible", "Perceptible", 13745 "Heavy Weight", "Backup", 13746 "A Services", "Home", 13747 "Previous", "B Services", "Cached" 13748 }; 13749 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 13750 "native", 13751 "sys", "pers", "fore", 13752 "vis", "percept", 13753 "heavy", "backup", 13754 "servicea", "home", 13755 "prev", "serviceb", "cached" 13756 }; 13757 13758 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 13759 long realtime, boolean isCheckinRequest, boolean isCompact) { 13760 if (isCheckinRequest || isCompact) { 13761 // short checkin version 13762 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 13763 } else { 13764 pw.println("Applications Memory Usage (kB):"); 13765 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 13766 } 13767 } 13768 13769 final void dumpApplicationMemoryUsage(FileDescriptor fd, 13770 PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) { 13771 boolean dumpDetails = false; 13772 boolean dumpFullDetails = false; 13773 boolean dumpDalvik = false; 13774 boolean oomOnly = false; 13775 boolean isCompact = false; 13776 boolean localOnly = false; 13777 13778 int opti = 0; 13779 while (opti < args.length) { 13780 String opt = args[opti]; 13781 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13782 break; 13783 } 13784 opti++; 13785 if ("-a".equals(opt)) { 13786 dumpDetails = true; 13787 dumpFullDetails = true; 13788 dumpDalvik = true; 13789 } else if ("-d".equals(opt)) { 13790 dumpDalvik = true; 13791 } else if ("-c".equals(opt)) { 13792 isCompact = true; 13793 } else if ("--oom".equals(opt)) { 13794 oomOnly = true; 13795 } else if ("--local".equals(opt)) { 13796 localOnly = true; 13797 } else if ("-h".equals(opt)) { 13798 pw.println("meminfo dump options: [-a] [-d] [-c] [--oom] [process]"); 13799 pw.println(" -a: include all available information for each process."); 13800 pw.println(" -d: include dalvik details when dumping process details."); 13801 pw.println(" -c: dump in a compact machine-parseable representation."); 13802 pw.println(" --oom: only show processes organized by oom adj."); 13803 pw.println(" --local: only collect details locally, don't call process."); 13804 pw.println("If [process] is specified it can be the name or "); 13805 pw.println("pid of a specific process to dump."); 13806 return; 13807 } else { 13808 pw.println("Unknown argument: " + opt + "; use -h for help"); 13809 } 13810 } 13811 13812 final boolean isCheckinRequest = scanArgs(args, "--checkin"); 13813 long uptime = SystemClock.uptimeMillis(); 13814 long realtime = SystemClock.elapsedRealtime(); 13815 final long[] tmpLong = new long[1]; 13816 13817 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args); 13818 if (procs == null) { 13819 // No Java processes. Maybe they want to print a native process. 13820 if (args != null && args.length > opti 13821 && args[opti].charAt(0) != '-') { 13822 ArrayList<ProcessCpuTracker.Stats> nativeProcs 13823 = new ArrayList<ProcessCpuTracker.Stats>(); 13824 updateCpuStatsNow(); 13825 int findPid = -1; 13826 try { 13827 findPid = Integer.parseInt(args[opti]); 13828 } catch (NumberFormatException e) { 13829 } 13830 synchronized (mProcessCpuTracker) { 13831 final int N = mProcessCpuTracker.countStats(); 13832 for (int i=0; i<N; i++) { 13833 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13834 if (st.pid == findPid || (st.baseName != null 13835 && st.baseName.equals(args[opti]))) { 13836 nativeProcs.add(st); 13837 } 13838 } 13839 } 13840 if (nativeProcs.size() > 0) { 13841 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, 13842 isCompact); 13843 Debug.MemoryInfo mi = null; 13844 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 13845 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 13846 final int pid = r.pid; 13847 if (!isCheckinRequest && dumpDetails) { 13848 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **"); 13849 } 13850 if (mi == null) { 13851 mi = new Debug.MemoryInfo(); 13852 } 13853 if (dumpDetails || (!brief && !oomOnly)) { 13854 Debug.getMemoryInfo(pid, mi); 13855 } else { 13856 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 13857 mi.dalvikPrivateDirty = (int)tmpLong[0]; 13858 } 13859 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 13860 dumpDalvik, pid, r.baseName, 0, 0, 0, 0, 0, 0); 13861 if (isCheckinRequest) { 13862 pw.println(); 13863 } 13864 } 13865 return; 13866 } 13867 } 13868 pw.println("No process found for: " + args[opti]); 13869 return; 13870 } 13871 13872 if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest)) { 13873 dumpDetails = true; 13874 } 13875 13876 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact); 13877 13878 String[] innerArgs = new String[args.length-opti]; 13879 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 13880 13881 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 13882 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 13883 long nativePss=0, dalvikPss=0, otherPss=0; 13884 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13885 13886 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 13887 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 13888 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 13889 13890 long totalPss = 0; 13891 long cachedPss = 0; 13892 13893 Debug.MemoryInfo mi = null; 13894 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13895 final ProcessRecord r = procs.get(i); 13896 final IApplicationThread thread; 13897 final int pid; 13898 final int oomAdj; 13899 final boolean hasActivities; 13900 synchronized (this) { 13901 thread = r.thread; 13902 pid = r.pid; 13903 oomAdj = r.getSetAdjWithServices(); 13904 hasActivities = r.activities.size() > 0; 13905 } 13906 if (thread != null) { 13907 if (!isCheckinRequest && dumpDetails) { 13908 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 13909 } 13910 if (mi == null) { 13911 mi = new Debug.MemoryInfo(); 13912 } 13913 if (dumpDetails || (!brief && !oomOnly)) { 13914 Debug.getMemoryInfo(pid, mi); 13915 } else { 13916 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 13917 mi.dalvikPrivateDirty = (int)tmpLong[0]; 13918 } 13919 if (dumpDetails) { 13920 if (localOnly) { 13921 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 13922 dumpDalvik, pid, r.processName, 0, 0, 0, 0, 0, 0); 13923 if (isCheckinRequest) { 13924 pw.println(); 13925 } 13926 } else { 13927 try { 13928 pw.flush(); 13929 thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails, 13930 dumpDalvik, innerArgs); 13931 } catch (RemoteException e) { 13932 if (!isCheckinRequest) { 13933 pw.println("Got RemoteException!"); 13934 pw.flush(); 13935 } 13936 } 13937 } 13938 } 13939 13940 final long myTotalPss = mi.getTotalPss(); 13941 final long myTotalUss = mi.getTotalUss(); 13942 13943 synchronized (this) { 13944 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 13945 // Record this for posterity if the process has been stable. 13946 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList); 13947 } 13948 } 13949 13950 if (!isCheckinRequest && mi != null) { 13951 totalPss += myTotalPss; 13952 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13953 (hasActivities ? " / activities)" : ")"), 13954 r.processName, myTotalPss, pid, hasActivities); 13955 procMems.add(pssItem); 13956 procMemsMap.put(pid, pssItem); 13957 13958 nativePss += mi.nativePss; 13959 dalvikPss += mi.dalvikPss; 13960 otherPss += mi.otherPss; 13961 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13962 long mem = mi.getOtherPss(j); 13963 miscPss[j] += mem; 13964 otherPss -= mem; 13965 } 13966 13967 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13968 cachedPss += myTotalPss; 13969 } 13970 13971 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13972 if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex] 13973 || oomIndex == (oomPss.length-1)) { 13974 oomPss[oomIndex] += myTotalPss; 13975 if (oomProcs[oomIndex] == null) { 13976 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13977 } 13978 oomProcs[oomIndex].add(pssItem); 13979 break; 13980 } 13981 } 13982 } 13983 } 13984 } 13985 13986 long nativeProcTotalPss = 0; 13987 13988 if (!isCheckinRequest && procs.size() > 1) { 13989 // If we are showing aggregations, also look for native processes to 13990 // include so that our aggregations are more accurate. 13991 updateCpuStatsNow(); 13992 synchronized (mProcessCpuTracker) { 13993 final int N = mProcessCpuTracker.countStats(); 13994 for (int i=0; i<N; i++) { 13995 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13996 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13997 if (mi == null) { 13998 mi = new Debug.MemoryInfo(); 13999 } 14000 if (!brief && !oomOnly) { 14001 Debug.getMemoryInfo(st.pid, mi); 14002 } else { 14003 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong); 14004 mi.nativePrivateDirty = (int)tmpLong[0]; 14005 } 14006 14007 final long myTotalPss = mi.getTotalPss(); 14008 totalPss += myTotalPss; 14009 nativeProcTotalPss += myTotalPss; 14010 14011 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 14012 st.name, myTotalPss, st.pid, false); 14013 procMems.add(pssItem); 14014 14015 nativePss += mi.nativePss; 14016 dalvikPss += mi.dalvikPss; 14017 otherPss += mi.otherPss; 14018 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14019 long mem = mi.getOtherPss(j); 14020 miscPss[j] += mem; 14021 otherPss -= mem; 14022 } 14023 oomPss[0] += myTotalPss; 14024 if (oomProcs[0] == null) { 14025 oomProcs[0] = new ArrayList<MemItem>(); 14026 } 14027 oomProcs[0].add(pssItem); 14028 } 14029 } 14030 } 14031 14032 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 14033 14034 catMems.add(new MemItem("Native", "Native", nativePss, -1)); 14035 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2)); 14036 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3)); 14037 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14038 String label = Debug.MemoryInfo.getOtherLabel(j); 14039 catMems.add(new MemItem(label, label, miscPss[j], j)); 14040 } 14041 14042 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 14043 for (int j=0; j<oomPss.length; j++) { 14044 if (oomPss[j] != 0) { 14045 String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 14046 : DUMP_MEM_OOM_LABEL[j]; 14047 MemItem item = new MemItem(label, label, oomPss[j], 14048 DUMP_MEM_OOM_ADJ[j]); 14049 item.subitems = oomProcs[j]; 14050 oomMems.add(item); 14051 } 14052 } 14053 14054 if (!brief && !oomOnly && !isCompact) { 14055 pw.println(); 14056 pw.println("Total PSS by process:"); 14057 dumpMemItems(pw, " ", "proc", procMems, true, isCompact); 14058 pw.println(); 14059 } 14060 if (!isCompact) { 14061 pw.println("Total PSS by OOM adjustment:"); 14062 } 14063 dumpMemItems(pw, " ", "oom", oomMems, false, isCompact); 14064 if (!brief && !oomOnly) { 14065 PrintWriter out = categoryPw != null ? categoryPw : pw; 14066 if (!isCompact) { 14067 out.println(); 14068 out.println("Total PSS by category:"); 14069 } 14070 dumpMemItems(out, " ", "cat", catMems, true, isCompact); 14071 } 14072 if (!isCompact) { 14073 pw.println(); 14074 } 14075 MemInfoReader memInfo = new MemInfoReader(); 14076 memInfo.readMemInfo(); 14077 if (nativeProcTotalPss > 0) { 14078 synchronized (this) { 14079 mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(), 14080 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(), 14081 memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()+memInfo.getSlabSizeKb(), 14082 nativeProcTotalPss); 14083 } 14084 } 14085 if (!brief) { 14086 if (!isCompact) { 14087 pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb()); 14088 pw.print(" kB (status "); 14089 switch (mLastMemoryLevel) { 14090 case ProcessStats.ADJ_MEM_FACTOR_NORMAL: 14091 pw.println("normal)"); 14092 break; 14093 case ProcessStats.ADJ_MEM_FACTOR_MODERATE: 14094 pw.println("moderate)"); 14095 break; 14096 case ProcessStats.ADJ_MEM_FACTOR_LOW: 14097 pw.println("low)"); 14098 break; 14099 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 14100 pw.println("critical)"); 14101 break; 14102 default: 14103 pw.print(mLastMemoryLevel); 14104 pw.println(")"); 14105 break; 14106 } 14107 pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb() 14108 + memInfo.getFreeSizeKb()); pw.print(" kB ("); 14109 pw.print(cachedPss); pw.print(" cached pss + "); 14110 pw.print(memInfo.getCachedSizeKb()); pw.print(" cached + "); 14111 pw.print(memInfo.getFreeSizeKb()); pw.println(" free)"); 14112 } else { 14113 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 14114 pw.print(cachedPss + memInfo.getCachedSizeKb() 14115 + memInfo.getFreeSizeKb()); pw.print(","); 14116 pw.println(totalPss - cachedPss); 14117 } 14118 } 14119 if (!isCompact) { 14120 pw.print(" Used RAM: "); pw.print(totalPss - cachedPss 14121 + memInfo.getBuffersSizeKb() + memInfo.getShmemSizeKb() 14122 + memInfo.getSlabSizeKb()); pw.print(" kB ("); 14123 pw.print(totalPss - cachedPss); pw.print(" used pss + "); 14124 pw.print(memInfo.getBuffersSizeKb()); pw.print(" buffers + "); 14125 pw.print(memInfo.getShmemSizeKb()); pw.print(" shmem + "); 14126 pw.print(memInfo.getSlabSizeKb()); pw.println(" slab)"); 14127 pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb() 14128 - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 14129 - memInfo.getBuffersSizeKb() - memInfo.getShmemSizeKb() 14130 - memInfo.getSlabSizeKb()); pw.println(" kB"); 14131 } 14132 if (!brief) { 14133 if (memInfo.getZramTotalSizeKb() != 0) { 14134 if (!isCompact) { 14135 pw.print(" ZRAM: "); pw.print(memInfo.getZramTotalSizeKb()); 14136 pw.print(" kB physical used for "); 14137 pw.print(memInfo.getSwapTotalSizeKb() 14138 - memInfo.getSwapFreeSizeKb()); 14139 pw.print(" kB in swap ("); 14140 pw.print(memInfo.getSwapTotalSizeKb()); 14141 pw.println(" kB total swap)"); 14142 } else { 14143 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 14144 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 14145 pw.println(memInfo.getSwapFreeSizeKb()); 14146 } 14147 } 14148 final int[] SINGLE_LONG_FORMAT = new int[] { 14149 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG 14150 }; 14151 long[] longOut = new long[1]; 14152 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared", 14153 SINGLE_LONG_FORMAT, null, longOut, null); 14154 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14155 longOut[0] = 0; 14156 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing", 14157 SINGLE_LONG_FORMAT, null, longOut, null); 14158 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14159 longOut[0] = 0; 14160 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared", 14161 SINGLE_LONG_FORMAT, null, longOut, null); 14162 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14163 longOut[0] = 0; 14164 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile", 14165 SINGLE_LONG_FORMAT, null, longOut, null); 14166 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024; 14167 if (!isCompact) { 14168 if (sharing != 0 || shared != 0 || unshared != 0 || voltile != 0) { 14169 pw.print(" KSM: "); pw.print(sharing); 14170 pw.print(" kB saved from shared "); 14171 pw.print(shared); pw.println(" kB"); 14172 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; "); 14173 pw.print(voltile); pw.println(" kB volatile"); 14174 } 14175 pw.print(" Tuning: "); 14176 pw.print(ActivityManager.staticGetMemoryClass()); 14177 pw.print(" (large "); 14178 pw.print(ActivityManager.staticGetLargeMemoryClass()); 14179 pw.print("), oom "); 14180 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 14181 pw.print(" kB"); 14182 pw.print(", restore limit "); 14183 pw.print(mProcessList.getCachedRestoreThresholdKb()); 14184 pw.print(" kB"); 14185 if (ActivityManager.isLowRamDeviceStatic()) { 14186 pw.print(" (low-ram)"); 14187 } 14188 if (ActivityManager.isHighEndGfx()) { 14189 pw.print(" (high-end-gfx)"); 14190 } 14191 pw.println(); 14192 } else { 14193 pw.print("ksm,"); pw.print(sharing); pw.print(","); 14194 pw.print(shared); pw.print(","); pw.print(unshared); pw.print(","); 14195 pw.println(voltile); 14196 pw.print("tuning,"); 14197 pw.print(ActivityManager.staticGetMemoryClass()); 14198 pw.print(','); 14199 pw.print(ActivityManager.staticGetLargeMemoryClass()); 14200 pw.print(','); 14201 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 14202 if (ActivityManager.isLowRamDeviceStatic()) { 14203 pw.print(",low-ram"); 14204 } 14205 if (ActivityManager.isHighEndGfx()) { 14206 pw.print(",high-end-gfx"); 14207 } 14208 pw.println(); 14209 } 14210 } 14211 } 14212 } 14213 14214 /** 14215 * Searches array of arguments for the specified string 14216 * @param args array of argument strings 14217 * @param value value to search for 14218 * @return true if the value is contained in the array 14219 */ 14220 private static boolean scanArgs(String[] args, String value) { 14221 if (args != null) { 14222 for (String arg : args) { 14223 if (value.equals(arg)) { 14224 return true; 14225 } 14226 } 14227 } 14228 return false; 14229 } 14230 14231 private final boolean removeDyingProviderLocked(ProcessRecord proc, 14232 ContentProviderRecord cpr, boolean always) { 14233 final boolean inLaunching = mLaunchingProviders.contains(cpr); 14234 14235 if (!inLaunching || always) { 14236 synchronized (cpr) { 14237 cpr.launchingApp = null; 14238 cpr.notifyAll(); 14239 } 14240 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid)); 14241 String names[] = cpr.info.authority.split(";"); 14242 for (int j = 0; j < names.length; j++) { 14243 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid)); 14244 } 14245 } 14246 14247 for (int i=0; i<cpr.connections.size(); i++) { 14248 ContentProviderConnection conn = cpr.connections.get(i); 14249 if (conn.waiting) { 14250 // If this connection is waiting for the provider, then we don't 14251 // need to mess with its process unless we are always removing 14252 // or for some reason the provider is not currently launching. 14253 if (inLaunching && !always) { 14254 continue; 14255 } 14256 } 14257 ProcessRecord capp = conn.client; 14258 conn.dead = true; 14259 if (conn.stableCount > 0) { 14260 if (!capp.persistent && capp.thread != null 14261 && capp.pid != 0 14262 && capp.pid != MY_PID) { 14263 capp.kill("depends on provider " 14264 + cpr.name.flattenToShortString() 14265 + " in dying proc " + (proc != null ? proc.processName : "??"), true); 14266 } 14267 } else if (capp.thread != null && conn.provider.provider != null) { 14268 try { 14269 capp.thread.unstableProviderDied(conn.provider.provider.asBinder()); 14270 } catch (RemoteException e) { 14271 } 14272 // In the protocol here, we don't expect the client to correctly 14273 // clean up this connection, we'll just remove it. 14274 cpr.connections.remove(i); 14275 conn.client.conProviders.remove(conn); 14276 } 14277 } 14278 14279 if (inLaunching && always) { 14280 mLaunchingProviders.remove(cpr); 14281 } 14282 return inLaunching; 14283 } 14284 14285 /** 14286 * Main code for cleaning up a process when it has gone away. This is 14287 * called both as a result of the process dying, or directly when stopping 14288 * a process when running in single process mode. 14289 */ 14290 private final void cleanUpApplicationRecordLocked(ProcessRecord app, 14291 boolean restarting, boolean allowRestart, int index) { 14292 if (index >= 0) { 14293 removeLruProcessLocked(app); 14294 ProcessList.remove(app.pid); 14295 } 14296 14297 mProcessesToGc.remove(app); 14298 mPendingPssProcesses.remove(app); 14299 14300 // Dismiss any open dialogs. 14301 if (app.crashDialog != null && !app.forceCrashReport) { 14302 app.crashDialog.dismiss(); 14303 app.crashDialog = null; 14304 } 14305 if (app.anrDialog != null) { 14306 app.anrDialog.dismiss(); 14307 app.anrDialog = null; 14308 } 14309 if (app.waitDialog != null) { 14310 app.waitDialog.dismiss(); 14311 app.waitDialog = null; 14312 } 14313 14314 app.crashing = false; 14315 app.notResponding = false; 14316 14317 app.resetPackageList(mProcessStats); 14318 app.unlinkDeathRecipient(); 14319 app.makeInactive(mProcessStats); 14320 app.waitingToKill = null; 14321 app.forcingToForeground = null; 14322 updateProcessForegroundLocked(app, false, false); 14323 app.foregroundActivities = false; 14324 app.hasShownUi = false; 14325 app.treatLikeActivity = false; 14326 app.hasAboveClient = false; 14327 app.hasClientActivities = false; 14328 14329 mServices.killServicesLocked(app, allowRestart); 14330 14331 boolean restart = false; 14332 14333 // Remove published content providers. 14334 for (int i=app.pubProviders.size()-1; i>=0; i--) { 14335 ContentProviderRecord cpr = app.pubProviders.valueAt(i); 14336 final boolean always = app.bad || !allowRestart; 14337 if (removeDyingProviderLocked(app, cpr, always) || always) { 14338 // We left the provider in the launching list, need to 14339 // restart it. 14340 restart = true; 14341 } 14342 14343 cpr.provider = null; 14344 cpr.proc = null; 14345 } 14346 app.pubProviders.clear(); 14347 14348 // Take care of any launching providers waiting for this process. 14349 if (checkAppInLaunchingProvidersLocked(app, false)) { 14350 restart = true; 14351 } 14352 14353 // Unregister from connected content providers. 14354 if (!app.conProviders.isEmpty()) { 14355 for (int i=0; i<app.conProviders.size(); i++) { 14356 ContentProviderConnection conn = app.conProviders.get(i); 14357 conn.provider.connections.remove(conn); 14358 } 14359 app.conProviders.clear(); 14360 } 14361 14362 // At this point there may be remaining entries in mLaunchingProviders 14363 // where we were the only one waiting, so they are no longer of use. 14364 // Look for these and clean up if found. 14365 // XXX Commented out for now. Trying to figure out a way to reproduce 14366 // the actual situation to identify what is actually going on. 14367 if (false) { 14368 for (int i=0; i<mLaunchingProviders.size(); i++) { 14369 ContentProviderRecord cpr = (ContentProviderRecord) 14370 mLaunchingProviders.get(i); 14371 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 14372 synchronized (cpr) { 14373 cpr.launchingApp = null; 14374 cpr.notifyAll(); 14375 } 14376 } 14377 } 14378 } 14379 14380 skipCurrentReceiverLocked(app); 14381 14382 // Unregister any receivers. 14383 for (int i=app.receivers.size()-1; i>=0; i--) { 14384 removeReceiverLocked(app.receivers.valueAt(i)); 14385 } 14386 app.receivers.clear(); 14387 14388 // If the app is undergoing backup, tell the backup manager about it 14389 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) { 14390 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App " 14391 + mBackupTarget.appInfo + " died during backup"); 14392 try { 14393 IBackupManager bm = IBackupManager.Stub.asInterface( 14394 ServiceManager.getService(Context.BACKUP_SERVICE)); 14395 bm.agentDisconnected(app.info.packageName); 14396 } catch (RemoteException e) { 14397 // can't happen; backup manager is local 14398 } 14399 } 14400 14401 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) { 14402 ProcessChangeItem item = mPendingProcessChanges.get(i); 14403 if (item.pid == app.pid) { 14404 mPendingProcessChanges.remove(i); 14405 mAvailProcessChanges.add(item); 14406 } 14407 } 14408 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget(); 14409 14410 // If the caller is restarting this app, then leave it in its 14411 // current lists and let the caller take care of it. 14412 if (restarting) { 14413 return; 14414 } 14415 14416 if (!app.persistent || app.isolated) { 14417 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, 14418 "Removing non-persistent process during cleanup: " + app); 14419 mProcessNames.remove(app.processName, app.uid); 14420 mIsolatedProcesses.remove(app.uid); 14421 if (mHeavyWeightProcess == app) { 14422 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 14423 mHeavyWeightProcess.userId, 0)); 14424 mHeavyWeightProcess = null; 14425 } 14426 } else if (!app.removed) { 14427 // This app is persistent, so we need to keep its record around. 14428 // If it is not already on the pending app list, add it there 14429 // and start a new process for it. 14430 if (mPersistentStartingProcesses.indexOf(app) < 0) { 14431 mPersistentStartingProcesses.add(app); 14432 restart = true; 14433 } 14434 } 14435 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG, 14436 "Clean-up removing on hold: " + app); 14437 mProcessesOnHold.remove(app); 14438 14439 if (app == mHomeProcess) { 14440 mHomeProcess = null; 14441 } 14442 if (app == mPreviousProcess) { 14443 mPreviousProcess = null; 14444 } 14445 14446 if (restart && !app.isolated) { 14447 // We have components that still need to be running in the 14448 // process, so re-launch it. 14449 mProcessNames.put(app.processName, app.uid, app); 14450 startProcessLocked(app, "restart", app.processName); 14451 } else if (app.pid > 0 && app.pid != MY_PID) { 14452 // Goodbye! 14453 boolean removed; 14454 synchronized (mPidsSelfLocked) { 14455 mPidsSelfLocked.remove(app.pid); 14456 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 14457 } 14458 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 14459 if (app.isolated) { 14460 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 14461 } 14462 app.setPid(0); 14463 } 14464 } 14465 14466 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 14467 // Look through the content providers we are waiting to have launched, 14468 // and if any run in this process then either schedule a restart of 14469 // the process or kill the client waiting for it if this process has 14470 // gone bad. 14471 int NL = mLaunchingProviders.size(); 14472 boolean restart = false; 14473 for (int i=0; i<NL; i++) { 14474 ContentProviderRecord cpr = mLaunchingProviders.get(i); 14475 if (cpr.launchingApp == app) { 14476 if (!alwaysBad && !app.bad) { 14477 restart = true; 14478 } else { 14479 removeDyingProviderLocked(app, cpr, true); 14480 // cpr should have been removed from mLaunchingProviders 14481 NL = mLaunchingProviders.size(); 14482 i--; 14483 } 14484 } 14485 } 14486 return restart; 14487 } 14488 14489 // ========================================================= 14490 // SERVICES 14491 // ========================================================= 14492 14493 @Override 14494 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, 14495 int flags) { 14496 enforceNotIsolatedCaller("getServices"); 14497 synchronized (this) { 14498 return mServices.getRunningServiceInfoLocked(maxNum, flags); 14499 } 14500 } 14501 14502 @Override 14503 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 14504 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 14505 synchronized (this) { 14506 return mServices.getRunningServiceControlPanelLocked(name); 14507 } 14508 } 14509 14510 @Override 14511 public ComponentName startService(IApplicationThread caller, Intent service, 14512 String resolvedType, int userId) { 14513 enforceNotIsolatedCaller("startService"); 14514 // Refuse possible leaked file descriptors 14515 if (service != null && service.hasFileDescriptors() == true) { 14516 throw new IllegalArgumentException("File descriptors passed in Intent"); 14517 } 14518 14519 if (DEBUG_SERVICE) 14520 Slog.v(TAG, "startService: " + service + " type=" + resolvedType); 14521 synchronized(this) { 14522 final int callingPid = Binder.getCallingPid(); 14523 final int callingUid = Binder.getCallingUid(); 14524 final long origId = Binder.clearCallingIdentity(); 14525 ComponentName res = mServices.startServiceLocked(caller, service, 14526 resolvedType, callingPid, callingUid, userId); 14527 Binder.restoreCallingIdentity(origId); 14528 return res; 14529 } 14530 } 14531 14532 ComponentName startServiceInPackage(int uid, 14533 Intent service, String resolvedType, int userId) { 14534 synchronized(this) { 14535 if (DEBUG_SERVICE) 14536 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType); 14537 final long origId = Binder.clearCallingIdentity(); 14538 ComponentName res = mServices.startServiceLocked(null, service, 14539 resolvedType, -1, uid, userId); 14540 Binder.restoreCallingIdentity(origId); 14541 return res; 14542 } 14543 } 14544 14545 @Override 14546 public int stopService(IApplicationThread caller, Intent service, 14547 String resolvedType, int userId) { 14548 enforceNotIsolatedCaller("stopService"); 14549 // Refuse possible leaked file descriptors 14550 if (service != null && service.hasFileDescriptors() == true) { 14551 throw new IllegalArgumentException("File descriptors passed in Intent"); 14552 } 14553 14554 synchronized(this) { 14555 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 14556 } 14557 } 14558 14559 @Override 14560 public IBinder peekService(Intent service, String resolvedType) { 14561 enforceNotIsolatedCaller("peekService"); 14562 // Refuse possible leaked file descriptors 14563 if (service != null && service.hasFileDescriptors() == true) { 14564 throw new IllegalArgumentException("File descriptors passed in Intent"); 14565 } 14566 synchronized(this) { 14567 return mServices.peekServiceLocked(service, resolvedType); 14568 } 14569 } 14570 14571 @Override 14572 public boolean stopServiceToken(ComponentName className, IBinder token, 14573 int startId) { 14574 synchronized(this) { 14575 return mServices.stopServiceTokenLocked(className, token, startId); 14576 } 14577 } 14578 14579 @Override 14580 public void setServiceForeground(ComponentName className, IBinder token, 14581 int id, Notification notification, boolean removeNotification) { 14582 synchronized(this) { 14583 mServices.setServiceForegroundLocked(className, token, id, notification, 14584 removeNotification); 14585 } 14586 } 14587 14588 @Override 14589 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 14590 boolean requireFull, String name, String callerPackage) { 14591 return handleIncomingUser(callingPid, callingUid, userId, allowAll, 14592 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 14593 } 14594 14595 int unsafeConvertIncomingUser(int userId) { 14596 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) 14597 ? mCurrentUserId : userId; 14598 } 14599 14600 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 14601 int allowMode, String name, String callerPackage) { 14602 final int callingUserId = UserHandle.getUserId(callingUid); 14603 if (callingUserId == userId) { 14604 return userId; 14605 } 14606 14607 // Note that we may be accessing mCurrentUserId outside of a lock... 14608 // shouldn't be a big deal, if this is being called outside 14609 // of a locked context there is intrinsically a race with 14610 // the value the caller will receive and someone else changing it. 14611 // We assume that USER_CURRENT_OR_SELF will use the current user; later 14612 // we will switch to the calling user if access to the current user fails. 14613 int targetUserId = unsafeConvertIncomingUser(userId); 14614 14615 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14616 final boolean allow; 14617 if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 14618 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 14619 // If the caller has this permission, they always pass go. And collect $200. 14620 allow = true; 14621 } else if (allowMode == ALLOW_FULL_ONLY) { 14622 // We require full access, sucks to be you. 14623 allow = false; 14624 } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 14625 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { 14626 // If the caller does not have either permission, they are always doomed. 14627 allow = false; 14628 } else if (allowMode == ALLOW_NON_FULL) { 14629 // We are blanket allowing non-full access, you lucky caller! 14630 allow = true; 14631 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) { 14632 // We may or may not allow this depending on whether the two users are 14633 // in the same profile. 14634 synchronized (mUserProfileGroupIdsSelfLocked) { 14635 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId, 14636 UserInfo.NO_PROFILE_GROUP_ID); 14637 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId, 14638 UserInfo.NO_PROFILE_GROUP_ID); 14639 allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID 14640 && callingProfile == targetProfile; 14641 } 14642 } else { 14643 throw new IllegalArgumentException("Unknown mode: " + allowMode); 14644 } 14645 if (!allow) { 14646 if (userId == UserHandle.USER_CURRENT_OR_SELF) { 14647 // In this case, they would like to just execute as their 14648 // owner user instead of failing. 14649 targetUserId = callingUserId; 14650 } else { 14651 StringBuilder builder = new StringBuilder(128); 14652 builder.append("Permission Denial: "); 14653 builder.append(name); 14654 if (callerPackage != null) { 14655 builder.append(" from "); 14656 builder.append(callerPackage); 14657 } 14658 builder.append(" asks to run as user "); 14659 builder.append(userId); 14660 builder.append(" but is calling from user "); 14661 builder.append(UserHandle.getUserId(callingUid)); 14662 builder.append("; this requires "); 14663 builder.append(INTERACT_ACROSS_USERS_FULL); 14664 if (allowMode != ALLOW_FULL_ONLY) { 14665 builder.append(" or "); 14666 builder.append(INTERACT_ACROSS_USERS); 14667 } 14668 String msg = builder.toString(); 14669 Slog.w(TAG, msg); 14670 throw new SecurityException(msg); 14671 } 14672 } 14673 } 14674 if (!allowAll && targetUserId < 0) { 14675 throw new IllegalArgumentException( 14676 "Call does not support special user #" + targetUserId); 14677 } 14678 // Check shell permission 14679 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_OWNER) { 14680 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, 14681 targetUserId)) { 14682 throw new SecurityException("Shell does not have permission to access user " 14683 + targetUserId + "\n " + Debug.getCallers(3)); 14684 } 14685 } 14686 return targetUserId; 14687 } 14688 14689 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 14690 String className, int flags) { 14691 boolean result = false; 14692 // For apps that don't have pre-defined UIDs, check for permission 14693 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) { 14694 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14695 if (ActivityManager.checkUidPermission( 14696 INTERACT_ACROSS_USERS, 14697 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 14698 ComponentName comp = new ComponentName(aInfo.packageName, className); 14699 String msg = "Permission Denial: Component " + comp.flattenToShortString() 14700 + " requests FLAG_SINGLE_USER, but app does not hold " 14701 + INTERACT_ACROSS_USERS; 14702 Slog.w(TAG, msg); 14703 throw new SecurityException(msg); 14704 } 14705 // Permission passed 14706 result = true; 14707 } 14708 } else if ("system".equals(componentProcessName)) { 14709 result = true; 14710 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 14711 // Phone app and persistent apps are allowed to export singleuser providers. 14712 result = UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID) 14713 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 14714 } 14715 if (DEBUG_MU) { 14716 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo 14717 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result); 14718 } 14719 return result; 14720 } 14721 14722 /** 14723 * Checks to see if the caller is in the same app as the singleton 14724 * component, or the component is in a special app. It allows special apps 14725 * to export singleton components but prevents exporting singleton 14726 * components for regular apps. 14727 */ 14728 boolean isValidSingletonCall(int callingUid, int componentUid) { 14729 int componentAppId = UserHandle.getAppId(componentUid); 14730 return UserHandle.isSameApp(callingUid, componentUid) 14731 || componentAppId == Process.SYSTEM_UID 14732 || componentAppId == Process.PHONE_UID 14733 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 14734 == PackageManager.PERMISSION_GRANTED; 14735 } 14736 14737 public int bindService(IApplicationThread caller, IBinder token, 14738 Intent service, String resolvedType, 14739 IServiceConnection connection, int flags, int userId) { 14740 enforceNotIsolatedCaller("bindService"); 14741 14742 // Refuse possible leaked file descriptors 14743 if (service != null && service.hasFileDescriptors() == true) { 14744 throw new IllegalArgumentException("File descriptors passed in Intent"); 14745 } 14746 14747 synchronized(this) { 14748 return mServices.bindServiceLocked(caller, token, service, resolvedType, 14749 connection, flags, userId); 14750 } 14751 } 14752 14753 public boolean unbindService(IServiceConnection connection) { 14754 synchronized (this) { 14755 return mServices.unbindServiceLocked(connection); 14756 } 14757 } 14758 14759 public void publishService(IBinder token, Intent intent, IBinder service) { 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 if (!(token instanceof ServiceRecord)) { 14767 throw new IllegalArgumentException("Invalid service token"); 14768 } 14769 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 14770 } 14771 } 14772 14773 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 14774 // Refuse possible leaked file descriptors 14775 if (intent != null && intent.hasFileDescriptors() == true) { 14776 throw new IllegalArgumentException("File descriptors passed in Intent"); 14777 } 14778 14779 synchronized(this) { 14780 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 14781 } 14782 } 14783 14784 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 14785 synchronized(this) { 14786 if (!(token instanceof ServiceRecord)) { 14787 throw new IllegalArgumentException("Invalid service token"); 14788 } 14789 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); 14790 } 14791 } 14792 14793 // ========================================================= 14794 // BACKUP AND RESTORE 14795 // ========================================================= 14796 14797 // Cause the target app to be launched if necessary and its backup agent 14798 // instantiated. The backup agent will invoke backupAgentCreated() on the 14799 // activity manager to announce its creation. 14800 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) { 14801 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode); 14802 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 14803 14804 synchronized(this) { 14805 // !!! TODO: currently no check here that we're already bound 14806 BatteryStatsImpl.Uid.Pkg.Serv ss = null; 14807 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 14808 synchronized (stats) { 14809 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name); 14810 } 14811 14812 // Backup agent is now in use, its package can't be stopped. 14813 try { 14814 AppGlobals.getPackageManager().setPackageStoppedState( 14815 app.packageName, false, UserHandle.getUserId(app.uid)); 14816 } catch (RemoteException e) { 14817 } catch (IllegalArgumentException e) { 14818 Slog.w(TAG, "Failed trying to unstop package " 14819 + app.packageName + ": " + e); 14820 } 14821 14822 BackupRecord r = new BackupRecord(ss, app, backupMode); 14823 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) 14824 ? new ComponentName(app.packageName, app.backupAgentName) 14825 : new ComponentName("android", "FullBackupAgent"); 14826 // startProcessLocked() returns existing proc's record if it's already running 14827 ProcessRecord proc = startProcessLocked(app.processName, app, 14828 false, 0, "backup", hostingName, false, false, false); 14829 if (proc == null) { 14830 Slog.e(TAG, "Unable to start backup agent process " + r); 14831 return false; 14832 } 14833 14834 r.app = proc; 14835 mBackupTarget = r; 14836 mBackupAppName = app.packageName; 14837 14838 // Try not to kill the process during backup 14839 updateOomAdjLocked(proc); 14840 14841 // If the process is already attached, schedule the creation of the backup agent now. 14842 // If it is not yet live, this will be done when it attaches to the framework. 14843 if (proc.thread != null) { 14844 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc); 14845 try { 14846 proc.thread.scheduleCreateBackupAgent(app, 14847 compatibilityInfoForPackageLocked(app), backupMode); 14848 } catch (RemoteException e) { 14849 // Will time out on the backup manager side 14850 } 14851 } else { 14852 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach"); 14853 } 14854 // Invariants: at this point, the target app process exists and the application 14855 // is either already running or in the process of coming up. mBackupTarget and 14856 // mBackupAppName describe the app, so that when it binds back to the AM we 14857 // know that it's scheduled for a backup-agent operation. 14858 } 14859 14860 return true; 14861 } 14862 14863 @Override 14864 public void clearPendingBackup() { 14865 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup"); 14866 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup"); 14867 14868 synchronized (this) { 14869 mBackupTarget = null; 14870 mBackupAppName = null; 14871 } 14872 } 14873 14874 // A backup agent has just come up 14875 public void backupAgentCreated(String agentPackageName, IBinder agent) { 14876 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName 14877 + " = " + agent); 14878 14879 synchronized(this) { 14880 if (!agentPackageName.equals(mBackupAppName)) { 14881 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14882 return; 14883 } 14884 } 14885 14886 long oldIdent = Binder.clearCallingIdentity(); 14887 try { 14888 IBackupManager bm = IBackupManager.Stub.asInterface( 14889 ServiceManager.getService(Context.BACKUP_SERVICE)); 14890 bm.agentConnected(agentPackageName, agent); 14891 } catch (RemoteException e) { 14892 // can't happen; the backup manager service is local 14893 } catch (Exception e) { 14894 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14895 e.printStackTrace(); 14896 } finally { 14897 Binder.restoreCallingIdentity(oldIdent); 14898 } 14899 } 14900 14901 // done with this agent 14902 public void unbindBackupAgent(ApplicationInfo appInfo) { 14903 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo); 14904 if (appInfo == null) { 14905 Slog.w(TAG, "unbind backup agent for null app"); 14906 return; 14907 } 14908 14909 synchronized(this) { 14910 try { 14911 if (mBackupAppName == null) { 14912 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14913 return; 14914 } 14915 14916 if (!mBackupAppName.equals(appInfo.packageName)) { 14917 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14918 return; 14919 } 14920 14921 // Not backing this app up any more; reset its OOM adjustment 14922 final ProcessRecord proc = mBackupTarget.app; 14923 updateOomAdjLocked(proc); 14924 14925 // If the app crashed during backup, 'thread' will be null here 14926 if (proc.thread != null) { 14927 try { 14928 proc.thread.scheduleDestroyBackupAgent(appInfo, 14929 compatibilityInfoForPackageLocked(appInfo)); 14930 } catch (Exception e) { 14931 Slog.e(TAG, "Exception when unbinding backup agent:"); 14932 e.printStackTrace(); 14933 } 14934 } 14935 } finally { 14936 mBackupTarget = null; 14937 mBackupAppName = null; 14938 } 14939 } 14940 } 14941 // ========================================================= 14942 // BROADCASTS 14943 // ========================================================= 14944 14945 private final List getStickiesLocked(String action, IntentFilter filter, 14946 List cur, int userId) { 14947 final ContentResolver resolver = mContext.getContentResolver(); 14948 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14949 if (stickies == null) { 14950 return cur; 14951 } 14952 final ArrayList<Intent> list = stickies.get(action); 14953 if (list == null) { 14954 return cur; 14955 } 14956 int N = list.size(); 14957 for (int i=0; i<N; i++) { 14958 Intent intent = list.get(i); 14959 if (filter.match(resolver, intent, true, TAG) >= 0) { 14960 if (cur == null) { 14961 cur = new ArrayList<Intent>(); 14962 } 14963 cur.add(intent); 14964 } 14965 } 14966 return cur; 14967 } 14968 14969 boolean isPendingBroadcastProcessLocked(int pid) { 14970 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 14971 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid); 14972 } 14973 14974 void skipPendingBroadcastLocked(int pid) { 14975 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 14976 for (BroadcastQueue queue : mBroadcastQueues) { 14977 queue.skipPendingBroadcastLocked(pid); 14978 } 14979 } 14980 14981 // The app just attached; send any pending broadcasts that it should receive 14982 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 14983 boolean didSomething = false; 14984 for (BroadcastQueue queue : mBroadcastQueues) { 14985 didSomething |= queue.sendPendingBroadcastsLocked(app); 14986 } 14987 return didSomething; 14988 } 14989 14990 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14991 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) { 14992 enforceNotIsolatedCaller("registerReceiver"); 14993 int callingUid; 14994 int callingPid; 14995 synchronized(this) { 14996 ProcessRecord callerApp = null; 14997 if (caller != null) { 14998 callerApp = getRecordForAppLocked(caller); 14999 if (callerApp == null) { 15000 throw new SecurityException( 15001 "Unable to find app for caller " + caller 15002 + " (pid=" + Binder.getCallingPid() 15003 + ") when registering receiver " + receiver); 15004 } 15005 if (callerApp.info.uid != Process.SYSTEM_UID && 15006 !callerApp.pkgList.containsKey(callerPackage) && 15007 !"android".equals(callerPackage)) { 15008 throw new SecurityException("Given caller package " + callerPackage 15009 + " is not running in process " + callerApp); 15010 } 15011 callingUid = callerApp.info.uid; 15012 callingPid = callerApp.pid; 15013 } else { 15014 callerPackage = null; 15015 callingUid = Binder.getCallingUid(); 15016 callingPid = Binder.getCallingPid(); 15017 } 15018 15019 userId = this.handleIncomingUser(callingPid, callingUid, userId, 15020 true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 15021 15022 List allSticky = null; 15023 15024 // Look for any matching sticky broadcasts... 15025 Iterator actions = filter.actionsIterator(); 15026 if (actions != null) { 15027 while (actions.hasNext()) { 15028 String action = (String)actions.next(); 15029 allSticky = getStickiesLocked(action, filter, allSticky, 15030 UserHandle.USER_ALL); 15031 allSticky = getStickiesLocked(action, filter, allSticky, 15032 UserHandle.getUserId(callingUid)); 15033 } 15034 } else { 15035 allSticky = getStickiesLocked(null, filter, allSticky, 15036 UserHandle.USER_ALL); 15037 allSticky = getStickiesLocked(null, filter, allSticky, 15038 UserHandle.getUserId(callingUid)); 15039 } 15040 15041 // The first sticky in the list is returned directly back to 15042 // the client. 15043 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null; 15044 15045 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter 15046 + ": " + sticky); 15047 15048 if (receiver == null) { 15049 return sticky; 15050 } 15051 15052 ReceiverList rl 15053 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder()); 15054 if (rl == null) { 15055 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 15056 userId, receiver); 15057 if (rl.app != null) { 15058 rl.app.receivers.add(rl); 15059 } else { 15060 try { 15061 receiver.asBinder().linkToDeath(rl, 0); 15062 } catch (RemoteException e) { 15063 return sticky; 15064 } 15065 rl.linkedToDeath = true; 15066 } 15067 mRegisteredReceivers.put(receiver.asBinder(), rl); 15068 } else if (rl.uid != callingUid) { 15069 throw new IllegalArgumentException( 15070 "Receiver requested to register for uid " + callingUid 15071 + " was previously registered for uid " + rl.uid); 15072 } else if (rl.pid != callingPid) { 15073 throw new IllegalArgumentException( 15074 "Receiver requested to register for pid " + callingPid 15075 + " was previously registered for pid " + rl.pid); 15076 } else if (rl.userId != userId) { 15077 throw new IllegalArgumentException( 15078 "Receiver requested to register for user " + userId 15079 + " was previously registered for user " + rl.userId); 15080 } 15081 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, 15082 permission, callingUid, userId); 15083 rl.add(bf); 15084 if (!bf.debugCheck()) { 15085 Slog.w(TAG, "==> For Dynamic broadast"); 15086 } 15087 mReceiverResolver.addFilter(bf); 15088 15089 // Enqueue broadcasts for all existing stickies that match 15090 // this filter. 15091 if (allSticky != null) { 15092 ArrayList receivers = new ArrayList(); 15093 receivers.add(bf); 15094 15095 int N = allSticky.size(); 15096 for (int i=0; i<N; i++) { 15097 Intent intent = (Intent)allSticky.get(i); 15098 BroadcastQueue queue = broadcastQueueForIntent(intent); 15099 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 15100 null, -1, -1, null, null, AppOpsManager.OP_NONE, receivers, null, 0, 15101 null, null, false, true, true, -1); 15102 queue.enqueueParallelBroadcastLocked(r); 15103 queue.scheduleBroadcastsLocked(); 15104 } 15105 } 15106 15107 return sticky; 15108 } 15109 } 15110 15111 public void unregisterReceiver(IIntentReceiver receiver) { 15112 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver); 15113 15114 final long origId = Binder.clearCallingIdentity(); 15115 try { 15116 boolean doTrim = false; 15117 15118 synchronized(this) { 15119 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 15120 if (rl != null) { 15121 if (rl.curBroadcast != null) { 15122 BroadcastRecord r = rl.curBroadcast; 15123 final boolean doNext = finishReceiverLocked( 15124 receiver.asBinder(), r.resultCode, r.resultData, 15125 r.resultExtras, r.resultAbort); 15126 if (doNext) { 15127 doTrim = true; 15128 r.queue.processNextBroadcast(false); 15129 } 15130 } 15131 15132 if (rl.app != null) { 15133 rl.app.receivers.remove(rl); 15134 } 15135 removeReceiverLocked(rl); 15136 if (rl.linkedToDeath) { 15137 rl.linkedToDeath = false; 15138 rl.receiver.asBinder().unlinkToDeath(rl, 0); 15139 } 15140 } 15141 } 15142 15143 // If we actually concluded any broadcasts, we might now be able 15144 // to trim the recipients' apps from our working set 15145 if (doTrim) { 15146 trimApplications(); 15147 return; 15148 } 15149 15150 } finally { 15151 Binder.restoreCallingIdentity(origId); 15152 } 15153 } 15154 15155 void removeReceiverLocked(ReceiverList rl) { 15156 mRegisteredReceivers.remove(rl.receiver.asBinder()); 15157 int N = rl.size(); 15158 for (int i=0; i<N; i++) { 15159 mReceiverResolver.removeFilter(rl.get(i)); 15160 } 15161 } 15162 15163 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 15164 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 15165 ProcessRecord r = mLruProcesses.get(i); 15166 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) { 15167 try { 15168 r.thread.dispatchPackageBroadcast(cmd, packages); 15169 } catch (RemoteException ex) { 15170 } 15171 } 15172 } 15173 } 15174 15175 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 15176 int callingUid, int[] users) { 15177 List<ResolveInfo> receivers = null; 15178 try { 15179 HashSet<ComponentName> singleUserReceivers = null; 15180 boolean scannedFirstReceivers = false; 15181 for (int user : users) { 15182 // Skip users that have Shell restrictions 15183 if (callingUid == Process.SHELL_UID 15184 && getUserManagerLocked().hasUserRestriction( 15185 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 15186 continue; 15187 } 15188 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 15189 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user); 15190 if (user != 0 && newReceivers != null) { 15191 // If this is not the primary user, we need to check for 15192 // any receivers that should be filtered out. 15193 for (int i=0; i<newReceivers.size(); i++) { 15194 ResolveInfo ri = newReceivers.get(i); 15195 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 15196 newReceivers.remove(i); 15197 i--; 15198 } 15199 } 15200 } 15201 if (newReceivers != null && newReceivers.size() == 0) { 15202 newReceivers = null; 15203 } 15204 if (receivers == null) { 15205 receivers = newReceivers; 15206 } else if (newReceivers != null) { 15207 // We need to concatenate the additional receivers 15208 // found with what we have do far. This would be easy, 15209 // but we also need to de-dup any receivers that are 15210 // singleUser. 15211 if (!scannedFirstReceivers) { 15212 // Collect any single user receivers we had already retrieved. 15213 scannedFirstReceivers = true; 15214 for (int i=0; i<receivers.size(); i++) { 15215 ResolveInfo ri = receivers.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 singleUserReceivers.add(cn); 15223 } 15224 } 15225 } 15226 // Add the new results to the existing results, tracking 15227 // and de-dupping single user receivers. 15228 for (int i=0; i<newReceivers.size(); i++) { 15229 ResolveInfo ri = newReceivers.get(i); 15230 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 15231 ComponentName cn = new ComponentName( 15232 ri.activityInfo.packageName, ri.activityInfo.name); 15233 if (singleUserReceivers == null) { 15234 singleUserReceivers = new HashSet<ComponentName>(); 15235 } 15236 if (!singleUserReceivers.contains(cn)) { 15237 singleUserReceivers.add(cn); 15238 receivers.add(ri); 15239 } 15240 } else { 15241 receivers.add(ri); 15242 } 15243 } 15244 } 15245 } 15246 } catch (RemoteException ex) { 15247 // pm is in same process, this will never happen. 15248 } 15249 return receivers; 15250 } 15251 15252 private final int broadcastIntentLocked(ProcessRecord callerApp, 15253 String callerPackage, Intent intent, String resolvedType, 15254 IIntentReceiver resultTo, int resultCode, String resultData, 15255 Bundle map, String requiredPermission, int appOp, 15256 boolean ordered, boolean sticky, int callingPid, int callingUid, 15257 int userId) { 15258 intent = new Intent(intent); 15259 15260 // By default broadcasts do not go to stopped apps. 15261 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 15262 15263 if (DEBUG_BROADCAST_LIGHT) Slog.v( 15264 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 15265 + " ordered=" + ordered + " userid=" + userId); 15266 if ((resultTo != null) && !ordered) { 15267 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 15268 } 15269 15270 userId = handleIncomingUser(callingPid, callingUid, userId, 15271 true, ALLOW_NON_FULL, "broadcast", callerPackage); 15272 15273 // Make sure that the user who is receiving this broadcast is started. 15274 // If not, we will just skip it. 15275 15276 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) { 15277 if (callingUid != Process.SYSTEM_UID || (intent.getFlags() 15278 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 15279 Slog.w(TAG, "Skipping broadcast of " + intent 15280 + ": user " + userId + " is stopped"); 15281 return ActivityManager.BROADCAST_SUCCESS; 15282 } 15283 } 15284 15285 /* 15286 * Prevent non-system code (defined here to be non-persistent 15287 * processes) from sending protected broadcasts. 15288 */ 15289 int callingAppId = UserHandle.getAppId(callingUid); 15290 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID 15291 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID 15292 || callingAppId == Process.NFC_UID || callingUid == 0) { 15293 // Always okay. 15294 } else if (callerApp == null || !callerApp.persistent) { 15295 try { 15296 if (AppGlobals.getPackageManager().isProtectedBroadcast( 15297 intent.getAction())) { 15298 String msg = "Permission Denial: not allowed to send broadcast " 15299 + intent.getAction() + " from pid=" 15300 + callingPid + ", uid=" + callingUid; 15301 Slog.w(TAG, msg); 15302 throw new SecurityException(msg); 15303 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) { 15304 // Special case for compatibility: we don't want apps to send this, 15305 // but historically it has not been protected and apps may be using it 15306 // to poke their own app widget. So, instead of making it protected, 15307 // just limit it to the caller. 15308 if (callerApp == null) { 15309 String msg = "Permission Denial: not allowed to send broadcast " 15310 + intent.getAction() + " from unknown caller."; 15311 Slog.w(TAG, msg); 15312 throw new SecurityException(msg); 15313 } else if (intent.getComponent() != null) { 15314 // They are good enough to send to an explicit component... verify 15315 // it is being sent to the calling app. 15316 if (!intent.getComponent().getPackageName().equals( 15317 callerApp.info.packageName)) { 15318 String msg = "Permission Denial: not allowed to send broadcast " 15319 + intent.getAction() + " to " 15320 + intent.getComponent().getPackageName() + " from " 15321 + callerApp.info.packageName; 15322 Slog.w(TAG, msg); 15323 throw new SecurityException(msg); 15324 } 15325 } else { 15326 // Limit broadcast to their own package. 15327 intent.setPackage(callerApp.info.packageName); 15328 } 15329 } 15330 } catch (RemoteException e) { 15331 Slog.w(TAG, "Remote exception", e); 15332 return ActivityManager.BROADCAST_SUCCESS; 15333 } 15334 } 15335 15336 // Handle special intents: if this broadcast is from the package 15337 // manager about a package being removed, we need to remove all of 15338 // its activities from the history stack. 15339 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals( 15340 intent.getAction()); 15341 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) 15342 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction()) 15343 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction()) 15344 || Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction()) 15345 || uidRemoved) { 15346 if (checkComponentPermission( 15347 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 15348 callingPid, callingUid, -1, true) 15349 == PackageManager.PERMISSION_GRANTED) { 15350 if (uidRemoved) { 15351 final Bundle intentExtras = intent.getExtras(); 15352 final int uid = intentExtras != null 15353 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 15354 if (uid >= 0) { 15355 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics(); 15356 synchronized (bs) { 15357 bs.removeUidStatsLocked(uid); 15358 } 15359 mAppOpsService.uidRemoved(uid); 15360 } 15361 } else { 15362 // If resources are unavailable just force stop all 15363 // those packages and flush the attribute cache as well. 15364 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) { 15365 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15366 if (list != null && (list.length > 0)) { 15367 for (String pkg : list) { 15368 forceStopPackageLocked(pkg, -1, false, true, true, false, false, userId, 15369 "storage unmount"); 15370 } 15371 cleanupRecentTasksLocked(UserHandle.USER_ALL); 15372 sendPackageBroadcastLocked( 15373 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId); 15374 } 15375 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals( 15376 intent.getAction())) { 15377 cleanupRecentTasksLocked(UserHandle.USER_ALL); 15378 } else { 15379 Uri data = intent.getData(); 15380 String ssp; 15381 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15382 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals( 15383 intent.getAction()); 15384 boolean fullUninstall = removed && 15385 !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 15386 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) { 15387 forceStopPackageLocked(ssp, UserHandle.getAppId( 15388 intent.getIntExtra(Intent.EXTRA_UID, -1)), false, true, true, 15389 false, fullUninstall, userId, 15390 removed ? "pkg removed" : "pkg changed"); 15391 } 15392 if (removed) { 15393 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED, 15394 new String[] {ssp}, userId); 15395 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 15396 mAppOpsService.packageRemoved( 15397 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 15398 15399 // Remove all permissions granted from/to this package 15400 removeUriPermissionsForPackageLocked(ssp, userId, true); 15401 } 15402 } 15403 } 15404 } 15405 } 15406 } else { 15407 String msg = "Permission Denial: " + intent.getAction() 15408 + " broadcast from " + callerPackage + " (pid=" + callingPid 15409 + ", uid=" + callingUid + ")" 15410 + " requires " 15411 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 15412 Slog.w(TAG, msg); 15413 throw new SecurityException(msg); 15414 } 15415 15416 // Special case for adding a package: by default turn on compatibility 15417 // mode. 15418 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) { 15419 Uri data = intent.getData(); 15420 String ssp; 15421 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 15422 mCompatModePackages.handlePackageAddedLocked(ssp, 15423 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)); 15424 } 15425 } 15426 15427 /* 15428 * If this is the time zone changed action, queue up a message that will reset the timezone 15429 * of all currently running processes. This message will get queued up before the broadcast 15430 * happens. 15431 */ 15432 if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) { 15433 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 15434 } 15435 15436 /* 15437 * If the user set the time, let all running processes know. 15438 */ 15439 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) { 15440 final int is24Hour = intent.getBooleanExtra( 15441 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 : 0; 15442 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0)); 15443 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 15444 synchronized (stats) { 15445 stats.noteCurrentTimeChangedLocked(); 15446 } 15447 } 15448 15449 if (Intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) { 15450 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 15451 } 15452 15453 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) { 15454 ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO); 15455 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy)); 15456 } 15457 15458 // Add to the sticky list if requested. 15459 if (sticky) { 15460 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 15461 callingPid, callingUid) 15462 != PackageManager.PERMISSION_GRANTED) { 15463 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 15464 + callingPid + ", uid=" + callingUid 15465 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15466 Slog.w(TAG, msg); 15467 throw new SecurityException(msg); 15468 } 15469 if (requiredPermission != null) { 15470 Slog.w(TAG, "Can't broadcast sticky intent " + intent 15471 + " and enforce permission " + requiredPermission); 15472 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 15473 } 15474 if (intent.getComponent() != null) { 15475 throw new SecurityException( 15476 "Sticky broadcasts can't target a specific component"); 15477 } 15478 // We use userId directly here, since the "all" target is maintained 15479 // as a separate set of sticky broadcasts. 15480 if (userId != UserHandle.USER_ALL) { 15481 // But first, if this is not a broadcast to all users, then 15482 // make sure it doesn't conflict with an existing broadcast to 15483 // all users. 15484 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 15485 UserHandle.USER_ALL); 15486 if (stickies != null) { 15487 ArrayList<Intent> list = stickies.get(intent.getAction()); 15488 if (list != null) { 15489 int N = list.size(); 15490 int i; 15491 for (i=0; i<N; i++) { 15492 if (intent.filterEquals(list.get(i))) { 15493 throw new IllegalArgumentException( 15494 "Sticky broadcast " + intent + " for user " 15495 + userId + " conflicts with existing global broadcast"); 15496 } 15497 } 15498 } 15499 } 15500 } 15501 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15502 if (stickies == null) { 15503 stickies = new ArrayMap<String, ArrayList<Intent>>(); 15504 mStickyBroadcasts.put(userId, stickies); 15505 } 15506 ArrayList<Intent> list = stickies.get(intent.getAction()); 15507 if (list == null) { 15508 list = new ArrayList<Intent>(); 15509 stickies.put(intent.getAction(), list); 15510 } 15511 int N = list.size(); 15512 int i; 15513 for (i=0; i<N; i++) { 15514 if (intent.filterEquals(list.get(i))) { 15515 // This sticky already exists, replace it. 15516 list.set(i, new Intent(intent)); 15517 break; 15518 } 15519 } 15520 if (i >= N) { 15521 list.add(new Intent(intent)); 15522 } 15523 } 15524 15525 int[] users; 15526 if (userId == UserHandle.USER_ALL) { 15527 // Caller wants broadcast to go to all started users. 15528 users = mStartedUserArray; 15529 } else { 15530 // Caller wants broadcast to go to one specific user. 15531 users = new int[] {userId}; 15532 } 15533 15534 // Figure out who all will receive this broadcast. 15535 List receivers = null; 15536 List<BroadcastFilter> registeredReceivers = null; 15537 // Need to resolve the intent to interested receivers... 15538 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 15539 == 0) { 15540 receivers = collectReceiverComponents(intent, resolvedType, callingUid, users); 15541 } 15542 if (intent.getComponent() == null) { 15543 if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) { 15544 // Query one target user at a time, excluding shell-restricted users 15545 UserManagerService ums = getUserManagerLocked(); 15546 for (int i = 0; i < users.length; i++) { 15547 if (ums.hasUserRestriction( 15548 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 15549 continue; 15550 } 15551 List<BroadcastFilter> registeredReceiversForUser = 15552 mReceiverResolver.queryIntent(intent, 15553 resolvedType, false, users[i]); 15554 if (registeredReceivers == null) { 15555 registeredReceivers = registeredReceiversForUser; 15556 } else if (registeredReceiversForUser != null) { 15557 registeredReceivers.addAll(registeredReceiversForUser); 15558 } 15559 } 15560 } else { 15561 registeredReceivers = mReceiverResolver.queryIntent(intent, 15562 resolvedType, false, userId); 15563 } 15564 } 15565 15566 final boolean replacePending = 15567 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 15568 15569 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction() 15570 + " replacePending=" + replacePending); 15571 15572 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 15573 if (!ordered && NR > 0) { 15574 // If we are not serializing this broadcast, then send the 15575 // registered receivers separately so they don't wait for the 15576 // components to be launched. 15577 final BroadcastQueue queue = broadcastQueueForIntent(intent); 15578 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15579 callerPackage, callingPid, callingUid, resolvedType, requiredPermission, 15580 appOp, registeredReceivers, resultTo, resultCode, resultData, map, 15581 ordered, sticky, false, userId); 15582 if (DEBUG_BROADCAST) Slog.v( 15583 TAG, "Enqueueing parallel broadcast " + r); 15584 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r); 15585 if (!replaced) { 15586 queue.enqueueParallelBroadcastLocked(r); 15587 queue.scheduleBroadcastsLocked(); 15588 } 15589 registeredReceivers = null; 15590 NR = 0; 15591 } 15592 15593 // Merge into one list. 15594 int ir = 0; 15595 if (receivers != null) { 15596 // A special case for PACKAGE_ADDED: do not allow the package 15597 // being added to see this broadcast. This prevents them from 15598 // using this as a back door to get run as soon as they are 15599 // installed. Maybe in the future we want to have a special install 15600 // broadcast or such for apps, but we'd like to deliberately make 15601 // this decision. 15602 String skipPackages[] = null; 15603 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 15604 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 15605 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 15606 Uri data = intent.getData(); 15607 if (data != null) { 15608 String pkgName = data.getSchemeSpecificPart(); 15609 if (pkgName != null) { 15610 skipPackages = new String[] { pkgName }; 15611 } 15612 } 15613 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 15614 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 15615 } 15616 if (skipPackages != null && (skipPackages.length > 0)) { 15617 for (String skipPackage : skipPackages) { 15618 if (skipPackage != null) { 15619 int NT = receivers.size(); 15620 for (int it=0; it<NT; it++) { 15621 ResolveInfo curt = (ResolveInfo)receivers.get(it); 15622 if (curt.activityInfo.packageName.equals(skipPackage)) { 15623 receivers.remove(it); 15624 it--; 15625 NT--; 15626 } 15627 } 15628 } 15629 } 15630 } 15631 15632 int NT = receivers != null ? receivers.size() : 0; 15633 int it = 0; 15634 ResolveInfo curt = null; 15635 BroadcastFilter curr = null; 15636 while (it < NT && ir < NR) { 15637 if (curt == null) { 15638 curt = (ResolveInfo)receivers.get(it); 15639 } 15640 if (curr == null) { 15641 curr = registeredReceivers.get(ir); 15642 } 15643 if (curr.getPriority() >= curt.priority) { 15644 // Insert this broadcast record into the final list. 15645 receivers.add(it, curr); 15646 ir++; 15647 curr = null; 15648 it++; 15649 NT++; 15650 } else { 15651 // Skip to the next ResolveInfo in the final list. 15652 it++; 15653 curt = null; 15654 } 15655 } 15656 } 15657 while (ir < NR) { 15658 if (receivers == null) { 15659 receivers = new ArrayList(); 15660 } 15661 receivers.add(registeredReceivers.get(ir)); 15662 ir++; 15663 } 15664 15665 if ((receivers != null && receivers.size() > 0) 15666 || resultTo != null) { 15667 BroadcastQueue queue = broadcastQueueForIntent(intent); 15668 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 15669 callerPackage, callingPid, callingUid, resolvedType, 15670 requiredPermission, appOp, receivers, resultTo, resultCode, 15671 resultData, map, ordered, sticky, false, userId); 15672 if (DEBUG_BROADCAST) Slog.v( 15673 TAG, "Enqueueing ordered broadcast " + r 15674 + ": prev had " + queue.mOrderedBroadcasts.size()); 15675 if (DEBUG_BROADCAST) { 15676 int seq = r.intent.getIntExtra("seq", -1); 15677 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq); 15678 } 15679 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r); 15680 if (!replaced) { 15681 queue.enqueueOrderedBroadcastLocked(r); 15682 queue.scheduleBroadcastsLocked(); 15683 } 15684 } 15685 15686 return ActivityManager.BROADCAST_SUCCESS; 15687 } 15688 15689 final Intent verifyBroadcastLocked(Intent intent) { 15690 // Refuse possible leaked file descriptors 15691 if (intent != null && intent.hasFileDescriptors() == true) { 15692 throw new IllegalArgumentException("File descriptors passed in Intent"); 15693 } 15694 15695 int flags = intent.getFlags(); 15696 15697 if (!mProcessesReady) { 15698 // if the caller really truly claims to know what they're doing, go 15699 // ahead and allow the broadcast without launching any receivers 15700 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 15701 intent = new Intent(intent); 15702 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 15703 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 15704 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 15705 + " before boot completion"); 15706 throw new IllegalStateException("Cannot broadcast before boot completed"); 15707 } 15708 } 15709 15710 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 15711 throw new IllegalArgumentException( 15712 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 15713 } 15714 15715 return intent; 15716 } 15717 15718 public final int broadcastIntent(IApplicationThread caller, 15719 Intent intent, String resolvedType, IIntentReceiver resultTo, 15720 int resultCode, String resultData, Bundle map, 15721 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) { 15722 enforceNotIsolatedCaller("broadcastIntent"); 15723 synchronized(this) { 15724 intent = verifyBroadcastLocked(intent); 15725 15726 final ProcessRecord callerApp = getRecordForAppLocked(caller); 15727 final int callingPid = Binder.getCallingPid(); 15728 final int callingUid = Binder.getCallingUid(); 15729 final long origId = Binder.clearCallingIdentity(); 15730 int res = broadcastIntentLocked(callerApp, 15731 callerApp != null ? callerApp.info.packageName : null, 15732 intent, resolvedType, resultTo, 15733 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky, 15734 callingPid, callingUid, userId); 15735 Binder.restoreCallingIdentity(origId); 15736 return res; 15737 } 15738 } 15739 15740 int broadcastIntentInPackage(String packageName, int uid, 15741 Intent intent, String resolvedType, IIntentReceiver resultTo, 15742 int resultCode, String resultData, Bundle map, 15743 String requiredPermission, boolean serialized, boolean sticky, int userId) { 15744 synchronized(this) { 15745 intent = verifyBroadcastLocked(intent); 15746 15747 final long origId = Binder.clearCallingIdentity(); 15748 int res = broadcastIntentLocked(null, packageName, intent, resolvedType, 15749 resultTo, resultCode, resultData, map, requiredPermission, 15750 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId); 15751 Binder.restoreCallingIdentity(origId); 15752 return res; 15753 } 15754 } 15755 15756 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 15757 // Refuse possible leaked file descriptors 15758 if (intent != null && intent.hasFileDescriptors() == true) { 15759 throw new IllegalArgumentException("File descriptors passed in Intent"); 15760 } 15761 15762 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15763 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 15764 15765 synchronized(this) { 15766 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 15767 != PackageManager.PERMISSION_GRANTED) { 15768 String msg = "Permission Denial: unbroadcastIntent() from pid=" 15769 + Binder.getCallingPid() 15770 + ", uid=" + Binder.getCallingUid() 15771 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 15772 Slog.w(TAG, msg); 15773 throw new SecurityException(msg); 15774 } 15775 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 15776 if (stickies != null) { 15777 ArrayList<Intent> list = stickies.get(intent.getAction()); 15778 if (list != null) { 15779 int N = list.size(); 15780 int i; 15781 for (i=0; i<N; i++) { 15782 if (intent.filterEquals(list.get(i))) { 15783 list.remove(i); 15784 break; 15785 } 15786 } 15787 if (list.size() <= 0) { 15788 stickies.remove(intent.getAction()); 15789 } 15790 } 15791 if (stickies.size() <= 0) { 15792 mStickyBroadcasts.remove(userId); 15793 } 15794 } 15795 } 15796 } 15797 15798 private final boolean finishReceiverLocked(IBinder receiver, int resultCode, 15799 String resultData, Bundle resultExtras, boolean resultAbort) { 15800 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver); 15801 if (r == null) { 15802 Slog.w(TAG, "finishReceiver called but not found on queue"); 15803 return false; 15804 } 15805 15806 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort, false); 15807 } 15808 15809 void backgroundServicesFinishedLocked(int userId) { 15810 for (BroadcastQueue queue : mBroadcastQueues) { 15811 queue.backgroundServicesFinishedLocked(userId); 15812 } 15813 } 15814 15815 public void finishReceiver(IBinder who, int resultCode, String resultData, 15816 Bundle resultExtras, boolean resultAbort) { 15817 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who); 15818 15819 // Refuse possible leaked file descriptors 15820 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 15821 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15822 } 15823 15824 final long origId = Binder.clearCallingIdentity(); 15825 try { 15826 boolean doNext = false; 15827 BroadcastRecord r; 15828 15829 synchronized(this) { 15830 r = broadcastRecordForReceiverLocked(who); 15831 if (r != null) { 15832 doNext = r.queue.finishReceiverLocked(r, resultCode, 15833 resultData, resultExtras, resultAbort, true); 15834 } 15835 } 15836 15837 if (doNext) { 15838 r.queue.processNextBroadcast(false); 15839 } 15840 trimApplications(); 15841 } finally { 15842 Binder.restoreCallingIdentity(origId); 15843 } 15844 } 15845 15846 // ========================================================= 15847 // INSTRUMENTATION 15848 // ========================================================= 15849 15850 public boolean startInstrumentation(ComponentName className, 15851 String profileFile, int flags, Bundle arguments, 15852 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 15853 int userId, String abiOverride) { 15854 enforceNotIsolatedCaller("startInstrumentation"); 15855 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 15856 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 15857 // Refuse possible leaked file descriptors 15858 if (arguments != null && arguments.hasFileDescriptors()) { 15859 throw new IllegalArgumentException("File descriptors passed in Bundle"); 15860 } 15861 15862 synchronized(this) { 15863 InstrumentationInfo ii = null; 15864 ApplicationInfo ai = null; 15865 try { 15866 ii = mContext.getPackageManager().getInstrumentationInfo( 15867 className, STOCK_PM_FLAGS); 15868 ai = AppGlobals.getPackageManager().getApplicationInfo( 15869 ii.targetPackage, STOCK_PM_FLAGS, userId); 15870 } catch (PackageManager.NameNotFoundException e) { 15871 } catch (RemoteException e) { 15872 } 15873 if (ii == null) { 15874 reportStartInstrumentationFailure(watcher, className, 15875 "Unable to find instrumentation info for: " + className); 15876 return false; 15877 } 15878 if (ai == null) { 15879 reportStartInstrumentationFailure(watcher, className, 15880 "Unable to find instrumentation target package: " + ii.targetPackage); 15881 return false; 15882 } 15883 15884 int match = mContext.getPackageManager().checkSignatures( 15885 ii.targetPackage, ii.packageName); 15886 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 15887 String msg = "Permission Denial: starting instrumentation " 15888 + className + " from pid=" 15889 + Binder.getCallingPid() 15890 + ", uid=" + Binder.getCallingPid() 15891 + " not allowed because package " + ii.packageName 15892 + " does not have a signature matching the target " 15893 + ii.targetPackage; 15894 reportStartInstrumentationFailure(watcher, className, msg); 15895 throw new SecurityException(msg); 15896 } 15897 15898 final long origId = Binder.clearCallingIdentity(); 15899 // Instrumentation can kill and relaunch even persistent processes 15900 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, 15901 "start instr"); 15902 ProcessRecord app = addAppLocked(ai, false, abiOverride); 15903 app.instrumentationClass = className; 15904 app.instrumentationInfo = ai; 15905 app.instrumentationProfileFile = profileFile; 15906 app.instrumentationArguments = arguments; 15907 app.instrumentationWatcher = watcher; 15908 app.instrumentationUiAutomationConnection = uiAutomationConnection; 15909 app.instrumentationResultClass = className; 15910 Binder.restoreCallingIdentity(origId); 15911 } 15912 15913 return true; 15914 } 15915 15916 /** 15917 * Report errors that occur while attempting to start Instrumentation. Always writes the 15918 * error to the logs, but if somebody is watching, send the report there too. This enables 15919 * the "am" command to report errors with more information. 15920 * 15921 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 15922 * @param cn The component name of the instrumentation. 15923 * @param report The error report. 15924 */ 15925 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher, 15926 ComponentName cn, String report) { 15927 Slog.w(TAG, report); 15928 try { 15929 if (watcher != null) { 15930 Bundle results = new Bundle(); 15931 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 15932 results.putString("Error", report); 15933 watcher.instrumentationStatus(cn, -1, results); 15934 } 15935 } catch (RemoteException e) { 15936 Slog.w(TAG, e); 15937 } 15938 } 15939 15940 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 15941 if (app.instrumentationWatcher != null) { 15942 try { 15943 // NOTE: IInstrumentationWatcher *must* be oneway here 15944 app.instrumentationWatcher.instrumentationFinished( 15945 app.instrumentationClass, 15946 resultCode, 15947 results); 15948 } catch (RemoteException e) { 15949 } 15950 } 15951 if (app.instrumentationUiAutomationConnection != null) { 15952 try { 15953 app.instrumentationUiAutomationConnection.shutdown(); 15954 } catch (RemoteException re) { 15955 /* ignore */ 15956 } 15957 // Only a UiAutomation can set this flag and now that 15958 // it is finished we make sure it is reset to its default. 15959 mUserIsMonkey = false; 15960 } 15961 app.instrumentationWatcher = null; 15962 app.instrumentationUiAutomationConnection = null; 15963 app.instrumentationClass = null; 15964 app.instrumentationInfo = null; 15965 app.instrumentationProfileFile = null; 15966 app.instrumentationArguments = null; 15967 15968 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId, 15969 "finished inst"); 15970 } 15971 15972 public void finishInstrumentation(IApplicationThread target, 15973 int resultCode, Bundle results) { 15974 int userId = UserHandle.getCallingUserId(); 15975 // Refuse possible leaked file descriptors 15976 if (results != null && results.hasFileDescriptors()) { 15977 throw new IllegalArgumentException("File descriptors passed in Intent"); 15978 } 15979 15980 synchronized(this) { 15981 ProcessRecord app = getRecordForAppLocked(target); 15982 if (app == null) { 15983 Slog.w(TAG, "finishInstrumentation: no app for " + target); 15984 return; 15985 } 15986 final long origId = Binder.clearCallingIdentity(); 15987 finishInstrumentationLocked(app, resultCode, results); 15988 Binder.restoreCallingIdentity(origId); 15989 } 15990 } 15991 15992 // ========================================================= 15993 // CONFIGURATION 15994 // ========================================================= 15995 15996 public ConfigurationInfo getDeviceConfigurationInfo() { 15997 ConfigurationInfo config = new ConfigurationInfo(); 15998 synchronized (this) { 15999 config.reqTouchScreen = mConfiguration.touchscreen; 16000 config.reqKeyboardType = mConfiguration.keyboard; 16001 config.reqNavigation = mConfiguration.navigation; 16002 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD 16003 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) { 16004 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV; 16005 } 16006 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED 16007 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) { 16008 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD; 16009 } 16010 config.reqGlEsVersion = GL_ES_VERSION; 16011 } 16012 return config; 16013 } 16014 16015 ActivityStack getFocusedStack() { 16016 return mStackSupervisor.getFocusedStack(); 16017 } 16018 16019 public Configuration getConfiguration() { 16020 Configuration ci; 16021 synchronized(this) { 16022 ci = new Configuration(mConfiguration); 16023 } 16024 return ci; 16025 } 16026 16027 public void updatePersistentConfiguration(Configuration values) { 16028 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 16029 "updateConfiguration()"); 16030 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS, 16031 "updateConfiguration()"); 16032 if (values == null) { 16033 throw new NullPointerException("Configuration must not be null"); 16034 } 16035 16036 synchronized(this) { 16037 final long origId = Binder.clearCallingIdentity(); 16038 updateConfigurationLocked(values, null, true, false); 16039 Binder.restoreCallingIdentity(origId); 16040 } 16041 } 16042 16043 public void updateConfiguration(Configuration values) { 16044 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 16045 "updateConfiguration()"); 16046 16047 synchronized(this) { 16048 if (values == null && mWindowManager != null) { 16049 // sentinel: fetch the current configuration from the window manager 16050 values = mWindowManager.computeNewConfiguration(); 16051 } 16052 16053 if (mWindowManager != null) { 16054 mProcessList.applyDisplaySize(mWindowManager); 16055 } 16056 16057 final long origId = Binder.clearCallingIdentity(); 16058 if (values != null) { 16059 Settings.System.clearConfiguration(values); 16060 } 16061 updateConfigurationLocked(values, null, false, false); 16062 Binder.restoreCallingIdentity(origId); 16063 } 16064 } 16065 16066 /** 16067 * Do either or both things: (1) change the current configuration, and (2) 16068 * make sure the given activity is running with the (now) current 16069 * configuration. Returns true if the activity has been left running, or 16070 * false if <var>starting</var> is being destroyed to match the new 16071 * configuration. 16072 * @param persistent TODO 16073 */ 16074 boolean updateConfigurationLocked(Configuration values, 16075 ActivityRecord starting, boolean persistent, boolean initLocale) { 16076 int changes = 0; 16077 16078 if (values != null) { 16079 Configuration newConfig = new Configuration(mConfiguration); 16080 changes = newConfig.updateFrom(values); 16081 if (changes != 0) { 16082 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 16083 Slog.i(TAG, "Updating configuration to: " + values); 16084 } 16085 16086 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes); 16087 16088 if (values.locale != null && !initLocale) { 16089 saveLocaleLocked(values.locale, 16090 !values.locale.equals(mConfiguration.locale), 16091 values.userSetLocale); 16092 } 16093 16094 mConfigurationSeq++; 16095 if (mConfigurationSeq <= 0) { 16096 mConfigurationSeq = 1; 16097 } 16098 newConfig.seq = mConfigurationSeq; 16099 mConfiguration = newConfig; 16100 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig); 16101 mUsageStatsService.reportConfigurationChange(newConfig, mCurrentUserId); 16102 //mUsageStatsService.noteStartConfig(newConfig); 16103 16104 final Configuration configCopy = new Configuration(mConfiguration); 16105 16106 // TODO: If our config changes, should we auto dismiss any currently 16107 // showing dialogs? 16108 mShowDialogs = shouldShowDialogs(newConfig); 16109 16110 AttributeCache ac = AttributeCache.instance(); 16111 if (ac != null) { 16112 ac.updateConfiguration(configCopy); 16113 } 16114 16115 // Make sure all resources in our process are updated 16116 // right now, so that anyone who is going to retrieve 16117 // resource values after we return will be sure to get 16118 // the new ones. This is especially important during 16119 // boot, where the first config change needs to guarantee 16120 // all resources have that config before following boot 16121 // code is executed. 16122 mSystemThread.applyConfigurationToResources(configCopy); 16123 16124 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) { 16125 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG); 16126 msg.obj = new Configuration(configCopy); 16127 mHandler.sendMessage(msg); 16128 } 16129 16130 for (int i=mLruProcesses.size()-1; i>=0; i--) { 16131 ProcessRecord app = mLruProcesses.get(i); 16132 try { 16133 if (app.thread != null) { 16134 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc " 16135 + app.processName + " new config " + mConfiguration); 16136 app.thread.scheduleConfigurationChanged(configCopy); 16137 } 16138 } catch (Exception e) { 16139 } 16140 } 16141 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 16142 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 16143 | Intent.FLAG_RECEIVER_REPLACE_PENDING 16144 | Intent.FLAG_RECEIVER_FOREGROUND); 16145 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, 16146 null, AppOpsManager.OP_NONE, false, false, MY_PID, 16147 Process.SYSTEM_UID, UserHandle.USER_ALL); 16148 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) { 16149 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 16150 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 16151 broadcastIntentLocked(null, null, intent, 16152 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 16153 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 16154 } 16155 } 16156 } 16157 16158 boolean kept = true; 16159 final ActivityStack mainStack = mStackSupervisor.getFocusedStack(); 16160 // mainStack is null during startup. 16161 if (mainStack != null) { 16162 if (changes != 0 && starting == null) { 16163 // If the configuration changed, and the caller is not already 16164 // in the process of starting an activity, then find the top 16165 // activity to check if its configuration needs to change. 16166 starting = mainStack.topRunningActivityLocked(null); 16167 } 16168 16169 if (starting != null) { 16170 kept = mainStack.ensureActivityConfigurationLocked(starting, changes); 16171 // And we need to make sure at this point that all other activities 16172 // are made visible with the correct configuration. 16173 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes); 16174 } 16175 } 16176 16177 if (values != null && mWindowManager != null) { 16178 mWindowManager.setNewConfiguration(mConfiguration); 16179 } 16180 16181 return kept; 16182 } 16183 16184 /** 16185 * Decide based on the configuration whether we should shouw the ANR, 16186 * crash, etc dialogs. The idea is that if there is no affordnace to 16187 * press the on-screen buttons, we shouldn't show the dialog. 16188 * 16189 * A thought: SystemUI might also want to get told about this, the Power 16190 * dialog / global actions also might want different behaviors. 16191 */ 16192 private static final boolean shouldShowDialogs(Configuration config) { 16193 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS 16194 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH); 16195 } 16196 16197 /** 16198 * Save the locale. You must be inside a synchronized (this) block. 16199 */ 16200 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) { 16201 if(isDiff) { 16202 SystemProperties.set("user.language", l.getLanguage()); 16203 SystemProperties.set("user.region", l.getCountry()); 16204 } 16205 16206 if(isPersist) { 16207 SystemProperties.set("persist.sys.language", l.getLanguage()); 16208 SystemProperties.set("persist.sys.country", l.getCountry()); 16209 SystemProperties.set("persist.sys.localevar", l.getVariant()); 16210 } 16211 } 16212 16213 @Override 16214 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) { 16215 synchronized (this) { 16216 ActivityRecord srec = ActivityRecord.forToken(token); 16217 if (srec.task != null && srec.task.stack != null) { 16218 return srec.task.stack.shouldUpRecreateTaskLocked(srec, destAffinity); 16219 } 16220 } 16221 return false; 16222 } 16223 16224 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode, 16225 Intent resultData) { 16226 16227 synchronized (this) { 16228 final ActivityStack stack = ActivityRecord.getStackLocked(token); 16229 if (stack != null) { 16230 return stack.navigateUpToLocked(token, destIntent, resultCode, resultData); 16231 } 16232 return false; 16233 } 16234 } 16235 16236 public int getLaunchedFromUid(IBinder activityToken) { 16237 ActivityRecord srec = ActivityRecord.forToken(activityToken); 16238 if (srec == null) { 16239 return -1; 16240 } 16241 return srec.launchedFromUid; 16242 } 16243 16244 public String getLaunchedFromPackage(IBinder activityToken) { 16245 ActivityRecord srec = ActivityRecord.forToken(activityToken); 16246 if (srec == null) { 16247 return null; 16248 } 16249 return srec.launchedFromPackage; 16250 } 16251 16252 // ========================================================= 16253 // LIFETIME MANAGEMENT 16254 // ========================================================= 16255 16256 // Returns which broadcast queue the app is the current [or imminent] receiver 16257 // on, or 'null' if the app is not an active broadcast recipient. 16258 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) { 16259 BroadcastRecord r = app.curReceiver; 16260 if (r != null) { 16261 return r.queue; 16262 } 16263 16264 // It's not the current receiver, but it might be starting up to become one 16265 synchronized (this) { 16266 for (BroadcastQueue queue : mBroadcastQueues) { 16267 r = queue.mPendingBroadcast; 16268 if (r != null && r.curApp == app) { 16269 // found it; report which queue it's in 16270 return queue; 16271 } 16272 } 16273 } 16274 16275 return null; 16276 } 16277 16278 private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, 16279 boolean doingAll, long now) { 16280 if (mAdjSeq == app.adjSeq) { 16281 // This adjustment has already been computed. 16282 return app.curRawAdj; 16283 } 16284 16285 if (app.thread == null) { 16286 app.adjSeq = mAdjSeq; 16287 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16288 app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16289 return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ); 16290 } 16291 16292 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN; 16293 app.adjSource = null; 16294 app.adjTarget = null; 16295 app.empty = false; 16296 app.cached = false; 16297 16298 final int activitiesSize = app.activities.size(); 16299 16300 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) { 16301 // The max adjustment doesn't allow this app to be anything 16302 // below foreground, so it is not worth doing work for it. 16303 app.adjType = "fixed"; 16304 app.adjSeq = mAdjSeq; 16305 app.curRawAdj = app.maxAdj; 16306 app.foregroundActivities = false; 16307 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 16308 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT; 16309 // System processes can do UI, and when they do we want to have 16310 // them trim their memory after the user leaves the UI. To 16311 // facilitate this, here we need to determine whether or not it 16312 // is currently showing UI. 16313 app.systemNoUi = true; 16314 if (app == TOP_APP) { 16315 app.systemNoUi = false; 16316 } else if (activitiesSize > 0) { 16317 for (int j = 0; j < activitiesSize; j++) { 16318 final ActivityRecord r = app.activities.get(j); 16319 if (r.visible) { 16320 app.systemNoUi = false; 16321 } 16322 } 16323 } 16324 if (!app.systemNoUi) { 16325 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI; 16326 } 16327 return (app.curAdj=app.maxAdj); 16328 } 16329 16330 app.systemNoUi = false; 16331 16332 // Determine the importance of the process, starting with most 16333 // important to least, and assign an appropriate OOM adjustment. 16334 int adj; 16335 int schedGroup; 16336 int procState; 16337 boolean foregroundActivities = false; 16338 BroadcastQueue queue; 16339 if (app == TOP_APP) { 16340 // The last app on the list is the foreground app. 16341 adj = ProcessList.FOREGROUND_APP_ADJ; 16342 schedGroup = Process.THREAD_GROUP_DEFAULT; 16343 app.adjType = "top-activity"; 16344 foregroundActivities = true; 16345 procState = ActivityManager.PROCESS_STATE_TOP; 16346 } else if (app.instrumentationClass != null) { 16347 // Don't want to kill running instrumentation. 16348 adj = ProcessList.FOREGROUND_APP_ADJ; 16349 schedGroup = Process.THREAD_GROUP_DEFAULT; 16350 app.adjType = "instrumentation"; 16351 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16352 } else if ((queue = isReceivingBroadcast(app)) != null) { 16353 // An app that is currently receiving a broadcast also 16354 // counts as being in the foreground for OOM killer purposes. 16355 // It's placed in a sched group based on the nature of the 16356 // broadcast as reflected by which queue it's active in. 16357 adj = ProcessList.FOREGROUND_APP_ADJ; 16358 schedGroup = (queue == mFgBroadcastQueue) 16359 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 16360 app.adjType = "broadcast"; 16361 procState = ActivityManager.PROCESS_STATE_RECEIVER; 16362 } else if (app.executingServices.size() > 0) { 16363 // An app that is currently executing a service callback also 16364 // counts as being in the foreground. 16365 adj = ProcessList.FOREGROUND_APP_ADJ; 16366 schedGroup = app.execServicesFg ? 16367 Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 16368 app.adjType = "exec-service"; 16369 procState = ActivityManager.PROCESS_STATE_SERVICE; 16370 //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app); 16371 } else { 16372 // As far as we know the process is empty. We may change our mind later. 16373 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16374 // At this point we don't actually know the adjustment. Use the cached adj 16375 // value that the caller wants us to. 16376 adj = cachedAdj; 16377 procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16378 app.cached = true; 16379 app.empty = true; 16380 app.adjType = "cch-empty"; 16381 } 16382 16383 // Examine all activities if not already foreground. 16384 if (!foregroundActivities && activitiesSize > 0) { 16385 for (int j = 0; j < activitiesSize; j++) { 16386 final ActivityRecord r = app.activities.get(j); 16387 if (r.app != app) { 16388 Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc " 16389 + app + "?!?"); 16390 continue; 16391 } 16392 if (r.visible) { 16393 // App has a visible activity; only upgrade adjustment. 16394 if (adj > ProcessList.VISIBLE_APP_ADJ) { 16395 adj = ProcessList.VISIBLE_APP_ADJ; 16396 app.adjType = "visible"; 16397 } 16398 if (procState > ActivityManager.PROCESS_STATE_TOP) { 16399 procState = ActivityManager.PROCESS_STATE_TOP; 16400 } 16401 schedGroup = Process.THREAD_GROUP_DEFAULT; 16402 app.cached = false; 16403 app.empty = false; 16404 foregroundActivities = true; 16405 break; 16406 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) { 16407 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16408 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16409 app.adjType = "pausing"; 16410 } 16411 if (procState > ActivityManager.PROCESS_STATE_TOP) { 16412 procState = ActivityManager.PROCESS_STATE_TOP; 16413 } 16414 schedGroup = Process.THREAD_GROUP_DEFAULT; 16415 app.cached = false; 16416 app.empty = false; 16417 foregroundActivities = true; 16418 } else if (r.state == ActivityState.STOPPING) { 16419 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16420 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16421 app.adjType = "stopping"; 16422 } 16423 // For the process state, we will at this point consider the 16424 // process to be cached. It will be cached either as an activity 16425 // or empty depending on whether the activity is finishing. We do 16426 // this so that we can treat the process as cached for purposes of 16427 // memory trimming (determing current memory level, trim command to 16428 // send to process) since there can be an arbitrary number of stopping 16429 // processes and they should soon all go into the cached state. 16430 if (!r.finishing) { 16431 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 16432 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 16433 } 16434 } 16435 app.cached = false; 16436 app.empty = false; 16437 foregroundActivities = true; 16438 } else { 16439 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16440 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 16441 app.adjType = "cch-act"; 16442 } 16443 } 16444 } 16445 } 16446 16447 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16448 if (app.foregroundServices) { 16449 // The user is aware of this app, so make it visible. 16450 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16451 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16452 app.cached = false; 16453 app.adjType = "fg-service"; 16454 schedGroup = Process.THREAD_GROUP_DEFAULT; 16455 } else if (app.forcingToForeground != null) { 16456 // The user is aware of this app, so make it visible. 16457 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16458 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16459 app.cached = false; 16460 app.adjType = "force-fg"; 16461 app.adjSource = app.forcingToForeground; 16462 schedGroup = Process.THREAD_GROUP_DEFAULT; 16463 } 16464 } 16465 16466 if (app == mHeavyWeightProcess) { 16467 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) { 16468 // We don't want to kill the current heavy-weight process. 16469 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ; 16470 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16471 app.cached = false; 16472 app.adjType = "heavy"; 16473 } 16474 if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 16475 procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT; 16476 } 16477 } 16478 16479 if (app == mHomeProcess) { 16480 if (adj > ProcessList.HOME_APP_ADJ) { 16481 // This process is hosting what we currently consider to be the 16482 // home app, so we don't want to let it go into the background. 16483 adj = ProcessList.HOME_APP_ADJ; 16484 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16485 app.cached = false; 16486 app.adjType = "home"; 16487 } 16488 if (procState > ActivityManager.PROCESS_STATE_HOME) { 16489 procState = ActivityManager.PROCESS_STATE_HOME; 16490 } 16491 } 16492 16493 if (app == mPreviousProcess && app.activities.size() > 0) { 16494 if (adj > ProcessList.PREVIOUS_APP_ADJ) { 16495 // This was the previous process that showed UI to the user. 16496 // We want to try to keep it around more aggressively, to give 16497 // a good experience around switching between two apps. 16498 adj = ProcessList.PREVIOUS_APP_ADJ; 16499 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 16500 app.cached = false; 16501 app.adjType = "previous"; 16502 } 16503 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 16504 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 16505 } 16506 } 16507 16508 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj 16509 + " reason=" + app.adjType); 16510 16511 // By default, we use the computed adjustment. It may be changed if 16512 // there are applications dependent on our services or providers, but 16513 // this gives us a baseline and makes sure we don't get into an 16514 // infinite recursion. 16515 app.adjSeq = mAdjSeq; 16516 app.curRawAdj = adj; 16517 app.hasStartedServices = false; 16518 16519 if (mBackupTarget != null && app == mBackupTarget.app) { 16520 // If possible we want to avoid killing apps while they're being backed up 16521 if (adj > ProcessList.BACKUP_APP_ADJ) { 16522 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app); 16523 adj = ProcessList.BACKUP_APP_ADJ; 16524 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 16525 procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 16526 } 16527 app.adjType = "backup"; 16528 app.cached = false; 16529 } 16530 if (procState > ActivityManager.PROCESS_STATE_BACKUP) { 16531 procState = ActivityManager.PROCESS_STATE_BACKUP; 16532 } 16533 } 16534 16535 boolean mayBeTop = false; 16536 16537 for (int is = app.services.size()-1; 16538 is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16539 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16540 || procState > ActivityManager.PROCESS_STATE_TOP); 16541 is--) { 16542 ServiceRecord s = app.services.valueAt(is); 16543 if (s.startRequested) { 16544 app.hasStartedServices = true; 16545 if (procState > ActivityManager.PROCESS_STATE_SERVICE) { 16546 procState = ActivityManager.PROCESS_STATE_SERVICE; 16547 } 16548 if (app.hasShownUi && app != mHomeProcess) { 16549 // If this process has shown some UI, let it immediately 16550 // go to the LRU list because it may be pretty heavy with 16551 // UI stuff. We'll tag it with a label just to help 16552 // debug and understand what is going on. 16553 if (adj > ProcessList.SERVICE_ADJ) { 16554 app.adjType = "cch-started-ui-services"; 16555 } 16556 } else { 16557 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) { 16558 // This service has seen some activity within 16559 // recent memory, so we will keep its process ahead 16560 // of the background processes. 16561 if (adj > ProcessList.SERVICE_ADJ) { 16562 adj = ProcessList.SERVICE_ADJ; 16563 app.adjType = "started-services"; 16564 app.cached = false; 16565 } 16566 } 16567 // If we have let the service slide into the background 16568 // state, still have some text describing what it is doing 16569 // even though the service no longer has an impact. 16570 if (adj > ProcessList.SERVICE_ADJ) { 16571 app.adjType = "cch-started-services"; 16572 } 16573 } 16574 } 16575 for (int conni = s.connections.size()-1; 16576 conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16577 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16578 || procState > ActivityManager.PROCESS_STATE_TOP); 16579 conni--) { 16580 ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni); 16581 for (int i = 0; 16582 i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ 16583 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16584 || procState > ActivityManager.PROCESS_STATE_TOP); 16585 i++) { 16586 // XXX should compute this based on the max of 16587 // all connected clients. 16588 ConnectionRecord cr = clist.get(i); 16589 if (cr.binding.client == app) { 16590 // Binding to ourself is not interesting. 16591 continue; 16592 } 16593 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) { 16594 ProcessRecord client = cr.binding.client; 16595 int clientAdj = computeOomAdjLocked(client, cachedAdj, 16596 TOP_APP, doingAll, now); 16597 int clientProcState = client.curProcState; 16598 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16599 // If the other app is cached for any reason, for purposes here 16600 // we are going to consider it empty. The specific cached state 16601 // doesn't propagate except under certain conditions. 16602 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16603 } 16604 String adjType = null; 16605 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) { 16606 // Not doing bind OOM management, so treat 16607 // this guy more like a started service. 16608 if (app.hasShownUi && app != mHomeProcess) { 16609 // If this process has shown some UI, let it immediately 16610 // go to the LRU list because it may be pretty heavy with 16611 // UI stuff. We'll tag it with a label just to help 16612 // debug and understand what is going on. 16613 if (adj > clientAdj) { 16614 adjType = "cch-bound-ui-services"; 16615 } 16616 app.cached = false; 16617 clientAdj = adj; 16618 clientProcState = procState; 16619 } else { 16620 if (now >= (s.lastActivity 16621 + ActiveServices.MAX_SERVICE_INACTIVITY)) { 16622 // This service has not seen activity within 16623 // recent memory, so allow it to drop to the 16624 // LRU list if there is no other reason to keep 16625 // it around. We'll also tag it with a label just 16626 // to help debug and undertand what is going on. 16627 if (adj > clientAdj) { 16628 adjType = "cch-bound-services"; 16629 } 16630 clientAdj = adj; 16631 } 16632 } 16633 } 16634 if (adj > clientAdj) { 16635 // If this process has recently shown UI, and 16636 // the process that is binding to it is less 16637 // important than being visible, then we don't 16638 // care about the binding as much as we care 16639 // about letting this process get into the LRU 16640 // list to be killed and restarted if needed for 16641 // memory. 16642 if (app.hasShownUi && app != mHomeProcess 16643 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16644 adjType = "cch-bound-ui-services"; 16645 } else { 16646 if ((cr.flags&(Context.BIND_ABOVE_CLIENT 16647 |Context.BIND_IMPORTANT)) != 0) { 16648 adj = clientAdj; 16649 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0 16650 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ 16651 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16652 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 16653 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) { 16654 adj = clientAdj; 16655 } else { 16656 if (adj > ProcessList.VISIBLE_APP_ADJ) { 16657 adj = ProcessList.VISIBLE_APP_ADJ; 16658 } 16659 } 16660 if (!client.cached) { 16661 app.cached = false; 16662 } 16663 adjType = "service"; 16664 } 16665 } 16666 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 16667 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 16668 schedGroup = Process.THREAD_GROUP_DEFAULT; 16669 } 16670 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 16671 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 16672 // Special handling of clients who are in the top state. 16673 // We *may* want to consider this process to be in the 16674 // top state as well, but only if there is not another 16675 // reason for it to be running. Being on the top is a 16676 // special state, meaning you are specifically running 16677 // for the current top app. If the process is already 16678 // running in the background for some other reason, it 16679 // is more important to continue considering it to be 16680 // in the background state. 16681 mayBeTop = true; 16682 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16683 } else { 16684 // Special handling for above-top states (persistent 16685 // processes). These should not bring the current process 16686 // into the top state, since they are not on top. Instead 16687 // give them the best state after that. 16688 clientProcState = 16689 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16690 } 16691 } 16692 } else { 16693 if (clientProcState < 16694 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 16695 clientProcState = 16696 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 16697 } 16698 } 16699 if (procState > clientProcState) { 16700 procState = clientProcState; 16701 } 16702 if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16703 && (cr.flags&Context.BIND_SHOWING_UI) != 0) { 16704 app.pendingUiClean = true; 16705 } 16706 if (adjType != null) { 16707 app.adjType = adjType; 16708 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16709 .REASON_SERVICE_IN_USE; 16710 app.adjSource = cr.binding.client; 16711 app.adjSourceProcState = clientProcState; 16712 app.adjTarget = s.name; 16713 } 16714 } 16715 if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 16716 app.treatLikeActivity = true; 16717 } 16718 final ActivityRecord a = cr.activity; 16719 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) { 16720 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ && 16721 (a.visible || a.state == ActivityState.RESUMED 16722 || a.state == ActivityState.PAUSING)) { 16723 adj = ProcessList.FOREGROUND_APP_ADJ; 16724 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 16725 schedGroup = Process.THREAD_GROUP_DEFAULT; 16726 } 16727 app.cached = false; 16728 app.adjType = "service"; 16729 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16730 .REASON_SERVICE_IN_USE; 16731 app.adjSource = a; 16732 app.adjSourceProcState = procState; 16733 app.adjTarget = s.name; 16734 } 16735 } 16736 } 16737 } 16738 } 16739 16740 for (int provi = app.pubProviders.size()-1; 16741 provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16742 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16743 || procState > ActivityManager.PROCESS_STATE_TOP); 16744 provi--) { 16745 ContentProviderRecord cpr = app.pubProviders.valueAt(provi); 16746 for (int i = cpr.connections.size()-1; 16747 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 16748 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 16749 || procState > ActivityManager.PROCESS_STATE_TOP); 16750 i--) { 16751 ContentProviderConnection conn = cpr.connections.get(i); 16752 ProcessRecord client = conn.client; 16753 if (client == app) { 16754 // Being our own client is not interesting. 16755 continue; 16756 } 16757 int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now); 16758 int clientProcState = client.curProcState; 16759 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 16760 // If the other app is cached for any reason, for purposes here 16761 // we are going to consider it empty. 16762 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16763 } 16764 if (adj > clientAdj) { 16765 if (app.hasShownUi && app != mHomeProcess 16766 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 16767 app.adjType = "cch-ui-provider"; 16768 } else { 16769 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ 16770 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ; 16771 app.adjType = "provider"; 16772 } 16773 app.cached &= client.cached; 16774 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 16775 .REASON_PROVIDER_IN_USE; 16776 app.adjSource = client; 16777 app.adjSourceProcState = clientProcState; 16778 app.adjTarget = cpr.name; 16779 } 16780 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 16781 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 16782 // Special handling of clients who are in the top state. 16783 // We *may* want to consider this process to be in the 16784 // top state as well, but only if there is not another 16785 // reason for it to be running. Being on the top is a 16786 // special state, meaning you are specifically running 16787 // for the current top app. If the process is already 16788 // running in the background for some other reason, it 16789 // is more important to continue considering it to be 16790 // in the background state. 16791 mayBeTop = true; 16792 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 16793 } else { 16794 // Special handling for above-top states (persistent 16795 // processes). These should not bring the current process 16796 // into the top state, since they are not on top. Instead 16797 // give them the best state after that. 16798 clientProcState = 16799 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16800 } 16801 } 16802 if (procState > clientProcState) { 16803 procState = clientProcState; 16804 } 16805 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 16806 schedGroup = Process.THREAD_GROUP_DEFAULT; 16807 } 16808 } 16809 // If the provider has external (non-framework) process 16810 // dependencies, ensure that its adjustment is at least 16811 // FOREGROUND_APP_ADJ. 16812 if (cpr.hasExternalProcessHandles()) { 16813 if (adj > ProcessList.FOREGROUND_APP_ADJ) { 16814 adj = ProcessList.FOREGROUND_APP_ADJ; 16815 schedGroup = Process.THREAD_GROUP_DEFAULT; 16816 app.cached = false; 16817 app.adjType = "provider"; 16818 app.adjTarget = cpr.name; 16819 } 16820 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 16821 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16822 } 16823 } 16824 } 16825 16826 if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) { 16827 // A client of one of our services or providers is in the top state. We 16828 // *may* want to be in the top state, but not if we are already running in 16829 // the background for some other reason. For the decision here, we are going 16830 // to pick out a few specific states that we want to remain in when a client 16831 // is top (states that tend to be longer-term) and otherwise allow it to go 16832 // to the top state. 16833 switch (procState) { 16834 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 16835 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 16836 case ActivityManager.PROCESS_STATE_SERVICE: 16837 // These all are longer-term states, so pull them up to the top 16838 // of the background states, but not all the way to the top state. 16839 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 16840 break; 16841 default: 16842 // Otherwise, top is a better choice, so take it. 16843 procState = ActivityManager.PROCESS_STATE_TOP; 16844 break; 16845 } 16846 } 16847 16848 if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 16849 if (app.hasClientActivities) { 16850 // This is a cached process, but with client activities. Mark it so. 16851 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT; 16852 app.adjType = "cch-client-act"; 16853 } else if (app.treatLikeActivity) { 16854 // This is a cached process, but somebody wants us to treat it like it has 16855 // an activity, okay! 16856 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 16857 app.adjType = "cch-as-act"; 16858 } 16859 } 16860 16861 if (adj == ProcessList.SERVICE_ADJ) { 16862 if (doingAll) { 16863 app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3); 16864 mNewNumServiceProcs++; 16865 //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb); 16866 if (!app.serviceb) { 16867 // This service isn't far enough down on the LRU list to 16868 // normally be a B service, but if we are low on RAM and it 16869 // is large we want to force it down since we would prefer to 16870 // keep launcher over it. 16871 if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 16872 && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) { 16873 app.serviceHighRam = true; 16874 app.serviceb = true; 16875 //Slog.i(TAG, "ADJ " + app + " high ram!"); 16876 } else { 16877 mNewNumAServiceProcs++; 16878 //Slog.i(TAG, "ADJ " + app + " not high ram!"); 16879 } 16880 } else { 16881 app.serviceHighRam = false; 16882 } 16883 } 16884 if (app.serviceb) { 16885 adj = ProcessList.SERVICE_B_ADJ; 16886 } 16887 } 16888 16889 app.curRawAdj = adj; 16890 16891 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid + 16892 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj); 16893 if (adj > app.maxAdj) { 16894 adj = app.maxAdj; 16895 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 16896 schedGroup = Process.THREAD_GROUP_DEFAULT; 16897 } 16898 } 16899 16900 // Do final modification to adj. Everything we do between here and applying 16901 // the final setAdj must be done in this function, because we will also use 16902 // it when computing the final cached adj later. Note that we don't need to 16903 // worry about this for max adj above, since max adj will always be used to 16904 // keep it out of the cached vaues. 16905 app.curAdj = app.modifyRawOomAdj(adj); 16906 app.curSchedGroup = schedGroup; 16907 app.curProcState = procState; 16908 app.foregroundActivities = foregroundActivities; 16909 16910 return app.curRawAdj; 16911 } 16912 16913 /** 16914 * Schedule PSS collection of a process. 16915 */ 16916 void requestPssLocked(ProcessRecord proc, int procState) { 16917 if (mPendingPssProcesses.contains(proc)) { 16918 return; 16919 } 16920 if (mPendingPssProcesses.size() == 0) { 16921 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16922 } 16923 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of: " + proc); 16924 proc.pssProcState = procState; 16925 mPendingPssProcesses.add(proc); 16926 } 16927 16928 /** 16929 * Schedule PSS collection of all processes. 16930 */ 16931 void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) { 16932 if (!always) { 16933 if (now < (mLastFullPssTime + 16934 (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) { 16935 return; 16936 } 16937 } 16938 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of all procs! memLowered=" + memLowered); 16939 mLastFullPssTime = now; 16940 mFullPssPending = true; 16941 mPendingPssProcesses.ensureCapacity(mLruProcesses.size()); 16942 mPendingPssProcesses.clear(); 16943 for (int i=mLruProcesses.size()-1; i>=0; i--) { 16944 ProcessRecord app = mLruProcesses.get(i); 16945 if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) { 16946 app.pssProcState = app.setProcState; 16947 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 16948 isSleeping(), now); 16949 mPendingPssProcesses.add(app); 16950 } 16951 } 16952 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16953 } 16954 16955 /** 16956 * Ask a given process to GC right now. 16957 */ 16958 final void performAppGcLocked(ProcessRecord app) { 16959 try { 16960 app.lastRequestedGc = SystemClock.uptimeMillis(); 16961 if (app.thread != null) { 16962 if (app.reportLowMemory) { 16963 app.reportLowMemory = false; 16964 app.thread.scheduleLowMemory(); 16965 } else { 16966 app.thread.processInBackground(); 16967 } 16968 } 16969 } catch (Exception e) { 16970 // whatever. 16971 } 16972 } 16973 16974 /** 16975 * Returns true if things are idle enough to perform GCs. 16976 */ 16977 private final boolean canGcNowLocked() { 16978 boolean processingBroadcasts = false; 16979 for (BroadcastQueue q : mBroadcastQueues) { 16980 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) { 16981 processingBroadcasts = true; 16982 } 16983 } 16984 return !processingBroadcasts 16985 && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle()); 16986 } 16987 16988 /** 16989 * Perform GCs on all processes that are waiting for it, but only 16990 * if things are idle. 16991 */ 16992 final void performAppGcsLocked() { 16993 final int N = mProcessesToGc.size(); 16994 if (N <= 0) { 16995 return; 16996 } 16997 if (canGcNowLocked()) { 16998 while (mProcessesToGc.size() > 0) { 16999 ProcessRecord proc = mProcessesToGc.remove(0); 17000 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) { 17001 if ((proc.lastRequestedGc+GC_MIN_INTERVAL) 17002 <= SystemClock.uptimeMillis()) { 17003 // To avoid spamming the system, we will GC processes one 17004 // at a time, waiting a few seconds between each. 17005 performAppGcLocked(proc); 17006 scheduleAppGcsLocked(); 17007 return; 17008 } else { 17009 // It hasn't been long enough since we last GCed this 17010 // process... put it in the list to wait for its time. 17011 addProcessToGcListLocked(proc); 17012 break; 17013 } 17014 } 17015 } 17016 17017 scheduleAppGcsLocked(); 17018 } 17019 } 17020 17021 /** 17022 * If all looks good, perform GCs on all processes waiting for them. 17023 */ 17024 final void performAppGcsIfAppropriateLocked() { 17025 if (canGcNowLocked()) { 17026 performAppGcsLocked(); 17027 return; 17028 } 17029 // Still not idle, wait some more. 17030 scheduleAppGcsLocked(); 17031 } 17032 17033 /** 17034 * Schedule the execution of all pending app GCs. 17035 */ 17036 final void scheduleAppGcsLocked() { 17037 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG); 17038 17039 if (mProcessesToGc.size() > 0) { 17040 // Schedule a GC for the time to the next process. 17041 ProcessRecord proc = mProcessesToGc.get(0); 17042 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG); 17043 17044 long when = proc.lastRequestedGc + GC_MIN_INTERVAL; 17045 long now = SystemClock.uptimeMillis(); 17046 if (when < (now+GC_TIMEOUT)) { 17047 when = now + GC_TIMEOUT; 17048 } 17049 mHandler.sendMessageAtTime(msg, when); 17050 } 17051 } 17052 17053 /** 17054 * Add a process to the array of processes waiting to be GCed. Keeps the 17055 * list in sorted order by the last GC time. The process can't already be 17056 * on the list. 17057 */ 17058 final void addProcessToGcListLocked(ProcessRecord proc) { 17059 boolean added = false; 17060 for (int i=mProcessesToGc.size()-1; i>=0; i--) { 17061 if (mProcessesToGc.get(i).lastRequestedGc < 17062 proc.lastRequestedGc) { 17063 added = true; 17064 mProcessesToGc.add(i+1, proc); 17065 break; 17066 } 17067 } 17068 if (!added) { 17069 mProcessesToGc.add(0, proc); 17070 } 17071 } 17072 17073 /** 17074 * Set up to ask a process to GC itself. This will either do it 17075 * immediately, or put it on the list of processes to gc the next 17076 * time things are idle. 17077 */ 17078 final void scheduleAppGcLocked(ProcessRecord app) { 17079 long now = SystemClock.uptimeMillis(); 17080 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) { 17081 return; 17082 } 17083 if (!mProcessesToGc.contains(app)) { 17084 addProcessToGcListLocked(app); 17085 scheduleAppGcsLocked(); 17086 } 17087 } 17088 17089 final void checkExcessivePowerUsageLocked(boolean doKills) { 17090 updateCpuStatsNow(); 17091 17092 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 17093 boolean doWakeKills = doKills; 17094 boolean doCpuKills = doKills; 17095 if (mLastPowerCheckRealtime == 0) { 17096 doWakeKills = false; 17097 } 17098 if (mLastPowerCheckUptime == 0) { 17099 doCpuKills = false; 17100 } 17101 if (stats.isScreenOn()) { 17102 doWakeKills = false; 17103 } 17104 final long curRealtime = SystemClock.elapsedRealtime(); 17105 final long realtimeSince = curRealtime - mLastPowerCheckRealtime; 17106 final long curUptime = SystemClock.uptimeMillis(); 17107 final long uptimeSince = curUptime - mLastPowerCheckUptime; 17108 mLastPowerCheckRealtime = curRealtime; 17109 mLastPowerCheckUptime = curUptime; 17110 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) { 17111 doWakeKills = false; 17112 } 17113 if (uptimeSince < CPU_MIN_CHECK_DURATION) { 17114 doCpuKills = false; 17115 } 17116 int i = mLruProcesses.size(); 17117 while (i > 0) { 17118 i--; 17119 ProcessRecord app = mLruProcesses.get(i); 17120 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 17121 long wtime; 17122 synchronized (stats) { 17123 wtime = stats.getProcessWakeTime(app.info.uid, 17124 app.pid, curRealtime); 17125 } 17126 long wtimeUsed = wtime - app.lastWakeTime; 17127 long cputimeUsed = app.curCpuTime - app.lastCpuTime; 17128 if (DEBUG_POWER) { 17129 StringBuilder sb = new StringBuilder(128); 17130 sb.append("Wake for "); 17131 app.toShortString(sb); 17132 sb.append(": over "); 17133 TimeUtils.formatDuration(realtimeSince, sb); 17134 sb.append(" used "); 17135 TimeUtils.formatDuration(wtimeUsed, sb); 17136 sb.append(" ("); 17137 sb.append((wtimeUsed*100)/realtimeSince); 17138 sb.append("%)"); 17139 Slog.i(TAG, sb.toString()); 17140 sb.setLength(0); 17141 sb.append("CPU for "); 17142 app.toShortString(sb); 17143 sb.append(": over "); 17144 TimeUtils.formatDuration(uptimeSince, sb); 17145 sb.append(" used "); 17146 TimeUtils.formatDuration(cputimeUsed, sb); 17147 sb.append(" ("); 17148 sb.append((cputimeUsed*100)/uptimeSince); 17149 sb.append("%)"); 17150 Slog.i(TAG, sb.toString()); 17151 } 17152 // If a process has held a wake lock for more 17153 // than 50% of the time during this period, 17154 // that sounds bad. Kill! 17155 if (doWakeKills && realtimeSince > 0 17156 && ((wtimeUsed*100)/realtimeSince) >= 50) { 17157 synchronized (stats) { 17158 stats.reportExcessiveWakeLocked(app.info.uid, app.processName, 17159 realtimeSince, wtimeUsed); 17160 } 17161 app.kill("excessive wake held " + wtimeUsed + " during " + realtimeSince, true); 17162 app.baseProcessTracker.reportExcessiveWake(app.pkgList); 17163 } else if (doCpuKills && uptimeSince > 0 17164 && ((cputimeUsed*100)/uptimeSince) >= 25) { 17165 synchronized (stats) { 17166 stats.reportExcessiveCpuLocked(app.info.uid, app.processName, 17167 uptimeSince, cputimeUsed); 17168 } 17169 app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince, true); 17170 app.baseProcessTracker.reportExcessiveCpu(app.pkgList); 17171 } else { 17172 app.lastWakeTime = wtime; 17173 app.lastCpuTime = app.curCpuTime; 17174 } 17175 } 17176 } 17177 } 17178 17179 private final boolean applyOomAdjLocked(ProcessRecord app, 17180 ProcessRecord TOP_APP, boolean doingAll, long now) { 17181 boolean success = true; 17182 17183 if (app.curRawAdj != app.setRawAdj) { 17184 app.setRawAdj = app.curRawAdj; 17185 } 17186 17187 int changes = 0; 17188 17189 if (app.curAdj != app.setAdj) { 17190 ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj); 17191 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v( 17192 TAG, "Set " + app.pid + " " + app.processName + 17193 " adj " + app.curAdj + ": " + app.adjType); 17194 app.setAdj = app.curAdj; 17195 } 17196 17197 if (app.setSchedGroup != app.curSchedGroup) { 17198 app.setSchedGroup = app.curSchedGroup; 17199 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17200 "Setting process group of " + app.processName 17201 + " to " + app.curSchedGroup); 17202 if (app.waitingToKill != null && 17203 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 17204 app.kill(app.waitingToKill, true); 17205 success = false; 17206 } else { 17207 if (true) { 17208 long oldId = Binder.clearCallingIdentity(); 17209 try { 17210 Process.setProcessGroup(app.pid, app.curSchedGroup); 17211 } catch (Exception e) { 17212 Slog.w(TAG, "Failed setting process group of " + app.pid 17213 + " to " + app.curSchedGroup); 17214 e.printStackTrace(); 17215 } finally { 17216 Binder.restoreCallingIdentity(oldId); 17217 } 17218 } else { 17219 if (app.thread != null) { 17220 try { 17221 app.thread.setSchedulingGroup(app.curSchedGroup); 17222 } catch (RemoteException e) { 17223 } 17224 } 17225 } 17226 Process.setSwappiness(app.pid, 17227 app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE); 17228 } 17229 } 17230 if (app.repForegroundActivities != app.foregroundActivities) { 17231 app.repForegroundActivities = app.foregroundActivities; 17232 changes |= ProcessChangeItem.CHANGE_ACTIVITIES; 17233 } 17234 if (app.repProcState != app.curProcState) { 17235 app.repProcState = app.curProcState; 17236 changes |= ProcessChangeItem.CHANGE_PROCESS_STATE; 17237 if (app.thread != null) { 17238 try { 17239 if (false) { 17240 //RuntimeException h = new RuntimeException("here"); 17241 Slog.i(TAG, "Sending new process state " + app.repProcState 17242 + " to " + app /*, h*/); 17243 } 17244 app.thread.setProcessState(app.repProcState); 17245 } catch (RemoteException e) { 17246 } 17247 } 17248 } 17249 if (app.setProcState < 0 || ProcessList.procStatesDifferForMem(app.curProcState, 17250 app.setProcState)) { 17251 app.lastStateTime = now; 17252 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 17253 isSleeping(), now); 17254 if (DEBUG_PSS) Slog.d(TAG, "Process state change from " 17255 + ProcessList.makeProcStateString(app.setProcState) + " to " 17256 + ProcessList.makeProcStateString(app.curProcState) + " next pss in " 17257 + (app.nextPssTime-now) + ": " + app); 17258 } else { 17259 if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL) 17260 && now > (app.lastStateTime+ProcessList.PSS_MIN_TIME_FROM_STATE_CHANGE))) { 17261 requestPssLocked(app, app.setProcState); 17262 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false, 17263 isSleeping(), now); 17264 } else if (false && DEBUG_PSS) { 17265 Slog.d(TAG, "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now)); 17266 } 17267 } 17268 if (app.setProcState != app.curProcState) { 17269 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17270 "Proc state change of " + app.processName 17271 + " to " + app.curProcState); 17272 boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE; 17273 boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE; 17274 if (setImportant && !curImportant) { 17275 // This app is no longer something we consider important enough to allow to 17276 // use arbitrary amounts of battery power. Note 17277 // its current wake lock time to later know to kill it if 17278 // it is not behaving well. 17279 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 17280 synchronized (stats) { 17281 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid, 17282 app.pid, SystemClock.elapsedRealtime()); 17283 } 17284 app.lastCpuTime = app.curCpuTime; 17285 17286 } 17287 app.setProcState = app.curProcState; 17288 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 17289 app.notCachedSinceIdle = false; 17290 } 17291 if (!doingAll) { 17292 setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now); 17293 } else { 17294 app.procStateChanged = true; 17295 } 17296 } 17297 17298 if (changes != 0) { 17299 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes); 17300 int i = mPendingProcessChanges.size()-1; 17301 ProcessChangeItem item = null; 17302 while (i >= 0) { 17303 item = mPendingProcessChanges.get(i); 17304 if (item.pid == app.pid) { 17305 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item); 17306 break; 17307 } 17308 i--; 17309 } 17310 if (i < 0) { 17311 // No existing item in pending changes; need a new one. 17312 final int NA = mAvailProcessChanges.size(); 17313 if (NA > 0) { 17314 item = mAvailProcessChanges.remove(NA-1); 17315 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item); 17316 } else { 17317 item = new ProcessChangeItem(); 17318 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item); 17319 } 17320 item.changes = 0; 17321 item.pid = app.pid; 17322 item.uid = app.info.uid; 17323 if (mPendingProcessChanges.size() == 0) { 17324 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, 17325 "*** Enqueueing dispatch processes changed!"); 17326 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget(); 17327 } 17328 mPendingProcessChanges.add(item); 17329 } 17330 item.changes |= changes; 17331 item.processState = app.repProcState; 17332 item.foregroundActivities = app.repForegroundActivities; 17333 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item " 17334 + Integer.toHexString(System.identityHashCode(item)) 17335 + " " + app.toShortString() + ": changes=" + item.changes 17336 + " procState=" + item.processState 17337 + " foreground=" + item.foregroundActivities 17338 + " type=" + app.adjType + " source=" + app.adjSource 17339 + " target=" + app.adjTarget); 17340 } 17341 17342 return success; 17343 } 17344 17345 private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) { 17346 if (proc.thread != null) { 17347 if (proc.baseProcessTracker != null) { 17348 proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList); 17349 } 17350 if (proc.repProcState >= 0) { 17351 mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid, 17352 proc.repProcState); 17353 } 17354 } 17355 } 17356 17357 private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj, 17358 ProcessRecord TOP_APP, boolean doingAll, long now) { 17359 if (app.thread == null) { 17360 return false; 17361 } 17362 17363 computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now); 17364 17365 return applyOomAdjLocked(app, TOP_APP, doingAll, now); 17366 } 17367 17368 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 17369 boolean oomAdj) { 17370 if (isForeground != proc.foregroundServices) { 17371 proc.foregroundServices = isForeground; 17372 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 17373 proc.info.uid); 17374 if (isForeground) { 17375 if (curProcs == null) { 17376 curProcs = new ArrayList<ProcessRecord>(); 17377 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 17378 } 17379 if (!curProcs.contains(proc)) { 17380 curProcs.add(proc); 17381 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 17382 proc.info.packageName, proc.info.uid); 17383 } 17384 } else { 17385 if (curProcs != null) { 17386 if (curProcs.remove(proc)) { 17387 mBatteryStatsService.noteEvent( 17388 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 17389 proc.info.packageName, proc.info.uid); 17390 if (curProcs.size() <= 0) { 17391 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 17392 } 17393 } 17394 } 17395 } 17396 if (oomAdj) { 17397 updateOomAdjLocked(); 17398 } 17399 } 17400 } 17401 17402 private final ActivityRecord resumedAppLocked() { 17403 ActivityRecord act = mStackSupervisor.resumedAppLocked(); 17404 String pkg; 17405 int uid; 17406 if (act != null) { 17407 pkg = act.packageName; 17408 uid = act.info.applicationInfo.uid; 17409 } else { 17410 pkg = null; 17411 uid = -1; 17412 } 17413 // Has the UID or resumed package name changed? 17414 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 17415 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 17416 if (mCurResumedPackage != null) { 17417 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 17418 mCurResumedPackage, mCurResumedUid); 17419 } 17420 mCurResumedPackage = pkg; 17421 mCurResumedUid = uid; 17422 if (mCurResumedPackage != null) { 17423 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 17424 mCurResumedPackage, mCurResumedUid); 17425 } 17426 } 17427 return act; 17428 } 17429 17430 final boolean updateOomAdjLocked(ProcessRecord app) { 17431 final ActivityRecord TOP_ACT = resumedAppLocked(); 17432 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 17433 final boolean wasCached = app.cached; 17434 17435 mAdjSeq++; 17436 17437 // This is the desired cached adjusment we want to tell it to use. 17438 // If our app is currently cached, we know it, and that is it. Otherwise, 17439 // we don't know it yet, and it needs to now be cached we will then 17440 // need to do a complete oom adj. 17441 final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ 17442 ? app.curRawAdj : ProcessList.UNKNOWN_ADJ; 17443 boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false, 17444 SystemClock.uptimeMillis()); 17445 if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) { 17446 // Changed to/from cached state, so apps after it in the LRU 17447 // list may also be changed. 17448 updateOomAdjLocked(); 17449 } 17450 return success; 17451 } 17452 17453 final void updateOomAdjLocked() { 17454 final ActivityRecord TOP_ACT = resumedAppLocked(); 17455 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 17456 final long now = SystemClock.uptimeMillis(); 17457 final long oldTime = now - ProcessList.MAX_EMPTY_TIME; 17458 final int N = mLruProcesses.size(); 17459 17460 if (false) { 17461 RuntimeException e = new RuntimeException(); 17462 e.fillInStackTrace(); 17463 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e); 17464 } 17465 17466 mAdjSeq++; 17467 mNewNumServiceProcs = 0; 17468 mNewNumAServiceProcs = 0; 17469 17470 final int emptyProcessLimit; 17471 final int cachedProcessLimit; 17472 if (mProcessLimit <= 0) { 17473 emptyProcessLimit = cachedProcessLimit = 0; 17474 } else if (mProcessLimit == 1) { 17475 emptyProcessLimit = 1; 17476 cachedProcessLimit = 0; 17477 } else { 17478 emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit); 17479 cachedProcessLimit = mProcessLimit - emptyProcessLimit; 17480 } 17481 17482 // Let's determine how many processes we have running vs. 17483 // how many slots we have for background processes; we may want 17484 // to put multiple processes in a slot of there are enough of 17485 // them. 17486 int numSlots = (ProcessList.CACHED_APP_MAX_ADJ 17487 - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2; 17488 int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs; 17489 if (numEmptyProcs > cachedProcessLimit) { 17490 // If there are more empty processes than our limit on cached 17491 // processes, then use the cached process limit for the factor. 17492 // This ensures that the really old empty processes get pushed 17493 // down to the bottom, so if we are running low on memory we will 17494 // have a better chance at keeping around more cached processes 17495 // instead of a gazillion empty processes. 17496 numEmptyProcs = cachedProcessLimit; 17497 } 17498 int emptyFactor = numEmptyProcs/numSlots; 17499 if (emptyFactor < 1) emptyFactor = 1; 17500 int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots; 17501 if (cachedFactor < 1) cachedFactor = 1; 17502 int stepCached = 0; 17503 int stepEmpty = 0; 17504 int numCached = 0; 17505 int numEmpty = 0; 17506 int numTrimming = 0; 17507 17508 mNumNonCachedProcs = 0; 17509 mNumCachedHiddenProcs = 0; 17510 17511 // First update the OOM adjustment for each of the 17512 // application processes based on their current state. 17513 int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ; 17514 int nextCachedAdj = curCachedAdj+1; 17515 int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ; 17516 int nextEmptyAdj = curEmptyAdj+2; 17517 for (int i=N-1; i>=0; i--) { 17518 ProcessRecord app = mLruProcesses.get(i); 17519 if (!app.killedByAm && app.thread != null) { 17520 app.procStateChanged = false; 17521 computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now); 17522 17523 // If we haven't yet assigned the final cached adj 17524 // to the process, do that now. 17525 if (app.curAdj >= ProcessList.UNKNOWN_ADJ) { 17526 switch (app.curProcState) { 17527 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 17528 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 17529 // This process is a cached process holding activities... 17530 // assign it the next cached value for that type, and then 17531 // step that cached level. 17532 app.curRawAdj = curCachedAdj; 17533 app.curAdj = app.modifyRawOomAdj(curCachedAdj); 17534 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning activity LRU #" + i 17535 + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj 17536 + ")"); 17537 if (curCachedAdj != nextCachedAdj) { 17538 stepCached++; 17539 if (stepCached >= cachedFactor) { 17540 stepCached = 0; 17541 curCachedAdj = nextCachedAdj; 17542 nextCachedAdj += 2; 17543 if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) { 17544 nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ; 17545 } 17546 } 17547 } 17548 break; 17549 default: 17550 // For everything else, assign next empty cached process 17551 // level and bump that up. Note that this means that 17552 // long-running services that have dropped down to the 17553 // cached level will be treated as empty (since their process 17554 // state is still as a service), which is what we want. 17555 app.curRawAdj = curEmptyAdj; 17556 app.curAdj = app.modifyRawOomAdj(curEmptyAdj); 17557 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning empty LRU #" + i 17558 + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj 17559 + ")"); 17560 if (curEmptyAdj != nextEmptyAdj) { 17561 stepEmpty++; 17562 if (stepEmpty >= emptyFactor) { 17563 stepEmpty = 0; 17564 curEmptyAdj = nextEmptyAdj; 17565 nextEmptyAdj += 2; 17566 if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) { 17567 nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ; 17568 } 17569 } 17570 } 17571 break; 17572 } 17573 } 17574 17575 applyOomAdjLocked(app, TOP_APP, true, now); 17576 17577 // Count the number of process types. 17578 switch (app.curProcState) { 17579 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 17580 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 17581 mNumCachedHiddenProcs++; 17582 numCached++; 17583 if (numCached > cachedProcessLimit) { 17584 app.kill("cached #" + numCached, true); 17585 } 17586 break; 17587 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 17588 if (numEmpty > ProcessList.TRIM_EMPTY_APPS 17589 && app.lastActivityTime < oldTime) { 17590 app.kill("empty for " 17591 + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime) 17592 / 1000) + "s", true); 17593 } else { 17594 numEmpty++; 17595 if (numEmpty > emptyProcessLimit) { 17596 app.kill("empty #" + numEmpty, true); 17597 } 17598 } 17599 break; 17600 default: 17601 mNumNonCachedProcs++; 17602 break; 17603 } 17604 17605 if (app.isolated && app.services.size() <= 0) { 17606 // If this is an isolated process, and there are no 17607 // services running in it, then the process is no longer 17608 // needed. We agressively kill these because we can by 17609 // definition not re-use the same process again, and it is 17610 // good to avoid having whatever code was running in them 17611 // left sitting around after no longer needed. 17612 app.kill("isolated not needed", true); 17613 } 17614 17615 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 17616 && !app.killedByAm) { 17617 numTrimming++; 17618 } 17619 } 17620 } 17621 17622 mNumServiceProcs = mNewNumServiceProcs; 17623 17624 // Now determine the memory trimming level of background processes. 17625 // Unfortunately we need to start at the back of the list to do this 17626 // properly. We only do this if the number of background apps we 17627 // are managing to keep around is less than half the maximum we desire; 17628 // if we are keeping a good number around, we'll let them use whatever 17629 // memory they want. 17630 final int numCachedAndEmpty = numCached + numEmpty; 17631 int memFactor; 17632 if (numCached <= ProcessList.TRIM_CACHED_APPS 17633 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) { 17634 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) { 17635 memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL; 17636 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) { 17637 memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW; 17638 } else { 17639 memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE; 17640 } 17641 } else { 17642 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 17643 } 17644 // We always allow the memory level to go up (better). We only allow it to go 17645 // down if we are in a state where that is allowed, *and* the total number of processes 17646 // has gone down since last time. 17647 if (DEBUG_OOM_ADJ) Slog.d(TAG, "oom: memFactor=" + memFactor + " last=" + mLastMemoryLevel 17648 + " allowLow=" + mAllowLowerMemLevel + " numProcs=" + mLruProcesses.size() 17649 + " last=" + mLastNumProcesses); 17650 if (memFactor > mLastMemoryLevel) { 17651 if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) { 17652 memFactor = mLastMemoryLevel; 17653 if (DEBUG_OOM_ADJ) Slog.d(TAG, "Keeping last mem factor!"); 17654 } 17655 } 17656 mLastMemoryLevel = memFactor; 17657 mLastNumProcesses = mLruProcesses.size(); 17658 boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now); 17659 final int trackerMemFactor = mProcessStats.getMemFactorLocked(); 17660 if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) { 17661 if (mLowRamStartTime == 0) { 17662 mLowRamStartTime = now; 17663 } 17664 int step = 0; 17665 int fgTrimLevel; 17666 switch (memFactor) { 17667 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 17668 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 17669 break; 17670 case ProcessStats.ADJ_MEM_FACTOR_LOW: 17671 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 17672 break; 17673 default: 17674 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 17675 break; 17676 } 17677 int factor = numTrimming/3; 17678 int minFactor = 2; 17679 if (mHomeProcess != null) minFactor++; 17680 if (mPreviousProcess != null) minFactor++; 17681 if (factor < minFactor) factor = minFactor; 17682 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 17683 for (int i=N-1; i>=0; i--) { 17684 ProcessRecord app = mLruProcesses.get(i); 17685 if (allChanged || app.procStateChanged) { 17686 setProcessTrackerStateLocked(app, trackerMemFactor, now); 17687 app.procStateChanged = false; 17688 } 17689 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 17690 && !app.killedByAm) { 17691 if (app.trimMemoryLevel < curLevel && app.thread != null) { 17692 try { 17693 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17694 "Trimming memory of " + app.processName 17695 + " to " + curLevel); 17696 app.thread.scheduleTrimMemory(curLevel); 17697 } catch (RemoteException e) { 17698 } 17699 if (false) { 17700 // For now we won't do this; our memory trimming seems 17701 // to be good enough at this point that destroying 17702 // activities causes more harm than good. 17703 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE 17704 && app != mHomeProcess && app != mPreviousProcess) { 17705 // Need to do this on its own message because the stack may not 17706 // be in a consistent state at this point. 17707 // For these apps we will also finish their activities 17708 // to help them free memory. 17709 mStackSupervisor.scheduleDestroyAllActivities(app, "trim"); 17710 } 17711 } 17712 } 17713 app.trimMemoryLevel = curLevel; 17714 step++; 17715 if (step >= factor) { 17716 step = 0; 17717 switch (curLevel) { 17718 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: 17719 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 17720 break; 17721 case ComponentCallbacks2.TRIM_MEMORY_MODERATE: 17722 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 17723 break; 17724 } 17725 } 17726 } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 17727 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND 17728 && app.thread != null) { 17729 try { 17730 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17731 "Trimming memory of heavy-weight " + app.processName 17732 + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 17733 app.thread.scheduleTrimMemory( 17734 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 17735 } catch (RemoteException e) { 17736 } 17737 } 17738 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 17739 } else { 17740 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 17741 || app.systemNoUi) && app.pendingUiClean) { 17742 // If this application is now in the background and it 17743 // had done UI, then give it the special trim level to 17744 // have it free UI resources. 17745 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 17746 if (app.trimMemoryLevel < level && app.thread != null) { 17747 try { 17748 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17749 "Trimming memory of bg-ui " + app.processName 17750 + " to " + level); 17751 app.thread.scheduleTrimMemory(level); 17752 } catch (RemoteException e) { 17753 } 17754 } 17755 app.pendingUiClean = false; 17756 } 17757 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) { 17758 try { 17759 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17760 "Trimming memory of fg " + app.processName 17761 + " to " + fgTrimLevel); 17762 app.thread.scheduleTrimMemory(fgTrimLevel); 17763 } catch (RemoteException e) { 17764 } 17765 } 17766 app.trimMemoryLevel = fgTrimLevel; 17767 } 17768 } 17769 } else { 17770 if (mLowRamStartTime != 0) { 17771 mLowRamTimeSinceLastIdle += now - mLowRamStartTime; 17772 mLowRamStartTime = 0; 17773 } 17774 for (int i=N-1; i>=0; i--) { 17775 ProcessRecord app = mLruProcesses.get(i); 17776 if (allChanged || app.procStateChanged) { 17777 setProcessTrackerStateLocked(app, trackerMemFactor, now); 17778 app.procStateChanged = false; 17779 } 17780 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 17781 || app.systemNoUi) && app.pendingUiClean) { 17782 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN 17783 && app.thread != null) { 17784 try { 17785 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 17786 "Trimming memory of ui hidden " + app.processName 17787 + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 17788 app.thread.scheduleTrimMemory( 17789 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 17790 } catch (RemoteException e) { 17791 } 17792 } 17793 app.pendingUiClean = false; 17794 } 17795 app.trimMemoryLevel = 0; 17796 } 17797 } 17798 17799 if (mAlwaysFinishActivities) { 17800 // Need to do this on its own message because the stack may not 17801 // be in a consistent state at this point. 17802 mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish"); 17803 } 17804 17805 if (allChanged) { 17806 requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered()); 17807 } 17808 17809 if (mProcessStats.shouldWriteNowLocked(now)) { 17810 mHandler.post(new Runnable() { 17811 @Override public void run() { 17812 synchronized (ActivityManagerService.this) { 17813 mProcessStats.writeStateAsyncLocked(); 17814 } 17815 } 17816 }); 17817 } 17818 17819 if (DEBUG_OOM_ADJ) { 17820 if (false) { 17821 RuntimeException here = new RuntimeException("here"); 17822 here.fillInStackTrace(); 17823 Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms", here); 17824 } else { 17825 Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms"); 17826 } 17827 } 17828 } 17829 17830 final void trimApplications() { 17831 synchronized (this) { 17832 int i; 17833 17834 // First remove any unused application processes whose package 17835 // has been removed. 17836 for (i=mRemovedProcesses.size()-1; i>=0; i--) { 17837 final ProcessRecord app = mRemovedProcesses.get(i); 17838 if (app.activities.size() == 0 17839 && app.curReceiver == null && app.services.size() == 0) { 17840 Slog.i( 17841 TAG, "Exiting empty application process " 17842 + app.processName + " (" 17843 + (app.thread != null ? app.thread.asBinder() : null) 17844 + ")\n"); 17845 if (app.pid > 0 && app.pid != MY_PID) { 17846 app.kill("empty", false); 17847 } else { 17848 try { 17849 app.thread.scheduleExit(); 17850 } catch (Exception e) { 17851 // Ignore exceptions. 17852 } 17853 } 17854 cleanUpApplicationRecordLocked(app, false, true, -1); 17855 mRemovedProcesses.remove(i); 17856 17857 if (app.persistent) { 17858 addAppLocked(app.info, false, null /* ABI override */); 17859 } 17860 } 17861 } 17862 17863 // Now update the oom adj for all processes. 17864 updateOomAdjLocked(); 17865 } 17866 } 17867 17868 /** This method sends the specified signal to each of the persistent apps */ 17869 public void signalPersistentProcesses(int sig) throws RemoteException { 17870 if (sig != Process.SIGNAL_USR1) { 17871 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 17872 } 17873 17874 synchronized (this) { 17875 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 17876 != PackageManager.PERMISSION_GRANTED) { 17877 throw new SecurityException("Requires permission " 17878 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 17879 } 17880 17881 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 17882 ProcessRecord r = mLruProcesses.get(i); 17883 if (r.thread != null && r.persistent) { 17884 Process.sendSignal(r.pid, sig); 17885 } 17886 } 17887 } 17888 } 17889 17890 private void stopProfilerLocked(ProcessRecord proc, int profileType) { 17891 if (proc == null || proc == mProfileProc) { 17892 proc = mProfileProc; 17893 profileType = mProfileType; 17894 clearProfilerLocked(); 17895 } 17896 if (proc == null) { 17897 return; 17898 } 17899 try { 17900 proc.thread.profilerControl(false, null, profileType); 17901 } catch (RemoteException e) { 17902 throw new IllegalStateException("Process disappeared"); 17903 } 17904 } 17905 17906 private void clearProfilerLocked() { 17907 if (mProfileFd != null) { 17908 try { 17909 mProfileFd.close(); 17910 } catch (IOException e) { 17911 } 17912 } 17913 mProfileApp = null; 17914 mProfileProc = null; 17915 mProfileFile = null; 17916 mProfileType = 0; 17917 mAutoStopProfiler = false; 17918 mSamplingInterval = 0; 17919 } 17920 17921 public boolean profileControl(String process, int userId, boolean start, 17922 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 17923 17924 try { 17925 synchronized (this) { 17926 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17927 // its own permission. 17928 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17929 != PackageManager.PERMISSION_GRANTED) { 17930 throw new SecurityException("Requires permission " 17931 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17932 } 17933 17934 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 17935 throw new IllegalArgumentException("null profile info or fd"); 17936 } 17937 17938 ProcessRecord proc = null; 17939 if (process != null) { 17940 proc = findProcessLocked(process, userId, "profileControl"); 17941 } 17942 17943 if (start && (proc == null || proc.thread == null)) { 17944 throw new IllegalArgumentException("Unknown process: " + process); 17945 } 17946 17947 if (start) { 17948 stopProfilerLocked(null, 0); 17949 setProfileApp(proc.info, proc.processName, profilerInfo); 17950 mProfileProc = proc; 17951 mProfileType = profileType; 17952 ParcelFileDescriptor fd = profilerInfo.profileFd; 17953 try { 17954 fd = fd.dup(); 17955 } catch (IOException e) { 17956 fd = null; 17957 } 17958 profilerInfo.profileFd = fd; 17959 proc.thread.profilerControl(start, profilerInfo, profileType); 17960 fd = null; 17961 mProfileFd = null; 17962 } else { 17963 stopProfilerLocked(proc, profileType); 17964 if (profilerInfo != null && profilerInfo.profileFd != null) { 17965 try { 17966 profilerInfo.profileFd.close(); 17967 } catch (IOException e) { 17968 } 17969 } 17970 } 17971 17972 return true; 17973 } 17974 } catch (RemoteException e) { 17975 throw new IllegalStateException("Process disappeared"); 17976 } finally { 17977 if (profilerInfo != null && profilerInfo.profileFd != null) { 17978 try { 17979 profilerInfo.profileFd.close(); 17980 } catch (IOException e) { 17981 } 17982 } 17983 } 17984 } 17985 17986 private ProcessRecord findProcessLocked(String process, int userId, String callName) { 17987 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17988 userId, true, ALLOW_FULL_ONLY, callName, null); 17989 ProcessRecord proc = null; 17990 try { 17991 int pid = Integer.parseInt(process); 17992 synchronized (mPidsSelfLocked) { 17993 proc = mPidsSelfLocked.get(pid); 17994 } 17995 } catch (NumberFormatException e) { 17996 } 17997 17998 if (proc == null) { 17999 ArrayMap<String, SparseArray<ProcessRecord>> all 18000 = mProcessNames.getMap(); 18001 SparseArray<ProcessRecord> procs = all.get(process); 18002 if (procs != null && procs.size() > 0) { 18003 proc = procs.valueAt(0); 18004 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 18005 for (int i=1; i<procs.size(); i++) { 18006 ProcessRecord thisProc = procs.valueAt(i); 18007 if (thisProc.userId == userId) { 18008 proc = thisProc; 18009 break; 18010 } 18011 } 18012 } 18013 } 18014 } 18015 18016 return proc; 18017 } 18018 18019 public boolean dumpHeap(String process, int userId, boolean managed, 18020 String path, ParcelFileDescriptor fd) throws RemoteException { 18021 18022 try { 18023 synchronized (this) { 18024 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 18025 // its own permission (same as profileControl). 18026 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 18027 != PackageManager.PERMISSION_GRANTED) { 18028 throw new SecurityException("Requires permission " 18029 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 18030 } 18031 18032 if (fd == null) { 18033 throw new IllegalArgumentException("null fd"); 18034 } 18035 18036 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap"); 18037 if (proc == null || proc.thread == null) { 18038 throw new IllegalArgumentException("Unknown process: " + process); 18039 } 18040 18041 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 18042 if (!isDebuggable) { 18043 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 18044 throw new SecurityException("Process not debuggable: " + proc); 18045 } 18046 } 18047 18048 proc.thread.dumpHeap(managed, path, fd); 18049 fd = null; 18050 return true; 18051 } 18052 } catch (RemoteException e) { 18053 throw new IllegalStateException("Process disappeared"); 18054 } finally { 18055 if (fd != null) { 18056 try { 18057 fd.close(); 18058 } catch (IOException e) { 18059 } 18060 } 18061 } 18062 } 18063 18064 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ 18065 public void monitor() { 18066 synchronized (this) { } 18067 } 18068 18069 void onCoreSettingsChange(Bundle settings) { 18070 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 18071 ProcessRecord processRecord = mLruProcesses.get(i); 18072 try { 18073 if (processRecord.thread != null) { 18074 processRecord.thread.setCoreSettings(settings); 18075 } 18076 } catch (RemoteException re) { 18077 /* ignore */ 18078 } 18079 } 18080 } 18081 18082 // Multi-user methods 18083 18084 /** 18085 * Start user, if its not already running, but don't bring it to foreground. 18086 */ 18087 @Override 18088 public boolean startUserInBackground(final int userId) { 18089 return startUser(userId, /* foreground */ false); 18090 } 18091 18092 /** 18093 * Start user, if its not already running, and bring it to foreground. 18094 */ 18095 boolean startUserInForeground(final int userId, Dialog dlg) { 18096 boolean result = startUser(userId, /* foreground */ true); 18097 dlg.dismiss(); 18098 return result; 18099 } 18100 18101 /** 18102 * Refreshes the list of users related to the current user when either a 18103 * user switch happens or when a new related user is started in the 18104 * background. 18105 */ 18106 private void updateCurrentProfileIdsLocked() { 18107 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18108 mCurrentUserId, false /* enabledOnly */); 18109 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null 18110 for (int i = 0; i < currentProfileIds.length; i++) { 18111 currentProfileIds[i] = profiles.get(i).id; 18112 } 18113 mCurrentProfileIds = currentProfileIds; 18114 18115 synchronized (mUserProfileGroupIdsSelfLocked) { 18116 mUserProfileGroupIdsSelfLocked.clear(); 18117 final List<UserInfo> users = getUserManagerLocked().getUsers(false); 18118 for (int i = 0; i < users.size(); i++) { 18119 UserInfo user = users.get(i); 18120 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 18121 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId); 18122 } 18123 } 18124 } 18125 } 18126 18127 private Set getProfileIdsLocked(int userId) { 18128 Set userIds = new HashSet<Integer>(); 18129 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18130 userId, false /* enabledOnly */); 18131 for (UserInfo user : profiles) { 18132 userIds.add(Integer.valueOf(user.id)); 18133 } 18134 return userIds; 18135 } 18136 18137 @Override 18138 public boolean switchUser(final int userId) { 18139 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 18140 String userName; 18141 synchronized (this) { 18142 UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 18143 if (userInfo == null) { 18144 Slog.w(TAG, "No user info for user #" + userId); 18145 return false; 18146 } 18147 if (userInfo.isManagedProfile()) { 18148 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 18149 return false; 18150 } 18151 userName = userInfo.name; 18152 mTargetUserId = userId; 18153 } 18154 mHandler.removeMessages(START_USER_SWITCH_MSG); 18155 mHandler.sendMessage(mHandler.obtainMessage(START_USER_SWITCH_MSG, userId, 0, userName)); 18156 return true; 18157 } 18158 18159 private void showUserSwitchDialog(int userId, String userName) { 18160 // The dialog will show and then initiate the user switch by calling startUserInForeground 18161 Dialog d = new UserSwitchingDialog(this, mContext, userId, userName, 18162 true /* above system */); 18163 d.show(); 18164 } 18165 18166 private boolean startUser(final int userId, final boolean foreground) { 18167 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18168 != PackageManager.PERMISSION_GRANTED) { 18169 String msg = "Permission Denial: switchUser() from pid=" 18170 + Binder.getCallingPid() 18171 + ", uid=" + Binder.getCallingUid() 18172 + " requires " + INTERACT_ACROSS_USERS_FULL; 18173 Slog.w(TAG, msg); 18174 throw new SecurityException(msg); 18175 } 18176 18177 if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground); 18178 18179 final long ident = Binder.clearCallingIdentity(); 18180 try { 18181 synchronized (this) { 18182 final int oldUserId = mCurrentUserId; 18183 if (oldUserId == userId) { 18184 return true; 18185 } 18186 18187 mStackSupervisor.setLockTaskModeLocked(null, false); 18188 18189 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 18190 if (userInfo == null) { 18191 Slog.w(TAG, "No user info for user #" + userId); 18192 return false; 18193 } 18194 if (foreground && userInfo.isManagedProfile()) { 18195 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 18196 return false; 18197 } 18198 18199 if (foreground) { 18200 mWindowManager.startFreezingScreen(R.anim.screen_user_exit, 18201 R.anim.screen_user_enter); 18202 } 18203 18204 boolean needStart = false; 18205 18206 // If the user we are switching to is not currently started, then 18207 // we need to start it now. 18208 if (mStartedUsers.get(userId) == null) { 18209 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false)); 18210 updateStartedUserArrayLocked(); 18211 needStart = true; 18212 } 18213 18214 final Integer userIdInt = Integer.valueOf(userId); 18215 mUserLru.remove(userIdInt); 18216 mUserLru.add(userIdInt); 18217 18218 if (foreground) { 18219 mCurrentUserId = userId; 18220 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up 18221 updateCurrentProfileIdsLocked(); 18222 mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 18223 // Once the internal notion of the active user has switched, we lock the device 18224 // with the option to show the user switcher on the keyguard. 18225 mWindowManager.lockNow(null); 18226 } else { 18227 final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId); 18228 updateCurrentProfileIdsLocked(); 18229 mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 18230 mUserLru.remove(currentUserIdInt); 18231 mUserLru.add(currentUserIdInt); 18232 } 18233 18234 final UserStartedState uss = mStartedUsers.get(userId); 18235 18236 // Make sure user is in the started state. If it is currently 18237 // stopping, we need to knock that off. 18238 if (uss.mState == UserStartedState.STATE_STOPPING) { 18239 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 18240 // so we can just fairly silently bring the user back from 18241 // the almost-dead. 18242 uss.mState = UserStartedState.STATE_RUNNING; 18243 updateStartedUserArrayLocked(); 18244 needStart = true; 18245 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) { 18246 // This means ACTION_SHUTDOWN has been sent, so we will 18247 // need to treat this as a new boot of the user. 18248 uss.mState = UserStartedState.STATE_BOOTING; 18249 updateStartedUserArrayLocked(); 18250 needStart = true; 18251 } 18252 18253 if (uss.mState == UserStartedState.STATE_BOOTING) { 18254 // Booting up a new user, need to tell system services about it. 18255 // Note that this is on the same handler as scheduling of broadcasts, 18256 // which is important because it needs to go first. 18257 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0)); 18258 } 18259 18260 if (foreground) { 18261 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 18262 oldUserId)); 18263 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 18264 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 18265 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 18266 oldUserId, userId, uss)); 18267 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 18268 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 18269 } 18270 18271 if (needStart) { 18272 // Send USER_STARTED broadcast 18273 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 18274 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18275 | Intent.FLAG_RECEIVER_FOREGROUND); 18276 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18277 broadcastIntentLocked(null, null, intent, 18278 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18279 false, false, MY_PID, Process.SYSTEM_UID, userId); 18280 } 18281 18282 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) { 18283 if (userId != UserHandle.USER_OWNER) { 18284 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); 18285 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 18286 broadcastIntentLocked(null, null, intent, null, 18287 new IIntentReceiver.Stub() { 18288 public void performReceive(Intent intent, int resultCode, 18289 String data, Bundle extras, boolean ordered, 18290 boolean sticky, int sendingUser) { 18291 onUserInitialized(uss, foreground, oldUserId, userId); 18292 } 18293 }, 0, null, null, null, AppOpsManager.OP_NONE, 18294 true, false, MY_PID, Process.SYSTEM_UID, 18295 userId); 18296 uss.initializing = true; 18297 } else { 18298 getUserManagerLocked().makeInitialized(userInfo.id); 18299 } 18300 } 18301 18302 if (foreground) { 18303 if (!uss.initializing) { 18304 moveUserToForeground(uss, oldUserId, userId); 18305 } 18306 } else { 18307 mStackSupervisor.startBackgroundUserLocked(userId, uss); 18308 } 18309 18310 if (needStart) { 18311 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 18312 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18313 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18314 broadcastIntentLocked(null, null, intent, 18315 null, new IIntentReceiver.Stub() { 18316 @Override 18317 public void performReceive(Intent intent, int resultCode, String data, 18318 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 18319 throws RemoteException { 18320 } 18321 }, 0, null, null, 18322 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 18323 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18324 } 18325 } 18326 } finally { 18327 Binder.restoreCallingIdentity(ident); 18328 } 18329 18330 return true; 18331 } 18332 18333 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) { 18334 long ident = Binder.clearCallingIdentity(); 18335 try { 18336 Intent intent; 18337 if (oldUserId >= 0) { 18338 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user 18339 List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false); 18340 int count = profiles.size(); 18341 for (int i = 0; i < count; i++) { 18342 int profileUserId = profiles.get(i).id; 18343 intent = new Intent(Intent.ACTION_USER_BACKGROUND); 18344 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18345 | Intent.FLAG_RECEIVER_FOREGROUND); 18346 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 18347 broadcastIntentLocked(null, null, intent, 18348 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18349 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 18350 } 18351 } 18352 if (newUserId >= 0) { 18353 // Send USER_FOREGROUND broadcast to all profiles of the incoming user 18354 List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false); 18355 int count = profiles.size(); 18356 for (int i = 0; i < count; i++) { 18357 int profileUserId = profiles.get(i).id; 18358 intent = new Intent(Intent.ACTION_USER_FOREGROUND); 18359 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18360 | Intent.FLAG_RECEIVER_FOREGROUND); 18361 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 18362 broadcastIntentLocked(null, null, intent, 18363 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 18364 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 18365 } 18366 intent = new Intent(Intent.ACTION_USER_SWITCHED); 18367 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 18368 | Intent.FLAG_RECEIVER_FOREGROUND); 18369 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId); 18370 broadcastIntentLocked(null, null, intent, 18371 null, null, 0, null, null, 18372 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE, 18373 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18374 } 18375 } finally { 18376 Binder.restoreCallingIdentity(ident); 18377 } 18378 } 18379 18380 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId, 18381 final int newUserId) { 18382 final int N = mUserSwitchObservers.beginBroadcast(); 18383 if (N > 0) { 18384 final IRemoteCallback callback = new IRemoteCallback.Stub() { 18385 int mCount = 0; 18386 @Override 18387 public void sendResult(Bundle data) throws RemoteException { 18388 synchronized (ActivityManagerService.this) { 18389 if (mCurUserSwitchCallback == this) { 18390 mCount++; 18391 if (mCount == N) { 18392 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18393 } 18394 } 18395 } 18396 } 18397 }; 18398 synchronized (this) { 18399 uss.switching = true; 18400 mCurUserSwitchCallback = callback; 18401 } 18402 for (int i=0; i<N; i++) { 18403 try { 18404 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching( 18405 newUserId, callback); 18406 } catch (RemoteException e) { 18407 } 18408 } 18409 } else { 18410 synchronized (this) { 18411 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18412 } 18413 } 18414 mUserSwitchObservers.finishBroadcast(); 18415 } 18416 18417 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 18418 synchronized (this) { 18419 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId); 18420 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 18421 } 18422 } 18423 18424 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) { 18425 mCurUserSwitchCallback = null; 18426 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 18427 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG, 18428 oldUserId, newUserId, uss)); 18429 } 18430 18431 void onUserInitialized(UserStartedState uss, boolean foreground, int oldUserId, int newUserId) { 18432 synchronized (this) { 18433 if (foreground) { 18434 moveUserToForeground(uss, oldUserId, newUserId); 18435 } 18436 } 18437 18438 completeSwitchAndInitalize(uss, newUserId, true, false); 18439 } 18440 18441 void moveUserToForeground(UserStartedState uss, int oldUserId, int newUserId) { 18442 boolean homeInFront = mStackSupervisor.switchUserLocked(newUserId, uss); 18443 if (homeInFront) { 18444 startHomeActivityLocked(newUserId); 18445 } else { 18446 mStackSupervisor.resumeTopActivitiesLocked(); 18447 } 18448 EventLogTags.writeAmSwitchUser(newUserId); 18449 getUserManagerLocked().userForeground(newUserId); 18450 sendUserSwitchBroadcastsLocked(oldUserId, newUserId); 18451 } 18452 18453 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 18454 completeSwitchAndInitalize(uss, newUserId, false, true); 18455 } 18456 18457 void completeSwitchAndInitalize(UserStartedState uss, int newUserId, 18458 boolean clearInitializing, boolean clearSwitching) { 18459 boolean unfrozen = false; 18460 synchronized (this) { 18461 if (clearInitializing) { 18462 uss.initializing = false; 18463 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier()); 18464 } 18465 if (clearSwitching) { 18466 uss.switching = false; 18467 } 18468 if (!uss.switching && !uss.initializing) { 18469 mWindowManager.stopFreezingScreen(); 18470 unfrozen = true; 18471 } 18472 } 18473 if (unfrozen) { 18474 final int N = mUserSwitchObservers.beginBroadcast(); 18475 for (int i=0; i<N; i++) { 18476 try { 18477 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId); 18478 } catch (RemoteException e) { 18479 } 18480 } 18481 mUserSwitchObservers.finishBroadcast(); 18482 } 18483 } 18484 18485 void scheduleStartProfilesLocked() { 18486 if (!mHandler.hasMessages(START_PROFILES_MSG)) { 18487 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG), 18488 DateUtils.SECOND_IN_MILLIS); 18489 } 18490 } 18491 18492 void startProfilesLocked() { 18493 if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked"); 18494 List<UserInfo> profiles = getUserManagerLocked().getProfiles( 18495 mCurrentUserId, false /* enabledOnly */); 18496 List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size()); 18497 for (UserInfo user : profiles) { 18498 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 18499 && user.id != mCurrentUserId) { 18500 toStart.add(user); 18501 } 18502 } 18503 final int n = toStart.size(); 18504 int i = 0; 18505 for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) { 18506 startUserInBackground(toStart.get(i).id); 18507 } 18508 if (i < n) { 18509 Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS"); 18510 } 18511 } 18512 18513 void finishUserBoot(UserStartedState uss) { 18514 synchronized (this) { 18515 if (uss.mState == UserStartedState.STATE_BOOTING 18516 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) { 18517 uss.mState = UserStartedState.STATE_RUNNING; 18518 final int userId = uss.mHandle.getIdentifier(); 18519 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 18520 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18521 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 18522 broadcastIntentLocked(null, null, intent, 18523 null, null, 0, null, null, 18524 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE, 18525 true, false, MY_PID, Process.SYSTEM_UID, userId); 18526 } 18527 } 18528 } 18529 18530 void finishUserSwitch(UserStartedState uss) { 18531 synchronized (this) { 18532 finishUserBoot(uss); 18533 18534 startProfilesLocked(); 18535 18536 int num = mUserLru.size(); 18537 int i = 0; 18538 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) { 18539 Integer oldUserId = mUserLru.get(i); 18540 UserStartedState oldUss = mStartedUsers.get(oldUserId); 18541 if (oldUss == null) { 18542 // Shouldn't happen, but be sane if it does. 18543 mUserLru.remove(i); 18544 num--; 18545 continue; 18546 } 18547 if (oldUss.mState == UserStartedState.STATE_STOPPING 18548 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) { 18549 // This user is already stopping, doesn't count. 18550 num--; 18551 i++; 18552 continue; 18553 } 18554 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) { 18555 // Owner and current can't be stopped, but count as running. 18556 i++; 18557 continue; 18558 } 18559 // This is a user to be stopped. 18560 stopUserLocked(oldUserId, null); 18561 num--; 18562 i++; 18563 } 18564 } 18565 } 18566 18567 @Override 18568 public int stopUser(final int userId, final IStopUserCallback callback) { 18569 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18570 != PackageManager.PERMISSION_GRANTED) { 18571 String msg = "Permission Denial: switchUser() from pid=" 18572 + Binder.getCallingPid() 18573 + ", uid=" + Binder.getCallingUid() 18574 + " requires " + INTERACT_ACROSS_USERS_FULL; 18575 Slog.w(TAG, msg); 18576 throw new SecurityException(msg); 18577 } 18578 if (userId <= 0) { 18579 throw new IllegalArgumentException("Can't stop primary user " + userId); 18580 } 18581 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 18582 synchronized (this) { 18583 return stopUserLocked(userId, callback); 18584 } 18585 } 18586 18587 private int stopUserLocked(final int userId, final IStopUserCallback callback) { 18588 if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId); 18589 if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) { 18590 return ActivityManager.USER_OP_IS_CURRENT; 18591 } 18592 18593 final UserStartedState uss = mStartedUsers.get(userId); 18594 if (uss == null) { 18595 // User is not started, nothing to do... but we do need to 18596 // callback if requested. 18597 if (callback != null) { 18598 mHandler.post(new Runnable() { 18599 @Override 18600 public void run() { 18601 try { 18602 callback.userStopped(userId); 18603 } catch (RemoteException e) { 18604 } 18605 } 18606 }); 18607 } 18608 return ActivityManager.USER_OP_SUCCESS; 18609 } 18610 18611 if (callback != null) { 18612 uss.mStopCallbacks.add(callback); 18613 } 18614 18615 if (uss.mState != UserStartedState.STATE_STOPPING 18616 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18617 uss.mState = UserStartedState.STATE_STOPPING; 18618 updateStartedUserArrayLocked(); 18619 18620 long ident = Binder.clearCallingIdentity(); 18621 try { 18622 // We are going to broadcast ACTION_USER_STOPPING and then 18623 // once that is done send a final ACTION_SHUTDOWN and then 18624 // stop the user. 18625 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING); 18626 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18627 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18628 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 18629 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 18630 // This is the result receiver for the final shutdown broadcast. 18631 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 18632 @Override 18633 public void performReceive(Intent intent, int resultCode, String data, 18634 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 18635 finishUserStop(uss); 18636 } 18637 }; 18638 // This is the result receiver for the initial stopping broadcast. 18639 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() { 18640 @Override 18641 public void performReceive(Intent intent, int resultCode, String data, 18642 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 18643 // On to the next. 18644 synchronized (ActivityManagerService.this) { 18645 if (uss.mState != UserStartedState.STATE_STOPPING) { 18646 // Whoops, we are being started back up. Abort, abort! 18647 return; 18648 } 18649 uss.mState = UserStartedState.STATE_SHUTDOWN; 18650 } 18651 mBatteryStatsService.noteEvent( 18652 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 18653 Integer.toString(userId), userId); 18654 mSystemServiceManager.stopUser(userId); 18655 broadcastIntentLocked(null, null, shutdownIntent, 18656 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE, 18657 true, false, MY_PID, Process.SYSTEM_UID, userId); 18658 } 18659 }; 18660 // Kick things off. 18661 broadcastIntentLocked(null, null, stoppingIntent, 18662 null, stoppingReceiver, 0, null, null, 18663 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 18664 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 18665 } finally { 18666 Binder.restoreCallingIdentity(ident); 18667 } 18668 } 18669 18670 return ActivityManager.USER_OP_SUCCESS; 18671 } 18672 18673 void finishUserStop(UserStartedState uss) { 18674 final int userId = uss.mHandle.getIdentifier(); 18675 boolean stopped; 18676 ArrayList<IStopUserCallback> callbacks; 18677 synchronized (this) { 18678 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks); 18679 if (mStartedUsers.get(userId) != uss) { 18680 stopped = false; 18681 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) { 18682 stopped = false; 18683 } else { 18684 stopped = true; 18685 // User can no longer run. 18686 mStartedUsers.remove(userId); 18687 mUserLru.remove(Integer.valueOf(userId)); 18688 updateStartedUserArrayLocked(); 18689 18690 // Clean up all state and processes associated with the user. 18691 // Kill all the processes for the user. 18692 forceStopUserLocked(userId, "finish user"); 18693 } 18694 18695 // Explicitly remove the old information in mRecentTasks. 18696 removeRecentTasksForUserLocked(userId); 18697 } 18698 18699 for (int i=0; i<callbacks.size(); i++) { 18700 try { 18701 if (stopped) callbacks.get(i).userStopped(userId); 18702 else callbacks.get(i).userStopAborted(userId); 18703 } catch (RemoteException e) { 18704 } 18705 } 18706 18707 if (stopped) { 18708 mSystemServiceManager.cleanupUser(userId); 18709 synchronized (this) { 18710 mStackSupervisor.removeUserLocked(userId); 18711 } 18712 } 18713 } 18714 18715 @Override 18716 public UserInfo getCurrentUser() { 18717 if ((checkCallingPermission(INTERACT_ACROSS_USERS) 18718 != PackageManager.PERMISSION_GRANTED) && ( 18719 checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18720 != PackageManager.PERMISSION_GRANTED)) { 18721 String msg = "Permission Denial: getCurrentUser() from pid=" 18722 + Binder.getCallingPid() 18723 + ", uid=" + Binder.getCallingUid() 18724 + " requires " + INTERACT_ACROSS_USERS; 18725 Slog.w(TAG, msg); 18726 throw new SecurityException(msg); 18727 } 18728 synchronized (this) { 18729 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 18730 return getUserManagerLocked().getUserInfo(userId); 18731 } 18732 } 18733 18734 int getCurrentUserIdLocked() { 18735 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 18736 } 18737 18738 @Override 18739 public boolean isUserRunning(int userId, boolean orStopped) { 18740 if (checkCallingPermission(INTERACT_ACROSS_USERS) 18741 != PackageManager.PERMISSION_GRANTED) { 18742 String msg = "Permission Denial: isUserRunning() from pid=" 18743 + Binder.getCallingPid() 18744 + ", uid=" + Binder.getCallingUid() 18745 + " requires " + INTERACT_ACROSS_USERS; 18746 Slog.w(TAG, msg); 18747 throw new SecurityException(msg); 18748 } 18749 synchronized (this) { 18750 return isUserRunningLocked(userId, orStopped); 18751 } 18752 } 18753 18754 boolean isUserRunningLocked(int userId, boolean orStopped) { 18755 UserStartedState state = mStartedUsers.get(userId); 18756 if (state == null) { 18757 return false; 18758 } 18759 if (orStopped) { 18760 return true; 18761 } 18762 return state.mState != UserStartedState.STATE_STOPPING 18763 && state.mState != UserStartedState.STATE_SHUTDOWN; 18764 } 18765 18766 @Override 18767 public int[] getRunningUserIds() { 18768 if (checkCallingPermission(INTERACT_ACROSS_USERS) 18769 != PackageManager.PERMISSION_GRANTED) { 18770 String msg = "Permission Denial: isUserRunning() from pid=" 18771 + Binder.getCallingPid() 18772 + ", uid=" + Binder.getCallingUid() 18773 + " requires " + INTERACT_ACROSS_USERS; 18774 Slog.w(TAG, msg); 18775 throw new SecurityException(msg); 18776 } 18777 synchronized (this) { 18778 return mStartedUserArray; 18779 } 18780 } 18781 18782 private void updateStartedUserArrayLocked() { 18783 int num = 0; 18784 for (int i=0; i<mStartedUsers.size(); i++) { 18785 UserStartedState uss = mStartedUsers.valueAt(i); 18786 // This list does not include stopping users. 18787 if (uss.mState != UserStartedState.STATE_STOPPING 18788 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18789 num++; 18790 } 18791 } 18792 mStartedUserArray = new int[num]; 18793 num = 0; 18794 for (int i=0; i<mStartedUsers.size(); i++) { 18795 UserStartedState uss = mStartedUsers.valueAt(i); 18796 if (uss.mState != UserStartedState.STATE_STOPPING 18797 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 18798 mStartedUserArray[num] = mStartedUsers.keyAt(i); 18799 num++; 18800 } 18801 } 18802 } 18803 18804 @Override 18805 public void registerUserSwitchObserver(IUserSwitchObserver observer) { 18806 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 18807 != PackageManager.PERMISSION_GRANTED) { 18808 String msg = "Permission Denial: registerUserSwitchObserver() from pid=" 18809 + Binder.getCallingPid() 18810 + ", uid=" + Binder.getCallingUid() 18811 + " requires " + INTERACT_ACROSS_USERS_FULL; 18812 Slog.w(TAG, msg); 18813 throw new SecurityException(msg); 18814 } 18815 18816 mUserSwitchObservers.register(observer); 18817 } 18818 18819 @Override 18820 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 18821 mUserSwitchObservers.unregister(observer); 18822 } 18823 18824 private boolean userExists(int userId) { 18825 if (userId == 0) { 18826 return true; 18827 } 18828 UserManagerService ums = getUserManagerLocked(); 18829 return ums != null ? (ums.getUserInfo(userId) != null) : false; 18830 } 18831 18832 int[] getUsersLocked() { 18833 UserManagerService ums = getUserManagerLocked(); 18834 return ums != null ? ums.getUserIds() : new int[] { 0 }; 18835 } 18836 18837 UserManagerService getUserManagerLocked() { 18838 if (mUserManager == null) { 18839 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 18840 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b); 18841 } 18842 return mUserManager; 18843 } 18844 18845 private int applyUserId(int uid, int userId) { 18846 return UserHandle.getUid(userId, uid); 18847 } 18848 18849 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 18850 if (info == null) return null; 18851 ApplicationInfo newInfo = new ApplicationInfo(info); 18852 newInfo.uid = applyUserId(info.uid, userId); 18853 newInfo.dataDir = USER_DATA_DIR + userId + "/" 18854 + info.packageName; 18855 return newInfo; 18856 } 18857 18858 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 18859 if (aInfo == null 18860 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 18861 return aInfo; 18862 } 18863 18864 ActivityInfo info = new ActivityInfo(aInfo); 18865 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 18866 return info; 18867 } 18868 18869 private final class LocalService extends ActivityManagerInternal { 18870 @Override 18871 public void goingToSleep() { 18872 ActivityManagerService.this.goingToSleep(); 18873 } 18874 18875 @Override 18876 public void wakingUp() { 18877 ActivityManagerService.this.wakingUp(); 18878 } 18879 18880 @Override 18881 public int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 18882 String processName, String abiOverride, int uid, Runnable crashHandler) { 18883 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 18884 processName, abiOverride, uid, crashHandler); 18885 } 18886 } 18887 18888 /** 18889 * An implementation of IAppTask, that allows an app to manage its own tasks via 18890 * {@link android.app.ActivityManager.AppTask}. We keep track of the callingUid to ensure that 18891 * only the process that calls getAppTasks() can call the AppTask methods. 18892 */ 18893 class AppTaskImpl extends IAppTask.Stub { 18894 private int mTaskId; 18895 private int mCallingUid; 18896 18897 public AppTaskImpl(int taskId, int callingUid) { 18898 mTaskId = taskId; 18899 mCallingUid = callingUid; 18900 } 18901 18902 private void checkCaller() { 18903 if (mCallingUid != Binder.getCallingUid()) { 18904 throw new SecurityException("Caller " + mCallingUid 18905 + " does not match caller of getAppTasks(): " + Binder.getCallingUid()); 18906 } 18907 } 18908 18909 @Override 18910 public void finishAndRemoveTask() { 18911 checkCaller(); 18912 18913 synchronized (ActivityManagerService.this) { 18914 long origId = Binder.clearCallingIdentity(); 18915 try { 18916 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18917 if (tr == null) { 18918 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18919 } 18920 // Only kill the process if we are not a new document 18921 int flags = tr.getBaseIntent().getFlags(); 18922 boolean isDocument = (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) == 18923 Intent.FLAG_ACTIVITY_NEW_DOCUMENT; 18924 removeTaskByIdLocked(mTaskId, 18925 !isDocument ? ActivityManager.REMOVE_TASK_KILL_PROCESS : 0); 18926 } finally { 18927 Binder.restoreCallingIdentity(origId); 18928 } 18929 } 18930 } 18931 18932 @Override 18933 public ActivityManager.RecentTaskInfo getTaskInfo() { 18934 checkCaller(); 18935 18936 synchronized (ActivityManagerService.this) { 18937 long origId = Binder.clearCallingIdentity(); 18938 try { 18939 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18940 if (tr == null) { 18941 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18942 } 18943 return createRecentTaskInfoFromTaskRecord(tr); 18944 } finally { 18945 Binder.restoreCallingIdentity(origId); 18946 } 18947 } 18948 } 18949 18950 @Override 18951 public void moveToFront() { 18952 checkCaller(); 18953 18954 final TaskRecord tr; 18955 synchronized (ActivityManagerService.this) { 18956 tr = recentTaskForIdLocked(mTaskId); 18957 if (tr == null) { 18958 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18959 } 18960 if (tr.getRootActivity() != null) { 18961 moveTaskToFrontLocked(tr.taskId, 0, null); 18962 } 18963 } 18964 18965 startActivityFromRecentsInner(tr.taskId, null); 18966 } 18967 18968 @Override 18969 public int startActivity(IBinder whoThread, String callingPackage, 18970 Intent intent, String resolvedType, Bundle options) { 18971 checkCaller(); 18972 18973 int callingUser = UserHandle.getCallingUserId(); 18974 TaskRecord tr; 18975 IApplicationThread appThread; 18976 synchronized (ActivityManagerService.this) { 18977 tr = recentTaskForIdLocked(mTaskId); 18978 if (tr == null) { 18979 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 18980 } 18981 appThread = ApplicationThreadNative.asInterface(whoThread); 18982 if (appThread == null) { 18983 throw new IllegalArgumentException("Bad app thread " + appThread); 18984 } 18985 } 18986 return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent, 18987 resolvedType, null, null, null, null, 0, 0, null, null, 18988 null, options, callingUser, null, tr); 18989 } 18990 18991 @Override 18992 public void setExcludeFromRecents(boolean exclude) { 18993 checkCaller(); 18994 18995 synchronized (ActivityManagerService.this) { 18996 long origId = Binder.clearCallingIdentity(); 18997 try { 18998 TaskRecord tr = recentTaskForIdLocked(mTaskId); 18999 if (tr == null) { 19000 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 19001 } 19002 Intent intent = tr.getBaseIntent(); 19003 if (exclude) { 19004 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 19005 } else { 19006 intent.setFlags(intent.getFlags() 19007 & ~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 19008 } 19009 } finally { 19010 Binder.restoreCallingIdentity(origId); 19011 } 19012 } 19013 } 19014 } 19015} 19016