ActivityManagerService.java revision 504d78ea10b04baee2a1a65707dc7003c94d1ee4
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.IActivityContainer; 37import android.app.IActivityContainerCallback; 38import android.app.IAppTask; 39import android.app.admin.DevicePolicyManager; 40import android.app.usage.UsageStats; 41import android.app.usage.UsageStatsManagerInternal; 42import android.appwidget.AppWidgetManager; 43import android.graphics.Rect; 44import android.os.BatteryStats; 45import android.os.PersistableBundle; 46import android.service.voice.IVoiceInteractionSession; 47import android.util.ArrayMap; 48import android.util.ArraySet; 49import android.util.SparseIntArray; 50 51import com.android.internal.R; 52import com.android.internal.annotations.GuardedBy; 53import com.android.internal.app.IAppOpsService; 54import com.android.internal.app.IVoiceInteractor; 55import com.android.internal.app.ProcessMap; 56import com.android.internal.app.ProcessStats; 57import com.android.internal.content.PackageMonitor; 58import com.android.internal.os.BackgroundThread; 59import com.android.internal.os.BatteryStatsImpl; 60import com.android.internal.os.ProcessCpuTracker; 61import com.android.internal.os.TransferPipe; 62import com.android.internal.os.Zygote; 63import com.android.internal.util.FastPrintWriter; 64import com.android.internal.util.FastXmlSerializer; 65import com.android.internal.util.MemInfoReader; 66import com.android.internal.util.Preconditions; 67import com.android.server.AppOpsService; 68import com.android.server.AttributeCache; 69import com.android.server.IntentResolver; 70import com.android.server.LocalServices; 71import com.android.server.ServiceThread; 72import com.android.server.SystemService; 73import com.android.server.SystemServiceManager; 74import com.android.server.Watchdog; 75import com.android.server.am.ActivityStack.ActivityState; 76import com.android.server.firewall.IntentFirewall; 77import com.android.server.pm.UserManagerService; 78import com.android.server.wm.AppTransition; 79import com.android.server.wm.WindowManagerService; 80import com.google.android.collect.Lists; 81import com.google.android.collect.Maps; 82 83import libcore.io.IoUtils; 84 85import org.xmlpull.v1.XmlPullParser; 86import org.xmlpull.v1.XmlPullParserException; 87import org.xmlpull.v1.XmlSerializer; 88 89import android.app.Activity; 90import android.app.ActivityManager; 91import android.app.ActivityManager.RunningTaskInfo; 92import android.app.ActivityManager.StackInfo; 93import android.app.ActivityManagerInternal; 94import android.app.ActivityManagerNative; 95import android.app.ActivityOptions; 96import android.app.ActivityThread; 97import android.app.AlertDialog; 98import android.app.AppGlobals; 99import android.app.ApplicationErrorReport; 100import android.app.Dialog; 101import android.app.IActivityController; 102import android.app.IApplicationThread; 103import android.app.IInstrumentationWatcher; 104import android.app.INotificationManager; 105import android.app.IProcessObserver; 106import android.app.IServiceConnection; 107import android.app.IStopUserCallback; 108import android.app.IUiAutomationConnection; 109import android.app.IUserSwitchObserver; 110import android.app.Instrumentation; 111import android.app.Notification; 112import android.app.NotificationManager; 113import android.app.PendingIntent; 114import android.app.backup.IBackupManager; 115import android.content.ActivityNotFoundException; 116import android.content.BroadcastReceiver; 117import android.content.ClipData; 118import android.content.ComponentCallbacks2; 119import android.content.ComponentName; 120import android.content.ContentProvider; 121import android.content.ContentResolver; 122import android.content.Context; 123import android.content.DialogInterface; 124import android.content.IContentProvider; 125import android.content.IIntentReceiver; 126import android.content.IIntentSender; 127import android.content.Intent; 128import android.content.IntentFilter; 129import android.content.IntentSender; 130import android.content.pm.ActivityInfo; 131import android.content.pm.ApplicationInfo; 132import android.content.pm.ConfigurationInfo; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageManager; 135import android.content.pm.InstrumentationInfo; 136import android.content.pm.PackageInfo; 137import android.content.pm.PackageManager; 138import android.content.pm.ParceledListSlice; 139import android.content.pm.UserInfo; 140import android.content.pm.PackageManager.NameNotFoundException; 141import android.content.pm.PathPermission; 142import android.content.pm.ProviderInfo; 143import android.content.pm.ResolveInfo; 144import android.content.pm.ServiceInfo; 145import android.content.res.CompatibilityInfo; 146import android.content.res.Configuration; 147import android.net.Proxy; 148import android.net.ProxyInfo; 149import android.net.Uri; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Debug; 154import android.os.DropBoxManager; 155import android.os.Environment; 156import android.os.FactoryTest; 157import android.os.FileObserver; 158import android.os.FileUtils; 159import android.os.Handler; 160import android.os.IBinder; 161import android.os.IPermissionController; 162import android.os.IRemoteCallback; 163import android.os.IUserManager; 164import android.os.Looper; 165import android.os.Message; 166import android.os.Parcel; 167import android.os.ParcelFileDescriptor; 168import android.os.Process; 169import android.os.RemoteCallbackList; 170import android.os.RemoteException; 171import android.os.SELinux; 172import android.os.ServiceManager; 173import android.os.StrictMode; 174import android.os.SystemClock; 175import android.os.SystemProperties; 176import android.os.UpdateLock; 177import android.os.UserHandle; 178import android.provider.Settings; 179import android.text.format.DateUtils; 180import android.text.format.Time; 181import android.util.AtomicFile; 182import android.util.EventLog; 183import android.util.Log; 184import android.util.Pair; 185import android.util.PrintWriterPrinter; 186import android.util.Slog; 187import android.util.SparseArray; 188import android.util.TimeUtils; 189import android.util.Xml; 190import android.view.Gravity; 191import android.view.LayoutInflater; 192import android.view.View; 193import android.view.WindowManager; 194 195import java.io.BufferedInputStream; 196import java.io.BufferedOutputStream; 197import java.io.DataInputStream; 198import java.io.DataOutputStream; 199import java.io.File; 200import java.io.FileDescriptor; 201import java.io.FileInputStream; 202import java.io.FileNotFoundException; 203import java.io.FileOutputStream; 204import java.io.IOException; 205import java.io.InputStreamReader; 206import java.io.PrintWriter; 207import java.io.StringWriter; 208import java.lang.ref.WeakReference; 209import java.util.ArrayList; 210import java.util.Arrays; 211import java.util.Collections; 212import java.util.Comparator; 213import java.util.HashMap; 214import java.util.HashSet; 215import java.util.Iterator; 216import java.util.List; 217import java.util.Locale; 218import java.util.Map; 219import java.util.Set; 220import java.util.concurrent.atomic.AtomicBoolean; 221import java.util.concurrent.atomic.AtomicLong; 222 223public final class ActivityManagerService extends ActivityManagerNative 224 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 225 226 private static final String USER_DATA_DIR = "/data/user/"; 227 // File that stores last updated system version and called preboot receivers 228 static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat"; 229 230 static final String TAG = "ActivityManager"; 231 static final String TAG_MU = "ActivityManagerServiceMU"; 232 static final boolean DEBUG = false; 233 static final boolean localLOGV = DEBUG; 234 static final boolean DEBUG_BACKUP = localLOGV || false; 235 static final boolean DEBUG_BROADCAST = localLOGV || false; 236 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false; 237 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false; 238 static final boolean DEBUG_CLEANUP = localLOGV || false; 239 static final boolean DEBUG_CONFIGURATION = localLOGV || false; 240 static final boolean DEBUG_FOCUS = false; 241 static final boolean DEBUG_IMMERSIVE = localLOGV || false; 242 static final boolean DEBUG_MU = localLOGV || false; 243 static final boolean DEBUG_OOM_ADJ = localLOGV || false; 244 static final boolean DEBUG_LRU = localLOGV || false; 245 static final boolean DEBUG_PAUSE = localLOGV || false; 246 static final boolean DEBUG_POWER = localLOGV || false; 247 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false; 248 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false; 249 static final boolean DEBUG_PROCESSES = localLOGV || false; 250 static final boolean DEBUG_PROVIDER = localLOGV || false; 251 static final boolean DEBUG_RESULTS = localLOGV || false; 252 static final boolean DEBUG_SERVICE = localLOGV || false; 253 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false; 254 static final boolean DEBUG_STACK = localLOGV || false; 255 static final boolean DEBUG_SWITCH = localLOGV || false; 256 static final boolean DEBUG_TASKS = localLOGV || false; 257 static final boolean DEBUG_THUMBNAILS = localLOGV || false; 258 static final boolean DEBUG_TRANSITION = localLOGV || false; 259 static final boolean DEBUG_URI_PERMISSION = localLOGV || false; 260 static final boolean DEBUG_USER_LEAVING = localLOGV || false; 261 static final boolean DEBUG_VISBILITY = localLOGV || false; 262 static final boolean DEBUG_PSS = localLOGV || false; 263 static final boolean DEBUG_LOCKSCREEN = localLOGV || false; 264 static final boolean VALIDATE_TOKENS = false; 265 static final boolean SHOW_ACTIVITY_START_TIME = true; 266 267 // Control over CPU and battery monitoring. 268 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes. 269 static final boolean MONITOR_CPU_USAGE = true; 270 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds. 271 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample. 272 static final boolean MONITOR_THREAD_CPU_USAGE = false; 273 274 // The flags that are set for all calls we make to the package manager. 275 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 276 277 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 278 279 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 280 281 // Maximum number of recent tasks that we can remember. 282 static final int MAX_RECENT_TASKS = ActivityManager.isLowRamDeviceStatic() ? 100 : 200; 283 284 // Maximum number recent bitmaps to keep in memory. 285 static final int MAX_RECENT_BITMAPS = 5; 286 287 // Amount of time after a call to stopAppSwitches() during which we will 288 // prevent further untrusted switches from happening. 289 static final long APP_SWITCH_DELAY_TIME = 5*1000; 290 291 // How long we wait for a launched process to attach to the activity manager 292 // before we decide it's never going to come up for real. 293 static final int PROC_START_TIMEOUT = 10*1000; 294 295 // How long we wait for a launched process to attach to the activity manager 296 // before we decide it's never going to come up for real, when the process was 297 // started with a wrapper for instrumentation (such as Valgrind) because it 298 // could take much longer than usual. 299 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 300 301 // How long to wait after going idle before forcing apps to GC. 302 static final int GC_TIMEOUT = 5*1000; 303 304 // The minimum amount of time between successive GC requests for a process. 305 static final int GC_MIN_INTERVAL = 60*1000; 306 307 // The minimum amount of time between successive PSS requests for a process. 308 static final int FULL_PSS_MIN_INTERVAL = 10*60*1000; 309 310 // The minimum amount of time between successive PSS requests for a process 311 // when the request is due to the memory state being lowered. 312 static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000; 313 314 // The rate at which we check for apps using excessive power -- 15 mins. 315 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 316 317 // The minimum sample duration we will allow before deciding we have 318 // enough data on wake locks to start killing things. 319 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 320 321 // The minimum sample duration we will allow before deciding we have 322 // enough data on CPU usage to start killing things. 323 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 324 325 // How long we allow a receiver to run before giving up on it. 326 static final int BROADCAST_FG_TIMEOUT = 10*1000; 327 static final int BROADCAST_BG_TIMEOUT = 60*1000; 328 329 // How long we wait until we timeout on key dispatching. 330 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 331 332 // How long we wait until we timeout on key dispatching during instrumentation. 333 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 334 335 // Amount of time we wait for observers to handle a user switch before 336 // giving up on them and unfreezing the screen. 337 static final int USER_SWITCH_TIMEOUT = 2*1000; 338 339 // Maximum number of users we allow to be running at a time. 340 static final int MAX_RUNNING_USERS = 3; 341 342 // How long to wait in getAssistContextExtras for the activity and foreground services 343 // to respond with the result. 344 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500; 345 346 // Maximum number of persisted Uri grants a package is allowed 347 static final int MAX_PERSISTED_URI_GRANTS = 128; 348 349 static final int MY_PID = Process.myPid(); 350 351 static final String[] EMPTY_STRING_ARRAY = new String[0]; 352 353 // How many bytes to write into the dropbox log before truncating 354 static final int DROPBOX_MAX_SIZE = 256 * 1024; 355 356 // Access modes for handleIncomingUser. 357 static final int ALLOW_NON_FULL = 0; 358 static final int ALLOW_NON_FULL_IN_PROFILE = 1; 359 static final int ALLOW_FULL_ONLY = 2; 360 361 static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000; 362 363 /** All system services */ 364 SystemServiceManager mSystemServiceManager; 365 366 /** Run all ActivityStacks through this */ 367 ActivityStackSupervisor mStackSupervisor; 368 369 public IntentFirewall mIntentFirewall; 370 371 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 372 // default actuion automatically. Important for devices without direct input 373 // devices. 374 private boolean mShowDialogs = true; 375 376 BroadcastQueue mFgBroadcastQueue; 377 BroadcastQueue mBgBroadcastQueue; 378 // Convenient for easy iteration over the queues. Foreground is first 379 // so that dispatch of foreground broadcasts gets precedence. 380 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 381 382 BroadcastQueue broadcastQueueForIntent(Intent intent) { 383 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 384 if (DEBUG_BACKGROUND_BROADCAST) { 385 Slog.i(TAG, "Broadcast intent " + intent + " on " 386 + (isFg ? "foreground" : "background") 387 + " queue"); 388 } 389 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 390 } 391 392 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) { 393 for (BroadcastQueue queue : mBroadcastQueues) { 394 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver); 395 if (r != null) { 396 return r; 397 } 398 } 399 return null; 400 } 401 402 /** 403 * Activity we have told the window manager to have key focus. 404 */ 405 ActivityRecord mFocusedActivity = null; 406 407 /** 408 * List of intents that were used to start the most recent tasks. 409 */ 410 ArrayList<TaskRecord> mRecentTasks; 411 ArraySet<TaskRecord> mTmpRecents = new ArraySet<TaskRecord>(); 412 413 public class PendingAssistExtras extends Binder implements Runnable { 414 public final ActivityRecord activity; 415 public boolean haveResult = false; 416 public Bundle result = null; 417 public PendingAssistExtras(ActivityRecord _activity) { 418 activity = _activity; 419 } 420 @Override 421 public void run() { 422 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity); 423 synchronized (this) { 424 haveResult = true; 425 notifyAll(); 426 } 427 } 428 } 429 430 final ArrayList<PendingAssistExtras> mPendingAssistExtras 431 = new ArrayList<PendingAssistExtras>(); 432 433 /** 434 * Process management. 435 */ 436 final ProcessList mProcessList = new ProcessList(); 437 438 /** 439 * All of the applications we currently have running organized by name. 440 * The keys are strings of the application package name (as 441 * returned by the package manager), and the keys are ApplicationRecord 442 * objects. 443 */ 444 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 445 446 /** 447 * Tracking long-term execution of processes to look for abuse and other 448 * bad app behavior. 449 */ 450 final ProcessStatsService mProcessStats; 451 452 /** 453 * The currently running isolated processes. 454 */ 455 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 456 457 /** 458 * Counter for assigning isolated process uids, to avoid frequently reusing the 459 * same ones. 460 */ 461 int mNextIsolatedProcessUid = 0; 462 463 /** 464 * The currently running heavy-weight process, if any. 465 */ 466 ProcessRecord mHeavyWeightProcess = null; 467 468 /** 469 * The last time that various processes have crashed. 470 */ 471 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 472 473 /** 474 * Information about a process that is currently marked as bad. 475 */ 476 static final class BadProcessInfo { 477 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) { 478 this.time = time; 479 this.shortMsg = shortMsg; 480 this.longMsg = longMsg; 481 this.stack = stack; 482 } 483 484 final long time; 485 final String shortMsg; 486 final String longMsg; 487 final String stack; 488 } 489 490 /** 491 * Set of applications that we consider to be bad, and will reject 492 * incoming broadcasts from (which the user has no control over). 493 * Processes are added to this set when they have crashed twice within 494 * a minimum amount of time; they are removed from it when they are 495 * later restarted (hopefully due to some user action). The value is the 496 * time it was added to the list. 497 */ 498 final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>(); 499 500 /** 501 * All of the processes we currently have running organized by pid. 502 * The keys are the pid running the application. 503 * 504 * <p>NOTE: This object is protected by its own lock, NOT the global 505 * activity manager lock! 506 */ 507 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 508 509 /** 510 * All of the processes that have been forced to be foreground. The key 511 * is the pid of the caller who requested it (we hold a death 512 * link on it). 513 */ 514 abstract class ForegroundToken implements IBinder.DeathRecipient { 515 int pid; 516 IBinder token; 517 } 518 final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>(); 519 520 /** 521 * List of records for processes that someone had tried to start before the 522 * system was ready. We don't start them at that point, but ensure they 523 * are started by the time booting is complete. 524 */ 525 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 526 527 /** 528 * List of persistent applications that are in the process 529 * of being started. 530 */ 531 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 532 533 /** 534 * Processes that are being forcibly torn down. 535 */ 536 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 537 538 /** 539 * List of running applications, sorted by recent usage. 540 * The first entry in the list is the least recently used. 541 */ 542 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 543 544 /** 545 * Where in mLruProcesses that the processes hosting activities start. 546 */ 547 int mLruProcessActivityStart = 0; 548 549 /** 550 * Where in mLruProcesses that the processes hosting services start. 551 * This is after (lower index) than mLruProcessesActivityStart. 552 */ 553 int mLruProcessServiceStart = 0; 554 555 /** 556 * List of processes that should gc as soon as things are idle. 557 */ 558 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 559 560 /** 561 * Processes we want to collect PSS data from. 562 */ 563 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 564 565 /** 566 * Last time we requested PSS data of all processes. 567 */ 568 long mLastFullPssTime = SystemClock.uptimeMillis(); 569 570 /** 571 * If set, the next time we collect PSS data we should do a full collection 572 * with data from native processes and the kernel. 573 */ 574 boolean mFullPssPending = false; 575 576 /** 577 * This is the process holding what we currently consider to be 578 * the "home" activity. 579 */ 580 ProcessRecord mHomeProcess; 581 582 /** 583 * This is the process holding the activity the user last visited that 584 * is in a different process from the one they are currently in. 585 */ 586 ProcessRecord mPreviousProcess; 587 588 /** 589 * The time at which the previous process was last visible. 590 */ 591 long mPreviousProcessVisibleTime; 592 593 /** 594 * Which uses have been started, so are allowed to run code. 595 */ 596 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>(); 597 598 /** 599 * LRU list of history of current users. Most recently current is at the end. 600 */ 601 final ArrayList<Integer> mUserLru = new ArrayList<Integer>(); 602 603 /** 604 * Constant array of the users that are currently started. 605 */ 606 int[] mStartedUserArray = new int[] { 0 }; 607 608 /** 609 * Registered observers of the user switching mechanics. 610 */ 611 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 612 = new RemoteCallbackList<IUserSwitchObserver>(); 613 614 /** 615 * Currently active user switch. 616 */ 617 Object mCurUserSwitchCallback; 618 619 /** 620 * Packages that the user has asked to have run in screen size 621 * compatibility mode instead of filling the screen. 622 */ 623 final CompatModePackages mCompatModePackages; 624 625 /** 626 * Set of IntentSenderRecord objects that are currently active. 627 */ 628 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 629 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 630 631 /** 632 * Fingerprints (hashCode()) of stack traces that we've 633 * already logged DropBox entries for. Guarded by itself. If 634 * something (rogue user app) forces this over 635 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 636 */ 637 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 638 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 639 640 /** 641 * Strict Mode background batched logging state. 642 * 643 * The string buffer is guarded by itself, and its lock is also 644 * used to determine if another batched write is already 645 * in-flight. 646 */ 647 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 648 649 /** 650 * Keeps track of all IIntentReceivers that have been registered for 651 * broadcasts. Hash keys are the receiver IBinder, hash value is 652 * a ReceiverList. 653 */ 654 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = 655 new HashMap<IBinder, ReceiverList>(); 656 657 /** 658 * Resolver for broadcast intents to registered receivers. 659 * Holds BroadcastFilter (subclass of IntentFilter). 660 */ 661 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 662 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 663 @Override 664 protected boolean allowFilterResult( 665 BroadcastFilter filter, List<BroadcastFilter> dest) { 666 IBinder target = filter.receiverList.receiver.asBinder(); 667 for (int i=dest.size()-1; i>=0; i--) { 668 if (dest.get(i).receiverList.receiver.asBinder() == target) { 669 return false; 670 } 671 } 672 return true; 673 } 674 675 @Override 676 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 677 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 678 || userId == filter.owningUserId) { 679 return super.newResult(filter, match, userId); 680 } 681 return null; 682 } 683 684 @Override 685 protected BroadcastFilter[] newArray(int size) { 686 return new BroadcastFilter[size]; 687 } 688 689 @Override 690 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 691 return packageName.equals(filter.packageName); 692 } 693 }; 694 695 /** 696 * State of all active sticky broadcasts per user. Keys are the action of the 697 * sticky Intent, values are an ArrayList of all broadcasted intents with 698 * that action (which should usually be one). The SparseArray is keyed 699 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 700 * for stickies that are sent to all users. 701 */ 702 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 703 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 704 705 final ActiveServices mServices; 706 707 /** 708 * Backup/restore process management 709 */ 710 String mBackupAppName = null; 711 BackupRecord mBackupTarget = null; 712 713 final ProviderMap mProviderMap; 714 715 /** 716 * List of content providers who have clients waiting for them. The 717 * application is currently being launched and the provider will be 718 * removed from this list once it is published. 719 */ 720 final ArrayList<ContentProviderRecord> mLaunchingProviders 721 = new ArrayList<ContentProviderRecord>(); 722 723 /** 724 * File storing persisted {@link #mGrantedUriPermissions}. 725 */ 726 private final AtomicFile mGrantFile; 727 728 /** XML constants used in {@link #mGrantFile} */ 729 private static final String TAG_URI_GRANTS = "uri-grants"; 730 private static final String TAG_URI_GRANT = "uri-grant"; 731 private static final String ATTR_USER_HANDLE = "userHandle"; 732 private static final String ATTR_SOURCE_USER_ID = "sourceUserId"; 733 private static final String ATTR_TARGET_USER_ID = "targetUserId"; 734 private static final String ATTR_SOURCE_PKG = "sourcePkg"; 735 private static final String ATTR_TARGET_PKG = "targetPkg"; 736 private static final String ATTR_URI = "uri"; 737 private static final String ATTR_MODE_FLAGS = "modeFlags"; 738 private static final String ATTR_CREATED_TIME = "createdTime"; 739 private static final String ATTR_PREFIX = "prefix"; 740 741 /** 742 * Global set of specific {@link Uri} permissions that have been granted. 743 * This optimized lookup structure maps from {@link UriPermission#targetUid} 744 * to {@link UriPermission#uri} to {@link UriPermission}. 745 */ 746 @GuardedBy("this") 747 private final SparseArray<ArrayMap<GrantUri, UriPermission>> 748 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>(); 749 750 public static class GrantUri { 751 public final int sourceUserId; 752 public final Uri uri; 753 public boolean prefix; 754 755 public GrantUri(int sourceUserId, Uri uri, boolean prefix) { 756 this.sourceUserId = sourceUserId; 757 this.uri = uri; 758 this.prefix = prefix; 759 } 760 761 @Override 762 public int hashCode() { 763 return toString().hashCode(); 764 } 765 766 @Override 767 public boolean equals(Object o) { 768 if (o instanceof GrantUri) { 769 GrantUri other = (GrantUri) o; 770 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId) 771 && prefix == other.prefix; 772 } 773 return false; 774 } 775 776 @Override 777 public String toString() { 778 String result = Integer.toString(sourceUserId) + " @ " + uri.toString(); 779 if (prefix) result += " [prefix]"; 780 return result; 781 } 782 783 public String toSafeString() { 784 String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString(); 785 if (prefix) result += " [prefix]"; 786 return result; 787 } 788 789 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) { 790 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle), 791 ContentProvider.getUriWithoutUserId(uri), false); 792 } 793 } 794 795 CoreSettingsObserver mCoreSettingsObserver; 796 797 /** 798 * Thread-local storage used to carry caller permissions over through 799 * indirect content-provider access. 800 */ 801 private class Identity { 802 public int pid; 803 public int uid; 804 805 Identity(int _pid, int _uid) { 806 pid = _pid; 807 uid = _uid; 808 } 809 } 810 811 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 812 813 /** 814 * All information we have collected about the runtime performance of 815 * any user id that can impact battery performance. 816 */ 817 final BatteryStatsService mBatteryStatsService; 818 819 /** 820 * Information about component usage 821 */ 822 UsageStatsManagerInternal mUsageStatsService; 823 824 /** 825 * Information about and control over application operations 826 */ 827 final AppOpsService mAppOpsService; 828 829 /** 830 * Save recent tasks information across reboots. 831 */ 832 final TaskPersister mTaskPersister; 833 834 /** 835 * Current configuration information. HistoryRecord objects are given 836 * a reference to this object to indicate which configuration they are 837 * currently running in, so this object must be kept immutable. 838 */ 839 Configuration mConfiguration = new Configuration(); 840 841 /** 842 * Current sequencing integer of the configuration, for skipping old 843 * configurations. 844 */ 845 int mConfigurationSeq = 0; 846 847 /** 848 * Hardware-reported OpenGLES version. 849 */ 850 final int GL_ES_VERSION; 851 852 /** 853 * List of initialization arguments to pass to all processes when binding applications to them. 854 * For example, references to the commonly used services. 855 */ 856 HashMap<String, IBinder> mAppBindArgs; 857 858 /** 859 * Temporary to avoid allocations. Protected by main lock. 860 */ 861 final StringBuilder mStringBuilder = new StringBuilder(256); 862 863 /** 864 * Used to control how we initialize the service. 865 */ 866 ComponentName mTopComponent; 867 String mTopAction = Intent.ACTION_MAIN; 868 String mTopData; 869 boolean mProcessesReady = false; 870 boolean mSystemReady = false; 871 boolean mBooting = false; 872 boolean mWaitingUpdate = false; 873 boolean mDidUpdate = false; 874 boolean mOnBattery = false; 875 boolean mLaunchWarningShown = false; 876 877 Context mContext; 878 879 int mFactoryTest; 880 881 boolean mCheckedForSetup; 882 883 /** 884 * The time at which we will allow normal application switches again, 885 * after a call to {@link #stopAppSwitches()}. 886 */ 887 long mAppSwitchesAllowedTime; 888 889 /** 890 * This is set to true after the first switch after mAppSwitchesAllowedTime 891 * is set; any switches after that will clear the time. 892 */ 893 boolean mDidAppSwitch; 894 895 /** 896 * Last time (in realtime) at which we checked for power usage. 897 */ 898 long mLastPowerCheckRealtime; 899 900 /** 901 * Last time (in uptime) at which we checked for power usage. 902 */ 903 long mLastPowerCheckUptime; 904 905 /** 906 * Set while we are wanting to sleep, to prevent any 907 * activities from being started/resumed. 908 */ 909 private boolean mSleeping = false; 910 911 /** 912 * Set while we are running a voice interaction. This overrides 913 * sleeping while it is active. 914 */ 915 private boolean mRunningVoice = false; 916 917 /** 918 * State of external calls telling us if the device is asleep. 919 */ 920 private boolean mWentToSleep = false; 921 922 /** 923 * State of external call telling us if the lock screen is shown. 924 */ 925 private boolean mLockScreenShown = false; 926 927 /** 928 * Set if we are shutting down the system, similar to sleeping. 929 */ 930 boolean mShuttingDown = false; 931 932 /** 933 * Current sequence id for oom_adj computation traversal. 934 */ 935 int mAdjSeq = 0; 936 937 /** 938 * Current sequence id for process LRU updating. 939 */ 940 int mLruSeq = 0; 941 942 /** 943 * Keep track of the non-cached/empty process we last found, to help 944 * determine how to distribute cached/empty processes next time. 945 */ 946 int mNumNonCachedProcs = 0; 947 948 /** 949 * Keep track of the number of cached hidden procs, to balance oom adj 950 * distribution between those and empty procs. 951 */ 952 int mNumCachedHiddenProcs = 0; 953 954 /** 955 * Keep track of the number of service processes we last found, to 956 * determine on the next iteration which should be B services. 957 */ 958 int mNumServiceProcs = 0; 959 int mNewNumAServiceProcs = 0; 960 int mNewNumServiceProcs = 0; 961 962 /** 963 * Allow the current computed overall memory level of the system to go down? 964 * This is set to false when we are killing processes for reasons other than 965 * memory management, so that the now smaller process list will not be taken as 966 * an indication that memory is tighter. 967 */ 968 boolean mAllowLowerMemLevel = false; 969 970 /** 971 * The last computed memory level, for holding when we are in a state that 972 * processes are going away for other reasons. 973 */ 974 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 975 976 /** 977 * The last total number of process we have, to determine if changes actually look 978 * like a shrinking number of process due to lower RAM. 979 */ 980 int mLastNumProcesses; 981 982 /** 983 * The uptime of the last time we performed idle maintenance. 984 */ 985 long mLastIdleTime = SystemClock.uptimeMillis(); 986 987 /** 988 * Total time spent with RAM that has been added in the past since the last idle time. 989 */ 990 long mLowRamTimeSinceLastIdle = 0; 991 992 /** 993 * If RAM is currently low, when that horrible situation started. 994 */ 995 long mLowRamStartTime = 0; 996 997 /** 998 * For reporting to battery stats the current top application. 999 */ 1000 private String mCurResumedPackage = null; 1001 private int mCurResumedUid = -1; 1002 1003 /** 1004 * For reporting to battery stats the apps currently running foreground 1005 * service. The ProcessMap is package/uid tuples; each of these contain 1006 * an array of the currently foreground processes. 1007 */ 1008 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1009 = new ProcessMap<ArrayList<ProcessRecord>>(); 1010 1011 /** 1012 * This is set if we had to do a delayed dexopt of an app before launching 1013 * it, to increase the ANR timeouts in that case. 1014 */ 1015 boolean mDidDexOpt; 1016 1017 /** 1018 * Set if the systemServer made a call to enterSafeMode. 1019 */ 1020 boolean mSafeMode; 1021 1022 String mDebugApp = null; 1023 boolean mWaitForDebugger = false; 1024 boolean mDebugTransient = false; 1025 String mOrigDebugApp = null; 1026 boolean mOrigWaitForDebugger = false; 1027 boolean mAlwaysFinishActivities = false; 1028 IActivityController mController = null; 1029 String mProfileApp = null; 1030 ProcessRecord mProfileProc = null; 1031 String mProfileFile; 1032 ParcelFileDescriptor mProfileFd; 1033 int mProfileType = 0; 1034 boolean mAutoStopProfiler = false; 1035 String mOpenGlTraceApp = null; 1036 1037 static class ProcessChangeItem { 1038 static final int CHANGE_ACTIVITIES = 1<<0; 1039 static final int CHANGE_PROCESS_STATE = 1<<1; 1040 int changes; 1041 int uid; 1042 int pid; 1043 int processState; 1044 boolean foregroundActivities; 1045 } 1046 1047 final RemoteCallbackList<IProcessObserver> mProcessObservers 1048 = new RemoteCallbackList<IProcessObserver>(); 1049 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 1050 1051 final ArrayList<ProcessChangeItem> mPendingProcessChanges 1052 = new ArrayList<ProcessChangeItem>(); 1053 final ArrayList<ProcessChangeItem> mAvailProcessChanges 1054 = new ArrayList<ProcessChangeItem>(); 1055 1056 /** 1057 * Runtime CPU use collection thread. This object's lock is used to 1058 * protect all related state. 1059 */ 1060 final Thread mProcessCpuThread; 1061 1062 /** 1063 * Used to collect process stats when showing not responding dialog. 1064 * Protected by mProcessCpuThread. 1065 */ 1066 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 1067 MONITOR_THREAD_CPU_USAGE); 1068 final AtomicLong mLastCpuTime = new AtomicLong(0); 1069 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 1070 1071 long mLastWriteTime = 0; 1072 1073 /** 1074 * Used to retain an update lock when the foreground activity is in 1075 * immersive mode. 1076 */ 1077 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 1078 1079 /** 1080 * Set to true after the system has finished booting. 1081 */ 1082 boolean mBooted = false; 1083 1084 int mProcessLimit = ProcessList.MAX_CACHED_APPS; 1085 int mProcessLimitOverride = -1; 1086 1087 WindowManagerService mWindowManager; 1088 1089 final ActivityThread mSystemThread; 1090 1091 int mCurrentUserId = 0; 1092 int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack 1093 1094 /** 1095 * Mapping from each known user ID to the profile group ID it is associated with. 1096 */ 1097 SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray(); 1098 1099 private UserManagerService mUserManager; 1100 1101 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1102 final ProcessRecord mApp; 1103 final int mPid; 1104 final IApplicationThread mAppThread; 1105 1106 AppDeathRecipient(ProcessRecord app, int pid, 1107 IApplicationThread thread) { 1108 if (localLOGV) Slog.v( 1109 TAG, "New death recipient " + this 1110 + " for thread " + thread.asBinder()); 1111 mApp = app; 1112 mPid = pid; 1113 mAppThread = thread; 1114 } 1115 1116 @Override 1117 public void binderDied() { 1118 if (localLOGV) Slog.v( 1119 TAG, "Death received in " + this 1120 + " for thread " + mAppThread.asBinder()); 1121 synchronized(ActivityManagerService.this) { 1122 appDiedLocked(mApp, mPid, mAppThread); 1123 } 1124 } 1125 } 1126 1127 static final int SHOW_ERROR_MSG = 1; 1128 static final int SHOW_NOT_RESPONDING_MSG = 2; 1129 static final int SHOW_FACTORY_ERROR_MSG = 3; 1130 static final int UPDATE_CONFIGURATION_MSG = 4; 1131 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1132 static final int WAIT_FOR_DEBUGGER_MSG = 6; 1133 static final int SERVICE_TIMEOUT_MSG = 12; 1134 static final int UPDATE_TIME_ZONE = 13; 1135 static final int SHOW_UID_ERROR_MSG = 14; 1136 static final int IM_FEELING_LUCKY_MSG = 15; 1137 static final int PROC_START_TIMEOUT_MSG = 20; 1138 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 1139 static final int KILL_APPLICATION_MSG = 22; 1140 static final int FINALIZE_PENDING_INTENT_MSG = 23; 1141 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 1142 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 1143 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 1144 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 1145 static final int CLEAR_DNS_CACHE_MSG = 28; 1146 static final int UPDATE_HTTP_PROXY_MSG = 29; 1147 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 1148 static final int DISPATCH_PROCESSES_CHANGED = 31; 1149 static final int DISPATCH_PROCESS_DIED = 32; 1150 static final int REPORT_MEM_USAGE_MSG = 33; 1151 static final int REPORT_USER_SWITCH_MSG = 34; 1152 static final int CONTINUE_USER_SWITCH_MSG = 35; 1153 static final int USER_SWITCH_TIMEOUT_MSG = 36; 1154 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 1155 static final int PERSIST_URI_GRANTS_MSG = 38; 1156 static final int REQUEST_ALL_PSS_MSG = 39; 1157 static final int START_PROFILES_MSG = 40; 1158 static final int UPDATE_TIME = 41; 1159 static final int SYSTEM_USER_START_MSG = 42; 1160 static final int SYSTEM_USER_CURRENT_MSG = 43; 1161 static final int ENTER_ANIMATION_COMPLETE_MSG = 44; 1162 static final int ENABLE_SCREEN_AFTER_BOOT_MSG = 45; 1163 1164 static final int FIRST_ACTIVITY_STACK_MSG = 100; 1165 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1166 static final int FIRST_COMPAT_MODE_MSG = 300; 1167 static final int FIRST_SUPERVISOR_STACK_MSG = 100; 1168 1169 AlertDialog mUidAlert; 1170 CompatModeDialog mCompatModeDialog; 1171 long mLastMemUsageReportTime = 0; 1172 1173 private LockToAppRequestDialog mLockToAppRequest; 1174 1175 /** 1176 * Flag whether the current user is a "monkey", i.e. whether 1177 * the UI is driven by a UI automation tool. 1178 */ 1179 private boolean mUserIsMonkey; 1180 1181 /** Flag whether the device has a recents UI */ 1182 final boolean mHasRecents; 1183 1184 final ServiceThread mHandlerThread; 1185 final MainHandler mHandler; 1186 1187 final class MainHandler extends Handler { 1188 public MainHandler(Looper looper) { 1189 super(looper, null, true); 1190 } 1191 1192 @Override 1193 public void handleMessage(Message msg) { 1194 switch (msg.what) { 1195 case SHOW_ERROR_MSG: { 1196 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1197 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 1198 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 1199 synchronized (ActivityManagerService.this) { 1200 ProcessRecord proc = (ProcessRecord)data.get("app"); 1201 AppErrorResult res = (AppErrorResult) data.get("result"); 1202 if (proc != null && proc.crashDialog != null) { 1203 Slog.e(TAG, "App already has crash dialog: " + proc); 1204 if (res != null) { 1205 res.set(0); 1206 } 1207 return; 1208 } 1209 boolean isBackground = (UserHandle.getAppId(proc.uid) 1210 >= Process.FIRST_APPLICATION_UID 1211 && proc.pid != MY_PID); 1212 for (int userId : mCurrentProfileIds) { 1213 isBackground &= (proc.userId != userId); 1214 } 1215 if (isBackground && !showBackground) { 1216 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 1217 if (res != null) { 1218 res.set(0); 1219 } 1220 return; 1221 } 1222 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1223 Dialog d = new AppErrorDialog(mContext, 1224 ActivityManagerService.this, res, proc); 1225 d.show(); 1226 proc.crashDialog = d; 1227 } else { 1228 // The device is asleep, so just pretend that the user 1229 // saw a crash dialog and hit "force quit". 1230 if (res != null) { 1231 res.set(0); 1232 } 1233 } 1234 } 1235 1236 ensureBootCompleted(); 1237 } break; 1238 case SHOW_NOT_RESPONDING_MSG: { 1239 synchronized (ActivityManagerService.this) { 1240 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1241 ProcessRecord proc = (ProcessRecord)data.get("app"); 1242 if (proc != null && proc.anrDialog != null) { 1243 Slog.e(TAG, "App already has anr dialog: " + proc); 1244 return; 1245 } 1246 1247 Intent intent = new Intent("android.intent.action.ANR"); 1248 if (!mProcessesReady) { 1249 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1250 | Intent.FLAG_RECEIVER_FOREGROUND); 1251 } 1252 broadcastIntentLocked(null, null, intent, 1253 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1254 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 1255 1256 if (mShowDialogs) { 1257 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 1258 mContext, proc, (ActivityRecord)data.get("activity"), 1259 msg.arg1 != 0); 1260 d.show(); 1261 proc.anrDialog = d; 1262 } else { 1263 // Just kill the app if there is no dialog to be shown. 1264 killAppAtUsersRequest(proc, null); 1265 } 1266 } 1267 1268 ensureBootCompleted(); 1269 } break; 1270 case SHOW_STRICT_MODE_VIOLATION_MSG: { 1271 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1272 synchronized (ActivityManagerService.this) { 1273 ProcessRecord proc = (ProcessRecord) data.get("app"); 1274 if (proc == null) { 1275 Slog.e(TAG, "App not found when showing strict mode dialog."); 1276 break; 1277 } 1278 if (proc.crashDialog != null) { 1279 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1280 return; 1281 } 1282 AppErrorResult res = (AppErrorResult) data.get("result"); 1283 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1284 Dialog d = new StrictModeViolationDialog(mContext, 1285 ActivityManagerService.this, res, proc); 1286 d.show(); 1287 proc.crashDialog = d; 1288 } else { 1289 // The device is asleep, so just pretend that the user 1290 // saw a crash dialog and hit "force quit". 1291 res.set(0); 1292 } 1293 } 1294 ensureBootCompleted(); 1295 } break; 1296 case SHOW_FACTORY_ERROR_MSG: { 1297 Dialog d = new FactoryErrorDialog( 1298 mContext, msg.getData().getCharSequence("msg")); 1299 d.show(); 1300 ensureBootCompleted(); 1301 } break; 1302 case UPDATE_CONFIGURATION_MSG: { 1303 final ContentResolver resolver = mContext.getContentResolver(); 1304 Settings.System.putConfiguration(resolver, (Configuration)msg.obj); 1305 } break; 1306 case GC_BACKGROUND_PROCESSES_MSG: { 1307 synchronized (ActivityManagerService.this) { 1308 performAppGcsIfAppropriateLocked(); 1309 } 1310 } break; 1311 case WAIT_FOR_DEBUGGER_MSG: { 1312 synchronized (ActivityManagerService.this) { 1313 ProcessRecord app = (ProcessRecord)msg.obj; 1314 if (msg.arg1 != 0) { 1315 if (!app.waitedForDebugger) { 1316 Dialog d = new AppWaitingForDebuggerDialog( 1317 ActivityManagerService.this, 1318 mContext, app); 1319 app.waitDialog = d; 1320 app.waitedForDebugger = true; 1321 d.show(); 1322 } 1323 } else { 1324 if (app.waitDialog != null) { 1325 app.waitDialog.dismiss(); 1326 app.waitDialog = null; 1327 } 1328 } 1329 } 1330 } break; 1331 case SERVICE_TIMEOUT_MSG: { 1332 if (mDidDexOpt) { 1333 mDidDexOpt = false; 1334 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1335 nmsg.obj = msg.obj; 1336 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1337 return; 1338 } 1339 mServices.serviceTimeout((ProcessRecord)msg.obj); 1340 } break; 1341 case UPDATE_TIME_ZONE: { 1342 synchronized (ActivityManagerService.this) { 1343 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1344 ProcessRecord r = mLruProcesses.get(i); 1345 if (r.thread != null) { 1346 try { 1347 r.thread.updateTimeZone(); 1348 } catch (RemoteException ex) { 1349 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1350 } 1351 } 1352 } 1353 } 1354 } break; 1355 case CLEAR_DNS_CACHE_MSG: { 1356 synchronized (ActivityManagerService.this) { 1357 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1358 ProcessRecord r = mLruProcesses.get(i); 1359 if (r.thread != null) { 1360 try { 1361 r.thread.clearDnsCache(); 1362 } catch (RemoteException ex) { 1363 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1364 } 1365 } 1366 } 1367 } 1368 } break; 1369 case UPDATE_HTTP_PROXY_MSG: { 1370 ProxyInfo proxy = (ProxyInfo)msg.obj; 1371 String host = ""; 1372 String port = ""; 1373 String exclList = ""; 1374 Uri pacFileUrl = Uri.EMPTY; 1375 if (proxy != null) { 1376 host = proxy.getHost(); 1377 port = Integer.toString(proxy.getPort()); 1378 exclList = proxy.getExclusionListAsString(); 1379 pacFileUrl = proxy.getPacFileUrl(); 1380 } 1381 synchronized (ActivityManagerService.this) { 1382 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1383 ProcessRecord r = mLruProcesses.get(i); 1384 if (r.thread != null) { 1385 try { 1386 r.thread.setHttpProxy(host, port, exclList, pacFileUrl); 1387 } catch (RemoteException ex) { 1388 Slog.w(TAG, "Failed to update http proxy for: " + 1389 r.info.processName); 1390 } 1391 } 1392 } 1393 } 1394 } break; 1395 case SHOW_UID_ERROR_MSG: { 1396 String title = "System UIDs Inconsistent"; 1397 String text = "UIDs on the system are inconsistent, you need to wipe your" 1398 + " data partition or your device will be unstable."; 1399 Log.e(TAG, title + ": " + text); 1400 if (mShowDialogs) { 1401 // XXX This is a temporary dialog, no need to localize. 1402 AlertDialog d = new BaseErrorDialog(mContext); 1403 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1404 d.setCancelable(false); 1405 d.setTitle(title); 1406 d.setMessage(text); 1407 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky", 1408 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG)); 1409 mUidAlert = d; 1410 d.show(); 1411 } 1412 } break; 1413 case IM_FEELING_LUCKY_MSG: { 1414 if (mUidAlert != null) { 1415 mUidAlert.dismiss(); 1416 mUidAlert = null; 1417 } 1418 } break; 1419 case PROC_START_TIMEOUT_MSG: { 1420 if (mDidDexOpt) { 1421 mDidDexOpt = false; 1422 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1423 nmsg.obj = msg.obj; 1424 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1425 return; 1426 } 1427 ProcessRecord app = (ProcessRecord)msg.obj; 1428 synchronized (ActivityManagerService.this) { 1429 processStartTimedOutLocked(app); 1430 } 1431 } break; 1432 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1433 synchronized (ActivityManagerService.this) { 1434 mStackSupervisor.doPendingActivityLaunchesLocked(true); 1435 } 1436 } break; 1437 case KILL_APPLICATION_MSG: { 1438 synchronized (ActivityManagerService.this) { 1439 int appid = msg.arg1; 1440 boolean restart = (msg.arg2 == 1); 1441 Bundle bundle = (Bundle)msg.obj; 1442 String pkg = bundle.getString("pkg"); 1443 String reason = bundle.getString("reason"); 1444 forceStopPackageLocked(pkg, appid, restart, false, true, false, 1445 false, UserHandle.USER_ALL, reason); 1446 } 1447 } break; 1448 case FINALIZE_PENDING_INTENT_MSG: { 1449 ((PendingIntentRecord)msg.obj).completeFinalize(); 1450 } break; 1451 case POST_HEAVY_NOTIFICATION_MSG: { 1452 INotificationManager inm = NotificationManager.getService(); 1453 if (inm == null) { 1454 return; 1455 } 1456 1457 ActivityRecord root = (ActivityRecord)msg.obj; 1458 ProcessRecord process = root.app; 1459 if (process == null) { 1460 return; 1461 } 1462 1463 try { 1464 Context context = mContext.createPackageContext(process.info.packageName, 0); 1465 String text = mContext.getString(R.string.heavy_weight_notification, 1466 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1467 Notification notification = new Notification(); 1468 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon; 1469 notification.when = 0; 1470 notification.flags = Notification.FLAG_ONGOING_EVENT; 1471 notification.tickerText = text; 1472 notification.defaults = 0; // please be quiet 1473 notification.sound = null; 1474 notification.vibrate = null; 1475 notification.setLatestEventInfo(context, text, 1476 mContext.getText(R.string.heavy_weight_notification_detail), 1477 PendingIntent.getActivityAsUser(mContext, 0, root.intent, 1478 PendingIntent.FLAG_CANCEL_CURRENT, null, 1479 new UserHandle(root.userId))); 1480 1481 try { 1482 int[] outId = new int[1]; 1483 inm.enqueueNotificationWithTag("android", "android", null, 1484 R.string.heavy_weight_notification, 1485 notification, outId, root.userId); 1486 } catch (RuntimeException e) { 1487 Slog.w(ActivityManagerService.TAG, 1488 "Error showing notification for heavy-weight app", e); 1489 } catch (RemoteException e) { 1490 } 1491 } catch (NameNotFoundException e) { 1492 Slog.w(TAG, "Unable to create context for heavy notification", e); 1493 } 1494 } break; 1495 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1496 INotificationManager inm = NotificationManager.getService(); 1497 if (inm == null) { 1498 return; 1499 } 1500 try { 1501 inm.cancelNotificationWithTag("android", null, 1502 R.string.heavy_weight_notification, msg.arg1); 1503 } catch (RuntimeException e) { 1504 Slog.w(ActivityManagerService.TAG, 1505 "Error canceling notification for service", e); 1506 } catch (RemoteException e) { 1507 } 1508 } break; 1509 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1510 synchronized (ActivityManagerService.this) { 1511 checkExcessivePowerUsageLocked(true); 1512 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1513 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1514 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1515 } 1516 } break; 1517 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1518 synchronized (ActivityManagerService.this) { 1519 ActivityRecord ar = (ActivityRecord)msg.obj; 1520 if (mCompatModeDialog != null) { 1521 if (mCompatModeDialog.mAppInfo.packageName.equals( 1522 ar.info.applicationInfo.packageName)) { 1523 return; 1524 } 1525 mCompatModeDialog.dismiss(); 1526 mCompatModeDialog = null; 1527 } 1528 if (ar != null && false) { 1529 if (mCompatModePackages.getPackageAskCompatModeLocked( 1530 ar.packageName)) { 1531 int mode = mCompatModePackages.computeCompatModeLocked( 1532 ar.info.applicationInfo); 1533 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1534 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1535 mCompatModeDialog = new CompatModeDialog( 1536 ActivityManagerService.this, mContext, 1537 ar.info.applicationInfo); 1538 mCompatModeDialog.show(); 1539 } 1540 } 1541 } 1542 } 1543 break; 1544 } 1545 case DISPATCH_PROCESSES_CHANGED: { 1546 dispatchProcessesChanged(); 1547 break; 1548 } 1549 case DISPATCH_PROCESS_DIED: { 1550 final int pid = msg.arg1; 1551 final int uid = msg.arg2; 1552 dispatchProcessDied(pid, uid); 1553 break; 1554 } 1555 case REPORT_MEM_USAGE_MSG: { 1556 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 1557 Thread thread = new Thread() { 1558 @Override public void run() { 1559 final SparseArray<ProcessMemInfo> infoMap 1560 = new SparseArray<ProcessMemInfo>(memInfos.size()); 1561 for (int i=0, N=memInfos.size(); i<N; i++) { 1562 ProcessMemInfo mi = memInfos.get(i); 1563 infoMap.put(mi.pid, mi); 1564 } 1565 updateCpuStatsNow(); 1566 synchronized (mProcessCpuThread) { 1567 final int N = mProcessCpuTracker.countStats(); 1568 for (int i=0; i<N; i++) { 1569 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 1570 if (st.vsize > 0) { 1571 long pss = Debug.getPss(st.pid, null); 1572 if (pss > 0) { 1573 if (infoMap.indexOfKey(st.pid) < 0) { 1574 ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid, 1575 ProcessList.NATIVE_ADJ, -1, "native", null); 1576 mi.pss = pss; 1577 memInfos.add(mi); 1578 } 1579 } 1580 } 1581 } 1582 } 1583 1584 long totalPss = 0; 1585 for (int i=0, N=memInfos.size(); i<N; i++) { 1586 ProcessMemInfo mi = memInfos.get(i); 1587 if (mi.pss == 0) { 1588 mi.pss = Debug.getPss(mi.pid, null); 1589 } 1590 totalPss += mi.pss; 1591 } 1592 Collections.sort(memInfos, new Comparator<ProcessMemInfo>() { 1593 @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) { 1594 if (lhs.oomAdj != rhs.oomAdj) { 1595 return lhs.oomAdj < rhs.oomAdj ? -1 : 1; 1596 } 1597 if (lhs.pss != rhs.pss) { 1598 return lhs.pss < rhs.pss ? 1 : -1; 1599 } 1600 return 0; 1601 } 1602 }); 1603 1604 StringBuilder tag = new StringBuilder(128); 1605 StringBuilder stack = new StringBuilder(128); 1606 tag.append("Low on memory -- "); 1607 appendMemBucket(tag, totalPss, "total", false); 1608 appendMemBucket(stack, totalPss, "total", true); 1609 1610 StringBuilder logBuilder = new StringBuilder(1024); 1611 logBuilder.append("Low on memory:\n"); 1612 1613 boolean firstLine = true; 1614 int lastOomAdj = Integer.MIN_VALUE; 1615 for (int i=0, N=memInfos.size(); i<N; i++) { 1616 ProcessMemInfo mi = memInfos.get(i); 1617 1618 if (mi.oomAdj != ProcessList.NATIVE_ADJ 1619 && (mi.oomAdj < ProcessList.SERVICE_ADJ 1620 || mi.oomAdj == ProcessList.HOME_APP_ADJ 1621 || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) { 1622 if (lastOomAdj != mi.oomAdj) { 1623 lastOomAdj = mi.oomAdj; 1624 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 1625 tag.append(" / "); 1626 } 1627 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) { 1628 if (firstLine) { 1629 stack.append(":"); 1630 firstLine = false; 1631 } 1632 stack.append("\n\t at "); 1633 } else { 1634 stack.append("$"); 1635 } 1636 } else { 1637 tag.append(" "); 1638 stack.append("$"); 1639 } 1640 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 1641 appendMemBucket(tag, mi.pss, mi.name, false); 1642 } 1643 appendMemBucket(stack, mi.pss, mi.name, true); 1644 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ 1645 && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) { 1646 stack.append("("); 1647 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) { 1648 if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) { 1649 stack.append(DUMP_MEM_OOM_LABEL[k]); 1650 stack.append(":"); 1651 stack.append(DUMP_MEM_OOM_ADJ[k]); 1652 } 1653 } 1654 stack.append(")"); 1655 } 1656 } 1657 1658 logBuilder.append(" "); 1659 logBuilder.append(ProcessList.makeOomAdjString(mi.oomAdj)); 1660 logBuilder.append(' '); 1661 logBuilder.append(ProcessList.makeProcStateString(mi.procState)); 1662 logBuilder.append(' '); 1663 ProcessList.appendRamKb(logBuilder, mi.pss); 1664 logBuilder.append(" kB: "); 1665 logBuilder.append(mi.name); 1666 logBuilder.append(" ("); 1667 logBuilder.append(mi.pid); 1668 logBuilder.append(") "); 1669 logBuilder.append(mi.adjType); 1670 logBuilder.append('\n'); 1671 if (mi.adjReason != null) { 1672 logBuilder.append(" "); 1673 logBuilder.append(mi.adjReason); 1674 logBuilder.append('\n'); 1675 } 1676 } 1677 1678 logBuilder.append(" "); 1679 ProcessList.appendRamKb(logBuilder, totalPss); 1680 logBuilder.append(" kB: TOTAL\n"); 1681 1682 long[] infos = new long[Debug.MEMINFO_COUNT]; 1683 Debug.getMemInfo(infos); 1684 logBuilder.append(" MemInfo: "); 1685 logBuilder.append(infos[Debug.MEMINFO_SLAB]).append(" kB slab, "); 1686 logBuilder.append(infos[Debug.MEMINFO_SHMEM]).append(" kB shmem, "); 1687 logBuilder.append(infos[Debug.MEMINFO_BUFFERS]).append(" kB buffers, "); 1688 logBuilder.append(infos[Debug.MEMINFO_CACHED]).append(" kB cached, "); 1689 logBuilder.append(infos[Debug.MEMINFO_FREE]).append(" kB free\n"); 1690 if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) { 1691 logBuilder.append(" ZRAM: "); 1692 logBuilder.append(infos[Debug.MEMINFO_ZRAM_TOTAL]); 1693 logBuilder.append(" kB RAM, "); 1694 logBuilder.append(infos[Debug.MEMINFO_SWAP_TOTAL]); 1695 logBuilder.append(" kB swap total, "); 1696 logBuilder.append(infos[Debug.MEMINFO_SWAP_FREE]); 1697 logBuilder.append(" kB swap free\n"); 1698 } 1699 Slog.i(TAG, logBuilder.toString()); 1700 1701 StringBuilder dropBuilder = new StringBuilder(1024); 1702 /* 1703 StringWriter oomSw = new StringWriter(); 1704 PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256); 1705 StringWriter catSw = new StringWriter(); 1706 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 1707 String[] emptyArgs = new String[] { }; 1708 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw); 1709 oomPw.flush(); 1710 String oomString = oomSw.toString(); 1711 */ 1712 dropBuilder.append(stack); 1713 dropBuilder.append('\n'); 1714 dropBuilder.append('\n'); 1715 dropBuilder.append(logBuilder); 1716 dropBuilder.append('\n'); 1717 /* 1718 dropBuilder.append(oomString); 1719 dropBuilder.append('\n'); 1720 */ 1721 StringWriter catSw = new StringWriter(); 1722 synchronized (ActivityManagerService.this) { 1723 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 1724 String[] emptyArgs = new String[] { }; 1725 catPw.println(); 1726 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 1727 catPw.println(); 1728 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0, 1729 false, false, null); 1730 catPw.println(); 1731 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 1732 catPw.flush(); 1733 } 1734 dropBuilder.append(catSw.toString()); 1735 addErrorToDropBox("lowmem", null, "system_server", null, 1736 null, tag.toString(), dropBuilder.toString(), null, null); 1737 //Slog.i(TAG, "Sent to dropbox:"); 1738 //Slog.i(TAG, dropBuilder.toString()); 1739 synchronized (ActivityManagerService.this) { 1740 long now = SystemClock.uptimeMillis(); 1741 if (mLastMemUsageReportTime < now) { 1742 mLastMemUsageReportTime = now; 1743 } 1744 } 1745 } 1746 }; 1747 thread.start(); 1748 break; 1749 } 1750 case REPORT_USER_SWITCH_MSG: { 1751 dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1752 break; 1753 } 1754 case CONTINUE_USER_SWITCH_MSG: { 1755 continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1756 break; 1757 } 1758 case USER_SWITCH_TIMEOUT_MSG: { 1759 timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2); 1760 break; 1761 } 1762 case IMMERSIVE_MODE_LOCK_MSG: { 1763 final boolean nextState = (msg.arg1 != 0); 1764 if (mUpdateLock.isHeld() != nextState) { 1765 if (DEBUG_IMMERSIVE) { 1766 final ActivityRecord r = (ActivityRecord) msg.obj; 1767 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r); 1768 } 1769 if (nextState) { 1770 mUpdateLock.acquire(); 1771 } else { 1772 mUpdateLock.release(); 1773 } 1774 } 1775 break; 1776 } 1777 case PERSIST_URI_GRANTS_MSG: { 1778 writeGrantedUriPermissions(); 1779 break; 1780 } 1781 case REQUEST_ALL_PSS_MSG: { 1782 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 1783 break; 1784 } 1785 case START_PROFILES_MSG: { 1786 synchronized (ActivityManagerService.this) { 1787 startProfilesLocked(); 1788 } 1789 break; 1790 } 1791 case UPDATE_TIME: { 1792 synchronized (ActivityManagerService.this) { 1793 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1794 ProcessRecord r = mLruProcesses.get(i); 1795 if (r.thread != null) { 1796 try { 1797 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true); 1798 } catch (RemoteException ex) { 1799 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName); 1800 } 1801 } 1802 } 1803 } 1804 break; 1805 } 1806 case SYSTEM_USER_START_MSG: { 1807 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 1808 Integer.toString(msg.arg1), msg.arg1); 1809 mSystemServiceManager.startUser(msg.arg1); 1810 break; 1811 } 1812 case SYSTEM_USER_CURRENT_MSG: { 1813 mBatteryStatsService.noteEvent( 1814 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH, 1815 Integer.toString(msg.arg2), msg.arg2); 1816 mBatteryStatsService.noteEvent( 1817 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 1818 Integer.toString(msg.arg1), msg.arg1); 1819 mSystemServiceManager.switchUser(msg.arg1); 1820 break; 1821 } 1822 case ENTER_ANIMATION_COMPLETE_MSG: { 1823 synchronized (ActivityManagerService.this) { 1824 ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj); 1825 if (r != null && r.app != null && r.app.thread != null) { 1826 try { 1827 r.app.thread.scheduleEnterAnimationComplete(r.appToken); 1828 } catch (RemoteException e) { 1829 } 1830 } 1831 } 1832 break; 1833 } 1834 case ENABLE_SCREEN_AFTER_BOOT_MSG: { 1835 enableScreenAfterBoot(); 1836 break; 1837 } 1838 } 1839 } 1840 }; 1841 1842 static final int COLLECT_PSS_BG_MSG = 1; 1843 1844 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 1845 @Override 1846 public void handleMessage(Message msg) { 1847 switch (msg.what) { 1848 case COLLECT_PSS_BG_MSG: { 1849 long start = SystemClock.uptimeMillis(); 1850 MemInfoReader memInfo = null; 1851 synchronized (ActivityManagerService.this) { 1852 if (mFullPssPending) { 1853 mFullPssPending = false; 1854 memInfo = new MemInfoReader(); 1855 } 1856 } 1857 if (memInfo != null) { 1858 updateCpuStatsNow(); 1859 long nativeTotalPss = 0; 1860 synchronized (mProcessCpuThread) { 1861 final int N = mProcessCpuTracker.countStats(); 1862 for (int j=0; j<N; j++) { 1863 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j); 1864 if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) { 1865 // This is definitely an application process; skip it. 1866 continue; 1867 } 1868 synchronized (mPidsSelfLocked) { 1869 if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) { 1870 // This is one of our own processes; skip it. 1871 continue; 1872 } 1873 } 1874 nativeTotalPss += Debug.getPss(st.pid, null); 1875 } 1876 } 1877 memInfo.readMemInfo(); 1878 synchronized (this) { 1879 if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in " 1880 + (SystemClock.uptimeMillis()-start) + "ms"); 1881 mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(), 1882 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(), 1883 memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb() 1884 +memInfo.getSlabSizeKb(), 1885 nativeTotalPss); 1886 } 1887 } 1888 1889 int i=0, num=0; 1890 long[] tmp = new long[1]; 1891 do { 1892 ProcessRecord proc; 1893 int procState; 1894 int pid; 1895 synchronized (ActivityManagerService.this) { 1896 if (i >= mPendingPssProcesses.size()) { 1897 if (DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num + " of " + i 1898 + " processes in " + (SystemClock.uptimeMillis()-start) + "ms"); 1899 mPendingPssProcesses.clear(); 1900 return; 1901 } 1902 proc = mPendingPssProcesses.get(i); 1903 procState = proc.pssProcState; 1904 if (proc.thread != null && procState == proc.setProcState) { 1905 pid = proc.pid; 1906 } else { 1907 proc = null; 1908 pid = 0; 1909 } 1910 i++; 1911 } 1912 if (proc != null) { 1913 long pss = Debug.getPss(pid, tmp); 1914 synchronized (ActivityManagerService.this) { 1915 if (proc.thread != null && proc.setProcState == procState 1916 && proc.pid == pid) { 1917 num++; 1918 proc.lastPssTime = SystemClock.uptimeMillis(); 1919 proc.baseProcessTracker.addPss(pss, tmp[0], true, proc.pkgList); 1920 if (DEBUG_PSS) Slog.d(TAG, "PSS of " + proc.toShortString() 1921 + ": " + pss + " lastPss=" + proc.lastPss 1922 + " state=" + ProcessList.makeProcStateString(procState)); 1923 if (proc.initialIdlePss == 0) { 1924 proc.initialIdlePss = pss; 1925 } 1926 proc.lastPss = pss; 1927 if (procState >= ActivityManager.PROCESS_STATE_HOME) { 1928 proc.lastCachedPss = pss; 1929 } 1930 } 1931 } 1932 } 1933 } while (true); 1934 } 1935 } 1936 } 1937 }; 1938 1939 /** 1940 * Monitor for package changes and update our internal state. 1941 */ 1942 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 1943 @Override 1944 public void onPackageRemoved(String packageName, int uid) { 1945 // Remove all tasks with activities in the specified package from the list of recent tasks 1946 synchronized (ActivityManagerService.this) { 1947 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 1948 TaskRecord tr = mRecentTasks.get(i); 1949 ComponentName cn = tr.intent.getComponent(); 1950 if (cn != null && cn.getPackageName().equals(packageName)) { 1951 // If the package name matches, remove the task and kill the process 1952 removeTaskByIdLocked(tr.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS); 1953 } 1954 } 1955 } 1956 } 1957 1958 @Override 1959 public boolean onPackageChanged(String packageName, int uid, String[] components) { 1960 onPackageModified(packageName); 1961 return true; 1962 } 1963 1964 @Override 1965 public void onPackageModified(String packageName) { 1966 final PackageManager pm = mContext.getPackageManager(); 1967 final ArrayList<Pair<Intent, Integer>> recentTaskIntents = 1968 new ArrayList<Pair<Intent, Integer>>(); 1969 final ArrayList<Integer> tasksToRemove = new ArrayList<Integer>(); 1970 // Copy the list of recent tasks so that we don't hold onto the lock on 1971 // ActivityManagerService for long periods while checking if components exist. 1972 synchronized (ActivityManagerService.this) { 1973 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 1974 TaskRecord tr = mRecentTasks.get(i); 1975 recentTaskIntents.add(new Pair<Intent, Integer>(tr.intent, tr.taskId)); 1976 } 1977 } 1978 // Check the recent tasks and filter out all tasks with components that no longer exist. 1979 Intent tmpI = new Intent(); 1980 for (int i = recentTaskIntents.size() - 1; i >= 0; i--) { 1981 Pair<Intent, Integer> p = recentTaskIntents.get(i); 1982 ComponentName cn = p.first.getComponent(); 1983 if (cn != null && cn.getPackageName().equals(packageName)) { 1984 try { 1985 // Add the task to the list to remove if the component no longer exists 1986 tmpI.setComponent(cn); 1987 if (pm.queryIntentActivities(tmpI, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) { 1988 tasksToRemove.add(p.second); 1989 } 1990 } catch (Exception e) {} 1991 } 1992 } 1993 // Prune all the tasks with removed components from the list of recent tasks 1994 synchronized (ActivityManagerService.this) { 1995 for (int i = tasksToRemove.size() - 1; i >= 0; i--) { 1996 // Remove the task but don't kill the process (since other components in that 1997 // package may still be running and in the background) 1998 removeTaskByIdLocked(tasksToRemove.get(i), 0); 1999 } 2000 } 2001 } 2002 2003 @Override 2004 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) { 2005 // Force stop the specified packages 2006 if (packages != null) { 2007 for (String pkg : packages) { 2008 synchronized (ActivityManagerService.this) { 2009 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 0, 2010 "finished booting")) { 2011 return true; 2012 } 2013 } 2014 } 2015 } 2016 return false; 2017 } 2018 }; 2019 2020 public void setSystemProcess() { 2021 try { 2022 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); 2023 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2024 ServiceManager.addService("meminfo", new MemBinder(this)); 2025 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2026 ServiceManager.addService("dbinfo", new DbBinder(this)); 2027 if (MONITOR_CPU_USAGE) { 2028 ServiceManager.addService("cpuinfo", new CpuBinder(this)); 2029 } 2030 ServiceManager.addService("permission", new PermissionController(this)); 2031 2032 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2033 "android", STOCK_PM_FLAGS); 2034 mSystemThread.installSystemApplicationInfo(info); 2035 2036 synchronized (this) { 2037 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); 2038 app.persistent = true; 2039 app.pid = MY_PID; 2040 app.maxAdj = ProcessList.SYSTEM_ADJ; 2041 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2042 mProcessNames.put(app.processName, app.uid, app); 2043 synchronized (mPidsSelfLocked) { 2044 mPidsSelfLocked.put(app.pid, app); 2045 } 2046 updateLruProcessLocked(app, false, null); 2047 updateOomAdjLocked(); 2048 } 2049 } catch (PackageManager.NameNotFoundException e) { 2050 throw new RuntimeException( 2051 "Unable to find android system package", e); 2052 } 2053 } 2054 2055 public void setWindowManager(WindowManagerService wm) { 2056 mWindowManager = wm; 2057 mStackSupervisor.setWindowManager(wm); 2058 } 2059 2060 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2061 mUsageStatsService = usageStatsManager; 2062 } 2063 2064 public void startObservingNativeCrashes() { 2065 final NativeCrashListener ncl = new NativeCrashListener(this); 2066 ncl.start(); 2067 } 2068 2069 public IAppOpsService getAppOpsService() { 2070 return mAppOpsService; 2071 } 2072 2073 static class MemBinder extends Binder { 2074 ActivityManagerService mActivityManagerService; 2075 MemBinder(ActivityManagerService activityManagerService) { 2076 mActivityManagerService = activityManagerService; 2077 } 2078 2079 @Override 2080 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2081 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2082 != PackageManager.PERMISSION_GRANTED) { 2083 pw.println("Permission Denial: can't dump meminfo from from pid=" 2084 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2085 + " without permission " + android.Manifest.permission.DUMP); 2086 return; 2087 } 2088 2089 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null); 2090 } 2091 } 2092 2093 static class GraphicsBinder extends Binder { 2094 ActivityManagerService mActivityManagerService; 2095 GraphicsBinder(ActivityManagerService activityManagerService) { 2096 mActivityManagerService = activityManagerService; 2097 } 2098 2099 @Override 2100 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2101 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2102 != PackageManager.PERMISSION_GRANTED) { 2103 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 2104 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2105 + " without permission " + android.Manifest.permission.DUMP); 2106 return; 2107 } 2108 2109 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2110 } 2111 } 2112 2113 static class DbBinder extends Binder { 2114 ActivityManagerService mActivityManagerService; 2115 DbBinder(ActivityManagerService activityManagerService) { 2116 mActivityManagerService = activityManagerService; 2117 } 2118 2119 @Override 2120 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2121 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2122 != PackageManager.PERMISSION_GRANTED) { 2123 pw.println("Permission Denial: can't dump dbinfo from from pid=" 2124 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2125 + " without permission " + android.Manifest.permission.DUMP); 2126 return; 2127 } 2128 2129 mActivityManagerService.dumpDbInfo(fd, pw, args); 2130 } 2131 } 2132 2133 static class CpuBinder extends Binder { 2134 ActivityManagerService mActivityManagerService; 2135 CpuBinder(ActivityManagerService activityManagerService) { 2136 mActivityManagerService = activityManagerService; 2137 } 2138 2139 @Override 2140 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2141 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2142 != PackageManager.PERMISSION_GRANTED) { 2143 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 2144 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2145 + " without permission " + android.Manifest.permission.DUMP); 2146 return; 2147 } 2148 2149 synchronized (mActivityManagerService.mProcessCpuThread) { 2150 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 2151 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 2152 SystemClock.uptimeMillis())); 2153 } 2154 } 2155 } 2156 2157 public static final class Lifecycle extends SystemService { 2158 private final ActivityManagerService mService; 2159 2160 public Lifecycle(Context context) { 2161 super(context); 2162 mService = new ActivityManagerService(context); 2163 } 2164 2165 @Override 2166 public void onStart() { 2167 mService.start(); 2168 } 2169 2170 public ActivityManagerService getService() { 2171 return mService; 2172 } 2173 } 2174 2175 // Note: This method is invoked on the main thread but may need to attach various 2176 // handlers to other threads. So take care to be explicit about the looper. 2177 public ActivityManagerService(Context systemContext) { 2178 mContext = systemContext; 2179 mFactoryTest = FactoryTest.getMode(); 2180 mSystemThread = ActivityThread.currentActivityThread(); 2181 2182 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2183 2184 mHandlerThread = new ServiceThread(TAG, 2185 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2186 mHandlerThread.start(); 2187 mHandler = new MainHandler(mHandlerThread.getLooper()); 2188 2189 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2190 "foreground", BROADCAST_FG_TIMEOUT, false); 2191 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2192 "background", BROADCAST_BG_TIMEOUT, true); 2193 mBroadcastQueues[0] = mFgBroadcastQueue; 2194 mBroadcastQueues[1] = mBgBroadcastQueue; 2195 2196 mServices = new ActiveServices(this); 2197 mProviderMap = new ProviderMap(this); 2198 2199 // TODO: Move creation of battery stats service outside of activity manager service. 2200 File dataDir = Environment.getDataDirectory(); 2201 File systemDir = new File(dataDir, "system"); 2202 systemDir.mkdirs(); 2203 mBatteryStatsService = new BatteryStatsService(new File( 2204 systemDir, "batterystats.bin").toString(), mHandler); 2205 mBatteryStatsService.getActiveStatistics().readLocked(); 2206 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 2207 mOnBattery = DEBUG_POWER ? true 2208 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2209 mBatteryStatsService.getActiveStatistics().setCallback(this); 2210 2211 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2212 2213 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler); 2214 2215 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml")); 2216 2217 // User 0 is the first and only user that runs at boot. 2218 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true)); 2219 mUserLru.add(Integer.valueOf(0)); 2220 updateStartedUserArrayLocked(); 2221 2222 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 2223 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 2224 2225 mConfiguration.setToDefaults(); 2226 mConfiguration.setLocale(Locale.getDefault()); 2227 2228 mConfigurationSeq = mConfiguration.seq = 1; 2229 mProcessCpuTracker.init(); 2230 2231 mHasRecents = mContext.getResources().getBoolean( 2232 com.android.internal.R.bool.config_hasRecents); 2233 2234 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler); 2235 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2236 mStackSupervisor = new ActivityStackSupervisor(this); 2237 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor); 2238 2239 mProcessCpuThread = new Thread("CpuTracker") { 2240 @Override 2241 public void run() { 2242 while (true) { 2243 try { 2244 try { 2245 synchronized(this) { 2246 final long now = SystemClock.uptimeMillis(); 2247 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 2248 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 2249 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 2250 // + ", write delay=" + nextWriteDelay); 2251 if (nextWriteDelay < nextCpuDelay) { 2252 nextCpuDelay = nextWriteDelay; 2253 } 2254 if (nextCpuDelay > 0) { 2255 mProcessCpuMutexFree.set(true); 2256 this.wait(nextCpuDelay); 2257 } 2258 } 2259 } catch (InterruptedException e) { 2260 } 2261 updateCpuStatsNow(); 2262 } catch (Exception e) { 2263 Slog.e(TAG, "Unexpected exception collecting process stats", e); 2264 } 2265 } 2266 } 2267 }; 2268 2269 mLockToAppRequest = new LockToAppRequestDialog(mContext, this); 2270 2271 Watchdog.getInstance().addMonitor(this); 2272 Watchdog.getInstance().addThread(mHandler); 2273 } 2274 2275 public void setSystemServiceManager(SystemServiceManager mgr) { 2276 mSystemServiceManager = mgr; 2277 } 2278 2279 private void start() { 2280 Process.removeAllProcessGroups(); 2281 mProcessCpuThread.start(); 2282 2283 mBatteryStatsService.publish(mContext); 2284 mAppOpsService.publish(mContext); 2285 Slog.d("AppOps", "AppOpsService published"); 2286 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 2287 } 2288 2289 public void initPowerManagement() { 2290 mStackSupervisor.initPowerManagement(); 2291 mBatteryStatsService.initPowerManagement(); 2292 } 2293 2294 @Override 2295 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2296 throws RemoteException { 2297 if (code == SYSPROPS_TRANSACTION) { 2298 // We need to tell all apps about the system property change. 2299 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2300 synchronized(this) { 2301 final int NP = mProcessNames.getMap().size(); 2302 for (int ip=0; ip<NP; ip++) { 2303 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2304 final int NA = apps.size(); 2305 for (int ia=0; ia<NA; ia++) { 2306 ProcessRecord app = apps.valueAt(ia); 2307 if (app.thread != null) { 2308 procs.add(app.thread.asBinder()); 2309 } 2310 } 2311 } 2312 } 2313 2314 int N = procs.size(); 2315 for (int i=0; i<N; i++) { 2316 Parcel data2 = Parcel.obtain(); 2317 try { 2318 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0); 2319 } catch (RemoteException e) { 2320 } 2321 data2.recycle(); 2322 } 2323 } 2324 try { 2325 return super.onTransact(code, data, reply, flags); 2326 } catch (RuntimeException e) { 2327 // The activity manager only throws security exceptions, so let's 2328 // log all others. 2329 if (!(e instanceof SecurityException)) { 2330 Slog.wtf(TAG, "Activity Manager Crash", e); 2331 } 2332 throw e; 2333 } 2334 } 2335 2336 void updateCpuStats() { 2337 final long now = SystemClock.uptimeMillis(); 2338 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 2339 return; 2340 } 2341 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 2342 synchronized (mProcessCpuThread) { 2343 mProcessCpuThread.notify(); 2344 } 2345 } 2346 } 2347 2348 void updateCpuStatsNow() { 2349 synchronized (mProcessCpuThread) { 2350 mProcessCpuMutexFree.set(false); 2351 final long now = SystemClock.uptimeMillis(); 2352 boolean haveNewCpuStats = false; 2353 2354 if (MONITOR_CPU_USAGE && 2355 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 2356 mLastCpuTime.set(now); 2357 haveNewCpuStats = true; 2358 mProcessCpuTracker.update(); 2359 //Slog.i(TAG, mProcessCpu.printCurrentState()); 2360 //Slog.i(TAG, "Total CPU usage: " 2361 // + mProcessCpu.getTotalCpuPercent() + "%"); 2362 2363 // Slog the cpu usage if the property is set. 2364 if ("true".equals(SystemProperties.get("events.cpu"))) { 2365 int user = mProcessCpuTracker.getLastUserTime(); 2366 int system = mProcessCpuTracker.getLastSystemTime(); 2367 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 2368 int irq = mProcessCpuTracker.getLastIrqTime(); 2369 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 2370 int idle = mProcessCpuTracker.getLastIdleTime(); 2371 2372 int total = user + system + iowait + irq + softIrq + idle; 2373 if (total == 0) total = 1; 2374 2375 EventLog.writeEvent(EventLogTags.CPU, 2376 ((user+system+iowait+irq+softIrq) * 100) / total, 2377 (user * 100) / total, 2378 (system * 100) / total, 2379 (iowait * 100) / total, 2380 (irq * 100) / total, 2381 (softIrq * 100) / total); 2382 } 2383 } 2384 2385 long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes(); 2386 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 2387 synchronized(bstats) { 2388 synchronized(mPidsSelfLocked) { 2389 if (haveNewCpuStats) { 2390 if (mOnBattery) { 2391 int perc = bstats.startAddingCpuLocked(); 2392 int totalUTime = 0; 2393 int totalSTime = 0; 2394 final int N = mProcessCpuTracker.countStats(); 2395 for (int i=0; i<N; i++) { 2396 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 2397 if (!st.working) { 2398 continue; 2399 } 2400 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 2401 int otherUTime = (st.rel_utime*perc)/100; 2402 int otherSTime = (st.rel_stime*perc)/100; 2403 totalUTime += otherUTime; 2404 totalSTime += otherSTime; 2405 if (pr != null) { 2406 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 2407 if (ps == null || !ps.isActive()) { 2408 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 2409 pr.info.uid, pr.processName); 2410 } 2411 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 2412 st.rel_stime-otherSTime); 2413 ps.addSpeedStepTimes(cpuSpeedTimes); 2414 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10; 2415 } else { 2416 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 2417 if (ps == null || !ps.isActive()) { 2418 st.batteryStats = ps = bstats.getProcessStatsLocked( 2419 bstats.mapUid(st.uid), st.name); 2420 } 2421 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 2422 st.rel_stime-otherSTime); 2423 ps.addSpeedStepTimes(cpuSpeedTimes); 2424 } 2425 } 2426 bstats.finishAddingCpuLocked(perc, totalUTime, 2427 totalSTime, cpuSpeedTimes); 2428 } 2429 } 2430 } 2431 2432 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 2433 mLastWriteTime = now; 2434 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 2435 } 2436 } 2437 } 2438 } 2439 2440 @Override 2441 public void batteryNeedsCpuUpdate() { 2442 updateCpuStatsNow(); 2443 } 2444 2445 @Override 2446 public void batteryPowerChanged(boolean onBattery) { 2447 // When plugging in, update the CPU stats first before changing 2448 // the plug state. 2449 updateCpuStatsNow(); 2450 synchronized (this) { 2451 synchronized(mPidsSelfLocked) { 2452 mOnBattery = DEBUG_POWER ? true : onBattery; 2453 } 2454 } 2455 } 2456 2457 /** 2458 * Initialize the application bind args. These are passed to each 2459 * process when the bindApplication() IPC is sent to the process. They're 2460 * lazily setup to make sure the services are running when they're asked for. 2461 */ 2462 private HashMap<String, IBinder> getCommonServicesLocked() { 2463 if (mAppBindArgs == null) { 2464 mAppBindArgs = new HashMap<String, IBinder>(); 2465 2466 // Setup the application init args 2467 mAppBindArgs.put("package", ServiceManager.getService("package")); 2468 mAppBindArgs.put("window", ServiceManager.getService("window")); 2469 mAppBindArgs.put(Context.ALARM_SERVICE, 2470 ServiceManager.getService(Context.ALARM_SERVICE)); 2471 } 2472 return mAppBindArgs; 2473 } 2474 2475 final void setFocusedActivityLocked(ActivityRecord r) { 2476 if (mFocusedActivity != r) { 2477 if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r); 2478 mFocusedActivity = r; 2479 if (r.task != null && r.task.voiceInteractor != null) { 2480 startRunningVoiceLocked(); 2481 } else { 2482 finishRunningVoiceLocked(); 2483 } 2484 mStackSupervisor.setFocusedStack(r); 2485 if (r != null) { 2486 mWindowManager.setFocusedApp(r.appToken, true); 2487 } 2488 applyUpdateLockStateLocked(r); 2489 } 2490 } 2491 2492 final void clearFocusedActivity(ActivityRecord r) { 2493 if (mFocusedActivity == r) { 2494 mFocusedActivity = null; 2495 } 2496 } 2497 2498 @Override 2499 public void setFocusedStack(int stackId) { 2500 if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId); 2501 synchronized (ActivityManagerService.this) { 2502 ActivityStack stack = mStackSupervisor.getStack(stackId); 2503 if (stack != null) { 2504 ActivityRecord r = stack.topRunningActivityLocked(null); 2505 if (r != null) { 2506 setFocusedActivityLocked(r); 2507 } 2508 } 2509 } 2510 } 2511 2512 @Override 2513 public void notifyActivityDrawn(IBinder token) { 2514 if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token); 2515 synchronized (this) { 2516 ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token); 2517 if (r != null) { 2518 r.task.stack.notifyActivityDrawnLocked(r); 2519 } 2520 } 2521 } 2522 2523 final void applyUpdateLockStateLocked(ActivityRecord r) { 2524 // Modifications to the UpdateLock state are done on our handler, outside 2525 // the activity manager's locks. The new state is determined based on the 2526 // state *now* of the relevant activity record. The object is passed to 2527 // the handler solely for logging detail, not to be consulted/modified. 2528 final boolean nextState = r != null && r.immersive; 2529 mHandler.sendMessage( 2530 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 2531 } 2532 2533 final void showAskCompatModeDialogLocked(ActivityRecord r) { 2534 Message msg = Message.obtain(); 2535 msg.what = SHOW_COMPAT_MODE_DIALOG_MSG; 2536 msg.obj = r.task.askedCompatMode ? null : r; 2537 mHandler.sendMessage(msg); 2538 } 2539 2540 private final int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 2541 String what, Object obj, ProcessRecord srcApp) { 2542 app.lastActivityTime = now; 2543 2544 if (app.activities.size() > 0) { 2545 // Don't want to touch dependent processes that are hosting activities. 2546 return index; 2547 } 2548 2549 int lrui = mLruProcesses.lastIndexOf(app); 2550 if (lrui < 0) { 2551 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 2552 + what + " " + obj + " from " + srcApp); 2553 return index; 2554 } 2555 2556 if (lrui >= index) { 2557 // Don't want to cause this to move dependent processes *back* in the 2558 // list as if they were less frequently used. 2559 return index; 2560 } 2561 2562 if (lrui >= mLruProcessActivityStart) { 2563 // Don't want to touch dependent processes that are hosting activities. 2564 return index; 2565 } 2566 2567 mLruProcesses.remove(lrui); 2568 if (index > 0) { 2569 index--; 2570 } 2571 if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index 2572 + " in LRU list: " + app); 2573 mLruProcesses.add(index, app); 2574 return index; 2575 } 2576 2577 final void removeLruProcessLocked(ProcessRecord app) { 2578 int lrui = mLruProcesses.lastIndexOf(app); 2579 if (lrui >= 0) { 2580 if (lrui <= mLruProcessActivityStart) { 2581 mLruProcessActivityStart--; 2582 } 2583 if (lrui <= mLruProcessServiceStart) { 2584 mLruProcessServiceStart--; 2585 } 2586 mLruProcesses.remove(lrui); 2587 } 2588 } 2589 2590 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2591 ProcessRecord client) { 2592 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities 2593 || app.treatLikeActivity; 2594 final boolean hasService = false; // not impl yet. app.services.size() > 0; 2595 if (!activityChange && hasActivity) { 2596 // The process has activities, so we are only allowing activity-based adjustments 2597 // to move it. It should be kept in the front of the list with other 2598 // processes that have activities, and we don't want those to change their 2599 // order except due to activity operations. 2600 return; 2601 } 2602 2603 mLruSeq++; 2604 final long now = SystemClock.uptimeMillis(); 2605 app.lastActivityTime = now; 2606 2607 // First a quick reject: if the app is already at the position we will 2608 // put it, then there is nothing to do. 2609 if (hasActivity) { 2610 final int N = mLruProcesses.size(); 2611 if (N > 0 && mLruProcesses.get(N-1) == app) { 2612 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app); 2613 return; 2614 } 2615 } else { 2616 if (mLruProcessServiceStart > 0 2617 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 2618 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app); 2619 return; 2620 } 2621 } 2622 2623 int lrui = mLruProcesses.lastIndexOf(app); 2624 2625 if (app.persistent && lrui >= 0) { 2626 // We don't care about the position of persistent processes, as long as 2627 // they are in the list. 2628 if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app); 2629 return; 2630 } 2631 2632 /* In progress: compute new position first, so we can avoid doing work 2633 if the process is not actually going to move. Not yet working. 2634 int addIndex; 2635 int nextIndex; 2636 boolean inActivity = false, inService = false; 2637 if (hasActivity) { 2638 // Process has activities, put it at the very tipsy-top. 2639 addIndex = mLruProcesses.size(); 2640 nextIndex = mLruProcessServiceStart; 2641 inActivity = true; 2642 } else if (hasService) { 2643 // Process has services, put it at the top of the service list. 2644 addIndex = mLruProcessActivityStart; 2645 nextIndex = mLruProcessServiceStart; 2646 inActivity = true; 2647 inService = true; 2648 } else { 2649 // Process not otherwise of interest, it goes to the top of the non-service area. 2650 addIndex = mLruProcessServiceStart; 2651 if (client != null) { 2652 int clientIndex = mLruProcesses.lastIndexOf(client); 2653 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 2654 + app); 2655 if (clientIndex >= 0 && addIndex > clientIndex) { 2656 addIndex = clientIndex; 2657 } 2658 } 2659 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 2660 } 2661 2662 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 2663 + mLruProcessActivityStart + "): " + app); 2664 */ 2665 2666 if (lrui >= 0) { 2667 if (lrui < mLruProcessActivityStart) { 2668 mLruProcessActivityStart--; 2669 } 2670 if (lrui < mLruProcessServiceStart) { 2671 mLruProcessServiceStart--; 2672 } 2673 /* 2674 if (addIndex > lrui) { 2675 addIndex--; 2676 } 2677 if (nextIndex > lrui) { 2678 nextIndex--; 2679 } 2680 */ 2681 mLruProcesses.remove(lrui); 2682 } 2683 2684 /* 2685 mLruProcesses.add(addIndex, app); 2686 if (inActivity) { 2687 mLruProcessActivityStart++; 2688 } 2689 if (inService) { 2690 mLruProcessActivityStart++; 2691 } 2692 */ 2693 2694 int nextIndex; 2695 if (hasActivity) { 2696 final int N = mLruProcesses.size(); 2697 if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) { 2698 // Process doesn't have activities, but has clients with 2699 // activities... move it up, but one below the top (the top 2700 // should always have a real activity). 2701 if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app); 2702 mLruProcesses.add(N-1, app); 2703 // To keep it from spamming the LRU list (by making a bunch of clients), 2704 // we will push down any other entries owned by the app. 2705 final int uid = app.info.uid; 2706 for (int i=N-2; i>mLruProcessActivityStart; i--) { 2707 ProcessRecord subProc = mLruProcesses.get(i); 2708 if (subProc.info.uid == uid) { 2709 // We want to push this one down the list. If the process after 2710 // it is for the same uid, however, don't do so, because we don't 2711 // want them internally to be re-ordered. 2712 if (mLruProcesses.get(i-1).info.uid != uid) { 2713 if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i 2714 + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1)); 2715 ProcessRecord tmp = mLruProcesses.get(i); 2716 mLruProcesses.set(i, mLruProcesses.get(i-1)); 2717 mLruProcesses.set(i-1, tmp); 2718 i--; 2719 } 2720 } else { 2721 // A gap, we can stop here. 2722 break; 2723 } 2724 } 2725 } else { 2726 // Process has activities, put it at the very tipsy-top. 2727 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app); 2728 mLruProcesses.add(app); 2729 } 2730 nextIndex = mLruProcessServiceStart; 2731 } else if (hasService) { 2732 // Process has services, put it at the top of the service list. 2733 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU service list: " + app); 2734 mLruProcesses.add(mLruProcessActivityStart, app); 2735 nextIndex = mLruProcessServiceStart; 2736 mLruProcessActivityStart++; 2737 } else { 2738 // Process not otherwise of interest, it goes to the top of the non-service area. 2739 int index = mLruProcessServiceStart; 2740 if (client != null) { 2741 // If there is a client, don't allow the process to be moved up higher 2742 // in the list than that client. 2743 int clientIndex = mLruProcesses.lastIndexOf(client); 2744 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG, "Unknown client " + client 2745 + " when updating " + app); 2746 if (clientIndex <= lrui) { 2747 // Don't allow the client index restriction to push it down farther in the 2748 // list than it already is. 2749 clientIndex = lrui; 2750 } 2751 if (clientIndex >= 0 && index > clientIndex) { 2752 index = clientIndex; 2753 } 2754 } 2755 if (DEBUG_LRU) Slog.d(TAG, "Adding at " + index + " of LRU list: " + app); 2756 mLruProcesses.add(index, app); 2757 nextIndex = index-1; 2758 mLruProcessActivityStart++; 2759 mLruProcessServiceStart++; 2760 } 2761 2762 // If the app is currently using a content provider or service, 2763 // bump those processes as well. 2764 for (int j=app.connections.size()-1; j>=0; j--) { 2765 ConnectionRecord cr = app.connections.valueAt(j); 2766 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 2767 && cr.binding.service.app != null 2768 && cr.binding.service.app.lruSeq != mLruSeq 2769 && !cr.binding.service.app.persistent) { 2770 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex, 2771 "service connection", cr, app); 2772 } 2773 } 2774 for (int j=app.conProviders.size()-1; j>=0; j--) { 2775 ContentProviderRecord cpr = app.conProviders.get(j).provider; 2776 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) { 2777 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, 2778 "provider reference", cpr, app); 2779 } 2780 } 2781 } 2782 2783 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 2784 if (uid == Process.SYSTEM_UID) { 2785 // The system gets to run in any process. If there are multiple 2786 // processes with the same uid, just pick the first (this 2787 // should never happen). 2788 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 2789 if (procs == null) return null; 2790 final int N = procs.size(); 2791 for (int i = 0; i < N; i++) { 2792 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i); 2793 } 2794 } 2795 ProcessRecord proc = mProcessNames.get(processName, uid); 2796 if (false && proc != null && !keepIfLarge 2797 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 2798 && proc.lastCachedPss >= 4000) { 2799 // Turn this condition on to cause killing to happen regularly, for testing. 2800 if (proc.baseProcessTracker != null) { 2801 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 2802 } 2803 killUnneededProcessLocked(proc, Long.toString(proc.lastCachedPss) 2804 + "k from cached"); 2805 } else if (proc != null && !keepIfLarge 2806 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 2807 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 2808 if (DEBUG_PSS) Slog.d(TAG, "May not keep " + proc + ": pss=" + proc.lastCachedPss); 2809 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) { 2810 if (proc.baseProcessTracker != null) { 2811 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 2812 } 2813 killUnneededProcessLocked(proc, Long.toString(proc.lastCachedPss) 2814 + "k from cached"); 2815 } 2816 } 2817 return proc; 2818 } 2819 2820 void ensurePackageDexOpt(String packageName) { 2821 IPackageManager pm = AppGlobals.getPackageManager(); 2822 try { 2823 if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) { 2824 mDidDexOpt = true; 2825 } 2826 } catch (RemoteException e) { 2827 } 2828 } 2829 2830 boolean isNextTransitionForward() { 2831 int transit = mWindowManager.getPendingAppTransition(); 2832 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN 2833 || transit == AppTransition.TRANSIT_TASK_OPEN 2834 || transit == AppTransition.TRANSIT_TASK_TO_FRONT; 2835 } 2836 2837 int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 2838 String processName, String abiOverride, int uid, Runnable crashHandler) { 2839 synchronized(this) { 2840 ApplicationInfo info = new ApplicationInfo(); 2841 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 2842 // For isolated processes, the former contains the parent's uid and the latter the 2843 // actual uid of the isolated process. 2844 // In the special case introduced by this method (which is, starting an isolated 2845 // process directly from the SystemServer without an actual parent app process) the 2846 // closest thing to a parent's uid is SYSTEM_UID. 2847 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 2848 // the |isolated| logic in the ProcessRecord constructor. 2849 info.uid = Process.SYSTEM_UID; 2850 info.processName = processName; 2851 info.className = entryPoint; 2852 info.packageName = "android"; 2853 ProcessRecord proc = startProcessLocked(processName, info /* info */, 2854 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */, 2855 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */, 2856 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 2857 crashHandler); 2858 return proc != null ? proc.pid : 0; 2859 } 2860 } 2861 2862 final ProcessRecord startProcessLocked(String processName, 2863 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2864 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 2865 boolean isolated, boolean keepIfLarge) { 2866 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, 2867 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 2868 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 2869 null /* crashHandler */); 2870 } 2871 2872 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 2873 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, 2874 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, 2875 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { 2876 ProcessRecord app; 2877 if (!isolated) { 2878 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 2879 } else { 2880 // If this is an isolated process, it can't re-use an existing process. 2881 app = null; 2882 } 2883 // We don't have to do anything more if: 2884 // (1) There is an existing application record; and 2885 // (2) The caller doesn't think it is dead, OR there is no thread 2886 // object attached to it so we know it couldn't have crashed; and 2887 // (3) There is a pid assigned to it, so it is either starting or 2888 // already running. 2889 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName 2890 + " app=" + app + " knownToBeDead=" + knownToBeDead 2891 + " thread=" + (app != null ? app.thread : null) 2892 + " pid=" + (app != null ? app.pid : -1)); 2893 if (app != null && app.pid > 0) { 2894 if (!knownToBeDead || app.thread == null) { 2895 // We already have the app running, or are waiting for it to 2896 // come up (we have a pid but not yet its thread), so keep it. 2897 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app); 2898 // If this is a new package in the process, add the package to the list 2899 app.addPackage(info.packageName, info.versionCode, mProcessStats); 2900 return app; 2901 } 2902 2903 // An application record is attached to a previous process, 2904 // clean it up now. 2905 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app); 2906 Process.killProcessGroup(app.info.uid, app.pid); 2907 handleAppDiedLocked(app, true, true); 2908 } 2909 2910 String hostingNameStr = hostingName != null 2911 ? hostingName.flattenToShortString() : null; 2912 2913 if (!isolated) { 2914 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) { 2915 // If we are in the background, then check to see if this process 2916 // is bad. If so, we will just silently fail. 2917 if (mBadProcesses.get(info.processName, info.uid) != null) { 2918 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 2919 + "/" + info.processName); 2920 return null; 2921 } 2922 } else { 2923 // When the user is explicitly starting a process, then clear its 2924 // crash count so that we won't make it bad until they see at 2925 // least one crash dialog again, and make the process good again 2926 // if it had been bad. 2927 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 2928 + "/" + info.processName); 2929 mProcessCrashTimes.remove(info.processName, info.uid); 2930 if (mBadProcesses.get(info.processName, info.uid) != null) { 2931 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 2932 UserHandle.getUserId(info.uid), info.uid, 2933 info.processName); 2934 mBadProcesses.remove(info.processName, info.uid); 2935 if (app != null) { 2936 app.bad = false; 2937 } 2938 } 2939 } 2940 } 2941 2942 if (app == null) { 2943 app = newProcessRecordLocked(info, processName, isolated, isolatedUid); 2944 app.crashHandler = crashHandler; 2945 if (app == null) { 2946 Slog.w(TAG, "Failed making new process record for " 2947 + processName + "/" + info.uid + " isolated=" + isolated); 2948 return null; 2949 } 2950 mProcessNames.put(processName, app.uid, app); 2951 if (isolated) { 2952 mIsolatedProcesses.put(app.uid, app); 2953 } 2954 } else { 2955 // If this is a new package in the process, add the package to the list 2956 app.addPackage(info.packageName, info.versionCode, mProcessStats); 2957 } 2958 2959 // If the system is not ready yet, then hold off on starting this 2960 // process until it is. 2961 if (!mProcessesReady 2962 && !isAllowedWhileBooting(info) 2963 && !allowWhileBooting) { 2964 if (!mProcessesOnHold.contains(app)) { 2965 mProcessesOnHold.add(app); 2966 } 2967 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app); 2968 return app; 2969 } 2970 2971 startProcessLocked( 2972 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs); 2973 return (app.pid != 0) ? app : null; 2974 } 2975 2976 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2977 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2978 } 2979 2980 private final void startProcessLocked(ProcessRecord app, 2981 String hostingType, String hostingNameStr) { 2982 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */, 2983 null /* entryPoint */, null /* entryPointArgs */); 2984 } 2985 2986 private final void startProcessLocked(ProcessRecord app, String hostingType, 2987 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { 2988 if (app.pid > 0 && app.pid != MY_PID) { 2989 synchronized (mPidsSelfLocked) { 2990 mPidsSelfLocked.remove(app.pid); 2991 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 2992 } 2993 app.setPid(0); 2994 } 2995 2996 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 2997 "startProcessLocked removing on hold: " + app); 2998 mProcessesOnHold.remove(app); 2999 3000 updateCpuStats(); 3001 3002 try { 3003 int uid = app.uid; 3004 3005 int[] gids = null; 3006 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 3007 if (!app.isolated) { 3008 int[] permGids = null; 3009 try { 3010 final PackageManager pm = mContext.getPackageManager(); 3011 permGids = pm.getPackageGids(app.info.packageName); 3012 3013 if (Environment.isExternalStorageEmulated()) { 3014 if (pm.checkPermission( 3015 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE, 3016 app.info.packageName) == PERMISSION_GRANTED) { 3017 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL; 3018 } else { 3019 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER; 3020 } 3021 } 3022 } catch (PackageManager.NameNotFoundException e) { 3023 Slog.w(TAG, "Unable to retrieve gids", e); 3024 } 3025 3026 /* 3027 * Add shared application and profile GIDs so applications can share some 3028 * resources like shared libraries and access user-wide resources 3029 */ 3030 if (permGids == null) { 3031 gids = new int[2]; 3032 } else { 3033 gids = new int[permGids.length + 2]; 3034 System.arraycopy(permGids, 0, gids, 2, permGids.length); 3035 } 3036 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 3037 gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 3038 } 3039 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) { 3040 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3041 && mTopComponent != null 3042 && app.processName.equals(mTopComponent.getPackageName())) { 3043 uid = 0; 3044 } 3045 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL 3046 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 3047 uid = 0; 3048 } 3049 } 3050 int debugFlags = 0; 3051 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 3052 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 3053 // Also turn on CheckJNI for debuggable apps. It's quite 3054 // awkward to turn on otherwise. 3055 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3056 } 3057 // Run the app in safe mode if its manifest requests so or the 3058 // system is booted in safe mode. 3059 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 3060 mSafeMode == true) { 3061 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 3062 } 3063 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 3064 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3065 } 3066 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 3067 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 3068 } 3069 if ("1".equals(SystemProperties.get("debug.assert"))) { 3070 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 3071 } 3072 3073 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 3074 if (requiredAbi == null) { 3075 requiredAbi = Build.SUPPORTED_ABIS[0]; 3076 } 3077 3078 // Start the process. It will either succeed and return a result containing 3079 // the PID of the new process, or else throw a RuntimeException. 3080 boolean isActivityProcess = (entryPoint == null); 3081 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 3082 Process.ProcessStartResult startResult = Process.start(entryPoint, 3083 app.processName, uid, uid, gids, debugFlags, mountExternal, 3084 app.info.targetSdkVersion, app.info.seinfo, requiredAbi, entryPointArgs); 3085 3086 if (app.isolated) { 3087 mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid); 3088 } 3089 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 3090 3091 EventLog.writeEvent(EventLogTags.AM_PROC_START, 3092 UserHandle.getUserId(uid), startResult.pid, uid, 3093 app.processName, hostingType, 3094 hostingNameStr != null ? hostingNameStr : ""); 3095 3096 if (app.persistent) { 3097 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 3098 } 3099 3100 StringBuilder buf = mStringBuilder; 3101 buf.setLength(0); 3102 buf.append("Start proc "); 3103 buf.append(app.processName); 3104 if (!isActivityProcess) { 3105 buf.append(" ["); 3106 buf.append(entryPoint); 3107 buf.append("]"); 3108 } 3109 buf.append(" for "); 3110 buf.append(hostingType); 3111 if (hostingNameStr != null) { 3112 buf.append(" "); 3113 buf.append(hostingNameStr); 3114 } 3115 buf.append(": pid="); 3116 buf.append(startResult.pid); 3117 buf.append(" uid="); 3118 buf.append(uid); 3119 buf.append(" gids={"); 3120 if (gids != null) { 3121 for (int gi=0; gi<gids.length; gi++) { 3122 if (gi != 0) buf.append(", "); 3123 buf.append(gids[gi]); 3124 3125 } 3126 } 3127 buf.append("}"); 3128 if (requiredAbi != null) { 3129 buf.append(" abi="); 3130 buf.append(requiredAbi); 3131 } 3132 Slog.i(TAG, buf.toString()); 3133 app.setPid(startResult.pid); 3134 app.usingWrapper = startResult.usingWrapper; 3135 app.removed = false; 3136 app.killedByAm = false; 3137 synchronized (mPidsSelfLocked) { 3138 this.mPidsSelfLocked.put(startResult.pid, app); 3139 if (isActivityProcess) { 3140 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 3141 msg.obj = app; 3142 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 3143 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 3144 } 3145 } 3146 } catch (RuntimeException e) { 3147 // XXX do better error recovery. 3148 app.setPid(0); 3149 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 3150 if (app.isolated) { 3151 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 3152 } 3153 Slog.e(TAG, "Failure starting process " + app.processName, e); 3154 } 3155 } 3156 3157 void updateUsageStats(ActivityRecord component, boolean resumed) { 3158 if (DEBUG_SWITCH) Slog.d(TAG, "updateUsageStats: comp=" + component + "res=" + resumed); 3159 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3160 if (resumed) { 3161 if (mUsageStatsService != null) { 3162 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3163 System.currentTimeMillis(), 3164 UsageStats.Event.MOVE_TO_FOREGROUND); 3165 } 3166 synchronized (stats) { 3167 stats.noteActivityResumedLocked(component.app.uid); 3168 } 3169 } else { 3170 if (mUsageStatsService != null) { 3171 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3172 System.currentTimeMillis(), 3173 UsageStats.Event.MOVE_TO_BACKGROUND); 3174 } 3175 synchronized (stats) { 3176 stats.noteActivityPausedLocked(component.app.uid); 3177 } 3178 } 3179 } 3180 3181 Intent getHomeIntent() { 3182 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); 3183 intent.setComponent(mTopComponent); 3184 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 3185 intent.addCategory(Intent.CATEGORY_HOME); 3186 } 3187 return intent; 3188 } 3189 3190 boolean startHomeActivityLocked(int userId) { 3191 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3192 && mTopAction == null) { 3193 // We are running in factory test mode, but unable to find 3194 // the factory test app, so just sit around displaying the 3195 // error message and don't try to start anything. 3196 return false; 3197 } 3198 Intent intent = getHomeIntent(); 3199 ActivityInfo aInfo = 3200 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 3201 if (aInfo != null) { 3202 intent.setComponent(new ComponentName( 3203 aInfo.applicationInfo.packageName, aInfo.name)); 3204 // Don't do this if the home app is currently being 3205 // instrumented. 3206 aInfo = new ActivityInfo(aInfo); 3207 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 3208 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 3209 aInfo.applicationInfo.uid, true); 3210 if (app == null || app.instrumentationClass == null) { 3211 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 3212 mStackSupervisor.startHomeActivity(intent, aInfo); 3213 } 3214 } 3215 3216 return true; 3217 } 3218 3219 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 3220 ActivityInfo ai = null; 3221 ComponentName comp = intent.getComponent(); 3222 try { 3223 if (comp != null) { 3224 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 3225 } else { 3226 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 3227 intent, 3228 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 3229 flags, userId); 3230 3231 if (info != null) { 3232 ai = info.activityInfo; 3233 } 3234 } 3235 } catch (RemoteException e) { 3236 // ignore 3237 } 3238 3239 return ai; 3240 } 3241 3242 /** 3243 * Starts the "new version setup screen" if appropriate. 3244 */ 3245 void startSetupActivityLocked() { 3246 // Only do this once per boot. 3247 if (mCheckedForSetup) { 3248 return; 3249 } 3250 3251 // We will show this screen if the current one is a different 3252 // version than the last one shown, and we are not running in 3253 // low-level factory test mode. 3254 final ContentResolver resolver = mContext.getContentResolver(); 3255 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL && 3256 Settings.Global.getInt(resolver, 3257 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 3258 mCheckedForSetup = true; 3259 3260 // See if we should be showing the platform update setup UI. 3261 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 3262 List<ResolveInfo> ris = mContext.getPackageManager() 3263 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 3264 3265 // We don't allow third party apps to replace this. 3266 ResolveInfo ri = null; 3267 for (int i=0; ris != null && i<ris.size(); i++) { 3268 if ((ris.get(i).activityInfo.applicationInfo.flags 3269 & ApplicationInfo.FLAG_SYSTEM) != 0) { 3270 ri = ris.get(i); 3271 break; 3272 } 3273 } 3274 3275 if (ri != null) { 3276 String vers = ri.activityInfo.metaData != null 3277 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 3278 : null; 3279 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 3280 vers = ri.activityInfo.applicationInfo.metaData.getString( 3281 Intent.METADATA_SETUP_VERSION); 3282 } 3283 String lastVers = Settings.Secure.getString( 3284 resolver, Settings.Secure.LAST_SETUP_SHOWN); 3285 if (vers != null && !vers.equals(lastVers)) { 3286 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 3287 intent.setComponent(new ComponentName( 3288 ri.activityInfo.packageName, ri.activityInfo.name)); 3289 mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo, 3290 null, null, null, null, 0, 0, 0, null, 0, null, false, null, null); 3291 } 3292 } 3293 } 3294 } 3295 3296 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 3297 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 3298 } 3299 3300 void enforceNotIsolatedCaller(String caller) { 3301 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3302 throw new SecurityException("Isolated process not allowed to call " + caller); 3303 } 3304 } 3305 3306 @Override 3307 public int getFrontActivityScreenCompatMode() { 3308 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 3309 synchronized (this) { 3310 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 3311 } 3312 } 3313 3314 @Override 3315 public void setFrontActivityScreenCompatMode(int mode) { 3316 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3317 "setFrontActivityScreenCompatMode"); 3318 synchronized (this) { 3319 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 3320 } 3321 } 3322 3323 @Override 3324 public int getPackageScreenCompatMode(String packageName) { 3325 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 3326 synchronized (this) { 3327 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 3328 } 3329 } 3330 3331 @Override 3332 public void setPackageScreenCompatMode(String packageName, int mode) { 3333 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3334 "setPackageScreenCompatMode"); 3335 synchronized (this) { 3336 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 3337 } 3338 } 3339 3340 @Override 3341 public boolean getPackageAskScreenCompat(String packageName) { 3342 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 3343 synchronized (this) { 3344 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 3345 } 3346 } 3347 3348 @Override 3349 public void setPackageAskScreenCompat(String packageName, boolean ask) { 3350 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3351 "setPackageAskScreenCompat"); 3352 synchronized (this) { 3353 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 3354 } 3355 } 3356 3357 private void dispatchProcessesChanged() { 3358 int N; 3359 synchronized (this) { 3360 N = mPendingProcessChanges.size(); 3361 if (mActiveProcessChanges.length < N) { 3362 mActiveProcessChanges = new ProcessChangeItem[N]; 3363 } 3364 mPendingProcessChanges.toArray(mActiveProcessChanges); 3365 mAvailProcessChanges.addAll(mPendingProcessChanges); 3366 mPendingProcessChanges.clear(); 3367 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes"); 3368 } 3369 3370 int i = mProcessObservers.beginBroadcast(); 3371 while (i > 0) { 3372 i--; 3373 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3374 if (observer != null) { 3375 try { 3376 for (int j=0; j<N; j++) { 3377 ProcessChangeItem item = mActiveProcessChanges[j]; 3378 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 3379 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid=" 3380 + item.pid + " uid=" + item.uid + ": " 3381 + item.foregroundActivities); 3382 observer.onForegroundActivitiesChanged(item.pid, item.uid, 3383 item.foregroundActivities); 3384 } 3385 if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) { 3386 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "PROCSTATE CHANGED pid=" 3387 + item.pid + " uid=" + item.uid + ": " + item.processState); 3388 observer.onProcessStateChanged(item.pid, item.uid, item.processState); 3389 } 3390 } 3391 } catch (RemoteException e) { 3392 } 3393 } 3394 } 3395 mProcessObservers.finishBroadcast(); 3396 } 3397 3398 private void dispatchProcessDied(int pid, int uid) { 3399 int i = mProcessObservers.beginBroadcast(); 3400 while (i > 0) { 3401 i--; 3402 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3403 if (observer != null) { 3404 try { 3405 observer.onProcessDied(pid, uid); 3406 } catch (RemoteException e) { 3407 } 3408 } 3409 } 3410 mProcessObservers.finishBroadcast(); 3411 } 3412 3413 @Override 3414 public final int startActivity(IApplicationThread caller, String callingPackage, 3415 Intent intent, String resolvedType, IBinder resultTo, 3416 String resultWho, int requestCode, int startFlags, 3417 String profileFile, ParcelFileDescriptor profileFd, Bundle options) { 3418 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 3419 resultWho, requestCode, 3420 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId()); 3421 } 3422 3423 @Override 3424 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3425 Intent intent, String resolvedType, IBinder resultTo, 3426 String resultWho, int requestCode, int startFlags, 3427 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) { 3428 enforceNotIsolatedCaller("startActivity"); 3429 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3430 false, ALLOW_FULL_ONLY, "startActivity", null); 3431 // TODO: Switch to user app stacks here. 3432 return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 3433 null, null, resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 3434 null, null, options, userId, null); 3435 } 3436 3437 @Override 3438 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3439 Intent intent, String resolvedType, IBinder resultTo, 3440 String resultWho, int requestCode, int startFlags, String profileFile, 3441 ParcelFileDescriptor profileFd, Bundle options, int userId) { 3442 enforceNotIsolatedCaller("startActivityAndWait"); 3443 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3444 false, ALLOW_FULL_ONLY, "startActivityAndWait", null); 3445 WaitResult res = new WaitResult(); 3446 // TODO: Switch to user app stacks here. 3447 mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 3448 null, null, resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 3449 res, null, options, userId, null); 3450 return res; 3451 } 3452 3453 @Override 3454 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 3455 Intent intent, String resolvedType, IBinder resultTo, 3456 String resultWho, int requestCode, int startFlags, Configuration config, 3457 Bundle options, int userId) { 3458 enforceNotIsolatedCaller("startActivityWithConfig"); 3459 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3460 false, ALLOW_FULL_ONLY, "startActivityWithConfig", null); 3461 // TODO: Switch to user app stacks here. 3462 int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, 3463 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3464 null, null, null, config, options, userId, null); 3465 return ret; 3466 } 3467 3468 @Override 3469 public int startActivityIntentSender(IApplicationThread caller, 3470 IntentSender intent, Intent fillInIntent, String resolvedType, 3471 IBinder resultTo, String resultWho, int requestCode, 3472 int flagsMask, int flagsValues, Bundle options) { 3473 enforceNotIsolatedCaller("startActivityIntentSender"); 3474 // Refuse possible leaked file descriptors 3475 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 3476 throw new IllegalArgumentException("File descriptors passed in Intent"); 3477 } 3478 3479 IIntentSender sender = intent.getTarget(); 3480 if (!(sender instanceof PendingIntentRecord)) { 3481 throw new IllegalArgumentException("Bad PendingIntent object"); 3482 } 3483 3484 PendingIntentRecord pir = (PendingIntentRecord)sender; 3485 3486 synchronized (this) { 3487 // If this is coming from the currently resumed activity, it is 3488 // effectively saying that app switches are allowed at this point. 3489 final ActivityStack stack = getFocusedStack(); 3490 if (stack.mResumedActivity != null && 3491 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) { 3492 mAppSwitchesAllowedTime = 0; 3493 } 3494 } 3495 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null, 3496 resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null); 3497 return ret; 3498 } 3499 3500 @Override 3501 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid, 3502 Intent intent, String resolvedType, IVoiceInteractionSession session, 3503 IVoiceInteractor interactor, int startFlags, String profileFile, 3504 ParcelFileDescriptor profileFd, Bundle options, int userId) { 3505 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 3506 != PackageManager.PERMISSION_GRANTED) { 3507 String msg = "Permission Denial: startVoiceActivity() from pid=" 3508 + Binder.getCallingPid() 3509 + ", uid=" + Binder.getCallingUid() 3510 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION; 3511 Slog.w(TAG, msg); 3512 throw new SecurityException(msg); 3513 } 3514 if (session == null || interactor == null) { 3515 throw new NullPointerException("null session or interactor"); 3516 } 3517 userId = handleIncomingUser(callingPid, callingUid, userId, 3518 false, ALLOW_FULL_ONLY, "startVoiceActivity", null); 3519 // TODO: Switch to user app stacks here. 3520 return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent, 3521 resolvedType, session, interactor, null, null, 0, startFlags, 3522 profileFile, profileFd, null, null, options, userId, null); 3523 } 3524 3525 @Override 3526 public boolean startNextMatchingActivity(IBinder callingActivity, 3527 Intent intent, Bundle options) { 3528 // Refuse possible leaked file descriptors 3529 if (intent != null && intent.hasFileDescriptors() == true) { 3530 throw new IllegalArgumentException("File descriptors passed in Intent"); 3531 } 3532 3533 synchronized (this) { 3534 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity); 3535 if (r == null) { 3536 ActivityOptions.abort(options); 3537 return false; 3538 } 3539 if (r.app == null || r.app.thread == null) { 3540 // The caller is not running... d'oh! 3541 ActivityOptions.abort(options); 3542 return false; 3543 } 3544 intent = new Intent(intent); 3545 // The caller is not allowed to change the data. 3546 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 3547 // And we are resetting to find the next component... 3548 intent.setComponent(null); 3549 3550 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3551 3552 ActivityInfo aInfo = null; 3553 try { 3554 List<ResolveInfo> resolves = 3555 AppGlobals.getPackageManager().queryIntentActivities( 3556 intent, r.resolvedType, 3557 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 3558 UserHandle.getCallingUserId()); 3559 3560 // Look for the original activity in the list... 3561 final int N = resolves != null ? resolves.size() : 0; 3562 for (int i=0; i<N; i++) { 3563 ResolveInfo rInfo = resolves.get(i); 3564 if (rInfo.activityInfo.packageName.equals(r.packageName) 3565 && rInfo.activityInfo.name.equals(r.info.name)) { 3566 // We found the current one... the next matching is 3567 // after it. 3568 i++; 3569 if (i<N) { 3570 aInfo = resolves.get(i).activityInfo; 3571 } 3572 if (debug) { 3573 Slog.v(TAG, "Next matching activity: found current " + r.packageName 3574 + "/" + r.info.name); 3575 Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName 3576 + "/" + aInfo.name); 3577 } 3578 break; 3579 } 3580 } 3581 } catch (RemoteException e) { 3582 } 3583 3584 if (aInfo == null) { 3585 // Nobody who is next! 3586 ActivityOptions.abort(options); 3587 if (debug) Slog.d(TAG, "Next matching activity: nothing found"); 3588 return false; 3589 } 3590 3591 intent.setComponent(new ComponentName( 3592 aInfo.applicationInfo.packageName, aInfo.name)); 3593 intent.setFlags(intent.getFlags()&~( 3594 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 3595 Intent.FLAG_ACTIVITY_CLEAR_TOP| 3596 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 3597 Intent.FLAG_ACTIVITY_NEW_TASK)); 3598 3599 // Okay now we need to start the new activity, replacing the 3600 // currently running activity. This is a little tricky because 3601 // we want to start the new one as if the current one is finished, 3602 // but not finish the current one first so that there is no flicker. 3603 // And thus... 3604 final boolean wasFinishing = r.finishing; 3605 r.finishing = true; 3606 3607 // Propagate reply information over to the new activity. 3608 final ActivityRecord resultTo = r.resultTo; 3609 final String resultWho = r.resultWho; 3610 final int requestCode = r.requestCode; 3611 r.resultTo = null; 3612 if (resultTo != null) { 3613 resultTo.removeResultsLocked(r, resultWho, requestCode); 3614 } 3615 3616 final long origId = Binder.clearCallingIdentity(); 3617 int res = mStackSupervisor.startActivityLocked(r.app.thread, intent, 3618 r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null, 3619 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0, 3620 options, false, null, null); 3621 Binder.restoreCallingIdentity(origId); 3622 3623 r.finishing = wasFinishing; 3624 if (res != ActivityManager.START_SUCCESS) { 3625 return false; 3626 } 3627 return true; 3628 } 3629 } 3630 3631 @Override 3632 public final int startActivityFromRecents(int taskId, Bundle options) { 3633 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) { 3634 String msg = "Permission Denial: startActivityFromRecents called without " + 3635 START_TASKS_FROM_RECENTS; 3636 Slog.w(TAG, msg); 3637 throw new SecurityException(msg); 3638 } 3639 final int callingUid; 3640 final String callingPackage; 3641 final Intent intent; 3642 final int userId; 3643 synchronized (this) { 3644 final TaskRecord task = recentTaskForIdLocked(taskId); 3645 if (task == null) { 3646 throw new ActivityNotFoundException("Task " + taskId + " not found."); 3647 } 3648 callingUid = task.mCallingUid; 3649 callingPackage = task.mCallingPackage; 3650 intent = task.intent; 3651 userId = task.userId; 3652 } 3653 return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0, 3654 options, userId, null); 3655 } 3656 3657 final int startActivityInPackage(int uid, String callingPackage, 3658 Intent intent, String resolvedType, IBinder resultTo, 3659 String resultWho, int requestCode, int startFlags, Bundle options, int userId, 3660 IActivityContainer container) { 3661 3662 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3663 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 3664 3665 // TODO: Switch to user app stacks here. 3666 int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent, resolvedType, 3667 null, null, resultTo, resultWho, requestCode, startFlags, 3668 null, null, null, null, options, userId, container); 3669 return ret; 3670 } 3671 3672 @Override 3673 public final int startActivities(IApplicationThread caller, String callingPackage, 3674 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, 3675 int userId) { 3676 enforceNotIsolatedCaller("startActivities"); 3677 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3678 false, ALLOW_FULL_ONLY, "startActivity", null); 3679 // TODO: Switch to user app stacks here. 3680 int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents, 3681 resolvedTypes, resultTo, options, userId); 3682 return ret; 3683 } 3684 3685 final int startActivitiesInPackage(int uid, String callingPackage, 3686 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 3687 Bundle options, int userId) { 3688 3689 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3690 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 3691 // TODO: Switch to user app stacks here. 3692 int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes, 3693 resultTo, options, userId); 3694 return ret; 3695 } 3696 3697 //explicitly remove thd old information in mRecentTasks when removing existing user. 3698 private void removeRecentTasksForUserLocked(int userId) { 3699 if(userId <= 0) { 3700 Slog.i(TAG, "Can't remove recent task on user " + userId); 3701 return; 3702 } 3703 3704 for (int i = mRecentTasks.size() - 1; i >= 0; --i) { 3705 TaskRecord tr = mRecentTasks.get(i); 3706 if (tr.userId == userId) { 3707 if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr 3708 + " when finishing user" + userId); 3709 tr.disposeThumbnail(); 3710 mRecentTasks.remove(i); 3711 } 3712 } 3713 3714 // Remove tasks from persistent storage. 3715 mTaskPersister.wakeup(null, true); 3716 } 3717 3718 final void addRecentTaskLocked(TaskRecord task) { 3719 int N = mRecentTasks.size(); 3720 // Quick case: check if the top-most recent task is the same. 3721 if (N > 0 && mRecentTasks.get(0) == task) { 3722 return; 3723 } 3724 // Another quick case: never add voice sessions. 3725 if (task.voiceSession != null) { 3726 return; 3727 } 3728 // Remove any existing entries that are the same kind of task. 3729 final Intent intent = task.intent; 3730 final boolean document = intent != null && intent.isDocument(); 3731 final ComponentName comp = intent.getComponent(); 3732 3733 int maxRecents = task.maxRecents - 1; 3734 for (int i=0; i<N; i++) { 3735 final TaskRecord tr = mRecentTasks.get(i); 3736 if (task != tr) { 3737 if (task.userId != tr.userId) { 3738 continue; 3739 } 3740 if (i > MAX_RECENT_BITMAPS) { 3741 tr.freeLastThumbnail(); 3742 } 3743 final Intent trIntent = tr.intent; 3744 if ((task.affinity == null || !task.affinity.equals(tr.affinity)) && 3745 (intent == null || !intent.filterEquals(trIntent))) { 3746 continue; 3747 } 3748 final boolean trIsDocument = trIntent != null && trIntent.isDocument(); 3749 if (document && trIsDocument) { 3750 // These are the same document activity (not necessarily the same doc). 3751 if (maxRecents > 0) { 3752 --maxRecents; 3753 continue; 3754 } 3755 // Hit the maximum number of documents for this task. Fall through 3756 // and remove this document from recents. 3757 } else if (document || trIsDocument) { 3758 // Only one of these is a document. Not the droid we're looking for. 3759 continue; 3760 } 3761 } 3762 3763 // Either task and tr are the same or, their affinities match or their intents match 3764 // and neither of them is a document, or they are documents using the same activity 3765 // and their maxRecents has been reached. 3766 tr.disposeThumbnail(); 3767 mRecentTasks.remove(i); 3768 if (task != tr) { 3769 tr.closeRecentsChain(); 3770 } 3771 i--; 3772 N--; 3773 if (task.intent == null) { 3774 // If the new recent task we are adding is not fully 3775 // specified, then replace it with the existing recent task. 3776 task = tr; 3777 } 3778 notifyTaskPersisterLocked(tr, false); 3779 } 3780 if (N >= MAX_RECENT_TASKS) { 3781 final TaskRecord tr = mRecentTasks.remove(N - 1); 3782 tr.disposeThumbnail(); 3783 tr.closeRecentsChain(); 3784 } 3785 mRecentTasks.add(0, task); 3786 } 3787 3788 @Override 3789 public void reportActivityFullyDrawn(IBinder token) { 3790 synchronized (this) { 3791 ActivityRecord r = ActivityRecord.isInStackLocked(token); 3792 if (r == null) { 3793 return; 3794 } 3795 r.reportFullyDrawnLocked(); 3796 } 3797 } 3798 3799 @Override 3800 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 3801 synchronized (this) { 3802 ActivityRecord r = ActivityRecord.isInStackLocked(token); 3803 if (r == null) { 3804 return; 3805 } 3806 final long origId = Binder.clearCallingIdentity(); 3807 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 3808 Configuration config = mWindowManager.updateOrientationFromAppTokens( 3809 mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 3810 if (config != null) { 3811 r.frozenBeforeDestroy = true; 3812 if (!updateConfigurationLocked(config, r, false, false)) { 3813 mStackSupervisor.resumeTopActivitiesLocked(); 3814 } 3815 } 3816 Binder.restoreCallingIdentity(origId); 3817 } 3818 } 3819 3820 @Override 3821 public int getRequestedOrientation(IBinder token) { 3822 synchronized (this) { 3823 ActivityRecord r = ActivityRecord.isInStackLocked(token); 3824 if (r == null) { 3825 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 3826 } 3827 return mWindowManager.getAppOrientation(r.appToken); 3828 } 3829 } 3830 3831 /** 3832 * This is the internal entry point for handling Activity.finish(). 3833 * 3834 * @param token The Binder token referencing the Activity we want to finish. 3835 * @param resultCode Result code, if any, from this Activity. 3836 * @param resultData Result data (Intent), if any, from this Activity. 3837 * @param finishTask Whether to finish the task associated with this Activity. Only applies to 3838 * the root Activity in the task. 3839 * 3840 * @return Returns true if the activity successfully finished, or false if it is still running. 3841 */ 3842 @Override 3843 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 3844 boolean finishTask) { 3845 // Refuse possible leaked file descriptors 3846 if (resultData != null && resultData.hasFileDescriptors() == true) { 3847 throw new IllegalArgumentException("File descriptors passed in Intent"); 3848 } 3849 3850 synchronized(this) { 3851 ActivityRecord r = ActivityRecord.isInStackLocked(token); 3852 if (r == null) { 3853 return true; 3854 } 3855 // Keep track of the root activity of the task before we finish it 3856 TaskRecord tr = r.task; 3857 ActivityRecord rootR = tr.getRootActivity(); 3858 // Do not allow task to finish in Lock Task mode. 3859 if (tr == mStackSupervisor.mLockTaskModeTask) { 3860 if (rootR == r) { 3861 mStackSupervisor.showLockTaskToast(); 3862 return false; 3863 } 3864 } 3865 if (mController != null) { 3866 // Find the first activity that is not finishing. 3867 ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0); 3868 if (next != null) { 3869 // ask watcher if this is allowed 3870 boolean resumeOK = true; 3871 try { 3872 resumeOK = mController.activityResuming(next.packageName); 3873 } catch (RemoteException e) { 3874 mController = null; 3875 Watchdog.getInstance().setActivityController(null); 3876 } 3877 3878 if (!resumeOK) { 3879 return false; 3880 } 3881 } 3882 } 3883 final long origId = Binder.clearCallingIdentity(); 3884 try { 3885 boolean res; 3886 if (finishTask && r == rootR) { 3887 // If requested, remove the task that is associated to this activity only if it 3888 // was the root activity in the task. The result code and data is ignored because 3889 // we don't support returning them across task boundaries. 3890 res = removeTaskByIdLocked(tr.taskId, 0); 3891 } else { 3892 res = tr.stack.requestFinishActivityLocked(token, resultCode, 3893 resultData, "app-request", true); 3894 } 3895 return res; 3896 } finally { 3897 Binder.restoreCallingIdentity(origId); 3898 } 3899 } 3900 } 3901 3902 @Override 3903 public final void finishHeavyWeightApp() { 3904 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3905 != PackageManager.PERMISSION_GRANTED) { 3906 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 3907 + Binder.getCallingPid() 3908 + ", uid=" + Binder.getCallingUid() 3909 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3910 Slog.w(TAG, msg); 3911 throw new SecurityException(msg); 3912 } 3913 3914 synchronized(this) { 3915 if (mHeavyWeightProcess == null) { 3916 return; 3917 } 3918 3919 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>( 3920 mHeavyWeightProcess.activities); 3921 for (int i=0; i<activities.size(); i++) { 3922 ActivityRecord r = activities.get(i); 3923 if (!r.finishing) { 3924 r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED, 3925 null, "finish-heavy", true); 3926 } 3927 } 3928 3929 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 3930 mHeavyWeightProcess.userId, 0)); 3931 mHeavyWeightProcess = null; 3932 } 3933 } 3934 3935 @Override 3936 public void crashApplication(int uid, int initialPid, String packageName, 3937 String message) { 3938 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3939 != PackageManager.PERMISSION_GRANTED) { 3940 String msg = "Permission Denial: crashApplication() from pid=" 3941 + Binder.getCallingPid() 3942 + ", uid=" + Binder.getCallingUid() 3943 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3944 Slog.w(TAG, msg); 3945 throw new SecurityException(msg); 3946 } 3947 3948 synchronized(this) { 3949 ProcessRecord proc = null; 3950 3951 // Figure out which process to kill. We don't trust that initialPid 3952 // still has any relation to current pids, so must scan through the 3953 // list. 3954 synchronized (mPidsSelfLocked) { 3955 for (int i=0; i<mPidsSelfLocked.size(); i++) { 3956 ProcessRecord p = mPidsSelfLocked.valueAt(i); 3957 if (p.uid != uid) { 3958 continue; 3959 } 3960 if (p.pid == initialPid) { 3961 proc = p; 3962 break; 3963 } 3964 if (p.pkgList.containsKey(packageName)) { 3965 proc = p; 3966 } 3967 } 3968 } 3969 3970 if (proc == null) { 3971 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 3972 + " initialPid=" + initialPid 3973 + " packageName=" + packageName); 3974 return; 3975 } 3976 3977 if (proc.thread != null) { 3978 if (proc.pid == Process.myPid()) { 3979 Log.w(TAG, "crashApplication: trying to crash self!"); 3980 return; 3981 } 3982 long ident = Binder.clearCallingIdentity(); 3983 try { 3984 proc.thread.scheduleCrash(message); 3985 } catch (RemoteException e) { 3986 } 3987 Binder.restoreCallingIdentity(ident); 3988 } 3989 } 3990 } 3991 3992 @Override 3993 public final void finishSubActivity(IBinder token, String resultWho, 3994 int requestCode) { 3995 synchronized(this) { 3996 final long origId = Binder.clearCallingIdentity(); 3997 ActivityRecord r = ActivityRecord.isInStackLocked(token); 3998 if (r != null) { 3999 r.task.stack.finishSubActivityLocked(r, resultWho, requestCode); 4000 } 4001 Binder.restoreCallingIdentity(origId); 4002 } 4003 } 4004 4005 @Override 4006 public boolean finishActivityAffinity(IBinder token) { 4007 synchronized(this) { 4008 final long origId = Binder.clearCallingIdentity(); 4009 try { 4010 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4011 4012 ActivityRecord rootR = r.task.getRootActivity(); 4013 // Do not allow task to finish in Lock Task mode. 4014 if (r.task == mStackSupervisor.mLockTaskModeTask) { 4015 if (rootR == r) { 4016 mStackSupervisor.showLockTaskToast(); 4017 return false; 4018 } 4019 } 4020 boolean res = false; 4021 if (r != null) { 4022 res = r.task.stack.finishActivityAffinityLocked(r); 4023 } 4024 return res; 4025 } finally { 4026 Binder.restoreCallingIdentity(origId); 4027 } 4028 } 4029 } 4030 4031 @Override 4032 public void finishVoiceTask(IVoiceInteractionSession session) { 4033 synchronized(this) { 4034 final long origId = Binder.clearCallingIdentity(); 4035 try { 4036 mStackSupervisor.finishVoiceTask(session); 4037 } finally { 4038 Binder.restoreCallingIdentity(origId); 4039 } 4040 } 4041 4042 } 4043 4044 @Override 4045 public boolean willActivityBeVisible(IBinder token) { 4046 synchronized(this) { 4047 ActivityStack stack = ActivityRecord.getStackLocked(token); 4048 if (stack != null) { 4049 return stack.willActivityBeVisibleLocked(token); 4050 } 4051 return false; 4052 } 4053 } 4054 4055 @Override 4056 public void overridePendingTransition(IBinder token, String packageName, 4057 int enterAnim, int exitAnim) { 4058 synchronized(this) { 4059 ActivityRecord self = ActivityRecord.isInStackLocked(token); 4060 if (self == null) { 4061 return; 4062 } 4063 4064 final long origId = Binder.clearCallingIdentity(); 4065 4066 if (self.state == ActivityState.RESUMED 4067 || self.state == ActivityState.PAUSING) { 4068 mWindowManager.overridePendingAppTransition(packageName, 4069 enterAnim, exitAnim, null); 4070 } 4071 4072 Binder.restoreCallingIdentity(origId); 4073 } 4074 } 4075 4076 /** 4077 * Main function for removing an existing process from the activity manager 4078 * as a result of that process going away. Clears out all connections 4079 * to the process. 4080 */ 4081 private final void handleAppDiedLocked(ProcessRecord app, 4082 boolean restarting, boolean allowRestart) { 4083 int pid = app.pid; 4084 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 4085 if (!restarting) { 4086 removeLruProcessLocked(app); 4087 if (pid > 0) { 4088 ProcessList.remove(pid); 4089 } 4090 } 4091 4092 if (mProfileProc == app) { 4093 clearProfilerLocked(); 4094 } 4095 4096 // Remove this application's activities from active lists. 4097 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app); 4098 4099 app.activities.clear(); 4100 4101 if (app.instrumentationClass != null) { 4102 Slog.w(TAG, "Crash of app " + app.processName 4103 + " running instrumentation " + app.instrumentationClass); 4104 Bundle info = new Bundle(); 4105 info.putString("shortMsg", "Process crashed."); 4106 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4107 } 4108 4109 if (!restarting) { 4110 if (!mStackSupervisor.resumeTopActivitiesLocked()) { 4111 // If there was nothing to resume, and we are not already 4112 // restarting this process, but there is a visible activity that 4113 // is hosted by the process... then make sure all visible 4114 // activities are running, taking care of restarting this 4115 // process. 4116 if (hasVisibleActivities) { 4117 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 4118 } 4119 } 4120 } 4121 } 4122 4123 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 4124 IBinder threadBinder = thread.asBinder(); 4125 // Find the application record. 4126 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4127 ProcessRecord rec = mLruProcesses.get(i); 4128 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 4129 return i; 4130 } 4131 } 4132 return -1; 4133 } 4134 4135 final ProcessRecord getRecordForAppLocked( 4136 IApplicationThread thread) { 4137 if (thread == null) { 4138 return null; 4139 } 4140 4141 int appIndex = getLRURecordIndexForAppLocked(thread); 4142 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 4143 } 4144 4145 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 4146 // If there are no longer any background processes running, 4147 // and the app that died was not running instrumentation, 4148 // then tell everyone we are now low on memory. 4149 boolean haveBg = false; 4150 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4151 ProcessRecord rec = mLruProcesses.get(i); 4152 if (rec.thread != null 4153 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 4154 haveBg = true; 4155 break; 4156 } 4157 } 4158 4159 if (!haveBg) { 4160 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 4161 if (doReport) { 4162 long now = SystemClock.uptimeMillis(); 4163 if (now < (mLastMemUsageReportTime+5*60*1000)) { 4164 doReport = false; 4165 } else { 4166 mLastMemUsageReportTime = now; 4167 } 4168 } 4169 final ArrayList<ProcessMemInfo> memInfos 4170 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null; 4171 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 4172 long now = SystemClock.uptimeMillis(); 4173 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4174 ProcessRecord rec = mLruProcesses.get(i); 4175 if (rec == dyingProc || rec.thread == null) { 4176 continue; 4177 } 4178 if (doReport) { 4179 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 4180 rec.setProcState, rec.adjType, rec.makeAdjReason())); 4181 } 4182 if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 4183 // The low memory report is overriding any current 4184 // state for a GC request. Make sure to do 4185 // heavy/important/visible/foreground processes first. 4186 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 4187 rec.lastRequestedGc = 0; 4188 } else { 4189 rec.lastRequestedGc = rec.lastLowMemory; 4190 } 4191 rec.reportLowMemory = true; 4192 rec.lastLowMemory = now; 4193 mProcessesToGc.remove(rec); 4194 addProcessToGcListLocked(rec); 4195 } 4196 } 4197 if (doReport) { 4198 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 4199 mHandler.sendMessage(msg); 4200 } 4201 scheduleAppGcsLocked(); 4202 } 4203 } 4204 4205 final void appDiedLocked(ProcessRecord app, int pid, 4206 IApplicationThread thread) { 4207 4208 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 4209 synchronized (stats) { 4210 stats.noteProcessDiedLocked(app.info.uid, pid); 4211 } 4212 4213 Process.killProcessGroup(app.info.uid, pid); 4214 4215 // Clean up already done if the process has been re-started. 4216 if (app.pid == pid && app.thread != null && 4217 app.thread.asBinder() == thread.asBinder()) { 4218 boolean doLowMem = app.instrumentationClass == null; 4219 boolean doOomAdj = doLowMem; 4220 if (!app.killedByAm) { 4221 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4222 + ") has died."); 4223 mAllowLowerMemLevel = true; 4224 } else { 4225 // Note that we always want to do oom adj to update our state with the 4226 // new number of procs. 4227 mAllowLowerMemLevel = false; 4228 doLowMem = false; 4229 } 4230 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4231 if (DEBUG_CLEANUP) Slog.v( 4232 TAG, "Dying app: " + app + ", pid: " + pid 4233 + ", thread: " + thread.asBinder()); 4234 handleAppDiedLocked(app, false, true); 4235 4236 if (doOomAdj) { 4237 updateOomAdjLocked(); 4238 } 4239 if (doLowMem) { 4240 doLowMemReportIfNeededLocked(app); 4241 } 4242 } else if (app.pid != pid) { 4243 // A new process has already been started. 4244 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4245 + ") has died and restarted (pid " + app.pid + ")."); 4246 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4247 } else if (DEBUG_PROCESSES) { 4248 Slog.d(TAG, "Received spurious death notification for thread " 4249 + thread.asBinder()); 4250 } 4251 } 4252 4253 /** 4254 * If a stack trace dump file is configured, dump process stack traces. 4255 * @param clearTraces causes the dump file to be erased prior to the new 4256 * traces being written, if true; when false, the new traces will be 4257 * appended to any existing file content. 4258 * @param firstPids of dalvik VM processes to dump stack traces for first 4259 * @param lastPids of dalvik VM processes to dump stack traces for last 4260 * @param nativeProcs optional list of native process names to dump stack crawls 4261 * @return file containing stack traces, or null if no dump file is configured 4262 */ 4263 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 4264 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4265 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4266 if (tracesPath == null || tracesPath.length() == 0) { 4267 return null; 4268 } 4269 4270 File tracesFile = new File(tracesPath); 4271 try { 4272 File tracesDir = tracesFile.getParentFile(); 4273 if (!tracesDir.exists()) { 4274 tracesFile.mkdirs(); 4275 if (!SELinux.restorecon(tracesDir)) { 4276 return null; 4277 } 4278 } 4279 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4280 4281 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 4282 tracesFile.createNewFile(); 4283 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 4284 } catch (IOException e) { 4285 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 4286 return null; 4287 } 4288 4289 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs); 4290 return tracesFile; 4291 } 4292 4293 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 4294 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4295 // Use a FileObserver to detect when traces finish writing. 4296 // The order of traces is considered important to maintain for legibility. 4297 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 4298 @Override 4299 public synchronized void onEvent(int event, String path) { notify(); } 4300 }; 4301 4302 try { 4303 observer.startWatching(); 4304 4305 // First collect all of the stacks of the most important pids. 4306 if (firstPids != null) { 4307 try { 4308 int num = firstPids.size(); 4309 for (int i = 0; i < num; i++) { 4310 synchronized (observer) { 4311 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 4312 observer.wait(200); // Wait for write-close, give up after 200msec 4313 } 4314 } 4315 } catch (InterruptedException e) { 4316 Log.wtf(TAG, e); 4317 } 4318 } 4319 4320 // Next collect the stacks of the native pids 4321 if (nativeProcs != null) { 4322 int[] pids = Process.getPidsForCommands(nativeProcs); 4323 if (pids != null) { 4324 for (int pid : pids) { 4325 Debug.dumpNativeBacktraceToFile(pid, tracesPath); 4326 } 4327 } 4328 } 4329 4330 // Lastly, measure CPU usage. 4331 if (processCpuTracker != null) { 4332 processCpuTracker.init(); 4333 System.gc(); 4334 processCpuTracker.update(); 4335 try { 4336 synchronized (processCpuTracker) { 4337 processCpuTracker.wait(500); // measure over 1/2 second. 4338 } 4339 } catch (InterruptedException e) { 4340 } 4341 processCpuTracker.update(); 4342 4343 // We'll take the stack crawls of just the top apps using CPU. 4344 final int N = processCpuTracker.countWorkingStats(); 4345 int numProcs = 0; 4346 for (int i=0; i<N && numProcs<5; i++) { 4347 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 4348 if (lastPids.indexOfKey(stats.pid) >= 0) { 4349 numProcs++; 4350 try { 4351 synchronized (observer) { 4352 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 4353 observer.wait(200); // Wait for write-close, give up after 200msec 4354 } 4355 } catch (InterruptedException e) { 4356 Log.wtf(TAG, e); 4357 } 4358 4359 } 4360 } 4361 } 4362 } finally { 4363 observer.stopWatching(); 4364 } 4365 } 4366 4367 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 4368 if (true || IS_USER_BUILD) { 4369 return; 4370 } 4371 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4372 if (tracesPath == null || tracesPath.length() == 0) { 4373 return; 4374 } 4375 4376 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 4377 StrictMode.allowThreadDiskWrites(); 4378 try { 4379 final File tracesFile = new File(tracesPath); 4380 final File tracesDir = tracesFile.getParentFile(); 4381 final File tracesTmp = new File(tracesDir, "__tmp__"); 4382 try { 4383 if (!tracesDir.exists()) { 4384 tracesFile.mkdirs(); 4385 if (!SELinux.restorecon(tracesDir.getPath())) { 4386 return; 4387 } 4388 } 4389 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4390 4391 if (tracesFile.exists()) { 4392 tracesTmp.delete(); 4393 tracesFile.renameTo(tracesTmp); 4394 } 4395 StringBuilder sb = new StringBuilder(); 4396 Time tobj = new Time(); 4397 tobj.set(System.currentTimeMillis()); 4398 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 4399 sb.append(": "); 4400 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 4401 sb.append(" since "); 4402 sb.append(msg); 4403 FileOutputStream fos = new FileOutputStream(tracesFile); 4404 fos.write(sb.toString().getBytes()); 4405 if (app == null) { 4406 fos.write("\n*** No application process!".getBytes()); 4407 } 4408 fos.close(); 4409 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 4410 } catch (IOException e) { 4411 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 4412 return; 4413 } 4414 4415 if (app != null) { 4416 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 4417 firstPids.add(app.pid); 4418 dumpStackTraces(tracesPath, firstPids, null, null, null); 4419 } 4420 4421 File lastTracesFile = null; 4422 File curTracesFile = null; 4423 for (int i=9; i>=0; i--) { 4424 String name = String.format(Locale.US, "slow%02d.txt", i); 4425 curTracesFile = new File(tracesDir, name); 4426 if (curTracesFile.exists()) { 4427 if (lastTracesFile != null) { 4428 curTracesFile.renameTo(lastTracesFile); 4429 } else { 4430 curTracesFile.delete(); 4431 } 4432 } 4433 lastTracesFile = curTracesFile; 4434 } 4435 tracesFile.renameTo(curTracesFile); 4436 if (tracesTmp.exists()) { 4437 tracesTmp.renameTo(tracesFile); 4438 } 4439 } finally { 4440 StrictMode.setThreadPolicy(oldPolicy); 4441 } 4442 } 4443 4444 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 4445 ActivityRecord parent, boolean aboveSystem, final String annotation) { 4446 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 4447 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 4448 4449 if (mController != null) { 4450 try { 4451 // 0 == continue, -1 = kill process immediately 4452 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 4453 if (res < 0 && app.pid != MY_PID) { 4454 Process.killProcess(app.pid); 4455 Process.killProcessGroup(app.info.uid, app.pid); 4456 } 4457 } catch (RemoteException e) { 4458 mController = null; 4459 Watchdog.getInstance().setActivityController(null); 4460 } 4461 } 4462 4463 long anrTime = SystemClock.uptimeMillis(); 4464 if (MONITOR_CPU_USAGE) { 4465 updateCpuStatsNow(); 4466 } 4467 4468 synchronized (this) { 4469 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 4470 if (mShuttingDown) { 4471 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 4472 return; 4473 } else if (app.notResponding) { 4474 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 4475 return; 4476 } else if (app.crashing) { 4477 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 4478 return; 4479 } 4480 4481 // In case we come through here for the same app before completing 4482 // this one, mark as anring now so we will bail out. 4483 app.notResponding = true; 4484 4485 // Log the ANR to the event log. 4486 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 4487 app.processName, app.info.flags, annotation); 4488 4489 // Dump thread traces as quickly as we can, starting with "interesting" processes. 4490 firstPids.add(app.pid); 4491 4492 int parentPid = app.pid; 4493 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 4494 if (parentPid != app.pid) firstPids.add(parentPid); 4495 4496 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 4497 4498 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 4499 ProcessRecord r = mLruProcesses.get(i); 4500 if (r != null && r.thread != null) { 4501 int pid = r.pid; 4502 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 4503 if (r.persistent) { 4504 firstPids.add(pid); 4505 } else { 4506 lastPids.put(pid, Boolean.TRUE); 4507 } 4508 } 4509 } 4510 } 4511 } 4512 4513 // Log the ANR to the main log. 4514 StringBuilder info = new StringBuilder(); 4515 info.setLength(0); 4516 info.append("ANR in ").append(app.processName); 4517 if (activity != null && activity.shortComponentName != null) { 4518 info.append(" (").append(activity.shortComponentName).append(")"); 4519 } 4520 info.append("\n"); 4521 info.append("PID: ").append(app.pid).append("\n"); 4522 if (annotation != null) { 4523 info.append("Reason: ").append(annotation).append("\n"); 4524 } 4525 if (parent != null && parent != activity) { 4526 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 4527 } 4528 4529 final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true); 4530 4531 File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids, 4532 NATIVE_STACKS_OF_INTEREST); 4533 4534 String cpuInfo = null; 4535 if (MONITOR_CPU_USAGE) { 4536 updateCpuStatsNow(); 4537 synchronized (mProcessCpuThread) { 4538 cpuInfo = mProcessCpuTracker.printCurrentState(anrTime); 4539 } 4540 info.append(processCpuTracker.printCurrentLoad()); 4541 info.append(cpuInfo); 4542 } 4543 4544 info.append(processCpuTracker.printCurrentState(anrTime)); 4545 4546 Slog.e(TAG, info.toString()); 4547 if (tracesFile == null) { 4548 // There is no trace file, so dump (only) the alleged culprit's threads to the log 4549 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 4550 } 4551 4552 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 4553 cpuInfo, tracesFile, null); 4554 4555 if (mController != null) { 4556 try { 4557 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 4558 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 4559 if (res != 0) { 4560 if (res < 0 && app.pid != MY_PID) { 4561 Process.killProcess(app.pid); 4562 Process.killProcessGroup(app.info.uid, app.pid); 4563 } else { 4564 synchronized (this) { 4565 mServices.scheduleServiceTimeoutLocked(app); 4566 } 4567 } 4568 return; 4569 } 4570 } catch (RemoteException e) { 4571 mController = null; 4572 Watchdog.getInstance().setActivityController(null); 4573 } 4574 } 4575 4576 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 4577 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 4578 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 4579 4580 synchronized (this) { 4581 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 4582 killUnneededProcessLocked(app, "background ANR"); 4583 return; 4584 } 4585 4586 // Set the app's notResponding state, and look up the errorReportReceiver 4587 makeAppNotRespondingLocked(app, 4588 activity != null ? activity.shortComponentName : null, 4589 annotation != null ? "ANR " + annotation : "ANR", 4590 info.toString()); 4591 4592 // Bring up the infamous App Not Responding dialog 4593 Message msg = Message.obtain(); 4594 HashMap<String, Object> map = new HashMap<String, Object>(); 4595 msg.what = SHOW_NOT_RESPONDING_MSG; 4596 msg.obj = map; 4597 msg.arg1 = aboveSystem ? 1 : 0; 4598 map.put("app", app); 4599 if (activity != null) { 4600 map.put("activity", activity); 4601 } 4602 4603 mHandler.sendMessage(msg); 4604 } 4605 } 4606 4607 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 4608 if (!mLaunchWarningShown) { 4609 mLaunchWarningShown = true; 4610 mHandler.post(new Runnable() { 4611 @Override 4612 public void run() { 4613 synchronized (ActivityManagerService.this) { 4614 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 4615 d.show(); 4616 mHandler.postDelayed(new Runnable() { 4617 @Override 4618 public void run() { 4619 synchronized (ActivityManagerService.this) { 4620 d.dismiss(); 4621 mLaunchWarningShown = false; 4622 } 4623 } 4624 }, 4000); 4625 } 4626 } 4627 }); 4628 } 4629 } 4630 4631 @Override 4632 public boolean clearApplicationUserData(final String packageName, 4633 final IPackageDataObserver observer, int userId) { 4634 enforceNotIsolatedCaller("clearApplicationUserData"); 4635 int uid = Binder.getCallingUid(); 4636 int pid = Binder.getCallingPid(); 4637 userId = handleIncomingUser(pid, uid, 4638 userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null); 4639 long callingId = Binder.clearCallingIdentity(); 4640 try { 4641 IPackageManager pm = AppGlobals.getPackageManager(); 4642 int pkgUid = -1; 4643 synchronized(this) { 4644 try { 4645 pkgUid = pm.getPackageUid(packageName, userId); 4646 } catch (RemoteException e) { 4647 } 4648 if (pkgUid == -1) { 4649 Slog.w(TAG, "Invalid packageName: " + packageName); 4650 if (observer != null) { 4651 try { 4652 observer.onRemoveCompleted(packageName, false); 4653 } catch (RemoteException e) { 4654 Slog.i(TAG, "Observer no longer exists."); 4655 } 4656 } 4657 return false; 4658 } 4659 if (uid == pkgUid || checkComponentPermission( 4660 android.Manifest.permission.CLEAR_APP_USER_DATA, 4661 pid, uid, -1, true) 4662 == PackageManager.PERMISSION_GRANTED) { 4663 forceStopPackageLocked(packageName, pkgUid, "clear data"); 4664 } else { 4665 throw new SecurityException("PID " + pid + " does not have permission " 4666 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 4667 + " of package " + packageName); 4668 } 4669 } 4670 4671 try { 4672 // Clear application user data 4673 pm.clearApplicationUserData(packageName, observer, userId); 4674 4675 // Remove all permissions granted from/to this package 4676 removeUriPermissionsForPackageLocked(packageName, userId, true); 4677 4678 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 4679 Uri.fromParts("package", packageName, null)); 4680 intent.putExtra(Intent.EXTRA_UID, pkgUid); 4681 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 4682 null, null, 0, null, null, null, false, false, userId); 4683 } catch (RemoteException e) { 4684 } 4685 } finally { 4686 Binder.restoreCallingIdentity(callingId); 4687 } 4688 return true; 4689 } 4690 4691 @Override 4692 public void killBackgroundProcesses(final String packageName, int userId) { 4693 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4694 != PackageManager.PERMISSION_GRANTED && 4695 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 4696 != PackageManager.PERMISSION_GRANTED) { 4697 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 4698 + Binder.getCallingPid() 4699 + ", uid=" + Binder.getCallingUid() 4700 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 4701 Slog.w(TAG, msg); 4702 throw new SecurityException(msg); 4703 } 4704 4705 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 4706 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 4707 long callingId = Binder.clearCallingIdentity(); 4708 try { 4709 IPackageManager pm = AppGlobals.getPackageManager(); 4710 synchronized(this) { 4711 int appId = -1; 4712 try { 4713 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0)); 4714 } catch (RemoteException e) { 4715 } 4716 if (appId == -1) { 4717 Slog.w(TAG, "Invalid packageName: " + packageName); 4718 return; 4719 } 4720 killPackageProcessesLocked(packageName, appId, userId, 4721 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 4722 } 4723 } finally { 4724 Binder.restoreCallingIdentity(callingId); 4725 } 4726 } 4727 4728 @Override 4729 public void killAllBackgroundProcesses() { 4730 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 4731 != PackageManager.PERMISSION_GRANTED) { 4732 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 4733 + Binder.getCallingPid() 4734 + ", uid=" + Binder.getCallingUid() 4735 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 4736 Slog.w(TAG, msg); 4737 throw new SecurityException(msg); 4738 } 4739 4740 long callingId = Binder.clearCallingIdentity(); 4741 try { 4742 synchronized(this) { 4743 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 4744 final int NP = mProcessNames.getMap().size(); 4745 for (int ip=0; ip<NP; ip++) { 4746 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 4747 final int NA = apps.size(); 4748 for (int ia=0; ia<NA; ia++) { 4749 ProcessRecord app = apps.valueAt(ia); 4750 if (app.persistent) { 4751 // we don't kill persistent processes 4752 continue; 4753 } 4754 if (app.removed) { 4755 procs.add(app); 4756 } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 4757 app.removed = true; 4758 procs.add(app); 4759 } 4760 } 4761 } 4762 4763 int N = procs.size(); 4764 for (int i=0; i<N; i++) { 4765 removeProcessLocked(procs.get(i), false, true, "kill all background"); 4766 } 4767 mAllowLowerMemLevel = true; 4768 updateOomAdjLocked(); 4769 doLowMemReportIfNeededLocked(null); 4770 } 4771 } finally { 4772 Binder.restoreCallingIdentity(callingId); 4773 } 4774 } 4775 4776 @Override 4777 public void forceStopPackage(final String packageName, int userId) { 4778 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4779 != PackageManager.PERMISSION_GRANTED) { 4780 String msg = "Permission Denial: forceStopPackage() from pid=" 4781 + Binder.getCallingPid() 4782 + ", uid=" + Binder.getCallingUid() 4783 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4784 Slog.w(TAG, msg); 4785 throw new SecurityException(msg); 4786 } 4787 final int callingPid = Binder.getCallingPid(); 4788 userId = handleIncomingUser(callingPid, Binder.getCallingUid(), 4789 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 4790 long callingId = Binder.clearCallingIdentity(); 4791 try { 4792 IPackageManager pm = AppGlobals.getPackageManager(); 4793 synchronized(this) { 4794 int[] users = userId == UserHandle.USER_ALL 4795 ? getUsersLocked() : new int[] { userId }; 4796 for (int user : users) { 4797 int pkgUid = -1; 4798 try { 4799 pkgUid = pm.getPackageUid(packageName, user); 4800 } catch (RemoteException e) { 4801 } 4802 if (pkgUid == -1) { 4803 Slog.w(TAG, "Invalid packageName: " + packageName); 4804 continue; 4805 } 4806 try { 4807 pm.setPackageStoppedState(packageName, true, user); 4808 } catch (RemoteException e) { 4809 } catch (IllegalArgumentException e) { 4810 Slog.w(TAG, "Failed trying to unstop package " 4811 + packageName + ": " + e); 4812 } 4813 if (isUserRunningLocked(user, false)) { 4814 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 4815 } 4816 } 4817 } 4818 } finally { 4819 Binder.restoreCallingIdentity(callingId); 4820 } 4821 } 4822 4823 @Override 4824 public void addPackageDependency(String packageName) { 4825 synchronized (this) { 4826 int callingPid = Binder.getCallingPid(); 4827 if (callingPid == Process.myPid()) { 4828 // Yeah, um, no. 4829 Slog.w(TAG, "Can't addPackageDependency on system process"); 4830 return; 4831 } 4832 ProcessRecord proc; 4833 synchronized (mPidsSelfLocked) { 4834 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 4835 } 4836 if (proc != null) { 4837 if (proc.pkgDeps == null) { 4838 proc.pkgDeps = new ArraySet<String>(1); 4839 } 4840 proc.pkgDeps.add(packageName); 4841 } 4842 } 4843 } 4844 4845 /* 4846 * The pkg name and app id have to be specified. 4847 */ 4848 @Override 4849 public void killApplicationWithAppId(String pkg, int appid, String reason) { 4850 if (pkg == null) { 4851 return; 4852 } 4853 // Make sure the uid is valid. 4854 if (appid < 0) { 4855 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 4856 return; 4857 } 4858 int callerUid = Binder.getCallingUid(); 4859 // Only the system server can kill an application 4860 if (callerUid == Process.SYSTEM_UID) { 4861 // Post an aysnc message to kill the application 4862 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 4863 msg.arg1 = appid; 4864 msg.arg2 = 0; 4865 Bundle bundle = new Bundle(); 4866 bundle.putString("pkg", pkg); 4867 bundle.putString("reason", reason); 4868 msg.obj = bundle; 4869 mHandler.sendMessage(msg); 4870 } else { 4871 throw new SecurityException(callerUid + " cannot kill pkg: " + 4872 pkg); 4873 } 4874 } 4875 4876 @Override 4877 public void closeSystemDialogs(String reason) { 4878 enforceNotIsolatedCaller("closeSystemDialogs"); 4879 4880 final int pid = Binder.getCallingPid(); 4881 final int uid = Binder.getCallingUid(); 4882 final long origId = Binder.clearCallingIdentity(); 4883 try { 4884 synchronized (this) { 4885 // Only allow this from foreground processes, so that background 4886 // applications can't abuse it to prevent system UI from being shown. 4887 if (uid >= Process.FIRST_APPLICATION_UID) { 4888 ProcessRecord proc; 4889 synchronized (mPidsSelfLocked) { 4890 proc = mPidsSelfLocked.get(pid); 4891 } 4892 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 4893 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 4894 + " from background process " + proc); 4895 return; 4896 } 4897 } 4898 closeSystemDialogsLocked(reason); 4899 } 4900 } finally { 4901 Binder.restoreCallingIdentity(origId); 4902 } 4903 } 4904 4905 void closeSystemDialogsLocked(String reason) { 4906 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 4907 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 4908 | Intent.FLAG_RECEIVER_FOREGROUND); 4909 if (reason != null) { 4910 intent.putExtra("reason", reason); 4911 } 4912 mWindowManager.closeSystemDialogs(reason); 4913 4914 mStackSupervisor.closeSystemDialogsLocked(); 4915 4916 broadcastIntentLocked(null, null, intent, null, 4917 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1, 4918 Process.SYSTEM_UID, UserHandle.USER_ALL); 4919 } 4920 4921 @Override 4922 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 4923 enforceNotIsolatedCaller("getProcessMemoryInfo"); 4924 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 4925 for (int i=pids.length-1; i>=0; i--) { 4926 ProcessRecord proc; 4927 int oomAdj; 4928 synchronized (this) { 4929 synchronized (mPidsSelfLocked) { 4930 proc = mPidsSelfLocked.get(pids[i]); 4931 oomAdj = proc != null ? proc.setAdj : 0; 4932 } 4933 } 4934 infos[i] = new Debug.MemoryInfo(); 4935 Debug.getMemoryInfo(pids[i], infos[i]); 4936 if (proc != null) { 4937 synchronized (this) { 4938 if (proc.thread != null && proc.setAdj == oomAdj) { 4939 // Record this for posterity if the process has been stable. 4940 proc.baseProcessTracker.addPss(infos[i].getTotalPss(), 4941 infos[i].getTotalUss(), false, proc.pkgList); 4942 } 4943 } 4944 } 4945 } 4946 return infos; 4947 } 4948 4949 @Override 4950 public long[] getProcessPss(int[] pids) { 4951 enforceNotIsolatedCaller("getProcessPss"); 4952 long[] pss = new long[pids.length]; 4953 for (int i=pids.length-1; i>=0; i--) { 4954 ProcessRecord proc; 4955 int oomAdj; 4956 synchronized (this) { 4957 synchronized (mPidsSelfLocked) { 4958 proc = mPidsSelfLocked.get(pids[i]); 4959 oomAdj = proc != null ? proc.setAdj : 0; 4960 } 4961 } 4962 long[] tmpUss = new long[1]; 4963 pss[i] = Debug.getPss(pids[i], tmpUss); 4964 if (proc != null) { 4965 synchronized (this) { 4966 if (proc.thread != null && proc.setAdj == oomAdj) { 4967 // Record this for posterity if the process has been stable. 4968 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList); 4969 } 4970 } 4971 } 4972 } 4973 return pss; 4974 } 4975 4976 @Override 4977 public void killApplicationProcess(String processName, int uid) { 4978 if (processName == null) { 4979 return; 4980 } 4981 4982 int callerUid = Binder.getCallingUid(); 4983 // Only the system server can kill an application 4984 if (callerUid == Process.SYSTEM_UID) { 4985 synchronized (this) { 4986 ProcessRecord app = getProcessRecordLocked(processName, uid, true); 4987 if (app != null && app.thread != null) { 4988 try { 4989 app.thread.scheduleSuicide(); 4990 } catch (RemoteException e) { 4991 // If the other end already died, then our work here is done. 4992 } 4993 } else { 4994 Slog.w(TAG, "Process/uid not found attempting kill of " 4995 + processName + " / " + uid); 4996 } 4997 } 4998 } else { 4999 throw new SecurityException(callerUid + " cannot kill app process: " + 5000 processName); 5001 } 5002 } 5003 5004 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 5005 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 5006 false, true, false, false, UserHandle.getUserId(uid), reason); 5007 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 5008 Uri.fromParts("package", packageName, null)); 5009 if (!mProcessesReady) { 5010 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5011 | Intent.FLAG_RECEIVER_FOREGROUND); 5012 } 5013 intent.putExtra(Intent.EXTRA_UID, uid); 5014 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 5015 broadcastIntentLocked(null, null, intent, 5016 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5017 false, false, 5018 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); 5019 } 5020 5021 private void forceStopUserLocked(int userId, String reason) { 5022 forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason); 5023 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 5024 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5025 | Intent.FLAG_RECEIVER_FOREGROUND); 5026 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 5027 broadcastIntentLocked(null, null, intent, 5028 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5029 false, false, 5030 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 5031 } 5032 5033 private final boolean killPackageProcessesLocked(String packageName, int appId, 5034 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 5035 boolean doit, boolean evenPersistent, String reason) { 5036 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 5037 5038 // Remove all processes this package may have touched: all with the 5039 // same UID (except for the system or root user), and all whose name 5040 // matches the package name. 5041 final int NP = mProcessNames.getMap().size(); 5042 for (int ip=0; ip<NP; ip++) { 5043 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 5044 final int NA = apps.size(); 5045 for (int ia=0; ia<NA; ia++) { 5046 ProcessRecord app = apps.valueAt(ia); 5047 if (app.persistent && !evenPersistent) { 5048 // we don't kill persistent processes 5049 continue; 5050 } 5051 if (app.removed) { 5052 if (doit) { 5053 procs.add(app); 5054 } 5055 continue; 5056 } 5057 5058 // Skip process if it doesn't meet our oom adj requirement. 5059 if (app.setAdj < minOomAdj) { 5060 continue; 5061 } 5062 5063 // If no package is specified, we call all processes under the 5064 // give user id. 5065 if (packageName == null) { 5066 if (app.userId != userId) { 5067 continue; 5068 } 5069 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 5070 continue; 5071 } 5072 // Package has been specified, we want to hit all processes 5073 // that match it. We need to qualify this by the processes 5074 // that are running under the specified app and user ID. 5075 } else { 5076 final boolean isDep = app.pkgDeps != null 5077 && app.pkgDeps.contains(packageName); 5078 if (!isDep && UserHandle.getAppId(app.uid) != appId) { 5079 continue; 5080 } 5081 if (userId != UserHandle.USER_ALL && app.userId != userId) { 5082 continue; 5083 } 5084 if (!app.pkgList.containsKey(packageName) && !isDep) { 5085 continue; 5086 } 5087 } 5088 5089 // Process has passed all conditions, kill it! 5090 if (!doit) { 5091 return true; 5092 } 5093 app.removed = true; 5094 procs.add(app); 5095 } 5096 } 5097 5098 int N = procs.size(); 5099 for (int i=0; i<N; i++) { 5100 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 5101 } 5102 updateOomAdjLocked(); 5103 return N > 0; 5104 } 5105 5106 private final boolean forceStopPackageLocked(String name, int appId, 5107 boolean callerWillRestart, boolean purgeCache, boolean doit, 5108 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 5109 int i; 5110 int N; 5111 5112 if (userId == UserHandle.USER_ALL && name == null) { 5113 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 5114 } 5115 5116 if (appId < 0 && name != null) { 5117 try { 5118 appId = UserHandle.getAppId( 5119 AppGlobals.getPackageManager().getPackageUid(name, 0)); 5120 } catch (RemoteException e) { 5121 } 5122 } 5123 5124 if (doit) { 5125 if (name != null) { 5126 Slog.i(TAG, "Force stopping " + name + " appid=" + appId 5127 + " user=" + userId + ": " + reason); 5128 } else { 5129 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 5130 } 5131 5132 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 5133 for (int ip=pmap.size()-1; ip>=0; ip--) { 5134 SparseArray<Long> ba = pmap.valueAt(ip); 5135 for (i=ba.size()-1; i>=0; i--) { 5136 boolean remove = false; 5137 final int entUid = ba.keyAt(i); 5138 if (name != null) { 5139 if (userId == UserHandle.USER_ALL) { 5140 if (UserHandle.getAppId(entUid) == appId) { 5141 remove = true; 5142 } 5143 } else { 5144 if (entUid == UserHandle.getUid(userId, appId)) { 5145 remove = true; 5146 } 5147 } 5148 } else if (UserHandle.getUserId(entUid) == userId) { 5149 remove = true; 5150 } 5151 if (remove) { 5152 ba.removeAt(i); 5153 } 5154 } 5155 if (ba.size() == 0) { 5156 pmap.removeAt(ip); 5157 } 5158 } 5159 } 5160 5161 boolean didSomething = killPackageProcessesLocked(name, appId, userId, 5162 -100, callerWillRestart, true, doit, evenPersistent, 5163 name == null ? ("stop user " + userId) : ("stop " + name)); 5164 5165 if (mStackSupervisor.forceStopPackageLocked(name, doit, evenPersistent, userId)) { 5166 if (!doit) { 5167 return true; 5168 } 5169 didSomething = true; 5170 } 5171 5172 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) { 5173 if (!doit) { 5174 return true; 5175 } 5176 didSomething = true; 5177 } 5178 5179 if (name == null) { 5180 // Remove all sticky broadcasts from this user. 5181 mStickyBroadcasts.remove(userId); 5182 } 5183 5184 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>(); 5185 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent, 5186 userId, providers)) { 5187 if (!doit) { 5188 return true; 5189 } 5190 didSomething = true; 5191 } 5192 N = providers.size(); 5193 for (i=0; i<N; i++) { 5194 removeDyingProviderLocked(null, providers.get(i), true); 5195 } 5196 5197 // Remove transient permissions granted from/to this package/user 5198 removeUriPermissionsForPackageLocked(name, userId, false); 5199 5200 if (name == null || uninstalling) { 5201 // Remove pending intents. For now we only do this when force 5202 // stopping users, because we have some problems when doing this 5203 // for packages -- app widgets are not currently cleaned up for 5204 // such packages, so they can be left with bad pending intents. 5205 if (mIntentSenderRecords.size() > 0) { 5206 Iterator<WeakReference<PendingIntentRecord>> it 5207 = mIntentSenderRecords.values().iterator(); 5208 while (it.hasNext()) { 5209 WeakReference<PendingIntentRecord> wpir = it.next(); 5210 if (wpir == null) { 5211 it.remove(); 5212 continue; 5213 } 5214 PendingIntentRecord pir = wpir.get(); 5215 if (pir == null) { 5216 it.remove(); 5217 continue; 5218 } 5219 if (name == null) { 5220 // Stopping user, remove all objects for the user. 5221 if (pir.key.userId != userId) { 5222 // Not the same user, skip it. 5223 continue; 5224 } 5225 } else { 5226 if (UserHandle.getAppId(pir.uid) != appId) { 5227 // Different app id, skip it. 5228 continue; 5229 } 5230 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 5231 // Different user, skip it. 5232 continue; 5233 } 5234 if (!pir.key.packageName.equals(name)) { 5235 // Different package, skip it. 5236 continue; 5237 } 5238 } 5239 if (!doit) { 5240 return true; 5241 } 5242 didSomething = true; 5243 it.remove(); 5244 pir.canceled = true; 5245 if (pir.key.activity != null) { 5246 pir.key.activity.pendingResults.remove(pir.ref); 5247 } 5248 } 5249 } 5250 } 5251 5252 if (doit) { 5253 if (purgeCache && name != null) { 5254 AttributeCache ac = AttributeCache.instance(); 5255 if (ac != null) { 5256 ac.removePackage(name); 5257 } 5258 } 5259 if (mBooted) { 5260 mStackSupervisor.resumeTopActivitiesLocked(); 5261 mStackSupervisor.scheduleIdleLocked(); 5262 } 5263 } 5264 5265 return didSomething; 5266 } 5267 5268 private final boolean removeProcessLocked(ProcessRecord app, 5269 boolean callerWillRestart, boolean allowRestart, String reason) { 5270 final String name = app.processName; 5271 final int uid = app.uid; 5272 if (DEBUG_PROCESSES) Slog.d( 5273 TAG, "Force removing proc " + app.toShortString() + " (" + name 5274 + "/" + uid + ")"); 5275 5276 mProcessNames.remove(name, uid); 5277 mIsolatedProcesses.remove(app.uid); 5278 if (mHeavyWeightProcess == app) { 5279 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5280 mHeavyWeightProcess.userId, 0)); 5281 mHeavyWeightProcess = null; 5282 } 5283 boolean needRestart = false; 5284 if (app.pid > 0 && app.pid != MY_PID) { 5285 int pid = app.pid; 5286 synchronized (mPidsSelfLocked) { 5287 mPidsSelfLocked.remove(pid); 5288 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 5289 } 5290 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5291 if (app.isolated) { 5292 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5293 } 5294 killUnneededProcessLocked(app, reason); 5295 Process.killProcessGroup(app.info.uid, app.pid); 5296 handleAppDiedLocked(app, true, allowRestart); 5297 removeLruProcessLocked(app); 5298 5299 if (app.persistent && !app.isolated) { 5300 if (!callerWillRestart) { 5301 addAppLocked(app.info, false, null /* ABI override */); 5302 } else { 5303 needRestart = true; 5304 } 5305 } 5306 } else { 5307 mRemovedProcesses.add(app); 5308 } 5309 5310 return needRestart; 5311 } 5312 5313 private final void processStartTimedOutLocked(ProcessRecord app) { 5314 final int pid = app.pid; 5315 boolean gone = false; 5316 synchronized (mPidsSelfLocked) { 5317 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 5318 if (knownApp != null && knownApp.thread == null) { 5319 mPidsSelfLocked.remove(pid); 5320 gone = true; 5321 } 5322 } 5323 5324 if (gone) { 5325 Slog.w(TAG, "Process " + app + " failed to attach"); 5326 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 5327 pid, app.uid, app.processName); 5328 mProcessNames.remove(app.processName, app.uid); 5329 mIsolatedProcesses.remove(app.uid); 5330 if (mHeavyWeightProcess == app) { 5331 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5332 mHeavyWeightProcess.userId, 0)); 5333 mHeavyWeightProcess = null; 5334 } 5335 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5336 if (app.isolated) { 5337 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5338 } 5339 // Take care of any launching providers waiting for this process. 5340 checkAppInLaunchingProvidersLocked(app, true); 5341 // Take care of any services that are waiting for the process. 5342 mServices.processStartTimedOutLocked(app); 5343 killUnneededProcessLocked(app, "start timeout"); 5344 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 5345 Slog.w(TAG, "Unattached app died before backup, skipping"); 5346 try { 5347 IBackupManager bm = IBackupManager.Stub.asInterface( 5348 ServiceManager.getService(Context.BACKUP_SERVICE)); 5349 bm.agentDisconnected(app.info.packageName); 5350 } catch (RemoteException e) { 5351 // Can't happen; the backup manager is local 5352 } 5353 } 5354 if (isPendingBroadcastProcessLocked(pid)) { 5355 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 5356 skipPendingBroadcastLocked(pid); 5357 } 5358 } else { 5359 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 5360 } 5361 } 5362 5363 private final boolean attachApplicationLocked(IApplicationThread thread, 5364 int pid) { 5365 5366 // Find the application record that is being attached... either via 5367 // the pid if we are running in multiple processes, or just pull the 5368 // next app record if we are emulating process with anonymous threads. 5369 ProcessRecord app; 5370 if (pid != MY_PID && pid >= 0) { 5371 synchronized (mPidsSelfLocked) { 5372 app = mPidsSelfLocked.get(pid); 5373 } 5374 } else { 5375 app = null; 5376 } 5377 5378 if (app == null) { 5379 Slog.w(TAG, "No pending application record for pid " + pid 5380 + " (IApplicationThread " + thread + "); dropping process"); 5381 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 5382 if (pid > 0 && pid != MY_PID) { 5383 Process.killProcessQuiet(pid); 5384 //TODO: Process.killProcessGroup(app.info.uid, pid); 5385 } else { 5386 try { 5387 thread.scheduleExit(); 5388 } catch (Exception e) { 5389 // Ignore exceptions. 5390 } 5391 } 5392 return false; 5393 } 5394 5395 // If this application record is still attached to a previous 5396 // process, clean it up now. 5397 if (app.thread != null) { 5398 handleAppDiedLocked(app, true, true); 5399 } 5400 5401 // Tell the process all about itself. 5402 5403 if (localLOGV) Slog.v( 5404 TAG, "Binding process pid " + pid + " to record " + app); 5405 5406 final String processName = app.processName; 5407 try { 5408 AppDeathRecipient adr = new AppDeathRecipient( 5409 app, pid, thread); 5410 thread.asBinder().linkToDeath(adr, 0); 5411 app.deathRecipient = adr; 5412 } catch (RemoteException e) { 5413 app.resetPackageList(mProcessStats); 5414 startProcessLocked(app, "link fail", processName); 5415 return false; 5416 } 5417 5418 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 5419 5420 app.makeActive(thread, mProcessStats); 5421 app.curAdj = app.setAdj = -100; 5422 app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT; 5423 app.forcingToForeground = null; 5424 updateProcessForegroundLocked(app, false, false); 5425 app.hasShownUi = false; 5426 app.debugging = false; 5427 app.cached = false; 5428 5429 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 5430 5431 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 5432 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null; 5433 5434 if (!normalMode) { 5435 Slog.i(TAG, "Launching preboot mode app: " + app); 5436 } 5437 5438 if (localLOGV) Slog.v( 5439 TAG, "New app record " + app 5440 + " thread=" + thread.asBinder() + " pid=" + pid); 5441 try { 5442 int testMode = IApplicationThread.DEBUG_OFF; 5443 if (mDebugApp != null && mDebugApp.equals(processName)) { 5444 testMode = mWaitForDebugger 5445 ? IApplicationThread.DEBUG_WAIT 5446 : IApplicationThread.DEBUG_ON; 5447 app.debugging = true; 5448 if (mDebugTransient) { 5449 mDebugApp = mOrigDebugApp; 5450 mWaitForDebugger = mOrigWaitForDebugger; 5451 } 5452 } 5453 String profileFile = app.instrumentationProfileFile; 5454 ParcelFileDescriptor profileFd = null; 5455 boolean profileAutoStop = false; 5456 if (mProfileApp != null && mProfileApp.equals(processName)) { 5457 mProfileProc = app; 5458 profileFile = mProfileFile; 5459 profileFd = mProfileFd; 5460 profileAutoStop = mAutoStopProfiler; 5461 } 5462 boolean enableOpenGlTrace = false; 5463 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) { 5464 enableOpenGlTrace = true; 5465 mOpenGlTraceApp = null; 5466 } 5467 5468 // If the app is being launched for restore or full backup, set it up specially 5469 boolean isRestrictedBackupMode = false; 5470 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 5471 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 5472 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 5473 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 5474 } 5475 5476 ensurePackageDexOpt(app.instrumentationInfo != null 5477 ? app.instrumentationInfo.packageName 5478 : app.info.packageName); 5479 if (app.instrumentationClass != null) { 5480 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 5481 } 5482 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc " 5483 + processName + " with config " + mConfiguration); 5484 ApplicationInfo appInfo = app.instrumentationInfo != null 5485 ? app.instrumentationInfo : app.info; 5486 app.compat = compatibilityInfoForPackageLocked(appInfo); 5487 if (profileFd != null) { 5488 profileFd = profileFd.dup(); 5489 } 5490 thread.bindApplication(processName, appInfo, providers, 5491 app.instrumentationClass, profileFile, profileFd, profileAutoStop, 5492 app.instrumentationArguments, app.instrumentationWatcher, 5493 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, 5494 isRestrictedBackupMode || !normalMode, app.persistent, 5495 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), 5496 mCoreSettingsObserver.getCoreSettingsLocked()); 5497 updateLruProcessLocked(app, false, null); 5498 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 5499 } catch (Exception e) { 5500 // todo: Yikes! What should we do? For now we will try to 5501 // start another process, but that could easily get us in 5502 // an infinite loop of restarting processes... 5503 Slog.w(TAG, "Exception thrown during bind!", e); 5504 5505 app.resetPackageList(mProcessStats); 5506 app.unlinkDeathRecipient(); 5507 startProcessLocked(app, "bind fail", processName); 5508 return false; 5509 } 5510 5511 // Remove this record from the list of starting applications. 5512 mPersistentStartingProcesses.remove(app); 5513 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 5514 "Attach application locked removing on hold: " + app); 5515 mProcessesOnHold.remove(app); 5516 5517 boolean badApp = false; 5518 boolean didSomething = false; 5519 5520 // See if the top visible activity is waiting to run in this process... 5521 if (normalMode) { 5522 try { 5523 if (mStackSupervisor.attachApplicationLocked(app)) { 5524 didSomething = true; 5525 } 5526 } catch (Exception e) { 5527 badApp = true; 5528 } 5529 } 5530 5531 // Find any services that should be running in this process... 5532 if (!badApp) { 5533 try { 5534 didSomething |= mServices.attachApplicationLocked(app, processName); 5535 } catch (Exception e) { 5536 badApp = true; 5537 } 5538 } 5539 5540 // Check if a next-broadcast receiver is in this process... 5541 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 5542 try { 5543 didSomething |= sendPendingBroadcastsLocked(app); 5544 } catch (Exception e) { 5545 // If the app died trying to launch the receiver we declare it 'bad' 5546 badApp = true; 5547 } 5548 } 5549 5550 // Check whether the next backup agent is in this process... 5551 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) { 5552 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app); 5553 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 5554 try { 5555 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 5556 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 5557 mBackupTarget.backupMode); 5558 } catch (Exception e) { 5559 Slog.w(TAG, "Exception scheduling backup agent creation: "); 5560 e.printStackTrace(); 5561 } 5562 } 5563 5564 if (badApp) { 5565 // todo: Also need to kill application to deal with all 5566 // kinds of exceptions. 5567 handleAppDiedLocked(app, false, true); 5568 return false; 5569 } 5570 5571 if (!didSomething) { 5572 updateOomAdjLocked(); 5573 } 5574 5575 return true; 5576 } 5577 5578 @Override 5579 public final void attachApplication(IApplicationThread thread) { 5580 synchronized (this) { 5581 int callingPid = Binder.getCallingPid(); 5582 final long origId = Binder.clearCallingIdentity(); 5583 attachApplicationLocked(thread, callingPid); 5584 Binder.restoreCallingIdentity(origId); 5585 } 5586 } 5587 5588 @Override 5589 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 5590 final long origId = Binder.clearCallingIdentity(); 5591 synchronized (this) { 5592 ActivityStack stack = ActivityRecord.getStackLocked(token); 5593 if (stack != null) { 5594 ActivityRecord r = 5595 mStackSupervisor.activityIdleInternalLocked(token, false, config); 5596 if (stopProfiling) { 5597 if ((mProfileProc == r.app) && (mProfileFd != null)) { 5598 try { 5599 mProfileFd.close(); 5600 } catch (IOException e) { 5601 } 5602 clearProfilerLocked(); 5603 } 5604 } 5605 } 5606 } 5607 Binder.restoreCallingIdentity(origId); 5608 } 5609 5610 void postEnableScreenAfterBootLocked() { 5611 mHandler.sendEmptyMessage(ENABLE_SCREEN_AFTER_BOOT_MSG); 5612 } 5613 5614 void enableScreenAfterBoot() { 5615 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 5616 SystemClock.uptimeMillis()); 5617 mWindowManager.enableScreenAfterBoot(); 5618 5619 synchronized (this) { 5620 updateEventDispatchingLocked(); 5621 } 5622 } 5623 5624 @Override 5625 public void showBootMessage(final CharSequence msg, final boolean always) { 5626 enforceNotIsolatedCaller("showBootMessage"); 5627 mWindowManager.showBootMessage(msg, always); 5628 } 5629 5630 @Override 5631 public void dismissKeyguardOnNextActivity() { 5632 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity"); 5633 final long token = Binder.clearCallingIdentity(); 5634 try { 5635 synchronized (this) { 5636 if (DEBUG_LOCKSCREEN) logLockScreen(""); 5637 if (mLockScreenShown) { 5638 mLockScreenShown = false; 5639 comeOutOfSleepIfNeededLocked(); 5640 } 5641 mStackSupervisor.setDismissKeyguard(true); 5642 } 5643 } finally { 5644 Binder.restoreCallingIdentity(token); 5645 } 5646 } 5647 5648 final void finishBooting() { 5649 // Register receivers to handle package update events 5650 mPackageMonitor.register(mContext, Looper.getMainLooper(), false); 5651 5652 synchronized (this) { 5653 // Ensure that any processes we had put on hold are now started 5654 // up. 5655 final int NP = mProcessesOnHold.size(); 5656 if (NP > 0) { 5657 ArrayList<ProcessRecord> procs = 5658 new ArrayList<ProcessRecord>(mProcessesOnHold); 5659 for (int ip=0; ip<NP; ip++) { 5660 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: " 5661 + procs.get(ip)); 5662 startProcessLocked(procs.get(ip), "on-hold", null); 5663 } 5664 } 5665 5666 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 5667 // Start looking for apps that are abusing wake locks. 5668 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 5669 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 5670 // Tell anyone interested that we are done booting! 5671 SystemProperties.set("sys.boot_completed", "1"); 5672 SystemProperties.set("dev.bootcomplete", "1"); 5673 for (int i=0; i<mStartedUsers.size(); i++) { 5674 UserStartedState uss = mStartedUsers.valueAt(i); 5675 if (uss.mState == UserStartedState.STATE_BOOTING) { 5676 uss.mState = UserStartedState.STATE_RUNNING; 5677 final int userId = mStartedUsers.keyAt(i); 5678 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 5679 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 5680 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 5681 broadcastIntentLocked(null, null, intent, null, 5682 new IIntentReceiver.Stub() { 5683 @Override 5684 public void performReceive(Intent intent, int resultCode, 5685 String data, Bundle extras, boolean ordered, 5686 boolean sticky, int sendingUser) { 5687 synchronized (ActivityManagerService.this) { 5688 requestPssAllProcsLocked(SystemClock.uptimeMillis(), 5689 true, false); 5690 } 5691 } 5692 }, 5693 0, null, null, 5694 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, 5695 AppOpsManager.OP_NONE, true, false, MY_PID, Process.SYSTEM_UID, 5696 userId); 5697 } 5698 } 5699 scheduleStartProfilesLocked(); 5700 } 5701 } 5702 } 5703 5704 final void ensureBootCompleted() { 5705 boolean booting; 5706 boolean enableScreen; 5707 synchronized (this) { 5708 booting = mBooting; 5709 mBooting = false; 5710 enableScreen = !mBooted; 5711 mBooted = true; 5712 } 5713 5714 if (booting) { 5715 finishBooting(); 5716 } 5717 5718 if (enableScreen) { 5719 enableScreenAfterBoot(); 5720 } 5721 } 5722 5723 @Override 5724 public final void activityResumed(IBinder token) { 5725 final long origId = Binder.clearCallingIdentity(); 5726 synchronized(this) { 5727 ActivityStack stack = ActivityRecord.getStackLocked(token); 5728 if (stack != null) { 5729 ActivityRecord.activityResumedLocked(token); 5730 } 5731 } 5732 Binder.restoreCallingIdentity(origId); 5733 } 5734 5735 @Override 5736 public final void activityPaused(IBinder token, PersistableBundle persistentState) { 5737 final long origId = Binder.clearCallingIdentity(); 5738 synchronized(this) { 5739 ActivityStack stack = ActivityRecord.getStackLocked(token); 5740 if (stack != null) { 5741 stack.activityPausedLocked(token, false, persistentState); 5742 } 5743 } 5744 Binder.restoreCallingIdentity(origId); 5745 } 5746 5747 @Override 5748 public final void activityStopped(IBinder token, Bundle icicle, 5749 PersistableBundle persistentState, CharSequence description) { 5750 if (localLOGV) Slog.v(TAG, "Activity stopped: token=" + token); 5751 5752 // Refuse possible leaked file descriptors 5753 if (icicle != null && icicle.hasFileDescriptors()) { 5754 throw new IllegalArgumentException("File descriptors passed in Bundle"); 5755 } 5756 5757 final long origId = Binder.clearCallingIdentity(); 5758 5759 synchronized (this) { 5760 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5761 if (r != null) { 5762 r.task.stack.activityStoppedLocked(r, icicle, persistentState, description); 5763 } 5764 } 5765 5766 trimApplications(); 5767 5768 Binder.restoreCallingIdentity(origId); 5769 } 5770 5771 @Override 5772 public final void activityDestroyed(IBinder token) { 5773 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token); 5774 synchronized (this) { 5775 ActivityStack stack = ActivityRecord.getStackLocked(token); 5776 if (stack != null) { 5777 stack.activityDestroyedLocked(token); 5778 } 5779 } 5780 } 5781 5782 @Override 5783 public final void mediaResourcesReleased(IBinder token) { 5784 final long origId = Binder.clearCallingIdentity(); 5785 try { 5786 synchronized (this) { 5787 ActivityStack stack = ActivityRecord.getStackLocked(token); 5788 if (stack != null) { 5789 stack.mediaResourcesReleased(token); 5790 } 5791 } 5792 } finally { 5793 Binder.restoreCallingIdentity(origId); 5794 } 5795 } 5796 5797 @Override 5798 public final void notifyLaunchTaskBehindComplete(IBinder token) { 5799 mStackSupervisor.scheduleLaunchTaskBehindComplete(token); 5800 } 5801 5802 @Override 5803 public final void notifyEnterAnimationComplete(IBinder token) { 5804 mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token)); 5805 } 5806 5807 @Override 5808 public String getCallingPackage(IBinder token) { 5809 synchronized (this) { 5810 ActivityRecord r = getCallingRecordLocked(token); 5811 return r != null ? r.info.packageName : null; 5812 } 5813 } 5814 5815 @Override 5816 public ComponentName getCallingActivity(IBinder token) { 5817 synchronized (this) { 5818 ActivityRecord r = getCallingRecordLocked(token); 5819 return r != null ? r.intent.getComponent() : null; 5820 } 5821 } 5822 5823 private ActivityRecord getCallingRecordLocked(IBinder token) { 5824 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5825 if (r == null) { 5826 return null; 5827 } 5828 return r.resultTo; 5829 } 5830 5831 @Override 5832 public ComponentName getActivityClassForToken(IBinder token) { 5833 synchronized(this) { 5834 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5835 if (r == null) { 5836 return null; 5837 } 5838 return r.intent.getComponent(); 5839 } 5840 } 5841 5842 @Override 5843 public String getPackageForToken(IBinder token) { 5844 synchronized(this) { 5845 ActivityRecord r = ActivityRecord.isInStackLocked(token); 5846 if (r == null) { 5847 return null; 5848 } 5849 return r.packageName; 5850 } 5851 } 5852 5853 @Override 5854 public IIntentSender getIntentSender(int type, 5855 String packageName, IBinder token, String resultWho, 5856 int requestCode, Intent[] intents, String[] resolvedTypes, 5857 int flags, Bundle options, int userId) { 5858 enforceNotIsolatedCaller("getIntentSender"); 5859 // Refuse possible leaked file descriptors 5860 if (intents != null) { 5861 if (intents.length < 1) { 5862 throw new IllegalArgumentException("Intents array length must be >= 1"); 5863 } 5864 for (int i=0; i<intents.length; i++) { 5865 Intent intent = intents[i]; 5866 if (intent != null) { 5867 if (intent.hasFileDescriptors()) { 5868 throw new IllegalArgumentException("File descriptors passed in Intent"); 5869 } 5870 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 5871 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 5872 throw new IllegalArgumentException( 5873 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 5874 } 5875 intents[i] = new Intent(intent); 5876 } 5877 } 5878 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 5879 throw new IllegalArgumentException( 5880 "Intent array length does not match resolvedTypes length"); 5881 } 5882 } 5883 if (options != null) { 5884 if (options.hasFileDescriptors()) { 5885 throw new IllegalArgumentException("File descriptors passed in options"); 5886 } 5887 } 5888 5889 synchronized(this) { 5890 int callingUid = Binder.getCallingUid(); 5891 int origUserId = userId; 5892 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 5893 type == ActivityManager.INTENT_SENDER_BROADCAST, 5894 ALLOW_NON_FULL, "getIntentSender", null); 5895 if (origUserId == UserHandle.USER_CURRENT) { 5896 // We don't want to evaluate this until the pending intent is 5897 // actually executed. However, we do want to always do the 5898 // security checking for it above. 5899 userId = UserHandle.USER_CURRENT; 5900 } 5901 try { 5902 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 5903 int uid = AppGlobals.getPackageManager() 5904 .getPackageUid(packageName, UserHandle.getUserId(callingUid)); 5905 if (!UserHandle.isSameApp(callingUid, uid)) { 5906 String msg = "Permission Denial: getIntentSender() from pid=" 5907 + Binder.getCallingPid() 5908 + ", uid=" + Binder.getCallingUid() 5909 + ", (need uid=" + uid + ")" 5910 + " is not allowed to send as package " + packageName; 5911 Slog.w(TAG, msg); 5912 throw new SecurityException(msg); 5913 } 5914 } 5915 5916 return getIntentSenderLocked(type, packageName, callingUid, userId, 5917 token, resultWho, requestCode, intents, resolvedTypes, flags, options); 5918 5919 } catch (RemoteException e) { 5920 throw new SecurityException(e); 5921 } 5922 } 5923 } 5924 5925 IIntentSender getIntentSenderLocked(int type, String packageName, 5926 int callingUid, int userId, IBinder token, String resultWho, 5927 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 5928 Bundle options) { 5929 if (DEBUG_MU) 5930 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 5931 ActivityRecord activity = null; 5932 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5933 activity = ActivityRecord.isInStackLocked(token); 5934 if (activity == null) { 5935 return null; 5936 } 5937 if (activity.finishing) { 5938 return null; 5939 } 5940 } 5941 5942 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 5943 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 5944 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 5945 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 5946 |PendingIntent.FLAG_UPDATE_CURRENT); 5947 5948 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 5949 type, packageName, activity, resultWho, 5950 requestCode, intents, resolvedTypes, flags, options, userId); 5951 WeakReference<PendingIntentRecord> ref; 5952 ref = mIntentSenderRecords.get(key); 5953 PendingIntentRecord rec = ref != null ? ref.get() : null; 5954 if (rec != null) { 5955 if (!cancelCurrent) { 5956 if (updateCurrent) { 5957 if (rec.key.requestIntent != null) { 5958 rec.key.requestIntent.replaceExtras(intents != null ? 5959 intents[intents.length - 1] : null); 5960 } 5961 if (intents != null) { 5962 intents[intents.length-1] = rec.key.requestIntent; 5963 rec.key.allIntents = intents; 5964 rec.key.allResolvedTypes = resolvedTypes; 5965 } else { 5966 rec.key.allIntents = null; 5967 rec.key.allResolvedTypes = null; 5968 } 5969 } 5970 return rec; 5971 } 5972 rec.canceled = true; 5973 mIntentSenderRecords.remove(key); 5974 } 5975 if (noCreate) { 5976 return rec; 5977 } 5978 rec = new PendingIntentRecord(this, key, callingUid); 5979 mIntentSenderRecords.put(key, rec.ref); 5980 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 5981 if (activity.pendingResults == null) { 5982 activity.pendingResults 5983 = new HashSet<WeakReference<PendingIntentRecord>>(); 5984 } 5985 activity.pendingResults.add(rec.ref); 5986 } 5987 return rec; 5988 } 5989 5990 @Override 5991 public void cancelIntentSender(IIntentSender sender) { 5992 if (!(sender instanceof PendingIntentRecord)) { 5993 return; 5994 } 5995 synchronized(this) { 5996 PendingIntentRecord rec = (PendingIntentRecord)sender; 5997 try { 5998 int uid = AppGlobals.getPackageManager() 5999 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId()); 6000 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 6001 String msg = "Permission Denial: cancelIntentSender() from pid=" 6002 + Binder.getCallingPid() 6003 + ", uid=" + Binder.getCallingUid() 6004 + " is not allowed to cancel packges " 6005 + rec.key.packageName; 6006 Slog.w(TAG, msg); 6007 throw new SecurityException(msg); 6008 } 6009 } catch (RemoteException e) { 6010 throw new SecurityException(e); 6011 } 6012 cancelIntentSenderLocked(rec, true); 6013 } 6014 } 6015 6016 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 6017 rec.canceled = true; 6018 mIntentSenderRecords.remove(rec.key); 6019 if (cleanActivity && rec.key.activity != null) { 6020 rec.key.activity.pendingResults.remove(rec.ref); 6021 } 6022 } 6023 6024 @Override 6025 public String getPackageForIntentSender(IIntentSender pendingResult) { 6026 if (!(pendingResult instanceof PendingIntentRecord)) { 6027 return null; 6028 } 6029 try { 6030 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6031 return res.key.packageName; 6032 } catch (ClassCastException e) { 6033 } 6034 return null; 6035 } 6036 6037 @Override 6038 public int getUidForIntentSender(IIntentSender sender) { 6039 if (sender instanceof PendingIntentRecord) { 6040 try { 6041 PendingIntentRecord res = (PendingIntentRecord)sender; 6042 return res.uid; 6043 } catch (ClassCastException e) { 6044 } 6045 } 6046 return -1; 6047 } 6048 6049 @Override 6050 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 6051 if (!(pendingResult instanceof PendingIntentRecord)) { 6052 return false; 6053 } 6054 try { 6055 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6056 if (res.key.allIntents == null) { 6057 return false; 6058 } 6059 for (int i=0; i<res.key.allIntents.length; i++) { 6060 Intent intent = res.key.allIntents[i]; 6061 if (intent.getPackage() != null && intent.getComponent() != null) { 6062 return false; 6063 } 6064 } 6065 return true; 6066 } catch (ClassCastException e) { 6067 } 6068 return false; 6069 } 6070 6071 @Override 6072 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 6073 if (!(pendingResult instanceof PendingIntentRecord)) { 6074 return false; 6075 } 6076 try { 6077 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6078 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 6079 return true; 6080 } 6081 return false; 6082 } catch (ClassCastException e) { 6083 } 6084 return false; 6085 } 6086 6087 @Override 6088 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 6089 if (!(pendingResult instanceof PendingIntentRecord)) { 6090 return null; 6091 } 6092 try { 6093 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6094 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 6095 } catch (ClassCastException e) { 6096 } 6097 return null; 6098 } 6099 6100 @Override 6101 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 6102 if (!(pendingResult instanceof PendingIntentRecord)) { 6103 return null; 6104 } 6105 try { 6106 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6107 Intent intent = res.key.requestIntent; 6108 if (intent != null) { 6109 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 6110 || res.lastTagPrefix.equals(prefix))) { 6111 return res.lastTag; 6112 } 6113 res.lastTagPrefix = prefix; 6114 StringBuilder sb = new StringBuilder(128); 6115 if (prefix != null) { 6116 sb.append(prefix); 6117 } 6118 if (intent.getAction() != null) { 6119 sb.append(intent.getAction()); 6120 } else if (intent.getComponent() != null) { 6121 intent.getComponent().appendShortString(sb); 6122 } else { 6123 sb.append("?"); 6124 } 6125 return res.lastTag = sb.toString(); 6126 } 6127 } catch (ClassCastException e) { 6128 } 6129 return null; 6130 } 6131 6132 @Override 6133 public void setProcessLimit(int max) { 6134 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6135 "setProcessLimit()"); 6136 synchronized (this) { 6137 mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max; 6138 mProcessLimitOverride = max; 6139 } 6140 trimApplications(); 6141 } 6142 6143 @Override 6144 public int getProcessLimit() { 6145 synchronized (this) { 6146 return mProcessLimitOverride; 6147 } 6148 } 6149 6150 void foregroundTokenDied(ForegroundToken token) { 6151 synchronized (ActivityManagerService.this) { 6152 synchronized (mPidsSelfLocked) { 6153 ForegroundToken cur 6154 = mForegroundProcesses.get(token.pid); 6155 if (cur != token) { 6156 return; 6157 } 6158 mForegroundProcesses.remove(token.pid); 6159 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 6160 if (pr == null) { 6161 return; 6162 } 6163 pr.forcingToForeground = null; 6164 updateProcessForegroundLocked(pr, false, false); 6165 } 6166 updateOomAdjLocked(); 6167 } 6168 } 6169 6170 @Override 6171 public void setProcessForeground(IBinder token, int pid, boolean isForeground) { 6172 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6173 "setProcessForeground()"); 6174 synchronized(this) { 6175 boolean changed = false; 6176 6177 synchronized (mPidsSelfLocked) { 6178 ProcessRecord pr = mPidsSelfLocked.get(pid); 6179 if (pr == null && isForeground) { 6180 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 6181 return; 6182 } 6183 ForegroundToken oldToken = mForegroundProcesses.get(pid); 6184 if (oldToken != null) { 6185 oldToken.token.unlinkToDeath(oldToken, 0); 6186 mForegroundProcesses.remove(pid); 6187 if (pr != null) { 6188 pr.forcingToForeground = null; 6189 } 6190 changed = true; 6191 } 6192 if (isForeground && token != null) { 6193 ForegroundToken newToken = new ForegroundToken() { 6194 @Override 6195 public void binderDied() { 6196 foregroundTokenDied(this); 6197 } 6198 }; 6199 newToken.pid = pid; 6200 newToken.token = token; 6201 try { 6202 token.linkToDeath(newToken, 0); 6203 mForegroundProcesses.put(pid, newToken); 6204 pr.forcingToForeground = token; 6205 changed = true; 6206 } catch (RemoteException e) { 6207 // If the process died while doing this, we will later 6208 // do the cleanup with the process death link. 6209 } 6210 } 6211 } 6212 6213 if (changed) { 6214 updateOomAdjLocked(); 6215 } 6216 } 6217 } 6218 6219 // ========================================================= 6220 // PERMISSIONS 6221 // ========================================================= 6222 6223 static class PermissionController extends IPermissionController.Stub { 6224 ActivityManagerService mActivityManagerService; 6225 PermissionController(ActivityManagerService activityManagerService) { 6226 mActivityManagerService = activityManagerService; 6227 } 6228 6229 @Override 6230 public boolean checkPermission(String permission, int pid, int uid) { 6231 return mActivityManagerService.checkPermission(permission, pid, 6232 uid) == PackageManager.PERMISSION_GRANTED; 6233 } 6234 } 6235 6236 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 6237 @Override 6238 public int checkComponentPermission(String permission, int pid, int uid, 6239 int owningUid, boolean exported) { 6240 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 6241 owningUid, exported); 6242 } 6243 6244 @Override 6245 public Object getAMSLock() { 6246 return ActivityManagerService.this; 6247 } 6248 } 6249 6250 /** 6251 * This can be called with or without the global lock held. 6252 */ 6253 int checkComponentPermission(String permission, int pid, int uid, 6254 int owningUid, boolean exported) { 6255 // We might be performing an operation on behalf of an indirect binder 6256 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 6257 // client identity accordingly before proceeding. 6258 Identity tlsIdentity = sCallerIdentity.get(); 6259 if (tlsIdentity != null) { 6260 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 6261 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 6262 uid = tlsIdentity.uid; 6263 pid = tlsIdentity.pid; 6264 } 6265 6266 if (pid == MY_PID) { 6267 return PackageManager.PERMISSION_GRANTED; 6268 } 6269 6270 return ActivityManager.checkComponentPermission(permission, uid, 6271 owningUid, exported); 6272 } 6273 6274 /** 6275 * As the only public entry point for permissions checking, this method 6276 * can enforce the semantic that requesting a check on a null global 6277 * permission is automatically denied. (Internally a null permission 6278 * string is used when calling {@link #checkComponentPermission} in cases 6279 * when only uid-based security is needed.) 6280 * 6281 * This can be called with or without the global lock held. 6282 */ 6283 @Override 6284 public int checkPermission(String permission, int pid, int uid) { 6285 if (permission == null) { 6286 return PackageManager.PERMISSION_DENIED; 6287 } 6288 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true); 6289 } 6290 6291 /** 6292 * Binder IPC calls go through the public entry point. 6293 * This can be called with or without the global lock held. 6294 */ 6295 int checkCallingPermission(String permission) { 6296 return checkPermission(permission, 6297 Binder.getCallingPid(), 6298 UserHandle.getAppId(Binder.getCallingUid())); 6299 } 6300 6301 /** 6302 * This can be called with or without the global lock held. 6303 */ 6304 void enforceCallingPermission(String permission, String func) { 6305 if (checkCallingPermission(permission) 6306 == PackageManager.PERMISSION_GRANTED) { 6307 return; 6308 } 6309 6310 String msg = "Permission Denial: " + func + " from pid=" 6311 + Binder.getCallingPid() 6312 + ", uid=" + Binder.getCallingUid() 6313 + " requires " + permission; 6314 Slog.w(TAG, msg); 6315 throw new SecurityException(msg); 6316 } 6317 6318 /** 6319 * Determine if UID is holding permissions required to access {@link Uri} in 6320 * the given {@link ProviderInfo}. Final permission checking is always done 6321 * in {@link ContentProvider}. 6322 */ 6323 private final boolean checkHoldingPermissionsLocked( 6324 IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) { 6325 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6326 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid); 6327 if (UserHandle.getUserId(uid) != grantUri.sourceUserId) { 6328 if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true) 6329 != PERMISSION_GRANTED) { 6330 return false; 6331 } 6332 } 6333 return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true); 6334 } 6335 6336 private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi, 6337 GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) { 6338 if (pi.applicationInfo.uid == uid) { 6339 return true; 6340 } else if (!pi.exported) { 6341 return false; 6342 } 6343 6344 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 6345 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 6346 try { 6347 // check if target holds top-level <provider> permissions 6348 if (!readMet && pi.readPermission != null && considerUidPermissions 6349 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 6350 readMet = true; 6351 } 6352 if (!writeMet && pi.writePermission != null && considerUidPermissions 6353 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 6354 writeMet = true; 6355 } 6356 6357 // track if unprotected read/write is allowed; any denied 6358 // <path-permission> below removes this ability 6359 boolean allowDefaultRead = pi.readPermission == null; 6360 boolean allowDefaultWrite = pi.writePermission == null; 6361 6362 // check if target holds any <path-permission> that match uri 6363 final PathPermission[] pps = pi.pathPermissions; 6364 if (pps != null) { 6365 final String path = grantUri.uri.getPath(); 6366 int i = pps.length; 6367 while (i > 0 && (!readMet || !writeMet)) { 6368 i--; 6369 PathPermission pp = pps[i]; 6370 if (pp.match(path)) { 6371 if (!readMet) { 6372 final String pprperm = pp.getReadPermission(); 6373 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for " 6374 + pprperm + " for " + pp.getPath() 6375 + ": match=" + pp.match(path) 6376 + " check=" + pm.checkUidPermission(pprperm, uid)); 6377 if (pprperm != null) { 6378 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid) 6379 == PERMISSION_GRANTED) { 6380 readMet = true; 6381 } else { 6382 allowDefaultRead = false; 6383 } 6384 } 6385 } 6386 if (!writeMet) { 6387 final String ppwperm = pp.getWritePermission(); 6388 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm " 6389 + ppwperm + " for " + pp.getPath() 6390 + ": match=" + pp.match(path) 6391 + " check=" + pm.checkUidPermission(ppwperm, uid)); 6392 if (ppwperm != null) { 6393 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid) 6394 == PERMISSION_GRANTED) { 6395 writeMet = true; 6396 } else { 6397 allowDefaultWrite = false; 6398 } 6399 } 6400 } 6401 } 6402 } 6403 } 6404 6405 // grant unprotected <provider> read/write, if not blocked by 6406 // <path-permission> above 6407 if (allowDefaultRead) readMet = true; 6408 if (allowDefaultWrite) writeMet = true; 6409 6410 } catch (RemoteException e) { 6411 return false; 6412 } 6413 6414 return readMet && writeMet; 6415 } 6416 6417 private ProviderInfo getProviderInfoLocked(String authority, int userHandle) { 6418 ProviderInfo pi = null; 6419 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle); 6420 if (cpr != null) { 6421 pi = cpr.info; 6422 } else { 6423 try { 6424 pi = AppGlobals.getPackageManager().resolveContentProvider( 6425 authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle); 6426 } catch (RemoteException ex) { 6427 } 6428 } 6429 return pi; 6430 } 6431 6432 private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) { 6433 final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 6434 if (targetUris != null) { 6435 return targetUris.get(grantUri); 6436 } 6437 return null; 6438 } 6439 6440 private UriPermission findOrCreateUriPermissionLocked(String sourcePkg, 6441 String targetPkg, int targetUid, GrantUri grantUri) { 6442 ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 6443 if (targetUris == null) { 6444 targetUris = Maps.newArrayMap(); 6445 mGrantedUriPermissions.put(targetUid, targetUris); 6446 } 6447 6448 UriPermission perm = targetUris.get(grantUri); 6449 if (perm == null) { 6450 perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri); 6451 targetUris.put(grantUri, perm); 6452 } 6453 6454 return perm; 6455 } 6456 6457 private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid, 6458 final int modeFlags) { 6459 final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0; 6460 final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE 6461 : UriPermission.STRENGTH_OWNED; 6462 6463 // Root gets to do everything. 6464 if (uid == 0) { 6465 return true; 6466 } 6467 6468 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 6469 if (perms == null) return false; 6470 6471 // First look for exact match 6472 final UriPermission exactPerm = perms.get(grantUri); 6473 if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) { 6474 return true; 6475 } 6476 6477 // No exact match, look for prefixes 6478 final int N = perms.size(); 6479 for (int i = 0; i < N; i++) { 6480 final UriPermission perm = perms.valueAt(i); 6481 if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri) 6482 && perm.getStrength(modeFlags) >= minStrength) { 6483 return true; 6484 } 6485 } 6486 6487 return false; 6488 } 6489 6490 @Override 6491 public int checkUriPermission(Uri uri, int pid, int uid, 6492 final int modeFlags, int userId) { 6493 enforceNotIsolatedCaller("checkUriPermission"); 6494 6495 // Another redirected-binder-call permissions check as in 6496 // {@link checkComponentPermission}. 6497 Identity tlsIdentity = sCallerIdentity.get(); 6498 if (tlsIdentity != null) { 6499 uid = tlsIdentity.uid; 6500 pid = tlsIdentity.pid; 6501 } 6502 6503 // Our own process gets to do everything. 6504 if (pid == MY_PID) { 6505 return PackageManager.PERMISSION_GRANTED; 6506 } 6507 synchronized (this) { 6508 return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags) 6509 ? PackageManager.PERMISSION_GRANTED 6510 : PackageManager.PERMISSION_DENIED; 6511 } 6512 } 6513 6514 /** 6515 * Check if the targetPkg can be granted permission to access uri by 6516 * the callingUid using the given modeFlags. Throws a security exception 6517 * if callingUid is not allowed to do this. Returns the uid of the target 6518 * if the URI permission grant should be performed; returns -1 if it is not 6519 * needed (for example targetPkg already has permission to access the URI). 6520 * If you already know the uid of the target, you can supply it in 6521 * lastTargetUid else set that to -1. 6522 */ 6523 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 6524 final int modeFlags, int lastTargetUid) { 6525 if (!Intent.isAccessUriMode(modeFlags)) { 6526 return -1; 6527 } 6528 6529 if (targetPkg != null) { 6530 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6531 "Checking grant " + targetPkg + " permission to " + grantUri); 6532 } 6533 6534 final IPackageManager pm = AppGlobals.getPackageManager(); 6535 6536 // If this is not a content: uri, we can't do anything with it. 6537 if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) { 6538 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6539 "Can't grant URI permission for non-content URI: " + grantUri); 6540 return -1; 6541 } 6542 6543 final String authority = grantUri.uri.getAuthority(); 6544 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 6545 if (pi == null) { 6546 Slog.w(TAG, "No content provider found for permission check: " + 6547 grantUri.uri.toSafeString()); 6548 return -1; 6549 } 6550 6551 int targetUid = lastTargetUid; 6552 if (targetUid < 0 && targetPkg != null) { 6553 try { 6554 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid)); 6555 if (targetUid < 0) { 6556 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6557 "Can't grant URI permission no uid for: " + targetPkg); 6558 return -1; 6559 } 6560 } catch (RemoteException ex) { 6561 return -1; 6562 } 6563 } 6564 6565 if (targetUid >= 0) { 6566 // First... does the target actually need this permission? 6567 if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) { 6568 // No need to grant the target this permission. 6569 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6570 "Target " + targetPkg + " already has full permission to " + grantUri); 6571 return -1; 6572 } 6573 } else { 6574 // First... there is no target package, so can anyone access it? 6575 boolean allowed = pi.exported; 6576 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 6577 if (pi.readPermission != null) { 6578 allowed = false; 6579 } 6580 } 6581 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 6582 if (pi.writePermission != null) { 6583 allowed = false; 6584 } 6585 } 6586 if (allowed) { 6587 return -1; 6588 } 6589 } 6590 6591 /* There is a special cross user grant if: 6592 * - The target is on another user. 6593 * - Apps on the current user can access the uri without any uid permissions. 6594 * In this case, we grant a uri permission, even if the ContentProvider does not normally 6595 * grant uri permissions. 6596 */ 6597 boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId 6598 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid, 6599 modeFlags, false /*without considering the uid permissions*/); 6600 6601 // Second... is the provider allowing granting of URI permissions? 6602 if (!specialCrossUserGrant) { 6603 if (!pi.grantUriPermissions) { 6604 throw new SecurityException("Provider " + pi.packageName 6605 + "/" + pi.name 6606 + " does not allow granting of Uri permissions (uri " 6607 + grantUri + ")"); 6608 } 6609 if (pi.uriPermissionPatterns != null) { 6610 final int N = pi.uriPermissionPatterns.length; 6611 boolean allowed = false; 6612 for (int i=0; i<N; i++) { 6613 if (pi.uriPermissionPatterns[i] != null 6614 && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) { 6615 allowed = true; 6616 break; 6617 } 6618 } 6619 if (!allowed) { 6620 throw new SecurityException("Provider " + pi.packageName 6621 + "/" + pi.name 6622 + " does not allow granting of permission to path of Uri " 6623 + grantUri); 6624 } 6625 } 6626 } 6627 6628 // Third... does the caller itself have permission to access 6629 // this uri? 6630 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) { 6631 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 6632 // Require they hold a strong enough Uri permission 6633 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) { 6634 throw new SecurityException("Uid " + callingUid 6635 + " does not have permission to uri " + grantUri); 6636 } 6637 } 6638 } 6639 return targetUid; 6640 } 6641 6642 @Override 6643 public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri, 6644 final int modeFlags, int userId) { 6645 enforceNotIsolatedCaller("checkGrantUriPermission"); 6646 synchronized(this) { 6647 return checkGrantUriPermissionLocked(callingUid, targetPkg, 6648 new GrantUri(userId, uri, false), modeFlags, -1); 6649 } 6650 } 6651 6652 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri, 6653 final int modeFlags, UriPermissionOwner owner) { 6654 if (!Intent.isAccessUriMode(modeFlags)) { 6655 return; 6656 } 6657 6658 // So here we are: the caller has the assumed permission 6659 // to the uri, and the target doesn't. Let's now give this to 6660 // the target. 6661 6662 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6663 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri); 6664 6665 final String authority = grantUri.uri.getAuthority(); 6666 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 6667 if (pi == null) { 6668 Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString()); 6669 return; 6670 } 6671 6672 if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) { 6673 grantUri.prefix = true; 6674 } 6675 final UriPermission perm = findOrCreateUriPermissionLocked( 6676 pi.packageName, targetPkg, targetUid, grantUri); 6677 perm.grantModes(modeFlags, owner); 6678 } 6679 6680 void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 6681 final int modeFlags, UriPermissionOwner owner, int targetUserId) { 6682 if (targetPkg == null) { 6683 throw new NullPointerException("targetPkg"); 6684 } 6685 int targetUid; 6686 final IPackageManager pm = AppGlobals.getPackageManager(); 6687 try { 6688 targetUid = pm.getPackageUid(targetPkg, targetUserId); 6689 } catch (RemoteException ex) { 6690 return; 6691 } 6692 6693 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags, 6694 targetUid); 6695 if (targetUid < 0) { 6696 return; 6697 } 6698 6699 grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags, 6700 owner); 6701 } 6702 6703 static class NeededUriGrants extends ArrayList<GrantUri> { 6704 final String targetPkg; 6705 final int targetUid; 6706 final int flags; 6707 6708 NeededUriGrants(String targetPkg, int targetUid, int flags) { 6709 this.targetPkg = targetPkg; 6710 this.targetUid = targetUid; 6711 this.flags = flags; 6712 } 6713 } 6714 6715 /** 6716 * Like checkGrantUriPermissionLocked, but takes an Intent. 6717 */ 6718 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid, 6719 String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) { 6720 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6721 "Checking URI perm to data=" + (intent != null ? intent.getData() : null) 6722 + " clip=" + (intent != null ? intent.getClipData() : null) 6723 + " from " + intent + "; flags=0x" 6724 + Integer.toHexString(intent != null ? intent.getFlags() : 0)); 6725 6726 if (targetPkg == null) { 6727 throw new NullPointerException("targetPkg"); 6728 } 6729 6730 if (intent == null) { 6731 return null; 6732 } 6733 Uri data = intent.getData(); 6734 ClipData clip = intent.getClipData(); 6735 if (data == null && clip == null) { 6736 return null; 6737 } 6738 // Default userId for uris in the intent (if they don't specify it themselves) 6739 int contentUserHint = intent.getContentUserHint(); 6740 if (contentUserHint == UserHandle.USER_CURRENT) { 6741 contentUserHint = UserHandle.getUserId(callingUid); 6742 } 6743 final IPackageManager pm = AppGlobals.getPackageManager(); 6744 int targetUid; 6745 if (needed != null) { 6746 targetUid = needed.targetUid; 6747 } else { 6748 try { 6749 targetUid = pm.getPackageUid(targetPkg, targetUserId); 6750 } catch (RemoteException ex) { 6751 return null; 6752 } 6753 if (targetUid < 0) { 6754 if (DEBUG_URI_PERMISSION) { 6755 Slog.v(TAG, "Can't grant URI permission no uid for: " + targetPkg 6756 + " on user " + targetUserId); 6757 } 6758 return null; 6759 } 6760 } 6761 if (data != null) { 6762 GrantUri grantUri = GrantUri.resolve(contentUserHint, data); 6763 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 6764 targetUid); 6765 if (targetUid > 0) { 6766 if (needed == null) { 6767 needed = new NeededUriGrants(targetPkg, targetUid, mode); 6768 } 6769 needed.add(grantUri); 6770 } 6771 } 6772 if (clip != null) { 6773 for (int i=0; i<clip.getItemCount(); i++) { 6774 Uri uri = clip.getItemAt(i).getUri(); 6775 if (uri != null) { 6776 GrantUri grantUri = GrantUri.resolve(contentUserHint, uri); 6777 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 6778 targetUid); 6779 if (targetUid > 0) { 6780 if (needed == null) { 6781 needed = new NeededUriGrants(targetPkg, targetUid, mode); 6782 } 6783 needed.add(grantUri); 6784 } 6785 } else { 6786 Intent clipIntent = clip.getItemAt(i).getIntent(); 6787 if (clipIntent != null) { 6788 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked( 6789 callingUid, targetPkg, clipIntent, mode, needed, targetUserId); 6790 if (newNeeded != null) { 6791 needed = newNeeded; 6792 } 6793 } 6794 } 6795 } 6796 } 6797 6798 return needed; 6799 } 6800 6801 /** 6802 * Like grantUriPermissionUncheckedLocked, but takes an Intent. 6803 */ 6804 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, 6805 UriPermissionOwner owner) { 6806 if (needed != null) { 6807 for (int i=0; i<needed.size(); i++) { 6808 GrantUri grantUri = needed.get(i); 6809 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg, 6810 grantUri, needed.flags, owner); 6811 } 6812 } 6813 } 6814 6815 void grantUriPermissionFromIntentLocked(int callingUid, 6816 String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) { 6817 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, 6818 intent, intent != null ? intent.getFlags() : 0, null, targetUserId); 6819 if (needed == null) { 6820 return; 6821 } 6822 6823 grantUriPermissionUncheckedFromIntentLocked(needed, owner); 6824 } 6825 6826 @Override 6827 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 6828 final int modeFlags, int userId) { 6829 enforceNotIsolatedCaller("grantUriPermission"); 6830 GrantUri grantUri = new GrantUri(userId, uri, false); 6831 synchronized(this) { 6832 final ProcessRecord r = getRecordForAppLocked(caller); 6833 if (r == null) { 6834 throw new SecurityException("Unable to find app for caller " 6835 + caller 6836 + " when granting permission to uri " + grantUri); 6837 } 6838 if (targetPkg == null) { 6839 throw new IllegalArgumentException("null target"); 6840 } 6841 if (grantUri == null) { 6842 throw new IllegalArgumentException("null uri"); 6843 } 6844 6845 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 6846 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 6847 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 6848 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 6849 6850 grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null, 6851 UserHandle.getUserId(r.uid)); 6852 } 6853 } 6854 6855 void removeUriPermissionIfNeededLocked(UriPermission perm) { 6856 if (perm.modeFlags == 0) { 6857 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 6858 perm.targetUid); 6859 if (perms != null) { 6860 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 6861 "Removing " + perm.targetUid + " permission to " + perm.uri); 6862 6863 perms.remove(perm.uri); 6864 if (perms.isEmpty()) { 6865 mGrantedUriPermissions.remove(perm.targetUid); 6866 } 6867 } 6868 } 6869 } 6870 6871 private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) { 6872 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Revoking all granted permissions to " + grantUri); 6873 6874 final IPackageManager pm = AppGlobals.getPackageManager(); 6875 final String authority = grantUri.uri.getAuthority(); 6876 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 6877 if (pi == null) { 6878 Slog.w(TAG, "No content provider found for permission revoke: " 6879 + grantUri.toSafeString()); 6880 return; 6881 } 6882 6883 // Does the caller have this permission on the URI? 6884 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 6885 // Right now, if you are not the original owner of the permission, 6886 // you are not allowed to revoke it. 6887 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) { 6888 throw new SecurityException("Uid " + callingUid 6889 + " does not have permission to uri " + grantUri); 6890 //} 6891 } 6892 6893 boolean persistChanged = false; 6894 6895 // Go through all of the permissions and remove any that match. 6896 int N = mGrantedUriPermissions.size(); 6897 for (int i = 0; i < N; i++) { 6898 final int targetUid = mGrantedUriPermissions.keyAt(i); 6899 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 6900 6901 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 6902 final UriPermission perm = it.next(); 6903 if (perm.uri.sourceUserId == grantUri.sourceUserId 6904 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 6905 if (DEBUG_URI_PERMISSION) 6906 Slog.v(TAG, 6907 "Revoking " + perm.targetUid + " permission to " + perm.uri); 6908 persistChanged |= perm.revokeModes( 6909 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 6910 if (perm.modeFlags == 0) { 6911 it.remove(); 6912 } 6913 } 6914 } 6915 6916 if (perms.isEmpty()) { 6917 mGrantedUriPermissions.remove(targetUid); 6918 N--; 6919 i--; 6920 } 6921 } 6922 6923 if (persistChanged) { 6924 schedulePersistUriGrants(); 6925 } 6926 } 6927 6928 @Override 6929 public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags, 6930 int userId) { 6931 enforceNotIsolatedCaller("revokeUriPermission"); 6932 synchronized(this) { 6933 final ProcessRecord r = getRecordForAppLocked(caller); 6934 if (r == null) { 6935 throw new SecurityException("Unable to find app for caller " 6936 + caller 6937 + " when revoking permission to uri " + uri); 6938 } 6939 if (uri == null) { 6940 Slog.w(TAG, "revokeUriPermission: null uri"); 6941 return; 6942 } 6943 6944 if (!Intent.isAccessUriMode(modeFlags)) { 6945 return; 6946 } 6947 6948 final IPackageManager pm = AppGlobals.getPackageManager(); 6949 final String authority = uri.getAuthority(); 6950 final ProviderInfo pi = getProviderInfoLocked(authority, userId); 6951 if (pi == null) { 6952 Slog.w(TAG, "No content provider found for permission revoke: " 6953 + uri.toSafeString()); 6954 return; 6955 } 6956 6957 revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags); 6958 } 6959 } 6960 6961 /** 6962 * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the 6963 * given package. 6964 * 6965 * @param packageName Package name to match, or {@code null} to apply to all 6966 * packages. 6967 * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply 6968 * to all users. 6969 * @param persistable If persistable grants should be removed. 6970 */ 6971 private void removeUriPermissionsForPackageLocked( 6972 String packageName, int userHandle, boolean persistable) { 6973 if (userHandle == UserHandle.USER_ALL && packageName == null) { 6974 throw new IllegalArgumentException("Must narrow by either package or user"); 6975 } 6976 6977 boolean persistChanged = false; 6978 6979 int N = mGrantedUriPermissions.size(); 6980 for (int i = 0; i < N; i++) { 6981 final int targetUid = mGrantedUriPermissions.keyAt(i); 6982 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 6983 6984 // Only inspect grants matching user 6985 if (userHandle == UserHandle.USER_ALL 6986 || userHandle == UserHandle.getUserId(targetUid)) { 6987 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 6988 final UriPermission perm = it.next(); 6989 6990 // Only inspect grants matching package 6991 if (packageName == null || perm.sourcePkg.equals(packageName) 6992 || perm.targetPkg.equals(packageName)) { 6993 persistChanged |= perm.revokeModes( 6994 persistable ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); 6995 6996 // Only remove when no modes remain; any persisted grants 6997 // will keep this alive. 6998 if (perm.modeFlags == 0) { 6999 it.remove(); 7000 } 7001 } 7002 } 7003 7004 if (perms.isEmpty()) { 7005 mGrantedUriPermissions.remove(targetUid); 7006 N--; 7007 i--; 7008 } 7009 } 7010 } 7011 7012 if (persistChanged) { 7013 schedulePersistUriGrants(); 7014 } 7015 } 7016 7017 @Override 7018 public IBinder newUriPermissionOwner(String name) { 7019 enforceNotIsolatedCaller("newUriPermissionOwner"); 7020 synchronized(this) { 7021 UriPermissionOwner owner = new UriPermissionOwner(this, name); 7022 return owner.getExternalTokenLocked(); 7023 } 7024 } 7025 7026 @Override 7027 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri, 7028 final int modeFlags, int sourceUserId, int targetUserId) { 7029 synchronized(this) { 7030 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7031 if (owner == null) { 7032 throw new IllegalArgumentException("Unknown owner: " + token); 7033 } 7034 if (fromUid != Binder.getCallingUid()) { 7035 if (Binder.getCallingUid() != Process.myUid()) { 7036 // Only system code can grant URI permissions on behalf 7037 // of other users. 7038 throw new SecurityException("nice try"); 7039 } 7040 } 7041 if (targetPkg == null) { 7042 throw new IllegalArgumentException("null target"); 7043 } 7044 if (uri == null) { 7045 throw new IllegalArgumentException("null uri"); 7046 } 7047 7048 grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false), 7049 modeFlags, owner, targetUserId); 7050 } 7051 } 7052 7053 @Override 7054 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) { 7055 synchronized(this) { 7056 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7057 if (owner == null) { 7058 throw new IllegalArgumentException("Unknown owner: " + token); 7059 } 7060 7061 if (uri == null) { 7062 owner.removeUriPermissionsLocked(mode); 7063 } else { 7064 owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode); 7065 } 7066 } 7067 } 7068 7069 private void schedulePersistUriGrants() { 7070 if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) { 7071 mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG), 7072 10 * DateUtils.SECOND_IN_MILLIS); 7073 } 7074 } 7075 7076 private void writeGrantedUriPermissions() { 7077 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "writeGrantedUriPermissions()"); 7078 7079 // Snapshot permissions so we can persist without lock 7080 ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList(); 7081 synchronized (this) { 7082 final int size = mGrantedUriPermissions.size(); 7083 for (int i = 0; i < size; i++) { 7084 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7085 for (UriPermission perm : perms.values()) { 7086 if (perm.persistedModeFlags != 0) { 7087 persist.add(perm.snapshot()); 7088 } 7089 } 7090 } 7091 } 7092 7093 FileOutputStream fos = null; 7094 try { 7095 fos = mGrantFile.startWrite(); 7096 7097 XmlSerializer out = new FastXmlSerializer(); 7098 out.setOutput(fos, "utf-8"); 7099 out.startDocument(null, true); 7100 out.startTag(null, TAG_URI_GRANTS); 7101 for (UriPermission.Snapshot perm : persist) { 7102 out.startTag(null, TAG_URI_GRANT); 7103 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId); 7104 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId); 7105 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg); 7106 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg); 7107 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri)); 7108 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix); 7109 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags); 7110 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime); 7111 out.endTag(null, TAG_URI_GRANT); 7112 } 7113 out.endTag(null, TAG_URI_GRANTS); 7114 out.endDocument(); 7115 7116 mGrantFile.finishWrite(fos); 7117 } catch (IOException e) { 7118 if (fos != null) { 7119 mGrantFile.failWrite(fos); 7120 } 7121 } 7122 } 7123 7124 private void readGrantedUriPermissionsLocked() { 7125 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "readGrantedUriPermissions()"); 7126 7127 final long now = System.currentTimeMillis(); 7128 7129 FileInputStream fis = null; 7130 try { 7131 fis = mGrantFile.openRead(); 7132 final XmlPullParser in = Xml.newPullParser(); 7133 in.setInput(fis, null); 7134 7135 int type; 7136 while ((type = in.next()) != END_DOCUMENT) { 7137 final String tag = in.getName(); 7138 if (type == START_TAG) { 7139 if (TAG_URI_GRANT.equals(tag)) { 7140 final int sourceUserId; 7141 final int targetUserId; 7142 final int userHandle = readIntAttribute(in, 7143 ATTR_USER_HANDLE, UserHandle.USER_NULL); 7144 if (userHandle != UserHandle.USER_NULL) { 7145 // For backwards compatibility. 7146 sourceUserId = userHandle; 7147 targetUserId = userHandle; 7148 } else { 7149 sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID); 7150 targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID); 7151 } 7152 final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG); 7153 final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG); 7154 final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI)); 7155 final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX); 7156 final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS); 7157 final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now); 7158 7159 // Sanity check that provider still belongs to source package 7160 final ProviderInfo pi = getProviderInfoLocked( 7161 uri.getAuthority(), sourceUserId); 7162 if (pi != null && sourcePkg.equals(pi.packageName)) { 7163 int targetUid = -1; 7164 try { 7165 targetUid = AppGlobals.getPackageManager() 7166 .getPackageUid(targetPkg, targetUserId); 7167 } catch (RemoteException e) { 7168 } 7169 if (targetUid != -1) { 7170 final UriPermission perm = findOrCreateUriPermissionLocked( 7171 sourcePkg, targetPkg, targetUid, 7172 new GrantUri(sourceUserId, uri, prefix)); 7173 perm.initPersistedModes(modeFlags, createdTime); 7174 } 7175 } else { 7176 Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg 7177 + " but instead found " + pi); 7178 } 7179 } 7180 } 7181 } 7182 } catch (FileNotFoundException e) { 7183 // Missing grants is okay 7184 } catch (IOException e) { 7185 Log.wtf(TAG, "Failed reading Uri grants", e); 7186 } catch (XmlPullParserException e) { 7187 Log.wtf(TAG, "Failed reading Uri grants", e); 7188 } finally { 7189 IoUtils.closeQuietly(fis); 7190 } 7191 } 7192 7193 @Override 7194 public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 7195 enforceNotIsolatedCaller("takePersistableUriPermission"); 7196 7197 Preconditions.checkFlagsArgument(modeFlags, 7198 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 7199 7200 synchronized (this) { 7201 final int callingUid = Binder.getCallingUid(); 7202 boolean persistChanged = false; 7203 GrantUri grantUri = new GrantUri(userId, uri, false); 7204 7205 UriPermission exactPerm = findUriPermissionLocked(callingUid, 7206 new GrantUri(userId, uri, false)); 7207 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 7208 new GrantUri(userId, uri, true)); 7209 7210 final boolean exactValid = (exactPerm != null) 7211 && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags); 7212 final boolean prefixValid = (prefixPerm != null) 7213 && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags); 7214 7215 if (!(exactValid || prefixValid)) { 7216 throw new SecurityException("No persistable permission grants found for UID " 7217 + callingUid + " and Uri " + grantUri.toSafeString()); 7218 } 7219 7220 if (exactValid) { 7221 persistChanged |= exactPerm.takePersistableModes(modeFlags); 7222 } 7223 if (prefixValid) { 7224 persistChanged |= prefixPerm.takePersistableModes(modeFlags); 7225 } 7226 7227 persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid); 7228 7229 if (persistChanged) { 7230 schedulePersistUriGrants(); 7231 } 7232 } 7233 } 7234 7235 @Override 7236 public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 7237 enforceNotIsolatedCaller("releasePersistableUriPermission"); 7238 7239 Preconditions.checkFlagsArgument(modeFlags, 7240 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 7241 7242 synchronized (this) { 7243 final int callingUid = Binder.getCallingUid(); 7244 boolean persistChanged = false; 7245 7246 UriPermission exactPerm = findUriPermissionLocked(callingUid, 7247 new GrantUri(userId, uri, false)); 7248 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 7249 new GrantUri(userId, uri, true)); 7250 if (exactPerm == null && prefixPerm == null) { 7251 throw new SecurityException("No permission grants found for UID " + callingUid 7252 + " and Uri " + uri.toSafeString()); 7253 } 7254 7255 if (exactPerm != null) { 7256 persistChanged |= exactPerm.releasePersistableModes(modeFlags); 7257 removeUriPermissionIfNeededLocked(exactPerm); 7258 } 7259 if (prefixPerm != null) { 7260 persistChanged |= prefixPerm.releasePersistableModes(modeFlags); 7261 removeUriPermissionIfNeededLocked(prefixPerm); 7262 } 7263 7264 if (persistChanged) { 7265 schedulePersistUriGrants(); 7266 } 7267 } 7268 } 7269 7270 /** 7271 * Prune any older {@link UriPermission} for the given UID until outstanding 7272 * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}. 7273 * 7274 * @return if any mutations occured that require persisting. 7275 */ 7276 private boolean maybePrunePersistedUriGrantsLocked(int uid) { 7277 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 7278 if (perms == null) return false; 7279 if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false; 7280 7281 final ArrayList<UriPermission> persisted = Lists.newArrayList(); 7282 for (UriPermission perm : perms.values()) { 7283 if (perm.persistedModeFlags != 0) { 7284 persisted.add(perm); 7285 } 7286 } 7287 7288 final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS; 7289 if (trimCount <= 0) return false; 7290 7291 Collections.sort(persisted, new UriPermission.PersistedTimeComparator()); 7292 for (int i = 0; i < trimCount; i++) { 7293 final UriPermission perm = persisted.get(i); 7294 7295 if (DEBUG_URI_PERMISSION) { 7296 Slog.v(TAG, "Trimming grant created at " + perm.persistedCreateTime); 7297 } 7298 7299 perm.releasePersistableModes(~0); 7300 removeUriPermissionIfNeededLocked(perm); 7301 } 7302 7303 return true; 7304 } 7305 7306 @Override 7307 public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions( 7308 String packageName, boolean incoming) { 7309 enforceNotIsolatedCaller("getPersistedUriPermissions"); 7310 Preconditions.checkNotNull(packageName, "packageName"); 7311 7312 final int callingUid = Binder.getCallingUid(); 7313 final IPackageManager pm = AppGlobals.getPackageManager(); 7314 try { 7315 final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid)); 7316 if (packageUid != callingUid) { 7317 throw new SecurityException( 7318 "Package " + packageName + " does not belong to calling UID " + callingUid); 7319 } 7320 } catch (RemoteException e) { 7321 throw new SecurityException("Failed to verify package name ownership"); 7322 } 7323 7324 final ArrayList<android.content.UriPermission> result = Lists.newArrayList(); 7325 synchronized (this) { 7326 if (incoming) { 7327 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 7328 callingUid); 7329 if (perms == null) { 7330 Slog.w(TAG, "No permission grants found for " + packageName); 7331 } else { 7332 for (UriPermission perm : perms.values()) { 7333 if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) { 7334 result.add(perm.buildPersistedPublicApiObject()); 7335 } 7336 } 7337 } 7338 } else { 7339 final int size = mGrantedUriPermissions.size(); 7340 for (int i = 0; i < size; i++) { 7341 final ArrayMap<GrantUri, UriPermission> perms = 7342 mGrantedUriPermissions.valueAt(i); 7343 for (UriPermission perm : perms.values()) { 7344 if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) { 7345 result.add(perm.buildPersistedPublicApiObject()); 7346 } 7347 } 7348 } 7349 } 7350 } 7351 return new ParceledListSlice<android.content.UriPermission>(result); 7352 } 7353 7354 @Override 7355 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 7356 synchronized (this) { 7357 ProcessRecord app = 7358 who != null ? getRecordForAppLocked(who) : null; 7359 if (app == null) return; 7360 7361 Message msg = Message.obtain(); 7362 msg.what = WAIT_FOR_DEBUGGER_MSG; 7363 msg.obj = app; 7364 msg.arg1 = waiting ? 1 : 0; 7365 mHandler.sendMessage(msg); 7366 } 7367 } 7368 7369 @Override 7370 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 7371 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ); 7372 final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ); 7373 outInfo.availMem = Process.getFreeMemory(); 7374 outInfo.totalMem = Process.getTotalMemory(); 7375 outInfo.threshold = homeAppMem; 7376 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2)); 7377 outInfo.hiddenAppThreshold = cachedAppMem; 7378 outInfo.secondaryServerThreshold = mProcessList.getMemLevel( 7379 ProcessList.SERVICE_ADJ); 7380 outInfo.visibleAppThreshold = mProcessList.getMemLevel( 7381 ProcessList.VISIBLE_APP_ADJ); 7382 outInfo.foregroundAppThreshold = mProcessList.getMemLevel( 7383 ProcessList.FOREGROUND_APP_ADJ); 7384 } 7385 7386 // ========================================================= 7387 // TASK MANAGEMENT 7388 // ========================================================= 7389 7390 @Override 7391 public List<IAppTask> getAppTasks() { 7392 final PackageManager pm = mContext.getPackageManager(); 7393 int callingUid = Binder.getCallingUid(); 7394 long ident = Binder.clearCallingIdentity(); 7395 7396 // Compose the list of packages for this id to test against 7397 HashSet<String> packages = new HashSet<String>(); 7398 String[] uidPackages = pm.getPackagesForUid(callingUid); 7399 for (int i = 0; i < uidPackages.length; i++) { 7400 packages.add(uidPackages[i]); 7401 } 7402 7403 synchronized(this) { 7404 ArrayList<IAppTask> list = new ArrayList<IAppTask>(); 7405 try { 7406 if (localLOGV) Slog.v(TAG, "getAppTasks"); 7407 7408 final int N = mRecentTasks.size(); 7409 for (int i = 0; i < N; i++) { 7410 TaskRecord tr = mRecentTasks.get(i); 7411 // Skip tasks that are not created by the caller 7412 if (packages.contains(tr.getBaseIntent().getComponent().getPackageName())) { 7413 ActivityManager.RecentTaskInfo taskInfo = 7414 createRecentTaskInfoFromTaskRecord(tr); 7415 AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid); 7416 list.add(taskImpl); 7417 } 7418 } 7419 } finally { 7420 Binder.restoreCallingIdentity(ident); 7421 } 7422 return list; 7423 } 7424 } 7425 7426 @Override 7427 public List<RunningTaskInfo> getTasks(int maxNum, int flags) { 7428 final int callingUid = Binder.getCallingUid(); 7429 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>(); 7430 7431 synchronized(this) { 7432 if (localLOGV) Slog.v( 7433 TAG, "getTasks: max=" + maxNum + ", flags=" + flags); 7434 7435 final boolean allowed = checkCallingPermission( 7436 android.Manifest.permission.GET_TASKS) 7437 == PackageManager.PERMISSION_GRANTED; 7438 if (!allowed) { 7439 Slog.w(TAG, "getTasks: caller " + callingUid 7440 + " does not hold GET_TASKS; limiting output"); 7441 } 7442 7443 // TODO: Improve with MRU list from all ActivityStacks. 7444 mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed); 7445 } 7446 7447 return list; 7448 } 7449 7450 TaskRecord getMostRecentTask() { 7451 return mRecentTasks.get(0); 7452 } 7453 7454 /** 7455 * Creates a new RecentTaskInfo from a TaskRecord. 7456 */ 7457 private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) { 7458 // Update the task description to reflect any changes in the task stack 7459 tr.updateTaskDescription(); 7460 7461 // Compose the recent task info 7462 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); 7463 rti.id = tr.getTopActivity() == null ? -1 : tr.taskId; 7464 rti.persistentId = tr.taskId; 7465 rti.baseIntent = new Intent(tr.getBaseIntent()); 7466 rti.origActivity = tr.origActivity; 7467 rti.description = tr.lastDescription; 7468 rti.stackId = tr.stack != null ? tr.stack.mStackId : -1; 7469 rti.userId = tr.userId; 7470 rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription); 7471 rti.firstActiveTime = tr.firstActiveTime; 7472 rti.lastActiveTime = tr.lastActiveTime; 7473 rti.affiliatedTaskId = tr.mAffiliatedTaskId; 7474 return rti; 7475 } 7476 7477 @Override 7478 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) { 7479 final int callingUid = Binder.getCallingUid(); 7480 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 7481 false, ALLOW_FULL_ONLY, "getRecentTasks", null); 7482 7483 final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0; 7484 final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0; 7485 synchronized (this) { 7486 final boolean allowed = checkCallingPermission(android.Manifest.permission.GET_TASKS) 7487 == PackageManager.PERMISSION_GRANTED; 7488 if (!allowed) { 7489 Slog.w(TAG, "getRecentTasks: caller " + callingUid 7490 + " does not hold GET_TASKS; limiting output"); 7491 } 7492 final boolean detailed = checkCallingPermission( 7493 android.Manifest.permission.GET_DETAILED_TASKS) 7494 == PackageManager.PERMISSION_GRANTED; 7495 7496 IPackageManager pm = AppGlobals.getPackageManager(); 7497 7498 final int N = mRecentTasks.size(); 7499 ArrayList<ActivityManager.RecentTaskInfo> res 7500 = new ArrayList<ActivityManager.RecentTaskInfo>( 7501 maxNum < N ? maxNum : N); 7502 7503 final Set<Integer> includedUsers; 7504 if (includeProfiles) { 7505 includedUsers = getProfileIdsLocked(userId); 7506 } else { 7507 includedUsers = new HashSet<Integer>(); 7508 } 7509 includedUsers.add(Integer.valueOf(userId)); 7510 7511 // Regroup affiliated tasks together. 7512 for (int i = 0; i < N; ) { 7513 TaskRecord task = mRecentTasks.remove(i); 7514 if (mTmpRecents.contains(task)) { 7515 continue; 7516 } 7517 int affiliatedTaskId = task.mAffiliatedTaskId; 7518 while (true) { 7519 TaskRecord next = task.mNextAffiliate; 7520 if (next == null) { 7521 break; 7522 } 7523 if (next.mAffiliatedTaskId != affiliatedTaskId) { 7524 Slog.e(TAG, "Error in Recents: next.affiliatedTaskId=" + 7525 next.mAffiliatedTaskId + " affiliatedTaskId=" + affiliatedTaskId); 7526 task.setNextAffiliate(null); 7527 if (next.mPrevAffiliate == task) { 7528 next.setPrevAffiliate(null); 7529 } 7530 break; 7531 } 7532 if (next.mPrevAffiliate != task) { 7533 Slog.e(TAG, "Error in Recents chain prev.mNextAffiliate=" + 7534 next.mPrevAffiliate + " task=" + task); 7535 next.setPrevAffiliate(null); 7536 break; 7537 } 7538 if (!mRecentTasks.contains(next)) { 7539 Slog.e(TAG, "Error in Recents: next=" + next + " not in mRecentTasks"); 7540 task.setNextAffiliate(null); 7541 if (next.mPrevAffiliate == task) { 7542 next.setPrevAffiliate(null); 7543 } 7544 break; 7545 } 7546 task = next; 7547 } 7548 // task is now the end of the list 7549 do { 7550 mRecentTasks.remove(task); 7551 mRecentTasks.add(i++, task); 7552 mTmpRecents.add(task); 7553 } while ((task = task.mPrevAffiliate) != null); 7554 } 7555 mTmpRecents.clear(); 7556 // mRecentTasks is now in sorted, affiliated order. 7557 7558 for (int i=0; i<N && maxNum > 0; i++) { 7559 TaskRecord tr = mRecentTasks.get(i); 7560 // Only add calling user or related users recent tasks 7561 if (!includedUsers.contains(Integer.valueOf(tr.userId))) continue; 7562 7563 // Return the entry if desired by the caller. We always return 7564 // the first entry, because callers always expect this to be the 7565 // foreground app. We may filter others if the caller has 7566 // not supplied RECENT_WITH_EXCLUDED and there is some reason 7567 // we should exclude the entry. 7568 7569 if (i == 0 7570 || withExcluded 7571 || (tr.intent == null) 7572 || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) 7573 == 0)) { 7574 if (!allowed) { 7575 // If the caller doesn't have the GET_TASKS permission, then only 7576 // allow them to see a small subset of tasks -- their own and home. 7577 if (!tr.isHomeTask() && tr.creatorUid != callingUid) { 7578 continue; 7579 } 7580 } 7581 if (tr.autoRemoveRecents && tr.getTopActivity() == null) { 7582 // Don't include auto remove tasks that are finished or finishing. 7583 continue; 7584 } 7585 7586 ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr); 7587 if (!detailed) { 7588 rti.baseIntent.replaceExtras((Bundle)null); 7589 } 7590 7591 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) { 7592 // Check whether this activity is currently available. 7593 try { 7594 if (rti.origActivity != null) { 7595 if (pm.getActivityInfo(rti.origActivity, 0, userId) 7596 == null) { 7597 continue; 7598 } 7599 } else if (rti.baseIntent != null) { 7600 if (pm.queryIntentActivities(rti.baseIntent, 7601 null, 0, userId) == null) { 7602 continue; 7603 } 7604 } 7605 } catch (RemoteException e) { 7606 // Will never happen. 7607 } 7608 } 7609 7610 res.add(rti); 7611 maxNum--; 7612 } 7613 } 7614 return res; 7615 } 7616 } 7617 7618 private TaskRecord recentTaskForIdLocked(int id) { 7619 final int N = mRecentTasks.size(); 7620 for (int i=0; i<N; i++) { 7621 TaskRecord tr = mRecentTasks.get(i); 7622 if (tr.taskId == id) { 7623 return tr; 7624 } 7625 } 7626 return null; 7627 } 7628 7629 @Override 7630 public ActivityManager.TaskThumbnail getTaskThumbnail(int id) { 7631 synchronized (this) { 7632 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 7633 "getTaskThumbnail()"); 7634 TaskRecord tr = recentTaskForIdLocked(id); 7635 if (tr != null) { 7636 return tr.getTaskThumbnailLocked(); 7637 } 7638 } 7639 return null; 7640 } 7641 7642 @Override 7643 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) { 7644 synchronized (this) { 7645 ActivityRecord r = ActivityRecord.isInStackLocked(token); 7646 if (r != null) { 7647 r.taskDescription = td; 7648 r.task.updateTaskDescription(); 7649 } 7650 } 7651 } 7652 7653 private void killUnneededProcessLocked(ProcessRecord pr, String reason) { 7654 if (!pr.killedByAm) { 7655 Slog.i(TAG, "Killing " + pr.toShortString() + " (adj " + pr.setAdj + "): " + reason); 7656 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid, 7657 pr.processName, pr.setAdj, reason); 7658 pr.killedByAm = true; 7659 Process.killProcessQuiet(pr.pid); 7660 Process.killProcessGroup(pr.info.uid, pr.pid); 7661 } 7662 } 7663 7664 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) { 7665 tr.disposeThumbnail(); 7666 mRecentTasks.remove(tr); 7667 tr.closeRecentsChain(); 7668 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0; 7669 Intent baseIntent = new Intent( 7670 tr.intent != null ? tr.intent : tr.affinityIntent); 7671 ComponentName component = baseIntent.getComponent(); 7672 if (component == null) { 7673 Slog.w(TAG, "Now component for base intent of task: " + tr); 7674 return; 7675 } 7676 7677 // Find any running services associated with this app. 7678 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent); 7679 7680 if (killProcesses) { 7681 // Find any running processes associated with this app. 7682 final String pkg = component.getPackageName(); 7683 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 7684 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 7685 for (int i=0; i<pmap.size(); i++) { 7686 SparseArray<ProcessRecord> uids = pmap.valueAt(i); 7687 for (int j=0; j<uids.size(); j++) { 7688 ProcessRecord proc = uids.valueAt(j); 7689 if (proc.userId != tr.userId) { 7690 continue; 7691 } 7692 if (!proc.pkgList.containsKey(pkg)) { 7693 continue; 7694 } 7695 procs.add(proc); 7696 } 7697 } 7698 7699 // Kill the running processes. 7700 for (int i=0; i<procs.size(); i++) { 7701 ProcessRecord pr = procs.get(i); 7702 if (pr == mHomeProcess) { 7703 // Don't kill the home process along with tasks from the same package. 7704 continue; 7705 } 7706 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 7707 killUnneededProcessLocked(pr, "remove task"); 7708 } else { 7709 pr.waitingToKill = "remove task"; 7710 } 7711 } 7712 } 7713 } 7714 7715 /** 7716 * Removes the task with the specified task id. 7717 * 7718 * @param taskId Identifier of the task to be removed. 7719 * @param flags Additional operational flags. May be 0 or 7720 * {@link ActivityManager#REMOVE_TASK_KILL_PROCESS}. 7721 * @return Returns true if the given task was found and removed. 7722 */ 7723 private boolean removeTaskByIdLocked(int taskId, int flags) { 7724 TaskRecord tr = recentTaskForIdLocked(taskId); 7725 if (tr != null) { 7726 tr.removeTaskActivitiesLocked(); 7727 cleanUpRemovedTaskLocked(tr, flags); 7728 if (tr.isPersistable) { 7729 notifyTaskPersisterLocked(null, true); 7730 } 7731 return true; 7732 } 7733 return false; 7734 } 7735 7736 @Override 7737 public boolean removeTask(int taskId, int flags) { 7738 synchronized (this) { 7739 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 7740 "removeTask()"); 7741 long ident = Binder.clearCallingIdentity(); 7742 try { 7743 return removeTaskByIdLocked(taskId, flags); 7744 } finally { 7745 Binder.restoreCallingIdentity(ident); 7746 } 7747 } 7748 } 7749 7750 /** 7751 * TODO: Add mController hook 7752 */ 7753 @Override 7754 public void moveTaskToFront(int taskId, int flags, Bundle options) { 7755 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 7756 "moveTaskToFront()"); 7757 7758 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToFront: moving taskId=" + taskId); 7759 synchronized(this) { 7760 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 7761 Binder.getCallingUid(), "Task to front")) { 7762 ActivityOptions.abort(options); 7763 return; 7764 } 7765 final long origId = Binder.clearCallingIdentity(); 7766 try { 7767 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 7768 if (task == null) { 7769 return; 7770 } 7771 if (mStackSupervisor.isLockTaskModeViolation(task)) { 7772 mStackSupervisor.showLockTaskToast(); 7773 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode"); 7774 return; 7775 } 7776 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked(); 7777 if (prev != null && prev.isRecentsActivity()) { 7778 task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE); 7779 } 7780 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options); 7781 } finally { 7782 Binder.restoreCallingIdentity(origId); 7783 } 7784 ActivityOptions.abort(options); 7785 } 7786 } 7787 7788 @Override 7789 public void moveTaskToBack(int taskId) { 7790 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 7791 "moveTaskToBack()"); 7792 7793 synchronized(this) { 7794 TaskRecord tr = recentTaskForIdLocked(taskId); 7795 if (tr != null) { 7796 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToBack: moving task=" + tr); 7797 ActivityStack stack = tr.stack; 7798 if (stack.mResumedActivity != null && stack.mResumedActivity.task == tr) { 7799 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 7800 Binder.getCallingUid(), "Task to back")) { 7801 return; 7802 } 7803 } 7804 final long origId = Binder.clearCallingIdentity(); 7805 try { 7806 stack.moveTaskToBackLocked(taskId, null); 7807 } finally { 7808 Binder.restoreCallingIdentity(origId); 7809 } 7810 } 7811 } 7812 } 7813 7814 /** 7815 * Moves an activity, and all of the other activities within the same task, to the bottom 7816 * of the history stack. The activity's order within the task is unchanged. 7817 * 7818 * @param token A reference to the activity we wish to move 7819 * @param nonRoot If false then this only works if the activity is the root 7820 * of a task; if true it will work for any activity in a task. 7821 * @return Returns true if the move completed, false if not. 7822 */ 7823 @Override 7824 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 7825 enforceNotIsolatedCaller("moveActivityTaskToBack"); 7826 synchronized(this) { 7827 final long origId = Binder.clearCallingIdentity(); 7828 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); 7829 if (taskId >= 0) { 7830 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId, null); 7831 } 7832 Binder.restoreCallingIdentity(origId); 7833 } 7834 return false; 7835 } 7836 7837 @Override 7838 public void moveTaskBackwards(int task) { 7839 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 7840 "moveTaskBackwards()"); 7841 7842 synchronized(this) { 7843 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 7844 Binder.getCallingUid(), "Task backwards")) { 7845 return; 7846 } 7847 final long origId = Binder.clearCallingIdentity(); 7848 moveTaskBackwardsLocked(task); 7849 Binder.restoreCallingIdentity(origId); 7850 } 7851 } 7852 7853 private final void moveTaskBackwardsLocked(int task) { 7854 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 7855 } 7856 7857 @Override 7858 public IBinder getHomeActivityToken() throws RemoteException { 7859 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7860 "getHomeActivityToken()"); 7861 synchronized (this) { 7862 return mStackSupervisor.getHomeActivityToken(); 7863 } 7864 } 7865 7866 @Override 7867 public IActivityContainer createActivityContainer(IBinder parentActivityToken, 7868 IActivityContainerCallback callback) throws RemoteException { 7869 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7870 "createActivityContainer()"); 7871 synchronized (this) { 7872 if (parentActivityToken == null) { 7873 throw new IllegalArgumentException("parent token must not be null"); 7874 } 7875 ActivityRecord r = ActivityRecord.forToken(parentActivityToken); 7876 if (r == null) { 7877 return null; 7878 } 7879 if (callback == null) { 7880 throw new IllegalArgumentException("callback must not be null"); 7881 } 7882 return mStackSupervisor.createActivityContainer(r, callback); 7883 } 7884 } 7885 7886 @Override 7887 public void deleteActivityContainer(IActivityContainer container) throws RemoteException { 7888 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7889 "deleteActivityContainer()"); 7890 synchronized (this) { 7891 mStackSupervisor.deleteActivityContainer(container); 7892 } 7893 } 7894 7895 @Override 7896 public IActivityContainer getEnclosingActivityContainer(IBinder activityToken) 7897 throws RemoteException { 7898 synchronized (this) { 7899 ActivityStack stack = ActivityRecord.getStackLocked(activityToken); 7900 if (stack != null) { 7901 return stack.mActivityContainer; 7902 } 7903 return null; 7904 } 7905 } 7906 7907 @Override 7908 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 7909 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7910 "moveTaskToStack()"); 7911 if (stackId == HOME_STACK_ID) { 7912 Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack", 7913 new RuntimeException("here").fillInStackTrace()); 7914 } 7915 synchronized (this) { 7916 long ident = Binder.clearCallingIdentity(); 7917 try { 7918 if (DEBUG_STACK) Slog.d(TAG, "moveTaskToStack: moving task=" + taskId + " to stackId=" 7919 + stackId + " toTop=" + toTop); 7920 mStackSupervisor.moveTaskToStack(taskId, stackId, toTop); 7921 } finally { 7922 Binder.restoreCallingIdentity(ident); 7923 } 7924 } 7925 } 7926 7927 @Override 7928 public void resizeStack(int stackBoxId, Rect bounds) { 7929 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7930 "resizeStackBox()"); 7931 long ident = Binder.clearCallingIdentity(); 7932 try { 7933 mWindowManager.resizeStack(stackBoxId, bounds); 7934 } finally { 7935 Binder.restoreCallingIdentity(ident); 7936 } 7937 } 7938 7939 @Override 7940 public List<StackInfo> getAllStackInfos() { 7941 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7942 "getAllStackInfos()"); 7943 long ident = Binder.clearCallingIdentity(); 7944 try { 7945 synchronized (this) { 7946 return mStackSupervisor.getAllStackInfosLocked(); 7947 } 7948 } finally { 7949 Binder.restoreCallingIdentity(ident); 7950 } 7951 } 7952 7953 @Override 7954 public StackInfo getStackInfo(int stackId) { 7955 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7956 "getStackInfo()"); 7957 long ident = Binder.clearCallingIdentity(); 7958 try { 7959 synchronized (this) { 7960 return mStackSupervisor.getStackInfoLocked(stackId); 7961 } 7962 } finally { 7963 Binder.restoreCallingIdentity(ident); 7964 } 7965 } 7966 7967 @Override 7968 public boolean isInHomeStack(int taskId) { 7969 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 7970 "getStackInfo()"); 7971 long ident = Binder.clearCallingIdentity(); 7972 try { 7973 synchronized (this) { 7974 TaskRecord tr = recentTaskForIdLocked(taskId); 7975 return tr != null && tr.stack != null && tr.stack.isHomeStack(); 7976 } 7977 } finally { 7978 Binder.restoreCallingIdentity(ident); 7979 } 7980 } 7981 7982 @Override 7983 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 7984 synchronized(this) { 7985 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot); 7986 } 7987 } 7988 7989 private boolean isLockTaskAuthorized(String pkg) { 7990 final DevicePolicyManager dpm = (DevicePolicyManager) 7991 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 7992 try { 7993 int uid = mContext.getPackageManager().getPackageUid(pkg, 7994 Binder.getCallingUserHandle().getIdentifier()); 7995 return (uid == Binder.getCallingUid()) && dpm != null && dpm.isLockTaskPermitted(pkg); 7996 } catch (NameNotFoundException e) { 7997 return false; 7998 } 7999 } 8000 8001 void startLockTaskMode(TaskRecord task) { 8002 final String pkg; 8003 synchronized (this) { 8004 pkg = task.intent.getComponent().getPackageName(); 8005 } 8006 boolean isSystemInitiated = Binder.getCallingUid() == Process.SYSTEM_UID; 8007 if (!isSystemInitiated && !isLockTaskAuthorized(pkg)) { 8008 final TaskRecord taskRecord = task; 8009 mHandler.post(new Runnable() { 8010 @Override 8011 public void run() { 8012 mLockToAppRequest.showLockTaskPrompt(taskRecord); 8013 } 8014 }); 8015 return; 8016 } 8017 long ident = Binder.clearCallingIdentity(); 8018 try { 8019 synchronized (this) { 8020 // Since we lost lock on task, make sure it is still there. 8021 task = mStackSupervisor.anyTaskForIdLocked(task.taskId); 8022 if (task != null) { 8023 if (!isSystemInitiated 8024 && ((mFocusedActivity == null) || (task != mFocusedActivity.task))) { 8025 throw new IllegalArgumentException("Invalid task, not in foreground"); 8026 } 8027 mStackSupervisor.setLockTaskModeLocked(task, !isSystemInitiated); 8028 } 8029 } 8030 } finally { 8031 Binder.restoreCallingIdentity(ident); 8032 } 8033 } 8034 8035 @Override 8036 public void startLockTaskMode(int taskId) { 8037 final TaskRecord task; 8038 long ident = Binder.clearCallingIdentity(); 8039 try { 8040 synchronized (this) { 8041 task = mStackSupervisor.anyTaskForIdLocked(taskId); 8042 } 8043 } finally { 8044 Binder.restoreCallingIdentity(ident); 8045 } 8046 if (task != null) { 8047 startLockTaskMode(task); 8048 } 8049 } 8050 8051 @Override 8052 public void startLockTaskMode(IBinder token) { 8053 final TaskRecord task; 8054 long ident = Binder.clearCallingIdentity(); 8055 try { 8056 synchronized (this) { 8057 final ActivityRecord r = ActivityRecord.forToken(token); 8058 if (r == null) { 8059 return; 8060 } 8061 task = r.task; 8062 } 8063 } finally { 8064 Binder.restoreCallingIdentity(ident); 8065 } 8066 if (task != null) { 8067 startLockTaskMode(task); 8068 } 8069 } 8070 8071 @Override 8072 public void startLockTaskModeOnCurrent() throws RemoteException { 8073 checkCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS); 8074 ActivityRecord r = null; 8075 synchronized (this) { 8076 r = mStackSupervisor.topRunningActivityLocked(); 8077 } 8078 startLockTaskMode(r.task); 8079 } 8080 8081 @Override 8082 public void stopLockTaskMode() { 8083 // Verify that the user matches the package of the intent for the TaskRecord 8084 // we are locked to or systtem. This will ensure the same caller for startLockTaskMode 8085 // and stopLockTaskMode. 8086 final int callingUid = Binder.getCallingUid(); 8087 if (callingUid != Process.SYSTEM_UID) { 8088 try { 8089 String pkg = 8090 mStackSupervisor.mLockTaskModeTask.intent.getComponent().getPackageName(); 8091 int uid = mContext.getPackageManager().getPackageUid(pkg, 8092 Binder.getCallingUserHandle().getIdentifier()); 8093 if (uid != callingUid) { 8094 throw new SecurityException("Invalid uid, expected " + uid); 8095 } 8096 } catch (NameNotFoundException e) { 8097 Log.d(TAG, "stopLockTaskMode " + e); 8098 return; 8099 } 8100 } 8101 long ident = Binder.clearCallingIdentity(); 8102 try { 8103 Log.d(TAG, "stopLockTaskMode"); 8104 // Stop lock task 8105 synchronized (this) { 8106 mStackSupervisor.setLockTaskModeLocked(null, false); 8107 } 8108 } finally { 8109 Binder.restoreCallingIdentity(ident); 8110 } 8111 } 8112 8113 @Override 8114 public void stopLockTaskModeOnCurrent() throws RemoteException { 8115 checkCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS); 8116 long ident = Binder.clearCallingIdentity(); 8117 try { 8118 stopLockTaskMode(); 8119 } finally { 8120 Binder.restoreCallingIdentity(ident); 8121 } 8122 } 8123 8124 @Override 8125 public boolean isInLockTaskMode() { 8126 synchronized (this) { 8127 return mStackSupervisor.isInLockTaskMode(); 8128 } 8129 } 8130 8131 // ========================================================= 8132 // CONTENT PROVIDERS 8133 // ========================================================= 8134 8135 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 8136 List<ProviderInfo> providers = null; 8137 try { 8138 providers = AppGlobals.getPackageManager(). 8139 queryContentProviders(app.processName, app.uid, 8140 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS); 8141 } catch (RemoteException ex) { 8142 } 8143 if (DEBUG_MU) 8144 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 8145 int userId = app.userId; 8146 if (providers != null) { 8147 int N = providers.size(); 8148 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 8149 for (int i=0; i<N; i++) { 8150 ProviderInfo cpi = 8151 (ProviderInfo)providers.get(i); 8152 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 8153 cpi.name, cpi.flags); 8154 if (singleton && UserHandle.getUserId(app.uid) != 0) { 8155 // This is a singleton provider, but a user besides the 8156 // default user is asking to initialize a process it runs 8157 // in... well, no, it doesn't actually run in this process, 8158 // it runs in the process of the default user. Get rid of it. 8159 providers.remove(i); 8160 N--; 8161 i--; 8162 continue; 8163 } 8164 8165 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 8166 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 8167 if (cpr == null) { 8168 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 8169 mProviderMap.putProviderByClass(comp, cpr); 8170 } 8171 if (DEBUG_MU) 8172 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 8173 app.pubProviders.put(cpi.name, cpr); 8174 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 8175 // Don't add this if it is a platform component that is marked 8176 // to run in multiple processes, because this is actually 8177 // part of the framework so doesn't make sense to track as a 8178 // separate apk in the process. 8179 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode, 8180 mProcessStats); 8181 } 8182 ensurePackageDexOpt(cpi.applicationInfo.packageName); 8183 } 8184 } 8185 return providers; 8186 } 8187 8188 /** 8189 * Check if {@link ProcessRecord} has a possible chance at accessing the 8190 * given {@link ProviderInfo}. Final permission checking is always done 8191 * in {@link ContentProvider}. 8192 */ 8193 private final String checkContentProviderPermissionLocked( 8194 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 8195 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 8196 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 8197 boolean checkedGrants = false; 8198 if (checkUser) { 8199 // Looking for cross-user grants before enforcing the typical cross-users permissions 8200 int tmpTargetUserId = unsafeConvertIncomingUser(userId); 8201 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 8202 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) { 8203 return null; 8204 } 8205 checkedGrants = true; 8206 } 8207 userId = handleIncomingUser(callingPid, callingUid, userId, 8208 false, ALLOW_NON_FULL, 8209 "checkContentProviderPermissionLocked " + cpi.authority, null); 8210 if (userId != tmpTargetUserId) { 8211 // When we actually went to determine the final targer user ID, this ended 8212 // up different than our initial check for the authority. This is because 8213 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 8214 // SELF. So we need to re-check the grants again. 8215 checkedGrants = false; 8216 } 8217 } 8218 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 8219 cpi.applicationInfo.uid, cpi.exported) 8220 == PackageManager.PERMISSION_GRANTED) { 8221 return null; 8222 } 8223 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 8224 cpi.applicationInfo.uid, cpi.exported) 8225 == PackageManager.PERMISSION_GRANTED) { 8226 return null; 8227 } 8228 8229 PathPermission[] pps = cpi.pathPermissions; 8230 if (pps != null) { 8231 int i = pps.length; 8232 while (i > 0) { 8233 i--; 8234 PathPermission pp = pps[i]; 8235 String pprperm = pp.getReadPermission(); 8236 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 8237 cpi.applicationInfo.uid, cpi.exported) 8238 == PackageManager.PERMISSION_GRANTED) { 8239 return null; 8240 } 8241 String ppwperm = pp.getWritePermission(); 8242 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 8243 cpi.applicationInfo.uid, cpi.exported) 8244 == PackageManager.PERMISSION_GRANTED) { 8245 return null; 8246 } 8247 } 8248 } 8249 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 8250 return null; 8251 } 8252 8253 String msg; 8254 if (!cpi.exported) { 8255 msg = "Permission Denial: opening provider " + cpi.name 8256 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 8257 + ", uid=" + callingUid + ") that is not exported from uid " 8258 + cpi.applicationInfo.uid; 8259 } else { 8260 msg = "Permission Denial: opening provider " + cpi.name 8261 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 8262 + ", uid=" + callingUid + ") requires " 8263 + cpi.readPermission + " or " + cpi.writePermission; 8264 } 8265 Slog.w(TAG, msg); 8266 return msg; 8267 } 8268 8269 /** 8270 * Returns if the ContentProvider has granted a uri to callingUid 8271 */ 8272 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) { 8273 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 8274 if (perms != null) { 8275 for (int i=perms.size()-1; i>=0; i--) { 8276 GrantUri grantUri = perms.keyAt(i); 8277 if (grantUri.sourceUserId == userId || !checkUser) { 8278 if (matchesProvider(grantUri.uri, cpi)) { 8279 return true; 8280 } 8281 } 8282 } 8283 } 8284 return false; 8285 } 8286 8287 /** 8288 * Returns true if the uri authority is one of the authorities specified in the provider. 8289 */ 8290 boolean matchesProvider(Uri uri, ProviderInfo cpi) { 8291 String uriAuth = uri.getAuthority(); 8292 String cpiAuth = cpi.authority; 8293 if (cpiAuth.indexOf(';') == -1) { 8294 return cpiAuth.equals(uriAuth); 8295 } 8296 String[] cpiAuths = cpiAuth.split(";"); 8297 int length = cpiAuths.length; 8298 for (int i = 0; i < length; i++) { 8299 if (cpiAuths[i].equals(uriAuth)) return true; 8300 } 8301 return false; 8302 } 8303 8304 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 8305 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 8306 if (r != null) { 8307 for (int i=0; i<r.conProviders.size(); i++) { 8308 ContentProviderConnection conn = r.conProviders.get(i); 8309 if (conn.provider == cpr) { 8310 if (DEBUG_PROVIDER) Slog.v(TAG, 8311 "Adding provider requested by " 8312 + r.processName + " from process " 8313 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 8314 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 8315 if (stable) { 8316 conn.stableCount++; 8317 conn.numStableIncs++; 8318 } else { 8319 conn.unstableCount++; 8320 conn.numUnstableIncs++; 8321 } 8322 return conn; 8323 } 8324 } 8325 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 8326 if (stable) { 8327 conn.stableCount = 1; 8328 conn.numStableIncs = 1; 8329 } else { 8330 conn.unstableCount = 1; 8331 conn.numUnstableIncs = 1; 8332 } 8333 cpr.connections.add(conn); 8334 r.conProviders.add(conn); 8335 return conn; 8336 } 8337 cpr.addExternalProcessHandleLocked(externalProcessToken); 8338 return null; 8339 } 8340 8341 boolean decProviderCountLocked(ContentProviderConnection conn, 8342 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 8343 if (conn != null) { 8344 cpr = conn.provider; 8345 if (DEBUG_PROVIDER) Slog.v(TAG, 8346 "Removing provider requested by " 8347 + conn.client.processName + " from process " 8348 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 8349 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 8350 if (stable) { 8351 conn.stableCount--; 8352 } else { 8353 conn.unstableCount--; 8354 } 8355 if (conn.stableCount == 0 && conn.unstableCount == 0) { 8356 cpr.connections.remove(conn); 8357 conn.client.conProviders.remove(conn); 8358 return true; 8359 } 8360 return false; 8361 } 8362 cpr.removeExternalProcessHandleLocked(externalProcessToken); 8363 return false; 8364 } 8365 8366 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 8367 String name, IBinder token, boolean stable, int userId) { 8368 ContentProviderRecord cpr; 8369 ContentProviderConnection conn = null; 8370 ProviderInfo cpi = null; 8371 8372 synchronized(this) { 8373 ProcessRecord r = null; 8374 if (caller != null) { 8375 r = getRecordForAppLocked(caller); 8376 if (r == null) { 8377 throw new SecurityException( 8378 "Unable to find app for caller " + caller 8379 + " (pid=" + Binder.getCallingPid() 8380 + ") when getting content provider " + name); 8381 } 8382 } 8383 8384 boolean checkCrossUser = true; 8385 8386 // First check if this content provider has been published... 8387 cpr = mProviderMap.getProviderByName(name, userId); 8388 // If that didn't work, check if it exists for user 0 and then 8389 // verify that it's a singleton provider before using it. 8390 if (cpr == null && userId != UserHandle.USER_OWNER) { 8391 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER); 8392 if (cpr != null) { 8393 cpi = cpr.info; 8394 if (isSingleton(cpi.processName, cpi.applicationInfo, 8395 cpi.name, cpi.flags) 8396 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 8397 userId = UserHandle.USER_OWNER; 8398 checkCrossUser = false; 8399 } else { 8400 cpr = null; 8401 cpi = null; 8402 } 8403 } 8404 } 8405 8406 boolean providerRunning = cpr != null; 8407 if (providerRunning) { 8408 cpi = cpr.info; 8409 String msg; 8410 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 8411 != null) { 8412 throw new SecurityException(msg); 8413 } 8414 8415 if (r != null && cpr.canRunHere(r)) { 8416 // This provider has been published or is in the process 8417 // of being published... but it is also allowed to run 8418 // in the caller's process, so don't make a connection 8419 // and just let the caller instantiate its own instance. 8420 ContentProviderHolder holder = cpr.newHolder(null); 8421 // don't give caller the provider object, it needs 8422 // to make its own. 8423 holder.provider = null; 8424 return holder; 8425 } 8426 8427 final long origId = Binder.clearCallingIdentity(); 8428 8429 // In this case the provider instance already exists, so we can 8430 // return it right away. 8431 conn = incProviderCountLocked(r, cpr, token, stable); 8432 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 8433 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 8434 // If this is a perceptible app accessing the provider, 8435 // make sure to count it as being accessed and thus 8436 // back up on the LRU list. This is good because 8437 // content providers are often expensive to start. 8438 updateLruProcessLocked(cpr.proc, false, null); 8439 } 8440 } 8441 8442 if (cpr.proc != null) { 8443 if (false) { 8444 if (cpr.name.flattenToShortString().equals( 8445 "com.android.providers.calendar/.CalendarProvider2")) { 8446 Slog.v(TAG, "****************** KILLING " 8447 + cpr.name.flattenToShortString()); 8448 Process.killProcess(cpr.proc.pid); 8449 } 8450 } 8451 boolean success = updateOomAdjLocked(cpr.proc); 8452 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success); 8453 // NOTE: there is still a race here where a signal could be 8454 // pending on the process even though we managed to update its 8455 // adj level. Not sure what to do about this, but at least 8456 // the race is now smaller. 8457 if (!success) { 8458 // Uh oh... it looks like the provider's process 8459 // has been killed on us. We need to wait for a new 8460 // process to be started, and make sure its death 8461 // doesn't kill our process. 8462 Slog.i(TAG, 8463 "Existing provider " + cpr.name.flattenToShortString() 8464 + " is crashing; detaching " + r); 8465 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 8466 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread); 8467 if (!lastRef) { 8468 // This wasn't the last ref our process had on 8469 // the provider... we have now been killed, bail. 8470 return null; 8471 } 8472 providerRunning = false; 8473 conn = null; 8474 } 8475 } 8476 8477 Binder.restoreCallingIdentity(origId); 8478 } 8479 8480 boolean singleton; 8481 if (!providerRunning) { 8482 try { 8483 cpi = AppGlobals.getPackageManager(). 8484 resolveContentProvider(name, 8485 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 8486 } catch (RemoteException ex) { 8487 } 8488 if (cpi == null) { 8489 return null; 8490 } 8491 // If the provider is a singleton AND 8492 // (it's a call within the same user || the provider is a 8493 // privileged app) 8494 // Then allow connecting to the singleton provider 8495 singleton = isSingleton(cpi.processName, cpi.applicationInfo, 8496 cpi.name, cpi.flags) 8497 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 8498 if (singleton) { 8499 userId = UserHandle.USER_OWNER; 8500 } 8501 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 8502 8503 String msg; 8504 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 8505 != null) { 8506 throw new SecurityException(msg); 8507 } 8508 8509 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate 8510 && !cpi.processName.equals("system")) { 8511 // If this content provider does not run in the system 8512 // process, and the system is not yet ready to run other 8513 // processes, then fail fast instead of hanging. 8514 throw new IllegalArgumentException( 8515 "Attempt to launch content provider before system ready"); 8516 } 8517 8518 // Make sure that the user who owns this provider is started. If not, 8519 // we don't want to allow it to run. 8520 if (mStartedUsers.get(userId) == null) { 8521 Slog.w(TAG, "Unable to launch app " 8522 + cpi.applicationInfo.packageName + "/" 8523 + cpi.applicationInfo.uid + " for provider " 8524 + name + ": user " + userId + " is stopped"); 8525 return null; 8526 } 8527 8528 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 8529 cpr = mProviderMap.getProviderByClass(comp, userId); 8530 final boolean firstClass = cpr == null; 8531 if (firstClass) { 8532 try { 8533 ApplicationInfo ai = 8534 AppGlobals.getPackageManager(). 8535 getApplicationInfo( 8536 cpi.applicationInfo.packageName, 8537 STOCK_PM_FLAGS, userId); 8538 if (ai == null) { 8539 Slog.w(TAG, "No package info for content provider " 8540 + cpi.name); 8541 return null; 8542 } 8543 ai = getAppInfoForUser(ai, userId); 8544 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 8545 } catch (RemoteException ex) { 8546 // pm is in same process, this will never happen. 8547 } 8548 } 8549 8550 if (r != null && cpr.canRunHere(r)) { 8551 // If this is a multiprocess provider, then just return its 8552 // info and allow the caller to instantiate it. Only do 8553 // this if the provider is the same user as the caller's 8554 // process, or can run as root (so can be in any process). 8555 return cpr.newHolder(null); 8556 } 8557 8558 if (DEBUG_PROVIDER) { 8559 RuntimeException e = new RuntimeException("here"); 8560 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null) 8561 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e); 8562 } 8563 8564 // This is single process, and our app is now connecting to it. 8565 // See if we are already in the process of launching this 8566 // provider. 8567 final int N = mLaunchingProviders.size(); 8568 int i; 8569 for (i=0; i<N; i++) { 8570 if (mLaunchingProviders.get(i) == cpr) { 8571 break; 8572 } 8573 } 8574 8575 // If the provider is not already being launched, then get it 8576 // started. 8577 if (i >= N) { 8578 final long origId = Binder.clearCallingIdentity(); 8579 8580 try { 8581 // Content provider is now in use, its package can't be stopped. 8582 try { 8583 AppGlobals.getPackageManager().setPackageStoppedState( 8584 cpr.appInfo.packageName, false, userId); 8585 } catch (RemoteException e) { 8586 } catch (IllegalArgumentException e) { 8587 Slog.w(TAG, "Failed trying to unstop package " 8588 + cpr.appInfo.packageName + ": " + e); 8589 } 8590 8591 // Use existing process if already started 8592 ProcessRecord proc = getProcessRecordLocked( 8593 cpi.processName, cpr.appInfo.uid, false); 8594 if (proc != null && proc.thread != null) { 8595 if (DEBUG_PROVIDER) { 8596 Slog.d(TAG, "Installing in existing process " + proc); 8597 } 8598 proc.pubProviders.put(cpi.name, cpr); 8599 try { 8600 proc.thread.scheduleInstallProvider(cpi); 8601 } catch (RemoteException e) { 8602 } 8603 } else { 8604 proc = startProcessLocked(cpi.processName, 8605 cpr.appInfo, false, 0, "content provider", 8606 new ComponentName(cpi.applicationInfo.packageName, 8607 cpi.name), false, false, false); 8608 if (proc == null) { 8609 Slog.w(TAG, "Unable to launch app " 8610 + cpi.applicationInfo.packageName + "/" 8611 + cpi.applicationInfo.uid + " for provider " 8612 + name + ": process is bad"); 8613 return null; 8614 } 8615 } 8616 cpr.launchingApp = proc; 8617 mLaunchingProviders.add(cpr); 8618 } finally { 8619 Binder.restoreCallingIdentity(origId); 8620 } 8621 } 8622 8623 // Make sure the provider is published (the same provider class 8624 // may be published under multiple names). 8625 if (firstClass) { 8626 mProviderMap.putProviderByClass(comp, cpr); 8627 } 8628 8629 mProviderMap.putProviderByName(name, cpr); 8630 conn = incProviderCountLocked(r, cpr, token, stable); 8631 if (conn != null) { 8632 conn.waiting = true; 8633 } 8634 } 8635 } 8636 8637 // Wait for the provider to be published... 8638 synchronized (cpr) { 8639 while (cpr.provider == null) { 8640 if (cpr.launchingApp == null) { 8641 Slog.w(TAG, "Unable to launch app " 8642 + cpi.applicationInfo.packageName + "/" 8643 + cpi.applicationInfo.uid + " for provider " 8644 + name + ": launching app became null"); 8645 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 8646 UserHandle.getUserId(cpi.applicationInfo.uid), 8647 cpi.applicationInfo.packageName, 8648 cpi.applicationInfo.uid, name); 8649 return null; 8650 } 8651 try { 8652 if (DEBUG_MU) { 8653 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp=" 8654 + cpr.launchingApp); 8655 } 8656 if (conn != null) { 8657 conn.waiting = true; 8658 } 8659 cpr.wait(); 8660 } catch (InterruptedException ex) { 8661 } finally { 8662 if (conn != null) { 8663 conn.waiting = false; 8664 } 8665 } 8666 } 8667 } 8668 return cpr != null ? cpr.newHolder(conn) : null; 8669 } 8670 8671 @Override 8672 public final ContentProviderHolder getContentProvider( 8673 IApplicationThread caller, String name, int userId, boolean stable) { 8674 enforceNotIsolatedCaller("getContentProvider"); 8675 if (caller == null) { 8676 String msg = "null IApplicationThread when getting content provider " 8677 + name; 8678 Slog.w(TAG, msg); 8679 throw new SecurityException(msg); 8680 } 8681 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 8682 // with cross-user grant. 8683 return getContentProviderImpl(caller, name, null, stable, userId); 8684 } 8685 8686 public ContentProviderHolder getContentProviderExternal( 8687 String name, int userId, IBinder token) { 8688 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 8689 "Do not have permission in call getContentProviderExternal()"); 8690 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 8691 false, ALLOW_FULL_ONLY, "getContentProvider", null); 8692 return getContentProviderExternalUnchecked(name, token, userId); 8693 } 8694 8695 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 8696 IBinder token, int userId) { 8697 return getContentProviderImpl(null, name, token, true, userId); 8698 } 8699 8700 /** 8701 * Drop a content provider from a ProcessRecord's bookkeeping 8702 */ 8703 public void removeContentProvider(IBinder connection, boolean stable) { 8704 enforceNotIsolatedCaller("removeContentProvider"); 8705 long ident = Binder.clearCallingIdentity(); 8706 try { 8707 synchronized (this) { 8708 ContentProviderConnection conn; 8709 try { 8710 conn = (ContentProviderConnection)connection; 8711 } catch (ClassCastException e) { 8712 String msg ="removeContentProvider: " + connection 8713 + " not a ContentProviderConnection"; 8714 Slog.w(TAG, msg); 8715 throw new IllegalArgumentException(msg); 8716 } 8717 if (conn == null) { 8718 throw new NullPointerException("connection is null"); 8719 } 8720 if (decProviderCountLocked(conn, null, null, stable)) { 8721 updateOomAdjLocked(); 8722 } 8723 } 8724 } finally { 8725 Binder.restoreCallingIdentity(ident); 8726 } 8727 } 8728 8729 public void removeContentProviderExternal(String name, IBinder token) { 8730 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 8731 "Do not have permission in call removeContentProviderExternal()"); 8732 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId()); 8733 } 8734 8735 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 8736 synchronized (this) { 8737 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 8738 if(cpr == null) { 8739 //remove from mProvidersByClass 8740 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list"); 8741 return; 8742 } 8743 8744 //update content provider record entry info 8745 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 8746 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 8747 if (localCpr.hasExternalProcessHandles()) { 8748 if (localCpr.removeExternalProcessHandleLocked(token)) { 8749 updateOomAdjLocked(); 8750 } else { 8751 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 8752 + " with no external reference for token: " 8753 + token + "."); 8754 } 8755 } else { 8756 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 8757 + " with no external references."); 8758 } 8759 } 8760 } 8761 8762 public final void publishContentProviders(IApplicationThread caller, 8763 List<ContentProviderHolder> providers) { 8764 if (providers == null) { 8765 return; 8766 } 8767 8768 enforceNotIsolatedCaller("publishContentProviders"); 8769 synchronized (this) { 8770 final ProcessRecord r = getRecordForAppLocked(caller); 8771 if (DEBUG_MU) 8772 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 8773 if (r == null) { 8774 throw new SecurityException( 8775 "Unable to find app for caller " + caller 8776 + " (pid=" + Binder.getCallingPid() 8777 + ") when publishing content providers"); 8778 } 8779 8780 final long origId = Binder.clearCallingIdentity(); 8781 8782 final int N = providers.size(); 8783 for (int i=0; i<N; i++) { 8784 ContentProviderHolder src = providers.get(i); 8785 if (src == null || src.info == null || src.provider == null) { 8786 continue; 8787 } 8788 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 8789 if (DEBUG_MU) 8790 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 8791 if (dst != null) { 8792 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 8793 mProviderMap.putProviderByClass(comp, dst); 8794 String names[] = dst.info.authority.split(";"); 8795 for (int j = 0; j < names.length; j++) { 8796 mProviderMap.putProviderByName(names[j], dst); 8797 } 8798 8799 int NL = mLaunchingProviders.size(); 8800 int j; 8801 for (j=0; j<NL; j++) { 8802 if (mLaunchingProviders.get(j) == dst) { 8803 mLaunchingProviders.remove(j); 8804 j--; 8805 NL--; 8806 } 8807 } 8808 synchronized (dst) { 8809 dst.provider = src.provider; 8810 dst.proc = r; 8811 dst.notifyAll(); 8812 } 8813 updateOomAdjLocked(r); 8814 } 8815 } 8816 8817 Binder.restoreCallingIdentity(origId); 8818 } 8819 } 8820 8821 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 8822 ContentProviderConnection conn; 8823 try { 8824 conn = (ContentProviderConnection)connection; 8825 } catch (ClassCastException e) { 8826 String msg ="refContentProvider: " + connection 8827 + " not a ContentProviderConnection"; 8828 Slog.w(TAG, msg); 8829 throw new IllegalArgumentException(msg); 8830 } 8831 if (conn == null) { 8832 throw new NullPointerException("connection is null"); 8833 } 8834 8835 synchronized (this) { 8836 if (stable > 0) { 8837 conn.numStableIncs += stable; 8838 } 8839 stable = conn.stableCount + stable; 8840 if (stable < 0) { 8841 throw new IllegalStateException("stableCount < 0: " + stable); 8842 } 8843 8844 if (unstable > 0) { 8845 conn.numUnstableIncs += unstable; 8846 } 8847 unstable = conn.unstableCount + unstable; 8848 if (unstable < 0) { 8849 throw new IllegalStateException("unstableCount < 0: " + unstable); 8850 } 8851 8852 if ((stable+unstable) <= 0) { 8853 throw new IllegalStateException("ref counts can't go to zero here: stable=" 8854 + stable + " unstable=" + unstable); 8855 } 8856 conn.stableCount = stable; 8857 conn.unstableCount = unstable; 8858 return !conn.dead; 8859 } 8860 } 8861 8862 public void unstableProviderDied(IBinder connection) { 8863 ContentProviderConnection conn; 8864 try { 8865 conn = (ContentProviderConnection)connection; 8866 } catch (ClassCastException e) { 8867 String msg ="refContentProvider: " + connection 8868 + " not a ContentProviderConnection"; 8869 Slog.w(TAG, msg); 8870 throw new IllegalArgumentException(msg); 8871 } 8872 if (conn == null) { 8873 throw new NullPointerException("connection is null"); 8874 } 8875 8876 // Safely retrieve the content provider associated with the connection. 8877 IContentProvider provider; 8878 synchronized (this) { 8879 provider = conn.provider.provider; 8880 } 8881 8882 if (provider == null) { 8883 // Um, yeah, we're way ahead of you. 8884 return; 8885 } 8886 8887 // Make sure the caller is being honest with us. 8888 if (provider.asBinder().pingBinder()) { 8889 // Er, no, still looks good to us. 8890 synchronized (this) { 8891 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 8892 + " says " + conn + " died, but we don't agree"); 8893 return; 8894 } 8895 } 8896 8897 // Well look at that! It's dead! 8898 synchronized (this) { 8899 if (conn.provider.provider != provider) { 8900 // But something changed... good enough. 8901 return; 8902 } 8903 8904 ProcessRecord proc = conn.provider.proc; 8905 if (proc == null || proc.thread == null) { 8906 // Seems like the process is already cleaned up. 8907 return; 8908 } 8909 8910 // As far as we're concerned, this is just like receiving a 8911 // death notification... just a bit prematurely. 8912 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid 8913 + ") early provider death"); 8914 final long ident = Binder.clearCallingIdentity(); 8915 try { 8916 appDiedLocked(proc, proc.pid, proc.thread); 8917 } finally { 8918 Binder.restoreCallingIdentity(ident); 8919 } 8920 } 8921 } 8922 8923 @Override 8924 public void appNotRespondingViaProvider(IBinder connection) { 8925 enforceCallingPermission( 8926 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()"); 8927 8928 final ContentProviderConnection conn = (ContentProviderConnection) connection; 8929 if (conn == null) { 8930 Slog.w(TAG, "ContentProviderConnection is null"); 8931 return; 8932 } 8933 8934 final ProcessRecord host = conn.provider.proc; 8935 if (host == null) { 8936 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 8937 return; 8938 } 8939 8940 final long token = Binder.clearCallingIdentity(); 8941 try { 8942 appNotResponding(host, null, null, false, "ContentProvider not responding"); 8943 } finally { 8944 Binder.restoreCallingIdentity(token); 8945 } 8946 } 8947 8948 public final void installSystemProviders() { 8949 List<ProviderInfo> providers; 8950 synchronized (this) { 8951 ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID); 8952 providers = generateApplicationProvidersLocked(app); 8953 if (providers != null) { 8954 for (int i=providers.size()-1; i>=0; i--) { 8955 ProviderInfo pi = (ProviderInfo)providers.get(i); 8956 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8957 Slog.w(TAG, "Not installing system proc provider " + pi.name 8958 + ": not system .apk"); 8959 providers.remove(i); 8960 } 8961 } 8962 } 8963 } 8964 if (providers != null) { 8965 mSystemThread.installSystemProviders(providers); 8966 } 8967 8968 mCoreSettingsObserver = new CoreSettingsObserver(this); 8969 8970 //mUsageStatsService.monitorPackages(); 8971 } 8972 8973 /** 8974 * Allows app to retrieve the MIME type of a URI without having permission 8975 * to access its content provider. 8976 * 8977 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 8978 * 8979 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 8980 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 8981 */ 8982 public String getProviderMimeType(Uri uri, int userId) { 8983 enforceNotIsolatedCaller("getProviderMimeType"); 8984 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 8985 userId, false, ALLOW_NON_FULL_IN_PROFILE, "getProviderMimeType", null); 8986 final String name = uri.getAuthority(); 8987 final long ident = Binder.clearCallingIdentity(); 8988 ContentProviderHolder holder = null; 8989 8990 try { 8991 holder = getContentProviderExternalUnchecked(name, null, userId); 8992 if (holder != null) { 8993 return holder.provider.getType(uri); 8994 } 8995 } catch (RemoteException e) { 8996 Log.w(TAG, "Content provider dead retrieving " + uri, e); 8997 return null; 8998 } finally { 8999 if (holder != null) { 9000 removeContentProviderExternalUnchecked(name, null, userId); 9001 } 9002 Binder.restoreCallingIdentity(ident); 9003 } 9004 9005 return null; 9006 } 9007 9008 // ========================================================= 9009 // GLOBAL MANAGEMENT 9010 // ========================================================= 9011 9012 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 9013 boolean isolated, int isolatedUid) { 9014 String proc = customProcess != null ? customProcess : info.processName; 9015 BatteryStatsImpl.Uid.Proc ps = null; 9016 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 9017 int uid = info.uid; 9018 if (isolated) { 9019 if (isolatedUid == 0) { 9020 int userId = UserHandle.getUserId(uid); 9021 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1; 9022 while (true) { 9023 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID 9024 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) { 9025 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID; 9026 } 9027 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid); 9028 mNextIsolatedProcessUid++; 9029 if (mIsolatedProcesses.indexOfKey(uid) < 0) { 9030 // No process for this uid, use it. 9031 break; 9032 } 9033 stepsLeft--; 9034 if (stepsLeft <= 0) { 9035 return null; 9036 } 9037 } 9038 } else { 9039 // Special case for startIsolatedProcess (internal only), where 9040 // the uid of the isolated process is specified by the caller. 9041 uid = isolatedUid; 9042 } 9043 } 9044 return new ProcessRecord(stats, info, proc, uid); 9045 } 9046 9047 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated, 9048 String abiOverride) { 9049 ProcessRecord app; 9050 if (!isolated) { 9051 app = getProcessRecordLocked(info.processName, info.uid, true); 9052 } else { 9053 app = null; 9054 } 9055 9056 if (app == null) { 9057 app = newProcessRecordLocked(info, null, isolated, 0); 9058 mProcessNames.put(info.processName, app.uid, app); 9059 if (isolated) { 9060 mIsolatedProcesses.put(app.uid, app); 9061 } 9062 updateLruProcessLocked(app, false, null); 9063 updateOomAdjLocked(); 9064 } 9065 9066 // This package really, really can not be stopped. 9067 try { 9068 AppGlobals.getPackageManager().setPackageStoppedState( 9069 info.packageName, false, UserHandle.getUserId(app.uid)); 9070 } catch (RemoteException e) { 9071 } catch (IllegalArgumentException e) { 9072 Slog.w(TAG, "Failed trying to unstop package " 9073 + info.packageName + ": " + e); 9074 } 9075 9076 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) 9077 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) { 9078 app.persistent = true; 9079 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 9080 } 9081 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 9082 mPersistentStartingProcesses.add(app); 9083 startProcessLocked(app, "added application", app.processName, abiOverride, 9084 null /* entryPoint */, null /* entryPointArgs */); 9085 } 9086 9087 return app; 9088 } 9089 9090 public void unhandledBack() { 9091 enforceCallingPermission(android.Manifest.permission.FORCE_BACK, 9092 "unhandledBack()"); 9093 9094 synchronized(this) { 9095 final long origId = Binder.clearCallingIdentity(); 9096 try { 9097 getFocusedStack().unhandledBackLocked(); 9098 } finally { 9099 Binder.restoreCallingIdentity(origId); 9100 } 9101 } 9102 } 9103 9104 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException { 9105 enforceNotIsolatedCaller("openContentUri"); 9106 final int userId = UserHandle.getCallingUserId(); 9107 String name = uri.getAuthority(); 9108 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId); 9109 ParcelFileDescriptor pfd = null; 9110 if (cph != null) { 9111 // We record the binder invoker's uid in thread-local storage before 9112 // going to the content provider to open the file. Later, in the code 9113 // that handles all permissions checks, we look for this uid and use 9114 // that rather than the Activity Manager's own uid. The effect is that 9115 // we do the check against the caller's permissions even though it looks 9116 // to the content provider like the Activity Manager itself is making 9117 // the request. 9118 sCallerIdentity.set(new Identity( 9119 Binder.getCallingPid(), Binder.getCallingUid())); 9120 try { 9121 pfd = cph.provider.openFile(null, uri, "r", null); 9122 } catch (FileNotFoundException e) { 9123 // do nothing; pfd will be returned null 9124 } finally { 9125 // Ensure that whatever happens, we clean up the identity state 9126 sCallerIdentity.remove(); 9127 } 9128 9129 // We've got the fd now, so we're done with the provider. 9130 removeContentProviderExternalUnchecked(name, null, userId); 9131 } else { 9132 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 9133 } 9134 return pfd; 9135 } 9136 9137 // Actually is sleeping or shutting down or whatever else in the future 9138 // is an inactive state. 9139 public boolean isSleepingOrShuttingDown() { 9140 return mSleeping || mShuttingDown; 9141 } 9142 9143 public boolean isSleeping() { 9144 return mSleeping; 9145 } 9146 9147 void goingToSleep() { 9148 synchronized(this) { 9149 mWentToSleep = true; 9150 updateEventDispatchingLocked(); 9151 goToSleepIfNeededLocked(); 9152 } 9153 } 9154 9155 void finishRunningVoiceLocked() { 9156 if (mRunningVoice) { 9157 mRunningVoice = false; 9158 goToSleepIfNeededLocked(); 9159 } 9160 } 9161 9162 void goToSleepIfNeededLocked() { 9163 if (mWentToSleep && !mRunningVoice) { 9164 if (!mSleeping) { 9165 mSleeping = true; 9166 mStackSupervisor.goingToSleepLocked(); 9167 9168 // Initialize the wake times of all processes. 9169 checkExcessivePowerUsageLocked(false); 9170 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9171 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 9172 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 9173 } 9174 } 9175 } 9176 9177 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { 9178 if (task != null && task.stack != null && task.stack.isHomeStack()) { 9179 // Never persist the home stack. 9180 return; 9181 } 9182 mTaskPersister.wakeup(task, flush); 9183 } 9184 9185 @Override 9186 public boolean shutdown(int timeout) { 9187 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 9188 != PackageManager.PERMISSION_GRANTED) { 9189 throw new SecurityException("Requires permission " 9190 + android.Manifest.permission.SHUTDOWN); 9191 } 9192 9193 boolean timedout = false; 9194 9195 synchronized(this) { 9196 mShuttingDown = true; 9197 updateEventDispatchingLocked(); 9198 timedout = mStackSupervisor.shutdownLocked(timeout); 9199 } 9200 9201 mAppOpsService.shutdown(); 9202 if (mUsageStatsService != null) { 9203 mUsageStatsService.prepareShutdown(); 9204 } 9205 mBatteryStatsService.shutdown(); 9206 synchronized (this) { 9207 mProcessStats.shutdownLocked(); 9208 } 9209 notifyTaskPersisterLocked(null, true); 9210 9211 return timedout; 9212 } 9213 9214 public final void activitySlept(IBinder token) { 9215 if (localLOGV) Slog.v(TAG, "Activity slept: token=" + token); 9216 9217 final long origId = Binder.clearCallingIdentity(); 9218 9219 synchronized (this) { 9220 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9221 if (r != null) { 9222 mStackSupervisor.activitySleptLocked(r); 9223 } 9224 } 9225 9226 Binder.restoreCallingIdentity(origId); 9227 } 9228 9229 void logLockScreen(String msg) { 9230 if (DEBUG_LOCKSCREEN) Slog.d(TAG, Debug.getCallers(2) + ":" + msg + 9231 " mLockScreenShown=" + mLockScreenShown + " mWentToSleep=" + 9232 mWentToSleep + " mSleeping=" + mSleeping + " mDismissKeyguardOnNextActivity=" + 9233 mStackSupervisor.mDismissKeyguardOnNextActivity); 9234 } 9235 9236 private void comeOutOfSleepIfNeededLocked() { 9237 if ((!mWentToSleep && !mLockScreenShown) || mRunningVoice) { 9238 if (mSleeping) { 9239 mSleeping = false; 9240 mStackSupervisor.comeOutOfSleepIfNeededLocked(); 9241 } 9242 } 9243 } 9244 9245 void wakingUp() { 9246 synchronized(this) { 9247 mWentToSleep = false; 9248 updateEventDispatchingLocked(); 9249 comeOutOfSleepIfNeededLocked(); 9250 } 9251 } 9252 9253 void startRunningVoiceLocked() { 9254 if (!mRunningVoice) { 9255 mRunningVoice = true; 9256 comeOutOfSleepIfNeededLocked(); 9257 } 9258 } 9259 9260 private void updateEventDispatchingLocked() { 9261 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown); 9262 } 9263 9264 public void setLockScreenShown(boolean shown) { 9265 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER) 9266 != PackageManager.PERMISSION_GRANTED) { 9267 throw new SecurityException("Requires permission " 9268 + android.Manifest.permission.DEVICE_POWER); 9269 } 9270 9271 synchronized(this) { 9272 long ident = Binder.clearCallingIdentity(); 9273 try { 9274 if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown); 9275 mLockScreenShown = shown; 9276 comeOutOfSleepIfNeededLocked(); 9277 } finally { 9278 Binder.restoreCallingIdentity(ident); 9279 } 9280 } 9281 } 9282 9283 @Override 9284 public void stopAppSwitches() { 9285 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 9286 != PackageManager.PERMISSION_GRANTED) { 9287 throw new SecurityException("Requires permission " 9288 + android.Manifest.permission.STOP_APP_SWITCHES); 9289 } 9290 9291 synchronized(this) { 9292 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() 9293 + APP_SWITCH_DELAY_TIME; 9294 mDidAppSwitch = false; 9295 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 9296 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 9297 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME); 9298 } 9299 } 9300 9301 public void resumeAppSwitches() { 9302 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 9303 != PackageManager.PERMISSION_GRANTED) { 9304 throw new SecurityException("Requires permission " 9305 + android.Manifest.permission.STOP_APP_SWITCHES); 9306 } 9307 9308 synchronized(this) { 9309 // Note that we don't execute any pending app switches... we will 9310 // let those wait until either the timeout, or the next start 9311 // activity request. 9312 mAppSwitchesAllowedTime = 0; 9313 } 9314 } 9315 9316 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid, 9317 String name) { 9318 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { 9319 return true; 9320 } 9321 9322 final int perm = checkComponentPermission( 9323 android.Manifest.permission.STOP_APP_SWITCHES, callingPid, 9324 callingUid, -1, true); 9325 if (perm == PackageManager.PERMISSION_GRANTED) { 9326 return true; 9327 } 9328 9329 Slog.w(TAG, name + " request from " + callingUid + " stopped"); 9330 return false; 9331 } 9332 9333 public void setDebugApp(String packageName, boolean waitForDebugger, 9334 boolean persistent) { 9335 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 9336 "setDebugApp()"); 9337 9338 long ident = Binder.clearCallingIdentity(); 9339 try { 9340 // Note that this is not really thread safe if there are multiple 9341 // callers into it at the same time, but that's not a situation we 9342 // care about. 9343 if (persistent) { 9344 final ContentResolver resolver = mContext.getContentResolver(); 9345 Settings.Global.putString( 9346 resolver, Settings.Global.DEBUG_APP, 9347 packageName); 9348 Settings.Global.putInt( 9349 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 9350 waitForDebugger ? 1 : 0); 9351 } 9352 9353 synchronized (this) { 9354 if (!persistent) { 9355 mOrigDebugApp = mDebugApp; 9356 mOrigWaitForDebugger = mWaitForDebugger; 9357 } 9358 mDebugApp = packageName; 9359 mWaitForDebugger = waitForDebugger; 9360 mDebugTransient = !persistent; 9361 if (packageName != null) { 9362 forceStopPackageLocked(packageName, -1, false, false, true, true, 9363 false, UserHandle.USER_ALL, "set debug app"); 9364 } 9365 } 9366 } finally { 9367 Binder.restoreCallingIdentity(ident); 9368 } 9369 } 9370 9371 void setOpenGlTraceApp(ApplicationInfo app, String processName) { 9372 synchronized (this) { 9373 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 9374 if (!isDebuggable) { 9375 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 9376 throw new SecurityException("Process not debuggable: " + app.packageName); 9377 } 9378 } 9379 9380 mOpenGlTraceApp = processName; 9381 } 9382 } 9383 9384 void setProfileApp(ApplicationInfo app, String processName, String profileFile, 9385 ParcelFileDescriptor profileFd, boolean autoStopProfiler) { 9386 synchronized (this) { 9387 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 9388 if (!isDebuggable) { 9389 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 9390 throw new SecurityException("Process not debuggable: " + app.packageName); 9391 } 9392 } 9393 mProfileApp = processName; 9394 mProfileFile = profileFile; 9395 if (mProfileFd != null) { 9396 try { 9397 mProfileFd.close(); 9398 } catch (IOException e) { 9399 } 9400 mProfileFd = null; 9401 } 9402 mProfileFd = profileFd; 9403 mProfileType = 0; 9404 mAutoStopProfiler = autoStopProfiler; 9405 } 9406 } 9407 9408 @Override 9409 public void setAlwaysFinish(boolean enabled) { 9410 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 9411 "setAlwaysFinish()"); 9412 9413 Settings.Global.putInt( 9414 mContext.getContentResolver(), 9415 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 9416 9417 synchronized (this) { 9418 mAlwaysFinishActivities = enabled; 9419 } 9420 } 9421 9422 @Override 9423 public void setActivityController(IActivityController controller) { 9424 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 9425 "setActivityController()"); 9426 synchronized (this) { 9427 mController = controller; 9428 Watchdog.getInstance().setActivityController(controller); 9429 } 9430 } 9431 9432 @Override 9433 public void setUserIsMonkey(boolean userIsMonkey) { 9434 synchronized (this) { 9435 synchronized (mPidsSelfLocked) { 9436 final int callingPid = Binder.getCallingPid(); 9437 ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid); 9438 if (precessRecord == null) { 9439 throw new SecurityException("Unknown process: " + callingPid); 9440 } 9441 if (precessRecord.instrumentationUiAutomationConnection == null) { 9442 throw new SecurityException("Only an instrumentation process " 9443 + "with a UiAutomation can call setUserIsMonkey"); 9444 } 9445 } 9446 mUserIsMonkey = userIsMonkey; 9447 } 9448 } 9449 9450 @Override 9451 public boolean isUserAMonkey() { 9452 synchronized (this) { 9453 // If there is a controller also implies the user is a monkey. 9454 return (mUserIsMonkey || mController != null); 9455 } 9456 } 9457 9458 public void requestBugReport() { 9459 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 9460 SystemProperties.set("ctl.start", "bugreport"); 9461 } 9462 9463 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) { 9464 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT; 9465 } 9466 9467 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) { 9468 if (r != null && (r.instrumentationClass != null || r.usingWrapper)) { 9469 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT; 9470 } 9471 return KEY_DISPATCHING_TIMEOUT; 9472 } 9473 9474 @Override 9475 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 9476 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 9477 != PackageManager.PERMISSION_GRANTED) { 9478 throw new SecurityException("Requires permission " 9479 + android.Manifest.permission.FILTER_EVENTS); 9480 } 9481 ProcessRecord proc; 9482 long timeout; 9483 synchronized (this) { 9484 synchronized (mPidsSelfLocked) { 9485 proc = mPidsSelfLocked.get(pid); 9486 } 9487 timeout = getInputDispatchingTimeoutLocked(proc); 9488 } 9489 9490 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) { 9491 return -1; 9492 } 9493 9494 return timeout; 9495 } 9496 9497 /** 9498 * Handle input dispatching timeouts. 9499 * Returns whether input dispatching should be aborted or not. 9500 */ 9501 public boolean inputDispatchingTimedOut(final ProcessRecord proc, 9502 final ActivityRecord activity, final ActivityRecord parent, 9503 final boolean aboveSystem, String reason) { 9504 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 9505 != PackageManager.PERMISSION_GRANTED) { 9506 throw new SecurityException("Requires permission " 9507 + android.Manifest.permission.FILTER_EVENTS); 9508 } 9509 9510 final String annotation; 9511 if (reason == null) { 9512 annotation = "Input dispatching timed out"; 9513 } else { 9514 annotation = "Input dispatching timed out (" + reason + ")"; 9515 } 9516 9517 if (proc != null) { 9518 synchronized (this) { 9519 if (proc.debugging) { 9520 return false; 9521 } 9522 9523 if (mDidDexOpt) { 9524 // Give more time since we were dexopting. 9525 mDidDexOpt = false; 9526 return false; 9527 } 9528 9529 if (proc.instrumentationClass != null) { 9530 Bundle info = new Bundle(); 9531 info.putString("shortMsg", "keyDispatchingTimedOut"); 9532 info.putString("longMsg", annotation); 9533 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 9534 return true; 9535 } 9536 } 9537 mHandler.post(new Runnable() { 9538 @Override 9539 public void run() { 9540 appNotResponding(proc, activity, parent, aboveSystem, annotation); 9541 } 9542 }); 9543 } 9544 9545 return true; 9546 } 9547 9548 public Bundle getAssistContextExtras(int requestType) { 9549 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO, 9550 "getAssistContextExtras()"); 9551 PendingAssistExtras pae; 9552 Bundle extras = new Bundle(); 9553 synchronized (this) { 9554 ActivityRecord activity = getFocusedStack().mResumedActivity; 9555 if (activity == null) { 9556 Slog.w(TAG, "getAssistContextExtras failed: no resumed activity"); 9557 return null; 9558 } 9559 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName); 9560 if (activity.app == null || activity.app.thread == null) { 9561 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity); 9562 return extras; 9563 } 9564 if (activity.app.pid == Binder.getCallingPid()) { 9565 Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity); 9566 return extras; 9567 } 9568 pae = new PendingAssistExtras(activity); 9569 try { 9570 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, 9571 requestType); 9572 mPendingAssistExtras.add(pae); 9573 mHandler.postDelayed(pae, PENDING_ASSIST_EXTRAS_TIMEOUT); 9574 } catch (RemoteException e) { 9575 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity); 9576 return extras; 9577 } 9578 } 9579 synchronized (pae) { 9580 while (!pae.haveResult) { 9581 try { 9582 pae.wait(); 9583 } catch (InterruptedException e) { 9584 } 9585 } 9586 if (pae.result != null) { 9587 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result); 9588 } 9589 } 9590 synchronized (this) { 9591 mPendingAssistExtras.remove(pae); 9592 mHandler.removeCallbacks(pae); 9593 } 9594 return extras; 9595 } 9596 9597 public void reportAssistContextExtras(IBinder token, Bundle extras) { 9598 PendingAssistExtras pae = (PendingAssistExtras)token; 9599 synchronized (pae) { 9600 pae.result = extras; 9601 pae.haveResult = true; 9602 pae.notifyAll(); 9603 } 9604 } 9605 9606 public void registerProcessObserver(IProcessObserver observer) { 9607 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 9608 "registerProcessObserver()"); 9609 synchronized (this) { 9610 mProcessObservers.register(observer); 9611 } 9612 } 9613 9614 @Override 9615 public void unregisterProcessObserver(IProcessObserver observer) { 9616 synchronized (this) { 9617 mProcessObservers.unregister(observer); 9618 } 9619 } 9620 9621 @Override 9622 public boolean convertFromTranslucent(IBinder token) { 9623 final long origId = Binder.clearCallingIdentity(); 9624 try { 9625 synchronized (this) { 9626 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9627 if (r == null) { 9628 return false; 9629 } 9630 if (r.changeWindowTranslucency(true)) { 9631 mWindowManager.setAppFullscreen(token, true); 9632 r.task.stack.releaseMediaResources(); 9633 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 9634 return true; 9635 } 9636 return false; 9637 } 9638 } finally { 9639 Binder.restoreCallingIdentity(origId); 9640 } 9641 } 9642 9643 @Override 9644 public boolean convertToTranslucent(IBinder token, ActivityOptions options) { 9645 final long origId = Binder.clearCallingIdentity(); 9646 try { 9647 synchronized (this) { 9648 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9649 if (r == null) { 9650 return false; 9651 } 9652 int index = r.task.mActivities.lastIndexOf(r); 9653 if (index > 0) { 9654 ActivityRecord under = r.task.mActivities.get(index - 1); 9655 under.returningOptions = options; 9656 } 9657 if (r.changeWindowTranslucency(false)) { 9658 r.task.stack.convertToTranslucent(r); 9659 mWindowManager.setAppFullscreen(token, false); 9660 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 9661 return true; 9662 } else { 9663 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 9664 return false; 9665 } 9666 } 9667 } finally { 9668 Binder.restoreCallingIdentity(origId); 9669 } 9670 } 9671 9672 @Override 9673 public boolean setMediaPlaying(IBinder token, boolean playing) { 9674 final long origId = Binder.clearCallingIdentity(); 9675 try { 9676 synchronized (this) { 9677 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9678 if (r != null) { 9679 return mStackSupervisor.setMediaPlayingLocked(r, playing); 9680 } 9681 } 9682 return false; 9683 } finally { 9684 Binder.restoreCallingIdentity(origId); 9685 } 9686 } 9687 9688 @Override 9689 public boolean isBackgroundMediaPlaying(IBinder token) { 9690 final long origId = Binder.clearCallingIdentity(); 9691 try { 9692 synchronized (this) { 9693 final ActivityStack stack = ActivityRecord.getStackLocked(token); 9694 final boolean playing = stack == null ? false : stack.isMediaPlaying(); 9695 if (ActivityStackSupervisor.DEBUG_MEDIA_VISIBILITY) Slog.d(TAG, 9696 "isBackgroundMediaPlaying: stack=" + stack + " playing=" + playing); 9697 return playing; 9698 } 9699 } finally { 9700 Binder.restoreCallingIdentity(origId); 9701 } 9702 } 9703 9704 @Override 9705 public ActivityOptions getActivityOptions(IBinder token) { 9706 final long origId = Binder.clearCallingIdentity(); 9707 try { 9708 synchronized (this) { 9709 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9710 if (r != null) { 9711 final ActivityOptions activityOptions = r.pendingOptions; 9712 r.pendingOptions = null; 9713 return activityOptions; 9714 } 9715 return null; 9716 } 9717 } finally { 9718 Binder.restoreCallingIdentity(origId); 9719 } 9720 } 9721 9722 @Override 9723 public void setImmersive(IBinder token, boolean immersive) { 9724 synchronized(this) { 9725 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 9726 if (r == null) { 9727 throw new IllegalArgumentException(); 9728 } 9729 r.immersive = immersive; 9730 9731 // update associated state if we're frontmost 9732 if (r == mFocusedActivity) { 9733 if (DEBUG_IMMERSIVE) { 9734 Slog.d(TAG, "Frontmost changed immersion: "+ r); 9735 } 9736 applyUpdateLockStateLocked(r); 9737 } 9738 } 9739 } 9740 9741 @Override 9742 public boolean isImmersive(IBinder token) { 9743 synchronized (this) { 9744 ActivityRecord r = ActivityRecord.isInStackLocked(token); 9745 if (r == null) { 9746 throw new IllegalArgumentException(); 9747 } 9748 return r.immersive; 9749 } 9750 } 9751 9752 public boolean isTopActivityImmersive() { 9753 enforceNotIsolatedCaller("startActivity"); 9754 synchronized (this) { 9755 ActivityRecord r = getFocusedStack().topRunningActivityLocked(null); 9756 return (r != null) ? r.immersive : false; 9757 } 9758 } 9759 9760 @Override 9761 public boolean isTopOfTask(IBinder token) { 9762 synchronized (this) { 9763 ActivityRecord r = ActivityRecord.isInStackLocked(token); 9764 if (r == null) { 9765 throw new IllegalArgumentException(); 9766 } 9767 return r.task.getTopActivity() == r; 9768 } 9769 } 9770 9771 public final void enterSafeMode() { 9772 synchronized(this) { 9773 // It only makes sense to do this before the system is ready 9774 // and started launching other packages. 9775 if (!mSystemReady) { 9776 try { 9777 AppGlobals.getPackageManager().enterSafeMode(); 9778 } catch (RemoteException e) { 9779 } 9780 } 9781 9782 mSafeMode = true; 9783 } 9784 } 9785 9786 public final void showSafeModeOverlay() { 9787 View v = LayoutInflater.from(mContext).inflate( 9788 com.android.internal.R.layout.safe_mode, null); 9789 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 9790 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 9791 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 9792 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 9793 lp.gravity = Gravity.BOTTOM | Gravity.START; 9794 lp.format = v.getBackground().getOpacity(); 9795 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 9796 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 9797 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 9798 ((WindowManager)mContext.getSystemService( 9799 Context.WINDOW_SERVICE)).addView(v, lp); 9800 } 9801 9802 public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg) { 9803 if (!(sender instanceof PendingIntentRecord)) { 9804 return; 9805 } 9806 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 9807 synchronized (stats) { 9808 if (mBatteryStatsService.isOnBattery()) { 9809 mBatteryStatsService.enforceCallingPermission(); 9810 PendingIntentRecord rec = (PendingIntentRecord)sender; 9811 int MY_UID = Binder.getCallingUid(); 9812 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 9813 BatteryStatsImpl.Uid.Pkg pkg = 9814 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid, 9815 sourcePkg != null ? sourcePkg : rec.key.packageName); 9816 pkg.incWakeupsLocked(); 9817 } 9818 } 9819 } 9820 9821 public boolean killPids(int[] pids, String pReason, boolean secure) { 9822 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 9823 throw new SecurityException("killPids only available to the system"); 9824 } 9825 String reason = (pReason == null) ? "Unknown" : pReason; 9826 // XXX Note: don't acquire main activity lock here, because the window 9827 // manager calls in with its locks held. 9828 9829 boolean killed = false; 9830 synchronized (mPidsSelfLocked) { 9831 int[] types = new int[pids.length]; 9832 int worstType = 0; 9833 for (int i=0; i<pids.length; i++) { 9834 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 9835 if (proc != null) { 9836 int type = proc.setAdj; 9837 types[i] = type; 9838 if (type > worstType) { 9839 worstType = type; 9840 } 9841 } 9842 } 9843 9844 // If the worst oom_adj is somewhere in the cached proc LRU range, 9845 // then constrain it so we will kill all cached procs. 9846 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 9847 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 9848 worstType = ProcessList.CACHED_APP_MIN_ADJ; 9849 } 9850 9851 // If this is not a secure call, don't let it kill processes that 9852 // are important. 9853 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 9854 worstType = ProcessList.SERVICE_ADJ; 9855 } 9856 9857 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 9858 for (int i=0; i<pids.length; i++) { 9859 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 9860 if (proc == null) { 9861 continue; 9862 } 9863 int adj = proc.setAdj; 9864 if (adj >= worstType && !proc.killedByAm) { 9865 killUnneededProcessLocked(proc, reason); 9866 killed = true; 9867 } 9868 } 9869 } 9870 return killed; 9871 } 9872 9873 @Override 9874 public void killUid(int uid, String reason) { 9875 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 9876 throw new SecurityException("killUid only available to the system"); 9877 } 9878 synchronized (this) { 9879 killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid), 9880 ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false, 9881 reason != null ? reason : "kill uid"); 9882 } 9883 } 9884 9885 @Override 9886 public boolean killProcessesBelowForeground(String reason) { 9887 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 9888 throw new SecurityException("killProcessesBelowForeground() only available to system"); 9889 } 9890 9891 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 9892 } 9893 9894 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 9895 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 9896 throw new SecurityException("killProcessesBelowAdj() only available to system"); 9897 } 9898 9899 boolean killed = false; 9900 synchronized (mPidsSelfLocked) { 9901 final int size = mPidsSelfLocked.size(); 9902 for (int i = 0; i < size; i++) { 9903 final int pid = mPidsSelfLocked.keyAt(i); 9904 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 9905 if (proc == null) continue; 9906 9907 final int adj = proc.setAdj; 9908 if (adj > belowAdj && !proc.killedByAm) { 9909 killUnneededProcessLocked(proc, reason); 9910 killed = true; 9911 } 9912 } 9913 } 9914 return killed; 9915 } 9916 9917 @Override 9918 public void hang(final IBinder who, boolean allowRestart) { 9919 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 9920 != PackageManager.PERMISSION_GRANTED) { 9921 throw new SecurityException("Requires permission " 9922 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 9923 } 9924 9925 final IBinder.DeathRecipient death = new DeathRecipient() { 9926 @Override 9927 public void binderDied() { 9928 synchronized (this) { 9929 notifyAll(); 9930 } 9931 } 9932 }; 9933 9934 try { 9935 who.linkToDeath(death, 0); 9936 } catch (RemoteException e) { 9937 Slog.w(TAG, "hang: given caller IBinder is already dead."); 9938 return; 9939 } 9940 9941 synchronized (this) { 9942 Watchdog.getInstance().setAllowRestart(allowRestart); 9943 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 9944 synchronized (death) { 9945 while (who.isBinderAlive()) { 9946 try { 9947 death.wait(); 9948 } catch (InterruptedException e) { 9949 } 9950 } 9951 } 9952 Watchdog.getInstance().setAllowRestart(true); 9953 } 9954 } 9955 9956 @Override 9957 public void restart() { 9958 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 9959 != PackageManager.PERMISSION_GRANTED) { 9960 throw new SecurityException("Requires permission " 9961 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 9962 } 9963 9964 Log.i(TAG, "Sending shutdown broadcast..."); 9965 9966 BroadcastReceiver br = new BroadcastReceiver() { 9967 @Override public void onReceive(Context context, Intent intent) { 9968 // Now the broadcast is done, finish up the low-level shutdown. 9969 Log.i(TAG, "Shutting down activity manager..."); 9970 shutdown(10000); 9971 Log.i(TAG, "Shutdown complete, restarting!"); 9972 Process.killProcess(Process.myPid()); 9973 System.exit(10); 9974 } 9975 }; 9976 9977 // First send the high-level shut down broadcast. 9978 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 9979 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9980 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 9981 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 9982 mContext.sendOrderedBroadcastAsUser(intent, 9983 UserHandle.ALL, null, br, mHandler, 0, null, null); 9984 */ 9985 br.onReceive(mContext, intent); 9986 } 9987 9988 private long getLowRamTimeSinceIdle(long now) { 9989 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 9990 } 9991 9992 @Override 9993 public void performIdleMaintenance() { 9994 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 9995 != PackageManager.PERMISSION_GRANTED) { 9996 throw new SecurityException("Requires permission " 9997 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 9998 } 9999 10000 synchronized (this) { 10001 final long now = SystemClock.uptimeMillis(); 10002 final long timeSinceLastIdle = now - mLastIdleTime; 10003 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 10004 mLastIdleTime = now; 10005 mLowRamTimeSinceLastIdle = 0; 10006 if (mLowRamStartTime != 0) { 10007 mLowRamStartTime = now; 10008 } 10009 10010 StringBuilder sb = new StringBuilder(128); 10011 sb.append("Idle maintenance over "); 10012 TimeUtils.formatDuration(timeSinceLastIdle, sb); 10013 sb.append(" low RAM for "); 10014 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 10015 Slog.i(TAG, sb.toString()); 10016 10017 // If at least 1/3 of our time since the last idle period has been spent 10018 // with RAM low, then we want to kill processes. 10019 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 10020 10021 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 10022 ProcessRecord proc = mLruProcesses.get(i); 10023 if (proc.notCachedSinceIdle) { 10024 if (proc.setProcState > ActivityManager.PROCESS_STATE_TOP 10025 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 10026 if (doKilling && proc.initialIdlePss != 0 10027 && proc.lastPss > ((proc.initialIdlePss*3)/2)) { 10028 killUnneededProcessLocked(proc, "idle maint (pss " + proc.lastPss 10029 + " from " + proc.initialIdlePss + ")"); 10030 } 10031 } 10032 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) { 10033 proc.notCachedSinceIdle = true; 10034 proc.initialIdlePss = 0; 10035 proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true, 10036 isSleeping(), now); 10037 } 10038 } 10039 10040 mHandler.removeMessages(REQUEST_ALL_PSS_MSG); 10041 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000); 10042 } 10043 } 10044 10045 private void retrieveSettings() { 10046 final ContentResolver resolver = mContext.getContentResolver(); 10047 String debugApp = Settings.Global.getString( 10048 resolver, Settings.Global.DEBUG_APP); 10049 boolean waitForDebugger = Settings.Global.getInt( 10050 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0; 10051 boolean alwaysFinishActivities = Settings.Global.getInt( 10052 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0; 10053 boolean forceRtl = Settings.Global.getInt( 10054 resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0; 10055 // Transfer any global setting for forcing RTL layout, into a System Property 10056 SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0"); 10057 10058 Configuration configuration = new Configuration(); 10059 Settings.System.getConfiguration(resolver, configuration); 10060 if (forceRtl) { 10061 // This will take care of setting the correct layout direction flags 10062 configuration.setLayoutDirection(configuration.locale); 10063 } 10064 10065 synchronized (this) { 10066 mDebugApp = mOrigDebugApp = debugApp; 10067 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 10068 mAlwaysFinishActivities = alwaysFinishActivities; 10069 // This happens before any activities are started, so we can 10070 // change mConfiguration in-place. 10071 updateConfigurationLocked(configuration, null, false, true); 10072 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration); 10073 } 10074 } 10075 10076 public boolean testIsSystemReady() { 10077 // no need to synchronize(this) just to read & return the value 10078 return mSystemReady; 10079 } 10080 10081 private static File getCalledPreBootReceiversFile() { 10082 File dataDir = Environment.getDataDirectory(); 10083 File systemDir = new File(dataDir, "system"); 10084 File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME); 10085 return fname; 10086 } 10087 10088 private static ArrayList<ComponentName> readLastDonePreBootReceivers() { 10089 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>(); 10090 File file = getCalledPreBootReceiversFile(); 10091 FileInputStream fis = null; 10092 try { 10093 fis = new FileInputStream(file); 10094 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048)); 10095 int fvers = dis.readInt(); 10096 if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) { 10097 String vers = dis.readUTF(); 10098 String codename = dis.readUTF(); 10099 String build = dis.readUTF(); 10100 if (android.os.Build.VERSION.RELEASE.equals(vers) 10101 && android.os.Build.VERSION.CODENAME.equals(codename) 10102 && android.os.Build.VERSION.INCREMENTAL.equals(build)) { 10103 int num = dis.readInt(); 10104 while (num > 0) { 10105 num--; 10106 String pkg = dis.readUTF(); 10107 String cls = dis.readUTF(); 10108 lastDoneReceivers.add(new ComponentName(pkg, cls)); 10109 } 10110 } 10111 } 10112 } catch (FileNotFoundException e) { 10113 } catch (IOException e) { 10114 Slog.w(TAG, "Failure reading last done pre-boot receivers", e); 10115 } finally { 10116 if (fis != null) { 10117 try { 10118 fis.close(); 10119 } catch (IOException e) { 10120 } 10121 } 10122 } 10123 return lastDoneReceivers; 10124 } 10125 10126 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) { 10127 File file = getCalledPreBootReceiversFile(); 10128 FileOutputStream fos = null; 10129 DataOutputStream dos = null; 10130 try { 10131 fos = new FileOutputStream(file); 10132 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048)); 10133 dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION); 10134 dos.writeUTF(android.os.Build.VERSION.RELEASE); 10135 dos.writeUTF(android.os.Build.VERSION.CODENAME); 10136 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL); 10137 dos.writeInt(list.size()); 10138 for (int i=0; i<list.size(); i++) { 10139 dos.writeUTF(list.get(i).getPackageName()); 10140 dos.writeUTF(list.get(i).getClassName()); 10141 } 10142 } catch (IOException e) { 10143 Slog.w(TAG, "Failure writing last done pre-boot receivers", e); 10144 file.delete(); 10145 } finally { 10146 FileUtils.sync(fos); 10147 if (dos != null) { 10148 try { 10149 dos.close(); 10150 } catch (IOException e) { 10151 // TODO Auto-generated catch block 10152 e.printStackTrace(); 10153 } 10154 } 10155 } 10156 } 10157 10158 private boolean deliverPreBootCompleted(final Runnable onFinishCallback, 10159 ArrayList<ComponentName> doneReceivers, int userId) { 10160 boolean waitingUpdate = false; 10161 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 10162 List<ResolveInfo> ris = null; 10163 try { 10164 ris = AppGlobals.getPackageManager().queryIntentReceivers( 10165 intent, null, 0, userId); 10166 } catch (RemoteException e) { 10167 } 10168 if (ris != null) { 10169 for (int i=ris.size()-1; i>=0; i--) { 10170 if ((ris.get(i).activityInfo.applicationInfo.flags 10171 &ApplicationInfo.FLAG_SYSTEM) == 0) { 10172 ris.remove(i); 10173 } 10174 } 10175 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); 10176 10177 // For User 0, load the version number. When delivering to a new user, deliver 10178 // to all receivers. 10179 if (userId == UserHandle.USER_OWNER) { 10180 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers(); 10181 for (int i=0; i<ris.size(); i++) { 10182 ActivityInfo ai = ris.get(i).activityInfo; 10183 ComponentName comp = new ComponentName(ai.packageName, ai.name); 10184 if (lastDoneReceivers.contains(comp)) { 10185 // We already did the pre boot receiver for this app with the current 10186 // platform version, so don't do it again... 10187 ris.remove(i); 10188 i--; 10189 // ...however, do keep it as one that has been done, so we don't 10190 // forget about it when rewriting the file of last done receivers. 10191 doneReceivers.add(comp); 10192 } 10193 } 10194 } 10195 10196 // If primary user, send broadcast to all available users, else just to userId 10197 final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked() 10198 : new int[] { userId }; 10199 for (int i = 0; i < ris.size(); i++) { 10200 ActivityInfo ai = ris.get(i).activityInfo; 10201 ComponentName comp = new ComponentName(ai.packageName, ai.name); 10202 doneReceivers.add(comp); 10203 intent.setComponent(comp); 10204 for (int j=0; j<users.length; j++) { 10205 IIntentReceiver finisher = null; 10206 // On last receiver and user, set up a completion callback 10207 if (i == ris.size() - 1 && j == users.length - 1 && onFinishCallback != null) { 10208 finisher = new IIntentReceiver.Stub() { 10209 public void performReceive(Intent intent, int resultCode, 10210 String data, Bundle extras, boolean ordered, 10211 boolean sticky, int sendingUser) { 10212 // The raw IIntentReceiver interface is called 10213 // with the AM lock held, so redispatch to 10214 // execute our code without the lock. 10215 mHandler.post(onFinishCallback); 10216 } 10217 }; 10218 } 10219 Slog.i(TAG, "Sending system update to " + intent.getComponent() 10220 + " for user " + users[j]); 10221 broadcastIntentLocked(null, null, intent, null, finisher, 10222 0, null, null, null, AppOpsManager.OP_NONE, 10223 true, false, MY_PID, Process.SYSTEM_UID, 10224 users[j]); 10225 if (finisher != null) { 10226 waitingUpdate = true; 10227 } 10228 } 10229 } 10230 } 10231 10232 return waitingUpdate; 10233 } 10234 10235 public void systemReady(final Runnable goingCallback) { 10236 synchronized(this) { 10237 if (mSystemReady) { 10238 // If we're done calling all the receivers, run the next "boot phase" passed in 10239 // by the SystemServer 10240 if (goingCallback != null) { 10241 goingCallback.run(); 10242 } 10243 return; 10244 } 10245 10246 // Make sure we have the current profile info, since it is needed for 10247 // security checks. 10248 updateCurrentProfileIdsLocked(); 10249 10250 if (mRecentTasks == null) { 10251 mRecentTasks = mTaskPersister.restoreTasksLocked(); 10252 if (!mRecentTasks.isEmpty()) { 10253 mStackSupervisor.createStackForRestoredTaskHistory(mRecentTasks); 10254 } 10255 mTaskPersister.startPersisting(); 10256 } 10257 10258 // Check to see if there are any update receivers to run. 10259 if (!mDidUpdate) { 10260 if (mWaitingUpdate) { 10261 return; 10262 } 10263 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); 10264 mWaitingUpdate = deliverPreBootCompleted(new Runnable() { 10265 public void run() { 10266 synchronized (ActivityManagerService.this) { 10267 mDidUpdate = true; 10268 } 10269 writeLastDonePreBootReceivers(doneReceivers); 10270 showBootMessage(mContext.getText( 10271 R.string.android_upgrading_complete), 10272 false); 10273 systemReady(goingCallback); 10274 } 10275 }, doneReceivers, UserHandle.USER_OWNER); 10276 10277 if (mWaitingUpdate) { 10278 return; 10279 } 10280 mDidUpdate = true; 10281 } 10282 10283 mAppOpsService.systemReady(); 10284 mSystemReady = true; 10285 } 10286 10287 ArrayList<ProcessRecord> procsToKill = null; 10288 synchronized(mPidsSelfLocked) { 10289 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 10290 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 10291 if (!isAllowedWhileBooting(proc.info)){ 10292 if (procsToKill == null) { 10293 procsToKill = new ArrayList<ProcessRecord>(); 10294 } 10295 procsToKill.add(proc); 10296 } 10297 } 10298 } 10299 10300 synchronized(this) { 10301 if (procsToKill != null) { 10302 for (int i=procsToKill.size()-1; i>=0; i--) { 10303 ProcessRecord proc = procsToKill.get(i); 10304 Slog.i(TAG, "Removing system update proc: " + proc); 10305 removeProcessLocked(proc, true, false, "system update done"); 10306 } 10307 } 10308 10309 // Now that we have cleaned up any update processes, we 10310 // are ready to start launching real processes and know that 10311 // we won't trample on them any more. 10312 mProcessesReady = true; 10313 } 10314 10315 Slog.i(TAG, "System now ready"); 10316 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, 10317 SystemClock.uptimeMillis()); 10318 10319 synchronized(this) { 10320 // Make sure we have no pre-ready processes sitting around. 10321 10322 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 10323 ResolveInfo ri = mContext.getPackageManager() 10324 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), 10325 STOCK_PM_FLAGS); 10326 CharSequence errorMsg = null; 10327 if (ri != null) { 10328 ActivityInfo ai = ri.activityInfo; 10329 ApplicationInfo app = ai.applicationInfo; 10330 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10331 mTopAction = Intent.ACTION_FACTORY_TEST; 10332 mTopData = null; 10333 mTopComponent = new ComponentName(app.packageName, 10334 ai.name); 10335 } else { 10336 errorMsg = mContext.getResources().getText( 10337 com.android.internal.R.string.factorytest_not_system); 10338 } 10339 } else { 10340 errorMsg = mContext.getResources().getText( 10341 com.android.internal.R.string.factorytest_no_action); 10342 } 10343 if (errorMsg != null) { 10344 mTopAction = null; 10345 mTopData = null; 10346 mTopComponent = null; 10347 Message msg = Message.obtain(); 10348 msg.what = SHOW_FACTORY_ERROR_MSG; 10349 msg.getData().putCharSequence("msg", errorMsg); 10350 mHandler.sendMessage(msg); 10351 } 10352 } 10353 } 10354 10355 retrieveSettings(); 10356 10357 synchronized (this) { 10358 readGrantedUriPermissionsLocked(); 10359 } 10360 10361 if (goingCallback != null) goingCallback.run(); 10362 10363 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 10364 Integer.toString(mCurrentUserId), mCurrentUserId); 10365 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 10366 Integer.toString(mCurrentUserId), mCurrentUserId); 10367 mSystemServiceManager.startUser(mCurrentUserId); 10368 10369 synchronized (this) { 10370 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 10371 try { 10372 List apps = AppGlobals.getPackageManager(). 10373 getPersistentApplications(STOCK_PM_FLAGS); 10374 if (apps != null) { 10375 int N = apps.size(); 10376 int i; 10377 for (i=0; i<N; i++) { 10378 ApplicationInfo info 10379 = (ApplicationInfo)apps.get(i); 10380 if (info != null && 10381 !info.packageName.equals("android")) { 10382 addAppLocked(info, false, null /* ABI override */); 10383 } 10384 } 10385 } 10386 } catch (RemoteException ex) { 10387 // pm is in same process, this will never happen. 10388 } 10389 } 10390 10391 // Start up initial activity. 10392 mBooting = true; 10393 10394 try { 10395 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { 10396 Message msg = Message.obtain(); 10397 msg.what = SHOW_UID_ERROR_MSG; 10398 mHandler.sendMessage(msg); 10399 } 10400 } catch (RemoteException e) { 10401 } 10402 10403 long ident = Binder.clearCallingIdentity(); 10404 try { 10405 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 10406 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 10407 | Intent.FLAG_RECEIVER_FOREGROUND); 10408 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 10409 broadcastIntentLocked(null, null, intent, 10410 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 10411 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId); 10412 intent = new Intent(Intent.ACTION_USER_STARTING); 10413 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 10414 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 10415 broadcastIntentLocked(null, null, intent, 10416 null, new IIntentReceiver.Stub() { 10417 @Override 10418 public void performReceive(Intent intent, int resultCode, String data, 10419 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 10420 throws RemoteException { 10421 } 10422 }, 0, null, null, 10423 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 10424 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 10425 } catch (Throwable t) { 10426 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 10427 } finally { 10428 Binder.restoreCallingIdentity(ident); 10429 } 10430 mStackSupervisor.resumeTopActivitiesLocked(); 10431 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId); 10432 } 10433 } 10434 10435 private boolean makeAppCrashingLocked(ProcessRecord app, 10436 String shortMsg, String longMsg, String stackTrace) { 10437 app.crashing = true; 10438 app.crashingReport = generateProcessError(app, 10439 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace); 10440 startAppProblemLocked(app); 10441 app.stopFreezingAllLocked(); 10442 return handleAppCrashLocked(app, shortMsg, longMsg, stackTrace); 10443 } 10444 10445 private void makeAppNotRespondingLocked(ProcessRecord app, 10446 String activity, String shortMsg, String longMsg) { 10447 app.notResponding = true; 10448 app.notRespondingReport = generateProcessError(app, 10449 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 10450 activity, shortMsg, longMsg, null); 10451 startAppProblemLocked(app); 10452 app.stopFreezingAllLocked(); 10453 } 10454 10455 /** 10456 * Generate a process error record, suitable for attachment to a ProcessRecord. 10457 * 10458 * @param app The ProcessRecord in which the error occurred. 10459 * @param condition Crashing, Application Not Responding, etc. Values are defined in 10460 * ActivityManager.AppErrorStateInfo 10461 * @param activity The activity associated with the crash, if known. 10462 * @param shortMsg Short message describing the crash. 10463 * @param longMsg Long message describing the crash. 10464 * @param stackTrace Full crash stack trace, may be null. 10465 * 10466 * @return Returns a fully-formed AppErrorStateInfo record. 10467 */ 10468 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app, 10469 int condition, String activity, String shortMsg, String longMsg, String stackTrace) { 10470 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo(); 10471 10472 report.condition = condition; 10473 report.processName = app.processName; 10474 report.pid = app.pid; 10475 report.uid = app.info.uid; 10476 report.tag = activity; 10477 report.shortMsg = shortMsg; 10478 report.longMsg = longMsg; 10479 report.stackTrace = stackTrace; 10480 10481 return report; 10482 } 10483 10484 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 10485 synchronized (this) { 10486 app.crashing = false; 10487 app.crashingReport = null; 10488 app.notResponding = false; 10489 app.notRespondingReport = null; 10490 if (app.anrDialog == fromDialog) { 10491 app.anrDialog = null; 10492 } 10493 if (app.waitDialog == fromDialog) { 10494 app.waitDialog = null; 10495 } 10496 if (app.pid > 0 && app.pid != MY_PID) { 10497 handleAppCrashLocked(app, null, null, null); 10498 killUnneededProcessLocked(app, "user request after error"); 10499 } 10500 } 10501 } 10502 10503 private boolean handleAppCrashLocked(ProcessRecord app, String shortMsg, String longMsg, 10504 String stackTrace) { 10505 long now = SystemClock.uptimeMillis(); 10506 10507 Long crashTime; 10508 if (!app.isolated) { 10509 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid); 10510 } else { 10511 crashTime = null; 10512 } 10513 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) { 10514 // This process loses! 10515 Slog.w(TAG, "Process " + app.info.processName 10516 + " has crashed too many times: killing!"); 10517 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, 10518 app.userId, app.info.processName, app.uid); 10519 mStackSupervisor.handleAppCrashLocked(app); 10520 if (!app.persistent) { 10521 // We don't want to start this process again until the user 10522 // explicitly does so... but for persistent process, we really 10523 // need to keep it running. If a persistent process is actually 10524 // repeatedly crashing, then badness for everyone. 10525 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, 10526 app.info.processName); 10527 if (!app.isolated) { 10528 // XXX We don't have a way to mark isolated processes 10529 // as bad, since they don't have a peristent identity. 10530 mBadProcesses.put(app.info.processName, app.uid, 10531 new BadProcessInfo(now, shortMsg, longMsg, stackTrace)); 10532 mProcessCrashTimes.remove(app.info.processName, app.uid); 10533 } 10534 app.bad = true; 10535 app.removed = true; 10536 // Don't let services in this process be restarted and potentially 10537 // annoy the user repeatedly. Unless it is persistent, since those 10538 // processes run critical code. 10539 removeProcessLocked(app, false, false, "crash"); 10540 mStackSupervisor.resumeTopActivitiesLocked(); 10541 return false; 10542 } 10543 mStackSupervisor.resumeTopActivitiesLocked(); 10544 } else { 10545 mStackSupervisor.finishTopRunningActivityLocked(app); 10546 } 10547 10548 // Bump up the crash count of any services currently running in the proc. 10549 for (int i=app.services.size()-1; i>=0; i--) { 10550 // Any services running in the application need to be placed 10551 // back in the pending list. 10552 ServiceRecord sr = app.services.valueAt(i); 10553 sr.crashCount++; 10554 } 10555 10556 // If the crashing process is what we consider to be the "home process" and it has been 10557 // replaced by a third-party app, clear the package preferred activities from packages 10558 // with a home activity running in the process to prevent a repeatedly crashing app 10559 // from blocking the user to manually clear the list. 10560 final ArrayList<ActivityRecord> activities = app.activities; 10561 if (app == mHomeProcess && activities.size() > 0 10562 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 10563 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 10564 final ActivityRecord r = activities.get(activityNdx); 10565 if (r.isHomeActivity()) { 10566 Log.i(TAG, "Clearing package preferred activities from " + r.packageName); 10567 try { 10568 ActivityThread.getPackageManager() 10569 .clearPackagePreferredActivities(r.packageName); 10570 } catch (RemoteException c) { 10571 // pm is in same process, this will never happen. 10572 } 10573 } 10574 } 10575 } 10576 10577 if (!app.isolated) { 10578 // XXX Can't keep track of crash times for isolated processes, 10579 // because they don't have a perisistent identity. 10580 mProcessCrashTimes.put(app.info.processName, app.uid, now); 10581 } 10582 10583 if (app.crashHandler != null) mHandler.post(app.crashHandler); 10584 return true; 10585 } 10586 10587 void startAppProblemLocked(ProcessRecord app) { 10588 if (app.userId == mCurrentUserId) { 10589 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver( 10590 mContext, app.info.packageName, app.info.flags); 10591 } else { 10592 // If this app is not running under the current user, then we 10593 // can't give it a report button because that would require 10594 // launching the report UI under a different user. 10595 app.errorReportReceiver = null; 10596 } 10597 skipCurrentReceiverLocked(app); 10598 } 10599 10600 void skipCurrentReceiverLocked(ProcessRecord app) { 10601 for (BroadcastQueue queue : mBroadcastQueues) { 10602 queue.skipCurrentReceiverLocked(app); 10603 } 10604 } 10605 10606 /** 10607 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 10608 * The application process will exit immediately after this call returns. 10609 * @param app object of the crashing app, null for the system server 10610 * @param crashInfo describing the exception 10611 */ 10612 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) { 10613 ProcessRecord r = findAppProcess(app, "Crash"); 10614 final String processName = app == null ? "system_server" 10615 : (r == null ? "unknown" : r.processName); 10616 10617 handleApplicationCrashInner("crash", r, processName, crashInfo); 10618 } 10619 10620 /* Native crash reporting uses this inner version because it needs to be somewhat 10621 * decoupled from the AM-managed cleanup lifecycle 10622 */ 10623 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 10624 ApplicationErrorReport.CrashInfo crashInfo) { 10625 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(), 10626 UserHandle.getUserId(Binder.getCallingUid()), processName, 10627 r == null ? -1 : r.info.flags, 10628 crashInfo.exceptionClassName, 10629 crashInfo.exceptionMessage, 10630 crashInfo.throwFileName, 10631 crashInfo.throwLineNumber); 10632 10633 addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo); 10634 10635 crashApplication(r, crashInfo); 10636 } 10637 10638 public void handleApplicationStrictModeViolation( 10639 IBinder app, 10640 int violationMask, 10641 StrictMode.ViolationInfo info) { 10642 ProcessRecord r = findAppProcess(app, "StrictMode"); 10643 if (r == null) { 10644 return; 10645 } 10646 10647 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) { 10648 Integer stackFingerprint = info.hashCode(); 10649 boolean logIt = true; 10650 synchronized (mAlreadyLoggedViolatedStacks) { 10651 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 10652 logIt = false; 10653 // TODO: sub-sample into EventLog for these, with 10654 // the info.durationMillis? Then we'd get 10655 // the relative pain numbers, without logging all 10656 // the stack traces repeatedly. We'd want to do 10657 // likewise in the client code, which also does 10658 // dup suppression, before the Binder call. 10659 } else { 10660 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 10661 mAlreadyLoggedViolatedStacks.clear(); 10662 } 10663 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 10664 } 10665 } 10666 if (logIt) { 10667 logStrictModeViolationToDropBox(r, info); 10668 } 10669 } 10670 10671 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) { 10672 AppErrorResult result = new AppErrorResult(); 10673 synchronized (this) { 10674 final long origId = Binder.clearCallingIdentity(); 10675 10676 Message msg = Message.obtain(); 10677 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG; 10678 HashMap<String, Object> data = new HashMap<String, Object>(); 10679 data.put("result", result); 10680 data.put("app", r); 10681 data.put("violationMask", violationMask); 10682 data.put("info", info); 10683 msg.obj = data; 10684 mHandler.sendMessage(msg); 10685 10686 Binder.restoreCallingIdentity(origId); 10687 } 10688 int res = result.get(); 10689 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 10690 } 10691 } 10692 10693 // Depending on the policy in effect, there could be a bunch of 10694 // these in quick succession so we try to batch these together to 10695 // minimize disk writes, number of dropbox entries, and maximize 10696 // compression, by having more fewer, larger records. 10697 private void logStrictModeViolationToDropBox( 10698 ProcessRecord process, 10699 StrictMode.ViolationInfo info) { 10700 if (info == null) { 10701 return; 10702 } 10703 final boolean isSystemApp = process == null || 10704 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 10705 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 10706 final String processName = process == null ? "unknown" : process.processName; 10707 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode"; 10708 final DropBoxManager dbox = (DropBoxManager) 10709 mContext.getSystemService(Context.DROPBOX_SERVICE); 10710 10711 // Exit early if the dropbox isn't configured to accept this report type. 10712 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 10713 10714 boolean bufferWasEmpty; 10715 boolean needsFlush; 10716 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024); 10717 synchronized (sb) { 10718 bufferWasEmpty = sb.length() == 0; 10719 appendDropBoxProcessHeaders(process, processName, sb); 10720 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 10721 sb.append("System-App: ").append(isSystemApp).append("\n"); 10722 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 10723 if (info.violationNumThisLoop != 0) { 10724 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 10725 } 10726 if (info.numAnimationsRunning != 0) { 10727 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 10728 } 10729 if (info.broadcastIntentAction != null) { 10730 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 10731 } 10732 if (info.durationMillis != -1) { 10733 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 10734 } 10735 if (info.numInstances != -1) { 10736 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 10737 } 10738 if (info.tags != null) { 10739 for (String tag : info.tags) { 10740 sb.append("Span-Tag: ").append(tag).append("\n"); 10741 } 10742 } 10743 sb.append("\n"); 10744 if (info.crashInfo != null && info.crashInfo.stackTrace != null) { 10745 sb.append(info.crashInfo.stackTrace); 10746 } 10747 sb.append("\n"); 10748 10749 // Only buffer up to ~64k. Various logging bits truncate 10750 // things at 128k. 10751 needsFlush = (sb.length() > 64 * 1024); 10752 } 10753 10754 // Flush immediately if the buffer's grown too large, or this 10755 // is a non-system app. Non-system apps are isolated with a 10756 // different tag & policy and not batched. 10757 // 10758 // Batching is useful during internal testing with 10759 // StrictMode settings turned up high. Without batching, 10760 // thousands of separate files could be created on boot. 10761 if (!isSystemApp || needsFlush) { 10762 new Thread("Error dump: " + dropboxTag) { 10763 @Override 10764 public void run() { 10765 String report; 10766 synchronized (sb) { 10767 report = sb.toString(); 10768 sb.delete(0, sb.length()); 10769 sb.trimToSize(); 10770 } 10771 if (report.length() != 0) { 10772 dbox.addText(dropboxTag, report); 10773 } 10774 } 10775 }.start(); 10776 return; 10777 } 10778 10779 // System app batching: 10780 if (!bufferWasEmpty) { 10781 // An existing dropbox-writing thread is outstanding, so 10782 // we don't need to start it up. The existing thread will 10783 // catch the buffer appends we just did. 10784 return; 10785 } 10786 10787 // Worker thread to both batch writes and to avoid blocking the caller on I/O. 10788 // (After this point, we shouldn't access AMS internal data structures.) 10789 new Thread("Error dump: " + dropboxTag) { 10790 @Override 10791 public void run() { 10792 // 5 second sleep to let stacks arrive and be batched together 10793 try { 10794 Thread.sleep(5000); // 5 seconds 10795 } catch (InterruptedException e) {} 10796 10797 String errorReport; 10798 synchronized (mStrictModeBuffer) { 10799 errorReport = mStrictModeBuffer.toString(); 10800 if (errorReport.length() == 0) { 10801 return; 10802 } 10803 mStrictModeBuffer.delete(0, mStrictModeBuffer.length()); 10804 mStrictModeBuffer.trimToSize(); 10805 } 10806 dbox.addText(dropboxTag, errorReport); 10807 } 10808 }.start(); 10809 } 10810 10811 /** 10812 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 10813 * @param app object of the crashing app, null for the system server 10814 * @param tag reported by the caller 10815 * @param crashInfo describing the context of the error 10816 * @return true if the process should exit immediately (WTF is fatal) 10817 */ 10818 public boolean handleApplicationWtf(IBinder app, String tag, 10819 ApplicationErrorReport.CrashInfo crashInfo) { 10820 ProcessRecord r = findAppProcess(app, "WTF"); 10821 final String processName = app == null ? "system_server" 10822 : (r == null ? "unknown" : r.processName); 10823 10824 EventLog.writeEvent(EventLogTags.AM_WTF, 10825 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(), 10826 processName, 10827 r == null ? -1 : r.info.flags, 10828 tag, crashInfo.exceptionMessage); 10829 10830 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo); 10831 10832 if (r != null && r.pid != Process.myPid() && 10833 Settings.Global.getInt(mContext.getContentResolver(), 10834 Settings.Global.WTF_IS_FATAL, 0) != 0) { 10835 crashApplication(r, crashInfo); 10836 return true; 10837 } else { 10838 return false; 10839 } 10840 } 10841 10842 /** 10843 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 10844 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 10845 */ 10846 private ProcessRecord findAppProcess(IBinder app, String reason) { 10847 if (app == null) { 10848 return null; 10849 } 10850 10851 synchronized (this) { 10852 final int NP = mProcessNames.getMap().size(); 10853 for (int ip=0; ip<NP; ip++) { 10854 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 10855 final int NA = apps.size(); 10856 for (int ia=0; ia<NA; ia++) { 10857 ProcessRecord p = apps.valueAt(ia); 10858 if (p.thread != null && p.thread.asBinder() == app) { 10859 return p; 10860 } 10861 } 10862 } 10863 10864 Slog.w(TAG, "Can't find mystery application for " + reason 10865 + " from pid=" + Binder.getCallingPid() 10866 + " uid=" + Binder.getCallingUid() + ": " + app); 10867 return null; 10868 } 10869 } 10870 10871 /** 10872 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 10873 * to append various headers to the dropbox log text. 10874 */ 10875 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 10876 StringBuilder sb) { 10877 // Watchdog thread ends up invoking this function (with 10878 // a null ProcessRecord) to add the stack file to dropbox. 10879 // Do not acquire a lock on this (am) in such cases, as it 10880 // could cause a potential deadlock, if and when watchdog 10881 // is invoked due to unavailability of lock on am and it 10882 // would prevent watchdog from killing system_server. 10883 if (process == null) { 10884 sb.append("Process: ").append(processName).append("\n"); 10885 return; 10886 } 10887 // Note: ProcessRecord 'process' is guarded by the service 10888 // instance. (notably process.pkgList, which could otherwise change 10889 // concurrently during execution of this method) 10890 synchronized (this) { 10891 sb.append("Process: ").append(processName).append("\n"); 10892 int flags = process.info.flags; 10893 IPackageManager pm = AppGlobals.getPackageManager(); 10894 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n"); 10895 for (int ip=0; ip<process.pkgList.size(); ip++) { 10896 String pkg = process.pkgList.keyAt(ip); 10897 sb.append("Package: ").append(pkg); 10898 try { 10899 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId()); 10900 if (pi != null) { 10901 sb.append(" v").append(pi.versionCode); 10902 if (pi.versionName != null) { 10903 sb.append(" (").append(pi.versionName).append(")"); 10904 } 10905 } 10906 } catch (RemoteException e) { 10907 Slog.e(TAG, "Error getting package info: " + pkg, e); 10908 } 10909 sb.append("\n"); 10910 } 10911 } 10912 } 10913 10914 private static String processClass(ProcessRecord process) { 10915 if (process == null || process.pid == MY_PID) { 10916 return "system_server"; 10917 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10918 return "system_app"; 10919 } else { 10920 return "data_app"; 10921 } 10922 } 10923 10924 /** 10925 * Write a description of an error (crash, WTF, ANR) to the drop box. 10926 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 10927 * @param process which caused the error, null means the system server 10928 * @param activity which triggered the error, null if unknown 10929 * @param parent activity related to the error, null if unknown 10930 * @param subject line related to the error, null if absent 10931 * @param report in long form describing the error, null if absent 10932 * @param logFile to include in the report, null if none 10933 * @param crashInfo giving an application stack trace, null if absent 10934 */ 10935 public void addErrorToDropBox(String eventType, 10936 ProcessRecord process, String processName, ActivityRecord activity, 10937 ActivityRecord parent, String subject, 10938 final String report, final File logFile, 10939 final ApplicationErrorReport.CrashInfo crashInfo) { 10940 // NOTE -- this must never acquire the ActivityManagerService lock, 10941 // otherwise the watchdog may be prevented from resetting the system. 10942 10943 final String dropboxTag = processClass(process) + "_" + eventType; 10944 final DropBoxManager dbox = (DropBoxManager) 10945 mContext.getSystemService(Context.DROPBOX_SERVICE); 10946 10947 // Exit early if the dropbox isn't configured to accept this report type. 10948 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 10949 10950 final StringBuilder sb = new StringBuilder(1024); 10951 appendDropBoxProcessHeaders(process, processName, sb); 10952 if (activity != null) { 10953 sb.append("Activity: ").append(activity.shortComponentName).append("\n"); 10954 } 10955 if (parent != null && parent.app != null && parent.app.pid != process.pid) { 10956 sb.append("Parent-Process: ").append(parent.app.processName).append("\n"); 10957 } 10958 if (parent != null && parent != activity) { 10959 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n"); 10960 } 10961 if (subject != null) { 10962 sb.append("Subject: ").append(subject).append("\n"); 10963 } 10964 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 10965 if (Debug.isDebuggerConnected()) { 10966 sb.append("Debugger: Connected\n"); 10967 } 10968 sb.append("\n"); 10969 10970 // Do the rest in a worker thread to avoid blocking the caller on I/O 10971 // (After this point, we shouldn't access AMS internal data structures.) 10972 Thread worker = new Thread("Error dump: " + dropboxTag) { 10973 @Override 10974 public void run() { 10975 if (report != null) { 10976 sb.append(report); 10977 } 10978 if (logFile != null) { 10979 try { 10980 sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE, 10981 "\n\n[[TRUNCATED]]")); 10982 } catch (IOException e) { 10983 Slog.e(TAG, "Error reading " + logFile, e); 10984 } 10985 } 10986 if (crashInfo != null && crashInfo.stackTrace != null) { 10987 sb.append(crashInfo.stackTrace); 10988 } 10989 10990 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 10991 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0); 10992 if (lines > 0) { 10993 sb.append("\n"); 10994 10995 // Merge several logcat streams, and take the last N lines 10996 InputStreamReader input = null; 10997 try { 10998 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat", 10999 "-v", "time", "-b", "events", "-b", "system", "-b", "main", 11000 "-t", String.valueOf(lines)).redirectErrorStream(true).start(); 11001 11002 try { logcat.getOutputStream().close(); } catch (IOException e) {} 11003 try { logcat.getErrorStream().close(); } catch (IOException e) {} 11004 input = new InputStreamReader(logcat.getInputStream()); 11005 11006 int num; 11007 char[] buf = new char[8192]; 11008 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 11009 } catch (IOException e) { 11010 Slog.e(TAG, "Error running logcat", e); 11011 } finally { 11012 if (input != null) try { input.close(); } catch (IOException e) {} 11013 } 11014 } 11015 11016 dbox.addText(dropboxTag, sb.toString()); 11017 } 11018 }; 11019 11020 if (process == null) { 11021 // If process is null, we are being called from some internal code 11022 // and may be about to die -- run this synchronously. 11023 worker.run(); 11024 } else { 11025 worker.start(); 11026 } 11027 } 11028 11029 /** 11030 * Bring up the "unexpected error" dialog box for a crashing app. 11031 * Deal with edge cases (intercepts from instrumented applications, 11032 * ActivityController, error intent receivers, that sort of thing). 11033 * @param r the application crashing 11034 * @param crashInfo describing the failure 11035 */ 11036 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) { 11037 long timeMillis = System.currentTimeMillis(); 11038 String shortMsg = crashInfo.exceptionClassName; 11039 String longMsg = crashInfo.exceptionMessage; 11040 String stackTrace = crashInfo.stackTrace; 11041 if (shortMsg != null && longMsg != null) { 11042 longMsg = shortMsg + ": " + longMsg; 11043 } else if (shortMsg != null) { 11044 longMsg = shortMsg; 11045 } 11046 11047 AppErrorResult result = new AppErrorResult(); 11048 synchronized (this) { 11049 if (mController != null) { 11050 try { 11051 String name = r != null ? r.processName : null; 11052 int pid = r != null ? r.pid : Binder.getCallingPid(); 11053 int uid = r != null ? r.info.uid : Binder.getCallingUid(); 11054 if (!mController.appCrashed(name, pid, 11055 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) { 11056 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")) 11057 && "Native crash".equals(crashInfo.exceptionClassName)) { 11058 Slog.w(TAG, "Skip killing native crashed app " + name 11059 + "(" + pid + ") during testing"); 11060 } else { 11061 Slog.w(TAG, "Force-killing crashed app " + name 11062 + " at watcher's request"); 11063 Process.killProcess(pid); 11064 if (r != null) { 11065 Process.killProcessGroup(uid, pid); 11066 } 11067 } 11068 return; 11069 } 11070 } catch (RemoteException e) { 11071 mController = null; 11072 Watchdog.getInstance().setActivityController(null); 11073 } 11074 } 11075 11076 final long origId = Binder.clearCallingIdentity(); 11077 11078 // If this process is running instrumentation, finish it. 11079 if (r != null && r.instrumentationClass != null) { 11080 Slog.w(TAG, "Error in app " + r.processName 11081 + " running instrumentation " + r.instrumentationClass + ":"); 11082 if (shortMsg != null) Slog.w(TAG, " " + shortMsg); 11083 if (longMsg != null) Slog.w(TAG, " " + longMsg); 11084 Bundle info = new Bundle(); 11085 info.putString("shortMsg", shortMsg); 11086 info.putString("longMsg", longMsg); 11087 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info); 11088 Binder.restoreCallingIdentity(origId); 11089 return; 11090 } 11091 11092 // If we can't identify the process or it's already exceeded its crash quota, 11093 // quit right away without showing a crash dialog. 11094 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) { 11095 Binder.restoreCallingIdentity(origId); 11096 return; 11097 } 11098 11099 Message msg = Message.obtain(); 11100 msg.what = SHOW_ERROR_MSG; 11101 HashMap data = new HashMap(); 11102 data.put("result", result); 11103 data.put("app", r); 11104 msg.obj = data; 11105 mHandler.sendMessage(msg); 11106 11107 Binder.restoreCallingIdentity(origId); 11108 } 11109 11110 int res = result.get(); 11111 11112 Intent appErrorIntent = null; 11113 synchronized (this) { 11114 if (r != null && !r.isolated) { 11115 // XXX Can't keep track of crash time for isolated processes, 11116 // since they don't have a persistent identity. 11117 mProcessCrashTimes.put(r.info.processName, r.uid, 11118 SystemClock.uptimeMillis()); 11119 } 11120 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) { 11121 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo); 11122 } 11123 } 11124 11125 if (appErrorIntent != null) { 11126 try { 11127 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId)); 11128 } catch (ActivityNotFoundException e) { 11129 Slog.w(TAG, "bug report receiver dissappeared", e); 11130 } 11131 } 11132 } 11133 11134 Intent createAppErrorIntentLocked(ProcessRecord r, 11135 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11136 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo); 11137 if (report == null) { 11138 return null; 11139 } 11140 Intent result = new Intent(Intent.ACTION_APP_ERROR); 11141 result.setComponent(r.errorReportReceiver); 11142 result.putExtra(Intent.EXTRA_BUG_REPORT, report); 11143 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11144 return result; 11145 } 11146 11147 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r, 11148 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 11149 if (r.errorReportReceiver == null) { 11150 return null; 11151 } 11152 11153 if (!r.crashing && !r.notResponding && !r.forceCrashReport) { 11154 return null; 11155 } 11156 11157 ApplicationErrorReport report = new ApplicationErrorReport(); 11158 report.packageName = r.info.packageName; 11159 report.installerPackageName = r.errorReportReceiver.getPackageName(); 11160 report.processName = r.processName; 11161 report.time = timeMillis; 11162 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11163 11164 if (r.crashing || r.forceCrashReport) { 11165 report.type = ApplicationErrorReport.TYPE_CRASH; 11166 report.crashInfo = crashInfo; 11167 } else if (r.notResponding) { 11168 report.type = ApplicationErrorReport.TYPE_ANR; 11169 report.anrInfo = new ApplicationErrorReport.AnrInfo(); 11170 11171 report.anrInfo.activity = r.notRespondingReport.tag; 11172 report.anrInfo.cause = r.notRespondingReport.shortMsg; 11173 report.anrInfo.info = r.notRespondingReport.longMsg; 11174 } 11175 11176 return report; 11177 } 11178 11179 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 11180 enforceNotIsolatedCaller("getProcessesInErrorState"); 11181 // assume our apps are happy - lazy create the list 11182 List<ActivityManager.ProcessErrorStateInfo> errList = null; 11183 11184 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 11185 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 11186 int userId = UserHandle.getUserId(Binder.getCallingUid()); 11187 11188 synchronized (this) { 11189 11190 // iterate across all processes 11191 for (int i=mLruProcesses.size()-1; i>=0; i--) { 11192 ProcessRecord app = mLruProcesses.get(i); 11193 if (!allUsers && app.userId != userId) { 11194 continue; 11195 } 11196 if ((app.thread != null) && (app.crashing || app.notResponding)) { 11197 // This one's in trouble, so we'll generate a report for it 11198 // crashes are higher priority (in case there's a crash *and* an anr) 11199 ActivityManager.ProcessErrorStateInfo report = null; 11200 if (app.crashing) { 11201 report = app.crashingReport; 11202 } else if (app.notResponding) { 11203 report = app.notRespondingReport; 11204 } 11205 11206 if (report != null) { 11207 if (errList == null) { 11208 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1); 11209 } 11210 errList.add(report); 11211 } else { 11212 Slog.w(TAG, "Missing app error report, app = " + app.processName + 11213 " crashing = " + app.crashing + 11214 " notResponding = " + app.notResponding); 11215 } 11216 } 11217 } 11218 } 11219 11220 return errList; 11221 } 11222 11223 static int procStateToImportance(int procState, int memAdj, 11224 ActivityManager.RunningAppProcessInfo currApp) { 11225 int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState); 11226 if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { 11227 currApp.lru = memAdj; 11228 } else { 11229 currApp.lru = 0; 11230 } 11231 return imp; 11232 } 11233 11234 private void fillInProcMemInfo(ProcessRecord app, 11235 ActivityManager.RunningAppProcessInfo outInfo) { 11236 outInfo.pid = app.pid; 11237 outInfo.uid = app.info.uid; 11238 if (mHeavyWeightProcess == app) { 11239 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE; 11240 } 11241 if (app.persistent) { 11242 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT; 11243 } 11244 if (app.activities.size() > 0) { 11245 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES; 11246 } 11247 outInfo.lastTrimLevel = app.trimMemoryLevel; 11248 int adj = app.curAdj; 11249 int procState = app.curProcState; 11250 outInfo.importance = procStateToImportance(procState, adj, outInfo); 11251 outInfo.importanceReasonCode = app.adjTypeCode; 11252 outInfo.processState = app.curProcState; 11253 } 11254 11255 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 11256 enforceNotIsolatedCaller("getRunningAppProcesses"); 11257 // Lazy instantiation of list 11258 List<ActivityManager.RunningAppProcessInfo> runList = null; 11259 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 11260 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 11261 int userId = UserHandle.getUserId(Binder.getCallingUid()); 11262 synchronized (this) { 11263 // Iterate across all processes 11264 for (int i=mLruProcesses.size()-1; i>=0; i--) { 11265 ProcessRecord app = mLruProcesses.get(i); 11266 if (!allUsers && app.userId != userId) { 11267 continue; 11268 } 11269 if ((app.thread != null) && (!app.crashing && !app.notResponding)) { 11270 // Generate process state info for running application 11271 ActivityManager.RunningAppProcessInfo currApp = 11272 new ActivityManager.RunningAppProcessInfo(app.processName, 11273 app.pid, app.getPackageList()); 11274 fillInProcMemInfo(app, currApp); 11275 if (app.adjSource instanceof ProcessRecord) { 11276 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid; 11277 currApp.importanceReasonImportance = 11278 ActivityManager.RunningAppProcessInfo.procStateToImportance( 11279 app.adjSourceProcState); 11280 } else if (app.adjSource instanceof ActivityRecord) { 11281 ActivityRecord r = (ActivityRecord)app.adjSource; 11282 if (r.app != null) currApp.importanceReasonPid = r.app.pid; 11283 } 11284 if (app.adjTarget instanceof ComponentName) { 11285 currApp.importanceReasonComponent = (ComponentName)app.adjTarget; 11286 } 11287 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance 11288 // + " lru=" + currApp.lru); 11289 if (runList == null) { 11290 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>(); 11291 } 11292 runList.add(currApp); 11293 } 11294 } 11295 } 11296 return runList; 11297 } 11298 11299 public List<ApplicationInfo> getRunningExternalApplications() { 11300 enforceNotIsolatedCaller("getRunningExternalApplications"); 11301 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 11302 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 11303 if (runningApps != null && runningApps.size() > 0) { 11304 Set<String> extList = new HashSet<String>(); 11305 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 11306 if (app.pkgList != null) { 11307 for (String pkg : app.pkgList) { 11308 extList.add(pkg); 11309 } 11310 } 11311 } 11312 IPackageManager pm = AppGlobals.getPackageManager(); 11313 for (String pkg : extList) { 11314 try { 11315 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 11316 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 11317 retList.add(info); 11318 } 11319 } catch (RemoteException e) { 11320 } 11321 } 11322 } 11323 return retList; 11324 } 11325 11326 @Override 11327 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) { 11328 enforceNotIsolatedCaller("getMyMemoryState"); 11329 synchronized (this) { 11330 ProcessRecord proc; 11331 synchronized (mPidsSelfLocked) { 11332 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 11333 } 11334 fillInProcMemInfo(proc, outInfo); 11335 } 11336 } 11337 11338 @Override 11339 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11340 if (checkCallingPermission(android.Manifest.permission.DUMP) 11341 != PackageManager.PERMISSION_GRANTED) { 11342 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11343 + Binder.getCallingPid() 11344 + ", uid=" + Binder.getCallingUid() 11345 + " without permission " 11346 + android.Manifest.permission.DUMP); 11347 return; 11348 } 11349 11350 boolean dumpAll = false; 11351 boolean dumpClient = false; 11352 String dumpPackage = null; 11353 11354 int opti = 0; 11355 while (opti < args.length) { 11356 String opt = args[opti]; 11357 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11358 break; 11359 } 11360 opti++; 11361 if ("-a".equals(opt)) { 11362 dumpAll = true; 11363 } else if ("-c".equals(opt)) { 11364 dumpClient = true; 11365 } else if ("-h".equals(opt)) { 11366 pw.println("Activity manager dump options:"); 11367 pw.println(" [-a] [-c] [-h] [cmd] ..."); 11368 pw.println(" cmd may be one of:"); 11369 pw.println(" a[ctivities]: activity stack state"); 11370 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state"); 11371 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state"); 11372 pw.println(" p[rocesses] [PACKAGE_NAME]: process state"); 11373 pw.println(" o[om]: out of memory management"); 11374 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state"); 11375 pw.println(" provider [COMP_SPEC]: provider client-side state"); 11376 pw.println(" s[ervices] [COMP_SPEC ...]: service state"); 11377 pw.println(" service [COMP_SPEC]: service client-side state"); 11378 pw.println(" package [PACKAGE_NAME]: all state related to given package"); 11379 pw.println(" all: dump all activities"); 11380 pw.println(" top: dump the top activity"); 11381 pw.println(" cmd may also be a COMP_SPEC to dump activities."); 11382 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),"); 11383 pw.println(" a partial substring in a component name, a"); 11384 pw.println(" hex object identifier."); 11385 pw.println(" -a: include all available server state."); 11386 pw.println(" -c: include client state."); 11387 return; 11388 } else { 11389 pw.println("Unknown argument: " + opt + "; use -h for help"); 11390 } 11391 } 11392 11393 long origId = Binder.clearCallingIdentity(); 11394 boolean more = false; 11395 // Is the caller requesting to dump a particular piece of data? 11396 if (opti < args.length) { 11397 String cmd = args[opti]; 11398 opti++; 11399 if ("activities".equals(cmd) || "a".equals(cmd)) { 11400 synchronized (this) { 11401 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null); 11402 } 11403 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 11404 String[] newArgs; 11405 String name; 11406 if (opti >= args.length) { 11407 name = null; 11408 newArgs = EMPTY_STRING_ARRAY; 11409 } else { 11410 name = args[opti]; 11411 opti++; 11412 newArgs = new String[args.length - opti]; 11413 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 11414 args.length - opti); 11415 } 11416 synchronized (this) { 11417 dumpBroadcastsLocked(fd, pw, args, opti, true, name); 11418 } 11419 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 11420 String[] newArgs; 11421 String name; 11422 if (opti >= args.length) { 11423 name = null; 11424 newArgs = EMPTY_STRING_ARRAY; 11425 } else { 11426 name = args[opti]; 11427 opti++; 11428 newArgs = new String[args.length - opti]; 11429 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 11430 args.length - opti); 11431 } 11432 synchronized (this) { 11433 dumpPendingIntentsLocked(fd, pw, args, opti, true, name); 11434 } 11435 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 11436 String[] newArgs; 11437 String name; 11438 if (opti >= args.length) { 11439 name = null; 11440 newArgs = EMPTY_STRING_ARRAY; 11441 } else { 11442 name = args[opti]; 11443 opti++; 11444 newArgs = new String[args.length - opti]; 11445 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 11446 args.length - opti); 11447 } 11448 synchronized (this) { 11449 dumpProcessesLocked(fd, pw, args, opti, true, name); 11450 } 11451 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 11452 synchronized (this) { 11453 dumpOomLocked(fd, pw, args, opti, true); 11454 } 11455 } else if ("provider".equals(cmd)) { 11456 String[] newArgs; 11457 String name; 11458 if (opti >= args.length) { 11459 name = null; 11460 newArgs = EMPTY_STRING_ARRAY; 11461 } else { 11462 name = args[opti]; 11463 opti++; 11464 newArgs = new String[args.length - opti]; 11465 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 11466 } 11467 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 11468 pw.println("No providers match: " + name); 11469 pw.println("Use -h for help."); 11470 } 11471 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 11472 synchronized (this) { 11473 dumpProvidersLocked(fd, pw, args, opti, true, null); 11474 } 11475 } else if ("service".equals(cmd)) { 11476 String[] newArgs; 11477 String name; 11478 if (opti >= args.length) { 11479 name = null; 11480 newArgs = EMPTY_STRING_ARRAY; 11481 } else { 11482 name = args[opti]; 11483 opti++; 11484 newArgs = new String[args.length - opti]; 11485 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 11486 args.length - opti); 11487 } 11488 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) { 11489 pw.println("No services match: " + name); 11490 pw.println("Use -h for help."); 11491 } 11492 } else if ("package".equals(cmd)) { 11493 String[] newArgs; 11494 if (opti >= args.length) { 11495 pw.println("package: no package name specified"); 11496 pw.println("Use -h for help."); 11497 } else { 11498 dumpPackage = args[opti]; 11499 opti++; 11500 newArgs = new String[args.length - opti]; 11501 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 11502 args.length - opti); 11503 args = newArgs; 11504 opti = 0; 11505 more = true; 11506 } 11507 } else if ("services".equals(cmd) || "s".equals(cmd)) { 11508 synchronized (this) { 11509 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null); 11510 } 11511 } else { 11512 // Dumping a single activity? 11513 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) { 11514 pw.println("Bad activity command, or no activities match: " + cmd); 11515 pw.println("Use -h for help."); 11516 } 11517 } 11518 if (!more) { 11519 Binder.restoreCallingIdentity(origId); 11520 return; 11521 } 11522 } 11523 11524 // No piece of data specified, dump everything. 11525 synchronized (this) { 11526 dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 11527 pw.println(); 11528 if (dumpAll) { 11529 pw.println("-------------------------------------------------------------------------------"); 11530 } 11531 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 11532 pw.println(); 11533 if (dumpAll) { 11534 pw.println("-------------------------------------------------------------------------------"); 11535 } 11536 dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 11537 pw.println(); 11538 if (dumpAll) { 11539 pw.println("-------------------------------------------------------------------------------"); 11540 } 11541 mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 11542 pw.println(); 11543 if (dumpAll) { 11544 pw.println("-------------------------------------------------------------------------------"); 11545 } 11546 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 11547 pw.println(); 11548 if (dumpAll) { 11549 pw.println("-------------------------------------------------------------------------------"); 11550 } 11551 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage); 11552 } 11553 Binder.restoreCallingIdentity(origId); 11554 } 11555 11556 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11557 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 11558 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)"); 11559 11560 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, 11561 dumpPackage); 11562 boolean needSep = printedAnything; 11563 11564 boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity, 11565 dumpPackage, needSep, " mFocusedActivity: "); 11566 if (printed) { 11567 printedAnything = true; 11568 needSep = false; 11569 } 11570 11571 if (dumpPackage == null) { 11572 if (needSep) { 11573 pw.println(); 11574 } 11575 needSep = true; 11576 printedAnything = true; 11577 mStackSupervisor.dump(pw, " "); 11578 } 11579 11580 if (mRecentTasks.size() > 0) { 11581 boolean printedHeader = false; 11582 11583 final int N = mRecentTasks.size(); 11584 for (int i=0; i<N; i++) { 11585 TaskRecord tr = mRecentTasks.get(i); 11586 if (dumpPackage != null) { 11587 if (tr.realActivity == null || 11588 !dumpPackage.equals(tr.realActivity)) { 11589 continue; 11590 } 11591 } 11592 if (!printedHeader) { 11593 if (needSep) { 11594 pw.println(); 11595 } 11596 pw.println(" Recent tasks:"); 11597 printedHeader = true; 11598 printedAnything = true; 11599 } 11600 pw.print(" * Recent #"); pw.print(i); pw.print(": "); 11601 pw.println(tr); 11602 if (dumpAll) { 11603 mRecentTasks.get(i).dump(pw, " "); 11604 } 11605 } 11606 } 11607 11608 if (!printedAnything) { 11609 pw.println(" (nothing)"); 11610 } 11611 } 11612 11613 void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 11614 int opti, boolean dumpAll, String dumpPackage) { 11615 boolean needSep = false; 11616 boolean printedAnything = false; 11617 int numPers = 0; 11618 11619 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)"); 11620 11621 if (dumpAll) { 11622 final int NP = mProcessNames.getMap().size(); 11623 for (int ip=0; ip<NP; ip++) { 11624 SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip); 11625 final int NA = procs.size(); 11626 for (int ia=0; ia<NA; ia++) { 11627 ProcessRecord r = procs.valueAt(ia); 11628 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 11629 continue; 11630 } 11631 if (!needSep) { 11632 pw.println(" All known processes:"); 11633 needSep = true; 11634 printedAnything = true; 11635 } 11636 pw.print(r.persistent ? " *PERS*" : " *APP*"); 11637 pw.print(" UID "); pw.print(procs.keyAt(ia)); 11638 pw.print(" "); pw.println(r); 11639 r.dump(pw, " "); 11640 if (r.persistent) { 11641 numPers++; 11642 } 11643 } 11644 } 11645 } 11646 11647 if (mIsolatedProcesses.size() > 0) { 11648 boolean printed = false; 11649 for (int i=0; i<mIsolatedProcesses.size(); i++) { 11650 ProcessRecord r = mIsolatedProcesses.valueAt(i); 11651 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 11652 continue; 11653 } 11654 if (!printed) { 11655 if (needSep) { 11656 pw.println(); 11657 } 11658 pw.println(" Isolated process list (sorted by uid):"); 11659 printedAnything = true; 11660 printed = true; 11661 needSep = true; 11662 } 11663 pw.println(String.format("%sIsolated #%2d: %s", 11664 " ", i, r.toString())); 11665 } 11666 } 11667 11668 if (mLruProcesses.size() > 0) { 11669 if (needSep) { 11670 pw.println(); 11671 } 11672 pw.print(" Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size()); 11673 pw.print(" total, non-act at "); 11674 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 11675 pw.print(", non-svc at "); 11676 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 11677 pw.println("):"); 11678 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", false, dumpPackage); 11679 needSep = true; 11680 printedAnything = true; 11681 } 11682 11683 if (dumpAll || dumpPackage != null) { 11684 synchronized (mPidsSelfLocked) { 11685 boolean printed = false; 11686 for (int i=0; i<mPidsSelfLocked.size(); i++) { 11687 ProcessRecord r = mPidsSelfLocked.valueAt(i); 11688 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 11689 continue; 11690 } 11691 if (!printed) { 11692 if (needSep) pw.println(); 11693 needSep = true; 11694 pw.println(" PID mappings:"); 11695 printed = true; 11696 printedAnything = true; 11697 } 11698 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 11699 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 11700 } 11701 } 11702 } 11703 11704 if (mForegroundProcesses.size() > 0) { 11705 synchronized (mPidsSelfLocked) { 11706 boolean printed = false; 11707 for (int i=0; i<mForegroundProcesses.size(); i++) { 11708 ProcessRecord r = mPidsSelfLocked.get( 11709 mForegroundProcesses.valueAt(i).pid); 11710 if (dumpPackage != null && (r == null 11711 || !r.pkgList.containsKey(dumpPackage))) { 11712 continue; 11713 } 11714 if (!printed) { 11715 if (needSep) pw.println(); 11716 needSep = true; 11717 pw.println(" Foreground Processes:"); 11718 printed = true; 11719 printedAnything = true; 11720 } 11721 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i)); 11722 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i)); 11723 } 11724 } 11725 } 11726 11727 if (mPersistentStartingProcesses.size() > 0) { 11728 if (needSep) pw.println(); 11729 needSep = true; 11730 printedAnything = true; 11731 pw.println(" Persisent processes that are starting:"); 11732 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 11733 "Starting Norm", "Restarting PERS", dumpPackage); 11734 } 11735 11736 if (mRemovedProcesses.size() > 0) { 11737 if (needSep) pw.println(); 11738 needSep = true; 11739 printedAnything = true; 11740 pw.println(" Processes that are being removed:"); 11741 dumpProcessList(pw, this, mRemovedProcesses, " ", 11742 "Removed Norm", "Removed PERS", dumpPackage); 11743 } 11744 11745 if (mProcessesOnHold.size() > 0) { 11746 if (needSep) pw.println(); 11747 needSep = true; 11748 printedAnything = true; 11749 pw.println(" Processes that are on old until the system is ready:"); 11750 dumpProcessList(pw, this, mProcessesOnHold, " ", 11751 "OnHold Norm", "OnHold PERS", dumpPackage); 11752 } 11753 11754 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage); 11755 11756 if (mProcessCrashTimes.getMap().size() > 0) { 11757 boolean printed = false; 11758 long now = SystemClock.uptimeMillis(); 11759 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 11760 final int NP = pmap.size(); 11761 for (int ip=0; ip<NP; ip++) { 11762 String pname = pmap.keyAt(ip); 11763 SparseArray<Long> uids = pmap.valueAt(ip); 11764 final int N = uids.size(); 11765 for (int i=0; i<N; i++) { 11766 int puid = uids.keyAt(i); 11767 ProcessRecord r = mProcessNames.get(pname, puid); 11768 if (dumpPackage != null && (r == null 11769 || !r.pkgList.containsKey(dumpPackage))) { 11770 continue; 11771 } 11772 if (!printed) { 11773 if (needSep) pw.println(); 11774 needSep = true; 11775 pw.println(" Time since processes crashed:"); 11776 printed = true; 11777 printedAnything = true; 11778 } 11779 pw.print(" Process "); pw.print(pname); 11780 pw.print(" uid "); pw.print(puid); 11781 pw.print(": last crashed "); 11782 TimeUtils.formatDuration(now-uids.valueAt(i), pw); 11783 pw.println(" ago"); 11784 } 11785 } 11786 } 11787 11788 if (mBadProcesses.getMap().size() > 0) { 11789 boolean printed = false; 11790 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap(); 11791 final int NP = pmap.size(); 11792 for (int ip=0; ip<NP; ip++) { 11793 String pname = pmap.keyAt(ip); 11794 SparseArray<BadProcessInfo> uids = pmap.valueAt(ip); 11795 final int N = uids.size(); 11796 for (int i=0; i<N; i++) { 11797 int puid = uids.keyAt(i); 11798 ProcessRecord r = mProcessNames.get(pname, puid); 11799 if (dumpPackage != null && (r == null 11800 || !r.pkgList.containsKey(dumpPackage))) { 11801 continue; 11802 } 11803 if (!printed) { 11804 if (needSep) pw.println(); 11805 needSep = true; 11806 pw.println(" Bad processes:"); 11807 printedAnything = true; 11808 } 11809 BadProcessInfo info = uids.valueAt(i); 11810 pw.print(" Bad process "); pw.print(pname); 11811 pw.print(" uid "); pw.print(puid); 11812 pw.print(": crashed at time "); pw.println(info.time); 11813 if (info.shortMsg != null) { 11814 pw.print(" Short msg: "); pw.println(info.shortMsg); 11815 } 11816 if (info.longMsg != null) { 11817 pw.print(" Long msg: "); pw.println(info.longMsg); 11818 } 11819 if (info.stack != null) { 11820 pw.println(" Stack:"); 11821 int lastPos = 0; 11822 for (int pos=0; pos<info.stack.length(); pos++) { 11823 if (info.stack.charAt(pos) == '\n') { 11824 pw.print(" "); 11825 pw.write(info.stack, lastPos, pos-lastPos); 11826 pw.println(); 11827 lastPos = pos+1; 11828 } 11829 } 11830 if (lastPos < info.stack.length()) { 11831 pw.print(" "); 11832 pw.write(info.stack, lastPos, info.stack.length()-lastPos); 11833 pw.println(); 11834 } 11835 } 11836 } 11837 } 11838 } 11839 11840 if (dumpPackage == null) { 11841 pw.println(); 11842 needSep = false; 11843 pw.println(" mStartedUsers:"); 11844 for (int i=0; i<mStartedUsers.size(); i++) { 11845 UserStartedState uss = mStartedUsers.valueAt(i); 11846 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier()); 11847 pw.print(": "); uss.dump("", pw); 11848 } 11849 pw.print(" mStartedUserArray: ["); 11850 for (int i=0; i<mStartedUserArray.length; i++) { 11851 if (i > 0) pw.print(", "); 11852 pw.print(mStartedUserArray[i]); 11853 } 11854 pw.println("]"); 11855 pw.print(" mUserLru: ["); 11856 for (int i=0; i<mUserLru.size(); i++) { 11857 if (i > 0) pw.print(", "); 11858 pw.print(mUserLru.get(i)); 11859 } 11860 pw.println("]"); 11861 if (dumpAll) { 11862 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray)); 11863 } 11864 synchronized (mUserProfileGroupIdsSelfLocked) { 11865 if (mUserProfileGroupIdsSelfLocked.size() > 0) { 11866 pw.println(" mUserProfileGroupIds:"); 11867 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) { 11868 pw.print(" User #"); 11869 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i)); 11870 pw.print(" -> profile #"); 11871 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i)); 11872 } 11873 } 11874 } 11875 } 11876 if (mHomeProcess != null && (dumpPackage == null 11877 || mHomeProcess.pkgList.containsKey(dumpPackage))) { 11878 if (needSep) { 11879 pw.println(); 11880 needSep = false; 11881 } 11882 pw.println(" mHomeProcess: " + mHomeProcess); 11883 } 11884 if (mPreviousProcess != null && (dumpPackage == null 11885 || mPreviousProcess.pkgList.containsKey(dumpPackage))) { 11886 if (needSep) { 11887 pw.println(); 11888 needSep = false; 11889 } 11890 pw.println(" mPreviousProcess: " + mPreviousProcess); 11891 } 11892 if (dumpAll) { 11893 StringBuilder sb = new StringBuilder(128); 11894 sb.append(" mPreviousProcessVisibleTime: "); 11895 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb); 11896 pw.println(sb); 11897 } 11898 if (mHeavyWeightProcess != null && (dumpPackage == null 11899 || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) { 11900 if (needSep) { 11901 pw.println(); 11902 needSep = false; 11903 } 11904 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 11905 } 11906 if (dumpPackage == null) { 11907 pw.println(" mConfiguration: " + mConfiguration); 11908 } 11909 if (dumpAll) { 11910 pw.println(" mConfigWillChange: " + getFocusedStack().mConfigWillChange); 11911 if (mCompatModePackages.getPackages().size() > 0) { 11912 boolean printed = false; 11913 for (Map.Entry<String, Integer> entry 11914 : mCompatModePackages.getPackages().entrySet()) { 11915 String pkg = entry.getKey(); 11916 int mode = entry.getValue(); 11917 if (dumpPackage != null && !dumpPackage.equals(pkg)) { 11918 continue; 11919 } 11920 if (!printed) { 11921 pw.println(" mScreenCompatPackages:"); 11922 printed = true; 11923 } 11924 pw.print(" "); pw.print(pkg); pw.print(": "); 11925 pw.print(mode); pw.println(); 11926 } 11927 } 11928 } 11929 if (dumpPackage == null) { 11930 if (mSleeping || mWentToSleep || mLockScreenShown) { 11931 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep 11932 + " mLockScreenShown " + mLockScreenShown); 11933 } 11934 if (mShuttingDown || mRunningVoice) { 11935 pw.print(" mShuttingDown=" + mShuttingDown + " mRunningVoice=" + mRunningVoice); 11936 } 11937 } 11938 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 11939 || mOrigWaitForDebugger) { 11940 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 11941 || dumpPackage.equals(mOrigDebugApp)) { 11942 if (needSep) { 11943 pw.println(); 11944 needSep = false; 11945 } 11946 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 11947 + " mDebugTransient=" + mDebugTransient 11948 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 11949 } 11950 } 11951 if (mOpenGlTraceApp != null) { 11952 if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) { 11953 if (needSep) { 11954 pw.println(); 11955 needSep = false; 11956 } 11957 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp); 11958 } 11959 } 11960 if (mProfileApp != null || mProfileProc != null || mProfileFile != null 11961 || mProfileFd != null) { 11962 if (dumpPackage == null || dumpPackage.equals(mProfileApp)) { 11963 if (needSep) { 11964 pw.println(); 11965 needSep = false; 11966 } 11967 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc); 11968 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd); 11969 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler=" 11970 + mAutoStopProfiler); 11971 } 11972 } 11973 if (dumpPackage == null) { 11974 if (mAlwaysFinishActivities || mController != null) { 11975 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities 11976 + " mController=" + mController); 11977 } 11978 if (dumpAll) { 11979 pw.println(" Total persistent processes: " + numPers); 11980 pw.println(" mProcessesReady=" + mProcessesReady 11981 + " mSystemReady=" + mSystemReady); 11982 pw.println(" mBooting=" + mBooting 11983 + " mBooted=" + mBooted 11984 + " mFactoryTest=" + mFactoryTest); 11985 pw.print(" mLastPowerCheckRealtime="); 11986 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw); 11987 pw.println(""); 11988 pw.print(" mLastPowerCheckUptime="); 11989 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 11990 pw.println(""); 11991 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep); 11992 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity); 11993 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq); 11994 pw.println(" mNumNonCachedProcs=" + mNumNonCachedProcs 11995 + " (" + mLruProcesses.size() + " total)" 11996 + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs 11997 + " mNumServiceProcs=" + mNumServiceProcs 11998 + " mNewNumServiceProcs=" + mNewNumServiceProcs); 11999 pw.println(" mAllowLowerMemLevel=" + mAllowLowerMemLevel 12000 + " mLastMemoryLevel" + mLastMemoryLevel 12001 + " mLastNumProcesses" + mLastNumProcesses); 12002 long now = SystemClock.uptimeMillis(); 12003 pw.print(" mLastIdleTime="); 12004 TimeUtils.formatDuration(now, mLastIdleTime, pw); 12005 pw.print(" mLowRamSinceLastIdle="); 12006 TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw); 12007 pw.println(); 12008 } 12009 } 12010 12011 if (!printedAnything) { 12012 pw.println(" (nothing)"); 12013 } 12014 } 12015 12016 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args, 12017 int opti, boolean needSep, boolean dumpAll, String dumpPackage) { 12018 if (mProcessesToGc.size() > 0) { 12019 boolean printed = false; 12020 long now = SystemClock.uptimeMillis(); 12021 for (int i=0; i<mProcessesToGc.size(); i++) { 12022 ProcessRecord proc = mProcessesToGc.get(i); 12023 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) { 12024 continue; 12025 } 12026 if (!printed) { 12027 if (needSep) pw.println(); 12028 needSep = true; 12029 pw.println(" Processes that are waiting to GC:"); 12030 printed = true; 12031 } 12032 pw.print(" Process "); pw.println(proc); 12033 pw.print(" lowMem="); pw.print(proc.reportLowMemory); 12034 pw.print(", last gced="); 12035 pw.print(now-proc.lastRequestedGc); 12036 pw.print(" ms ago, last lowMem="); 12037 pw.print(now-proc.lastLowMemory); 12038 pw.println(" ms ago"); 12039 12040 } 12041 } 12042 return needSep; 12043 } 12044 12045 void printOomLevel(PrintWriter pw, String name, int adj) { 12046 pw.print(" "); 12047 if (adj >= 0) { 12048 pw.print(' '); 12049 if (adj < 10) pw.print(' '); 12050 } else { 12051 if (adj > -10) pw.print(' '); 12052 } 12053 pw.print(adj); 12054 pw.print(": "); 12055 pw.print(name); 12056 pw.print(" ("); 12057 pw.print(mProcessList.getMemLevel(adj)/1024); 12058 pw.println(" kB)"); 12059 } 12060 12061 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12062 int opti, boolean dumpAll) { 12063 boolean needSep = false; 12064 12065 if (mLruProcesses.size() > 0) { 12066 if (needSep) pw.println(); 12067 needSep = true; 12068 pw.println(" OOM levels:"); 12069 printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ); 12070 printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ); 12071 printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ); 12072 printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ); 12073 printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ); 12074 printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ); 12075 printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ); 12076 printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ); 12077 printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ); 12078 printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ); 12079 printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ); 12080 printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ); 12081 printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ); 12082 12083 if (needSep) pw.println(); 12084 pw.print(" Process OOM control ("); pw.print(mLruProcesses.size()); 12085 pw.print(" total, non-act at "); 12086 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 12087 pw.print(", non-svc at "); 12088 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 12089 pw.println("):"); 12090 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", true, null); 12091 needSep = true; 12092 } 12093 12094 dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null); 12095 12096 pw.println(); 12097 pw.println(" mHomeProcess: " + mHomeProcess); 12098 pw.println(" mPreviousProcess: " + mPreviousProcess); 12099 if (mHeavyWeightProcess != null) { 12100 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 12101 } 12102 12103 return true; 12104 } 12105 12106 /** 12107 * There are three ways to call this: 12108 * - no provider specified: dump all the providers 12109 * - a flattened component name that matched an existing provider was specified as the 12110 * first arg: dump that one provider 12111 * - the first arg isn't the flattened component name of an existing provider: 12112 * dump all providers whose component contains the first arg as a substring 12113 */ 12114 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 12115 int opti, boolean dumpAll) { 12116 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 12117 } 12118 12119 static class ItemMatcher { 12120 ArrayList<ComponentName> components; 12121 ArrayList<String> strings; 12122 ArrayList<Integer> objects; 12123 boolean all; 12124 12125 ItemMatcher() { 12126 all = true; 12127 } 12128 12129 void build(String name) { 12130 ComponentName componentName = ComponentName.unflattenFromString(name); 12131 if (componentName != null) { 12132 if (components == null) { 12133 components = new ArrayList<ComponentName>(); 12134 } 12135 components.add(componentName); 12136 all = false; 12137 } else { 12138 int objectId = 0; 12139 // Not a '/' separated full component name; maybe an object ID? 12140 try { 12141 objectId = Integer.parseInt(name, 16); 12142 if (objects == null) { 12143 objects = new ArrayList<Integer>(); 12144 } 12145 objects.add(objectId); 12146 all = false; 12147 } catch (RuntimeException e) { 12148 // Not an integer; just do string match. 12149 if (strings == null) { 12150 strings = new ArrayList<String>(); 12151 } 12152 strings.add(name); 12153 all = false; 12154 } 12155 } 12156 } 12157 12158 int build(String[] args, int opti) { 12159 for (; opti<args.length; opti++) { 12160 String name = args[opti]; 12161 if ("--".equals(name)) { 12162 return opti+1; 12163 } 12164 build(name); 12165 } 12166 return opti; 12167 } 12168 12169 boolean match(Object object, ComponentName comp) { 12170 if (all) { 12171 return true; 12172 } 12173 if (components != null) { 12174 for (int i=0; i<components.size(); i++) { 12175 if (components.get(i).equals(comp)) { 12176 return true; 12177 } 12178 } 12179 } 12180 if (objects != null) { 12181 for (int i=0; i<objects.size(); i++) { 12182 if (System.identityHashCode(object) == objects.get(i)) { 12183 return true; 12184 } 12185 } 12186 } 12187 if (strings != null) { 12188 String flat = comp.flattenToString(); 12189 for (int i=0; i<strings.size(); i++) { 12190 if (flat.contains(strings.get(i))) { 12191 return true; 12192 } 12193 } 12194 } 12195 return false; 12196 } 12197 } 12198 12199 /** 12200 * There are three things that cmd can be: 12201 * - a flattened component name that matches an existing activity 12202 * - the cmd arg isn't the flattened component name of an existing activity: 12203 * dump all activity whose component contains the cmd as a substring 12204 * - A hex number of the ActivityRecord object instance. 12205 */ 12206 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, 12207 int opti, boolean dumpAll) { 12208 ArrayList<ActivityRecord> activities; 12209 12210 synchronized (this) { 12211 activities = mStackSupervisor.getDumpActivitiesLocked(name); 12212 } 12213 12214 if (activities.size() <= 0) { 12215 return false; 12216 } 12217 12218 String[] newArgs = new String[args.length - opti]; 12219 System.arraycopy(args, opti, newArgs, 0, args.length - opti); 12220 12221 TaskRecord lastTask = null; 12222 boolean needSep = false; 12223 for (int i=activities.size()-1; i>=0; i--) { 12224 ActivityRecord r = activities.get(i); 12225 if (needSep) { 12226 pw.println(); 12227 } 12228 needSep = true; 12229 synchronized (this) { 12230 if (lastTask != r.task) { 12231 lastTask = r.task; 12232 pw.print("TASK "); pw.print(lastTask.affinity); 12233 pw.print(" id="); pw.println(lastTask.taskId); 12234 if (dumpAll) { 12235 lastTask.dump(pw, " "); 12236 } 12237 } 12238 } 12239 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll); 12240 } 12241 return true; 12242 } 12243 12244 /** 12245 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if 12246 * there is a thread associated with the activity. 12247 */ 12248 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, 12249 final ActivityRecord r, String[] args, boolean dumpAll) { 12250 String innerPrefix = prefix + " "; 12251 synchronized (this) { 12252 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName); 12253 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r))); 12254 pw.print(" pid="); 12255 if (r.app != null) pw.println(r.app.pid); 12256 else pw.println("(not running)"); 12257 if (dumpAll) { 12258 r.dump(pw, innerPrefix); 12259 } 12260 } 12261 if (r.app != null && r.app.thread != null) { 12262 // flush anything that is already in the PrintWriter since the thread is going 12263 // to write to the file descriptor directly 12264 pw.flush(); 12265 try { 12266 TransferPipe tp = new TransferPipe(); 12267 try { 12268 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), 12269 r.appToken, innerPrefix, args); 12270 tp.go(fd); 12271 } finally { 12272 tp.kill(); 12273 } 12274 } catch (IOException e) { 12275 pw.println(innerPrefix + "Failure while dumping the activity: " + e); 12276 } catch (RemoteException e) { 12277 pw.println(innerPrefix + "Got a RemoteException while dumping the activity"); 12278 } 12279 } 12280 } 12281 12282 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12283 int opti, boolean dumpAll, String dumpPackage) { 12284 boolean needSep = false; 12285 boolean onlyHistory = false; 12286 boolean printedAnything = false; 12287 12288 if ("history".equals(dumpPackage)) { 12289 if (opti < args.length && "-s".equals(args[opti])) { 12290 dumpAll = false; 12291 } 12292 onlyHistory = true; 12293 dumpPackage = null; 12294 } 12295 12296 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 12297 if (!onlyHistory && dumpAll) { 12298 if (mRegisteredReceivers.size() > 0) { 12299 boolean printed = false; 12300 Iterator it = mRegisteredReceivers.values().iterator(); 12301 while (it.hasNext()) { 12302 ReceiverList r = (ReceiverList)it.next(); 12303 if (dumpPackage != null && (r.app == null || 12304 !dumpPackage.equals(r.app.info.packageName))) { 12305 continue; 12306 } 12307 if (!printed) { 12308 pw.println(" Registered Receivers:"); 12309 needSep = true; 12310 printed = true; 12311 printedAnything = true; 12312 } 12313 pw.print(" * "); pw.println(r); 12314 r.dump(pw, " "); 12315 } 12316 } 12317 12318 if (mReceiverResolver.dump(pw, needSep ? 12319 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 12320 " ", dumpPackage, false)) { 12321 needSep = true; 12322 printedAnything = true; 12323 } 12324 } 12325 12326 for (BroadcastQueue q : mBroadcastQueues) { 12327 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 12328 printedAnything |= needSep; 12329 } 12330 12331 needSep = true; 12332 12333 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 12334 for (int user=0; user<mStickyBroadcasts.size(); user++) { 12335 if (needSep) { 12336 pw.println(); 12337 } 12338 needSep = true; 12339 printedAnything = true; 12340 pw.print(" Sticky broadcasts for user "); 12341 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 12342 StringBuilder sb = new StringBuilder(128); 12343 for (Map.Entry<String, ArrayList<Intent>> ent 12344 : mStickyBroadcasts.valueAt(user).entrySet()) { 12345 pw.print(" * Sticky action "); pw.print(ent.getKey()); 12346 if (dumpAll) { 12347 pw.println(":"); 12348 ArrayList<Intent> intents = ent.getValue(); 12349 final int N = intents.size(); 12350 for (int i=0; i<N; i++) { 12351 sb.setLength(0); 12352 sb.append(" Intent: "); 12353 intents.get(i).toShortString(sb, false, true, false, false); 12354 pw.println(sb.toString()); 12355 Bundle bundle = intents.get(i).getExtras(); 12356 if (bundle != null) { 12357 pw.print(" "); 12358 pw.println(bundle.toString()); 12359 } 12360 } 12361 } else { 12362 pw.println(""); 12363 } 12364 } 12365 } 12366 } 12367 12368 if (!onlyHistory && dumpAll) { 12369 pw.println(); 12370 for (BroadcastQueue queue : mBroadcastQueues) { 12371 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 12372 + queue.mBroadcastsScheduled); 12373 } 12374 pw.println(" mHandler:"); 12375 mHandler.dump(new PrintWriterPrinter(pw), " "); 12376 needSep = true; 12377 printedAnything = true; 12378 } 12379 12380 if (!printedAnything) { 12381 pw.println(" (nothing)"); 12382 } 12383 } 12384 12385 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12386 int opti, boolean dumpAll, String dumpPackage) { 12387 boolean needSep; 12388 boolean printedAnything = false; 12389 12390 ItemMatcher matcher = new ItemMatcher(); 12391 matcher.build(args, opti); 12392 12393 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 12394 12395 needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 12396 printedAnything |= needSep; 12397 12398 if (mLaunchingProviders.size() > 0) { 12399 boolean printed = false; 12400 for (int i=mLaunchingProviders.size()-1; i>=0; i--) { 12401 ContentProviderRecord r = mLaunchingProviders.get(i); 12402 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 12403 continue; 12404 } 12405 if (!printed) { 12406 if (needSep) pw.println(); 12407 needSep = true; 12408 pw.println(" Launching content providers:"); 12409 printed = true; 12410 printedAnything = true; 12411 } 12412 pw.print(" Launching #"); pw.print(i); pw.print(": "); 12413 pw.println(r); 12414 } 12415 } 12416 12417 if (mGrantedUriPermissions.size() > 0) { 12418 boolean printed = false; 12419 int dumpUid = -2; 12420 if (dumpPackage != null) { 12421 try { 12422 dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0); 12423 } catch (NameNotFoundException e) { 12424 dumpUid = -1; 12425 } 12426 } 12427 for (int i=0; i<mGrantedUriPermissions.size(); i++) { 12428 int uid = mGrantedUriPermissions.keyAt(i); 12429 if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) { 12430 continue; 12431 } 12432 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 12433 if (!printed) { 12434 if (needSep) pw.println(); 12435 needSep = true; 12436 pw.println(" Granted Uri Permissions:"); 12437 printed = true; 12438 printedAnything = true; 12439 } 12440 pw.print(" * UID "); pw.print(uid); pw.println(" holds:"); 12441 for (UriPermission perm : perms.values()) { 12442 pw.print(" "); pw.println(perm); 12443 if (dumpAll) { 12444 perm.dump(pw, " "); 12445 } 12446 } 12447 } 12448 } 12449 12450 if (!printedAnything) { 12451 pw.println(" (nothing)"); 12452 } 12453 } 12454 12455 void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 12456 int opti, boolean dumpAll, String dumpPackage) { 12457 boolean printed = false; 12458 12459 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)"); 12460 12461 if (mIntentSenderRecords.size() > 0) { 12462 Iterator<WeakReference<PendingIntentRecord>> it 12463 = mIntentSenderRecords.values().iterator(); 12464 while (it.hasNext()) { 12465 WeakReference<PendingIntentRecord> ref = it.next(); 12466 PendingIntentRecord rec = ref != null ? ref.get(): null; 12467 if (dumpPackage != null && (rec == null 12468 || !dumpPackage.equals(rec.key.packageName))) { 12469 continue; 12470 } 12471 printed = true; 12472 if (rec != null) { 12473 pw.print(" * "); pw.println(rec); 12474 if (dumpAll) { 12475 rec.dump(pw, " "); 12476 } 12477 } else { 12478 pw.print(" * "); pw.println(ref); 12479 } 12480 } 12481 } 12482 12483 if (!printed) { 12484 pw.println(" (nothing)"); 12485 } 12486 } 12487 12488 private static final int dumpProcessList(PrintWriter pw, 12489 ActivityManagerService service, List list, 12490 String prefix, String normalLabel, String persistentLabel, 12491 String dumpPackage) { 12492 int numPers = 0; 12493 final int N = list.size()-1; 12494 for (int i=N; i>=0; i--) { 12495 ProcessRecord r = (ProcessRecord)list.get(i); 12496 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 12497 continue; 12498 } 12499 pw.println(String.format("%s%s #%2d: %s", 12500 prefix, (r.persistent ? persistentLabel : normalLabel), 12501 i, r.toString())); 12502 if (r.persistent) { 12503 numPers++; 12504 } 12505 } 12506 return numPers; 12507 } 12508 12509 private static final boolean dumpProcessOomList(PrintWriter pw, 12510 ActivityManagerService service, List<ProcessRecord> origList, 12511 String prefix, String normalLabel, String persistentLabel, 12512 boolean inclDetails, String dumpPackage) { 12513 12514 ArrayList<Pair<ProcessRecord, Integer>> list 12515 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size()); 12516 for (int i=0; i<origList.size(); i++) { 12517 ProcessRecord r = origList.get(i); 12518 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 12519 continue; 12520 } 12521 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i)); 12522 } 12523 12524 if (list.size() <= 0) { 12525 return false; 12526 } 12527 12528 Comparator<Pair<ProcessRecord, Integer>> comparator 12529 = new Comparator<Pair<ProcessRecord, Integer>>() { 12530 @Override 12531 public int compare(Pair<ProcessRecord, Integer> object1, 12532 Pair<ProcessRecord, Integer> object2) { 12533 if (object1.first.setAdj != object2.first.setAdj) { 12534 return object1.first.setAdj > object2.first.setAdj ? -1 : 1; 12535 } 12536 if (object1.second.intValue() != object2.second.intValue()) { 12537 return object1.second.intValue() > object2.second.intValue() ? -1 : 1; 12538 } 12539 return 0; 12540 } 12541 }; 12542 12543 Collections.sort(list, comparator); 12544 12545 final long curRealtime = SystemClock.elapsedRealtime(); 12546 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime; 12547 final long curUptime = SystemClock.uptimeMillis(); 12548 final long uptimeSince = curUptime - service.mLastPowerCheckUptime; 12549 12550 for (int i=list.size()-1; i>=0; i--) { 12551 ProcessRecord r = list.get(i).first; 12552 String oomAdj = ProcessList.makeOomAdjString(r.setAdj); 12553 char schedGroup; 12554 switch (r.setSchedGroup) { 12555 case Process.THREAD_GROUP_BG_NONINTERACTIVE: 12556 schedGroup = 'B'; 12557 break; 12558 case Process.THREAD_GROUP_DEFAULT: 12559 schedGroup = 'F'; 12560 break; 12561 default: 12562 schedGroup = '?'; 12563 break; 12564 } 12565 char foreground; 12566 if (r.foregroundActivities) { 12567 foreground = 'A'; 12568 } else if (r.foregroundServices) { 12569 foreground = 'S'; 12570 } else { 12571 foreground = ' '; 12572 } 12573 String procState = ProcessList.makeProcStateString(r.curProcState); 12574 pw.print(prefix); 12575 pw.print(r.persistent ? persistentLabel : normalLabel); 12576 pw.print(" #"); 12577 int num = (origList.size()-1)-list.get(i).second; 12578 if (num < 10) pw.print(' '); 12579 pw.print(num); 12580 pw.print(": "); 12581 pw.print(oomAdj); 12582 pw.print(' '); 12583 pw.print(schedGroup); 12584 pw.print('/'); 12585 pw.print(foreground); 12586 pw.print('/'); 12587 pw.print(procState); 12588 pw.print(" trm:"); 12589 if (r.trimMemoryLevel < 10) pw.print(' '); 12590 pw.print(r.trimMemoryLevel); 12591 pw.print(' '); 12592 pw.print(r.toShortString()); 12593 pw.print(" ("); 12594 pw.print(r.adjType); 12595 pw.println(')'); 12596 if (r.adjSource != null || r.adjTarget != null) { 12597 pw.print(prefix); 12598 pw.print(" "); 12599 if (r.adjTarget instanceof ComponentName) { 12600 pw.print(((ComponentName)r.adjTarget).flattenToShortString()); 12601 } else if (r.adjTarget != null) { 12602 pw.print(r.adjTarget.toString()); 12603 } else { 12604 pw.print("{null}"); 12605 } 12606 pw.print("<="); 12607 if (r.adjSource instanceof ProcessRecord) { 12608 pw.print("Proc{"); 12609 pw.print(((ProcessRecord)r.adjSource).toShortString()); 12610 pw.println("}"); 12611 } else if (r.adjSource != null) { 12612 pw.println(r.adjSource.toString()); 12613 } else { 12614 pw.println("{null}"); 12615 } 12616 } 12617 if (inclDetails) { 12618 pw.print(prefix); 12619 pw.print(" "); 12620 pw.print("oom: max="); pw.print(r.maxAdj); 12621 pw.print(" curRaw="); pw.print(r.curRawAdj); 12622 pw.print(" setRaw="); pw.print(r.setRawAdj); 12623 pw.print(" cur="); pw.print(r.curAdj); 12624 pw.print(" set="); pw.println(r.setAdj); 12625 pw.print(prefix); 12626 pw.print(" "); 12627 pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState)); 12628 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState)); 12629 pw.print(" lastPss="); pw.print(r.lastPss); 12630 pw.print(" lastCachedPss="); pw.println(r.lastCachedPss); 12631 pw.print(prefix); 12632 pw.print(" "); 12633 pw.print("cached="); pw.print(r.cached); 12634 pw.print(" empty="); pw.print(r.empty); 12635 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient); 12636 12637 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 12638 if (r.lastWakeTime != 0) { 12639 long wtime; 12640 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics(); 12641 synchronized (stats) { 12642 wtime = stats.getProcessWakeTime(r.info.uid, 12643 r.pid, curRealtime); 12644 } 12645 long timeUsed = wtime - r.lastWakeTime; 12646 pw.print(prefix); 12647 pw.print(" "); 12648 pw.print("keep awake over "); 12649 TimeUtils.formatDuration(realtimeSince, pw); 12650 pw.print(" used "); 12651 TimeUtils.formatDuration(timeUsed, pw); 12652 pw.print(" ("); 12653 pw.print((timeUsed*100)/realtimeSince); 12654 pw.println("%)"); 12655 } 12656 if (r.lastCpuTime != 0) { 12657 long timeUsed = r.curCpuTime - r.lastCpuTime; 12658 pw.print(prefix); 12659 pw.print(" "); 12660 pw.print("run cpu over "); 12661 TimeUtils.formatDuration(uptimeSince, pw); 12662 pw.print(" used "); 12663 TimeUtils.formatDuration(timeUsed, pw); 12664 pw.print(" ("); 12665 pw.print((timeUsed*100)/uptimeSince); 12666 pw.println("%)"); 12667 } 12668 } 12669 } 12670 } 12671 return true; 12672 } 12673 12674 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) { 12675 ArrayList<ProcessRecord> procs; 12676 synchronized (this) { 12677 if (args != null && args.length > start 12678 && args[start].charAt(0) != '-') { 12679 procs = new ArrayList<ProcessRecord>(); 12680 int pid = -1; 12681 try { 12682 pid = Integer.parseInt(args[start]); 12683 } catch (NumberFormatException e) { 12684 } 12685 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12686 ProcessRecord proc = mLruProcesses.get(i); 12687 if (proc.pid == pid) { 12688 procs.add(proc); 12689 } else if (proc.processName.equals(args[start])) { 12690 procs.add(proc); 12691 } 12692 } 12693 if (procs.size() <= 0) { 12694 return null; 12695 } 12696 } else { 12697 procs = new ArrayList<ProcessRecord>(mLruProcesses); 12698 } 12699 } 12700 return procs; 12701 } 12702 12703 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 12704 PrintWriter pw, String[] args) { 12705 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 12706 if (procs == null) { 12707 pw.println("No process found for: " + args[0]); 12708 return; 12709 } 12710 12711 long uptime = SystemClock.uptimeMillis(); 12712 long realtime = SystemClock.elapsedRealtime(); 12713 pw.println("Applications Graphics Acceleration Info:"); 12714 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12715 12716 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12717 ProcessRecord r = procs.get(i); 12718 if (r.thread != null) { 12719 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **"); 12720 pw.flush(); 12721 try { 12722 TransferPipe tp = new TransferPipe(); 12723 try { 12724 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args); 12725 tp.go(fd); 12726 } finally { 12727 tp.kill(); 12728 } 12729 } catch (IOException e) { 12730 pw.println("Failure while dumping the app: " + r); 12731 pw.flush(); 12732 } catch (RemoteException e) { 12733 pw.println("Got a RemoteException while dumping the app " + r); 12734 pw.flush(); 12735 } 12736 } 12737 } 12738 } 12739 12740 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 12741 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args); 12742 if (procs == null) { 12743 pw.println("No process found for: " + args[0]); 12744 return; 12745 } 12746 12747 pw.println("Applications Database Info:"); 12748 12749 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 12750 ProcessRecord r = procs.get(i); 12751 if (r.thread != null) { 12752 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **"); 12753 pw.flush(); 12754 try { 12755 TransferPipe tp = new TransferPipe(); 12756 try { 12757 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args); 12758 tp.go(fd); 12759 } finally { 12760 tp.kill(); 12761 } 12762 } catch (IOException e) { 12763 pw.println("Failure while dumping the app: " + r); 12764 pw.flush(); 12765 } catch (RemoteException e) { 12766 pw.println("Got a RemoteException while dumping the app " + r); 12767 pw.flush(); 12768 } 12769 } 12770 } 12771 } 12772 12773 final static class MemItem { 12774 final boolean isProc; 12775 final String label; 12776 final String shortLabel; 12777 final long pss; 12778 final int id; 12779 final boolean hasActivities; 12780 ArrayList<MemItem> subitems; 12781 12782 public MemItem(String _label, String _shortLabel, long _pss, int _id, 12783 boolean _hasActivities) { 12784 isProc = true; 12785 label = _label; 12786 shortLabel = _shortLabel; 12787 pss = _pss; 12788 id = _id; 12789 hasActivities = _hasActivities; 12790 } 12791 12792 public MemItem(String _label, String _shortLabel, long _pss, int _id) { 12793 isProc = false; 12794 label = _label; 12795 shortLabel = _shortLabel; 12796 pss = _pss; 12797 id = _id; 12798 hasActivities = false; 12799 } 12800 } 12801 12802 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 12803 ArrayList<MemItem> items, boolean sort, boolean isCompact) { 12804 if (sort && !isCompact) { 12805 Collections.sort(items, new Comparator<MemItem>() { 12806 @Override 12807 public int compare(MemItem lhs, MemItem rhs) { 12808 if (lhs.pss < rhs.pss) { 12809 return 1; 12810 } else if (lhs.pss > rhs.pss) { 12811 return -1; 12812 } 12813 return 0; 12814 } 12815 }); 12816 } 12817 12818 for (int i=0; i<items.size(); i++) { 12819 MemItem mi = items.get(i); 12820 if (!isCompact) { 12821 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label); 12822 } else if (mi.isProc) { 12823 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 12824 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); 12825 pw.println(mi.hasActivities ? ",a" : ",e"); 12826 } else { 12827 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 12828 pw.println(mi.pss); 12829 } 12830 if (mi.subitems != null) { 12831 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 12832 true, isCompact); 12833 } 12834 } 12835 } 12836 12837 // These are in KB. 12838 static final long[] DUMP_MEM_BUCKETS = new long[] { 12839 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 12840 120*1024, 160*1024, 200*1024, 12841 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 12842 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 12843 }; 12844 12845 static final void appendMemBucket(StringBuilder out, long memKB, String label, 12846 boolean stackLike) { 12847 int start = label.lastIndexOf('.'); 12848 if (start >= 0) start++; 12849 else start = 0; 12850 int end = label.length(); 12851 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 12852 if (DUMP_MEM_BUCKETS[i] >= memKB) { 12853 long bucket = DUMP_MEM_BUCKETS[i]/1024; 12854 out.append(bucket); 12855 out.append(stackLike ? "MB." : "MB "); 12856 out.append(label, start, end); 12857 return; 12858 } 12859 } 12860 out.append(memKB/1024); 12861 out.append(stackLike ? "MB." : "MB "); 12862 out.append(label, start, end); 12863 } 12864 12865 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 12866 ProcessList.NATIVE_ADJ, 12867 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ, 12868 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, 12869 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 12870 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 12871 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ 12872 }; 12873 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 12874 "Native", 12875 "System", "Persistent", "Foreground", 12876 "Visible", "Perceptible", 12877 "Heavy Weight", "Backup", 12878 "A Services", "Home", 12879 "Previous", "B Services", "Cached" 12880 }; 12881 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 12882 "native", 12883 "sys", "pers", "fore", 12884 "vis", "percept", 12885 "heavy", "backup", 12886 "servicea", "home", 12887 "prev", "serviceb", "cached" 12888 }; 12889 12890 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 12891 long realtime, boolean isCheckinRequest, boolean isCompact) { 12892 if (isCheckinRequest || isCompact) { 12893 // short checkin version 12894 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 12895 } else { 12896 pw.println("Applications Memory Usage (kB):"); 12897 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 12898 } 12899 } 12900 12901 final void dumpApplicationMemoryUsage(FileDescriptor fd, 12902 PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) { 12903 boolean dumpDetails = false; 12904 boolean dumpFullDetails = false; 12905 boolean dumpDalvik = false; 12906 boolean oomOnly = false; 12907 boolean isCompact = false; 12908 boolean localOnly = false; 12909 12910 int opti = 0; 12911 while (opti < args.length) { 12912 String opt = args[opti]; 12913 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12914 break; 12915 } 12916 opti++; 12917 if ("-a".equals(opt)) { 12918 dumpDetails = true; 12919 dumpFullDetails = true; 12920 dumpDalvik = true; 12921 } else if ("-d".equals(opt)) { 12922 dumpDalvik = true; 12923 } else if ("-c".equals(opt)) { 12924 isCompact = true; 12925 } else if ("--oom".equals(opt)) { 12926 oomOnly = true; 12927 } else if ("--local".equals(opt)) { 12928 localOnly = true; 12929 } else if ("-h".equals(opt)) { 12930 pw.println("meminfo dump options: [-a] [-d] [-c] [--oom] [process]"); 12931 pw.println(" -a: include all available information for each process."); 12932 pw.println(" -d: include dalvik details when dumping process details."); 12933 pw.println(" -c: dump in a compact machine-parseable representation."); 12934 pw.println(" --oom: only show processes organized by oom adj."); 12935 pw.println(" --local: only collect details locally, don't call process."); 12936 pw.println("If [process] is specified it can be the name or "); 12937 pw.println("pid of a specific process to dump."); 12938 return; 12939 } else { 12940 pw.println("Unknown argument: " + opt + "; use -h for help"); 12941 } 12942 } 12943 12944 final boolean isCheckinRequest = scanArgs(args, "--checkin"); 12945 long uptime = SystemClock.uptimeMillis(); 12946 long realtime = SystemClock.elapsedRealtime(); 12947 final long[] tmpLong = new long[1]; 12948 12949 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args); 12950 if (procs == null) { 12951 // No Java processes. Maybe they want to print a native process. 12952 if (args != null && args.length > opti 12953 && args[opti].charAt(0) != '-') { 12954 ArrayList<ProcessCpuTracker.Stats> nativeProcs 12955 = new ArrayList<ProcessCpuTracker.Stats>(); 12956 updateCpuStatsNow(); 12957 int findPid = -1; 12958 try { 12959 findPid = Integer.parseInt(args[opti]); 12960 } catch (NumberFormatException e) { 12961 } 12962 synchronized (mProcessCpuThread) { 12963 final int N = mProcessCpuTracker.countStats(); 12964 for (int i=0; i<N; i++) { 12965 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 12966 if (st.pid == findPid || (st.baseName != null 12967 && st.baseName.equals(args[opti]))) { 12968 nativeProcs.add(st); 12969 } 12970 } 12971 } 12972 if (nativeProcs.size() > 0) { 12973 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, 12974 isCompact); 12975 Debug.MemoryInfo mi = null; 12976 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 12977 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 12978 final int pid = r.pid; 12979 if (!isCheckinRequest && dumpDetails) { 12980 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **"); 12981 } 12982 if (mi == null) { 12983 mi = new Debug.MemoryInfo(); 12984 } 12985 if (dumpDetails || (!brief && !oomOnly)) { 12986 Debug.getMemoryInfo(pid, mi); 12987 } else { 12988 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 12989 mi.dalvikPrivateDirty = (int)tmpLong[0]; 12990 } 12991 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 12992 dumpDalvik, pid, r.baseName, 0, 0, 0, 0, 0, 0); 12993 if (isCheckinRequest) { 12994 pw.println(); 12995 } 12996 } 12997 return; 12998 } 12999 } 13000 pw.println("No process found for: " + args[opti]); 13001 return; 13002 } 13003 13004 if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest)) { 13005 dumpDetails = true; 13006 } 13007 13008 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact); 13009 13010 String[] innerArgs = new String[args.length-opti]; 13011 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 13012 13013 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 13014 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 13015 long nativePss=0, dalvikPss=0, otherPss=0; 13016 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 13017 13018 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 13019 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 13020 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 13021 13022 long totalPss = 0; 13023 long cachedPss = 0; 13024 13025 Debug.MemoryInfo mi = null; 13026 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 13027 final ProcessRecord r = procs.get(i); 13028 final IApplicationThread thread; 13029 final int pid; 13030 final int oomAdj; 13031 final boolean hasActivities; 13032 synchronized (this) { 13033 thread = r.thread; 13034 pid = r.pid; 13035 oomAdj = r.getSetAdjWithServices(); 13036 hasActivities = r.activities.size() > 0; 13037 } 13038 if (thread != null) { 13039 if (!isCheckinRequest && dumpDetails) { 13040 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 13041 } 13042 if (mi == null) { 13043 mi = new Debug.MemoryInfo(); 13044 } 13045 if (dumpDetails || (!brief && !oomOnly)) { 13046 Debug.getMemoryInfo(pid, mi); 13047 } else { 13048 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong); 13049 mi.dalvikPrivateDirty = (int)tmpLong[0]; 13050 } 13051 if (dumpDetails) { 13052 if (localOnly) { 13053 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 13054 dumpDalvik, pid, r.processName, 0, 0, 0, 0, 0, 0); 13055 if (isCheckinRequest) { 13056 pw.println(); 13057 } 13058 } else { 13059 try { 13060 pw.flush(); 13061 thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails, 13062 dumpDalvik, innerArgs); 13063 } catch (RemoteException e) { 13064 if (!isCheckinRequest) { 13065 pw.println("Got RemoteException!"); 13066 pw.flush(); 13067 } 13068 } 13069 } 13070 } 13071 13072 final long myTotalPss = mi.getTotalPss(); 13073 final long myTotalUss = mi.getTotalUss(); 13074 13075 synchronized (this) { 13076 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 13077 // Record this for posterity if the process has been stable. 13078 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList); 13079 } 13080 } 13081 13082 if (!isCheckinRequest && mi != null) { 13083 totalPss += myTotalPss; 13084 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 13085 (hasActivities ? " / activities)" : ")"), 13086 r.processName, myTotalPss, pid, hasActivities); 13087 procMems.add(pssItem); 13088 procMemsMap.put(pid, pssItem); 13089 13090 nativePss += mi.nativePss; 13091 dalvikPss += mi.dalvikPss; 13092 otherPss += mi.otherPss; 13093 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13094 long mem = mi.getOtherPss(j); 13095 miscPss[j] += mem; 13096 otherPss -= mem; 13097 } 13098 13099 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 13100 cachedPss += myTotalPss; 13101 } 13102 13103 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 13104 if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex] 13105 || oomIndex == (oomPss.length-1)) { 13106 oomPss[oomIndex] += myTotalPss; 13107 if (oomProcs[oomIndex] == null) { 13108 oomProcs[oomIndex] = new ArrayList<MemItem>(); 13109 } 13110 oomProcs[oomIndex].add(pssItem); 13111 break; 13112 } 13113 } 13114 } 13115 } 13116 } 13117 13118 long nativeProcTotalPss = 0; 13119 13120 if (!isCheckinRequest && procs.size() > 1) { 13121 // If we are showing aggregations, also look for native processes to 13122 // include so that our aggregations are more accurate. 13123 updateCpuStatsNow(); 13124 synchronized (mProcessCpuThread) { 13125 final int N = mProcessCpuTracker.countStats(); 13126 for (int i=0; i<N; i++) { 13127 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 13128 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 13129 if (mi == null) { 13130 mi = new Debug.MemoryInfo(); 13131 } 13132 if (!brief && !oomOnly) { 13133 Debug.getMemoryInfo(st.pid, mi); 13134 } else { 13135 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong); 13136 mi.nativePrivateDirty = (int)tmpLong[0]; 13137 } 13138 13139 final long myTotalPss = mi.getTotalPss(); 13140 totalPss += myTotalPss; 13141 nativeProcTotalPss += myTotalPss; 13142 13143 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 13144 st.name, myTotalPss, st.pid, false); 13145 procMems.add(pssItem); 13146 13147 nativePss += mi.nativePss; 13148 dalvikPss += mi.dalvikPss; 13149 otherPss += mi.otherPss; 13150 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13151 long mem = mi.getOtherPss(j); 13152 miscPss[j] += mem; 13153 otherPss -= mem; 13154 } 13155 oomPss[0] += myTotalPss; 13156 if (oomProcs[0] == null) { 13157 oomProcs[0] = new ArrayList<MemItem>(); 13158 } 13159 oomProcs[0].add(pssItem); 13160 } 13161 } 13162 } 13163 13164 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 13165 13166 catMems.add(new MemItem("Native", "Native", nativePss, -1)); 13167 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2)); 13168 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3)); 13169 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 13170 String label = Debug.MemoryInfo.getOtherLabel(j); 13171 catMems.add(new MemItem(label, label, miscPss[j], j)); 13172 } 13173 13174 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 13175 for (int j=0; j<oomPss.length; j++) { 13176 if (oomPss[j] != 0) { 13177 String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 13178 : DUMP_MEM_OOM_LABEL[j]; 13179 MemItem item = new MemItem(label, label, oomPss[j], 13180 DUMP_MEM_OOM_ADJ[j]); 13181 item.subitems = oomProcs[j]; 13182 oomMems.add(item); 13183 } 13184 } 13185 13186 if (!brief && !oomOnly && !isCompact) { 13187 pw.println(); 13188 pw.println("Total PSS by process:"); 13189 dumpMemItems(pw, " ", "proc", procMems, true, isCompact); 13190 pw.println(); 13191 } 13192 if (!isCompact) { 13193 pw.println("Total PSS by OOM adjustment:"); 13194 } 13195 dumpMemItems(pw, " ", "oom", oomMems, false, isCompact); 13196 if (!brief && !oomOnly) { 13197 PrintWriter out = categoryPw != null ? categoryPw : pw; 13198 if (!isCompact) { 13199 out.println(); 13200 out.println("Total PSS by category:"); 13201 } 13202 dumpMemItems(out, " ", "cat", catMems, true, isCompact); 13203 } 13204 if (!isCompact) { 13205 pw.println(); 13206 } 13207 MemInfoReader memInfo = new MemInfoReader(); 13208 memInfo.readMemInfo(); 13209 if (nativeProcTotalPss > 0) { 13210 synchronized (this) { 13211 mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(), 13212 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(), 13213 memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()+memInfo.getSlabSizeKb(), 13214 nativeProcTotalPss); 13215 } 13216 } 13217 if (!brief) { 13218 if (!isCompact) { 13219 pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb()); 13220 pw.print(" kB (status "); 13221 switch (mLastMemoryLevel) { 13222 case ProcessStats.ADJ_MEM_FACTOR_NORMAL: 13223 pw.println("normal)"); 13224 break; 13225 case ProcessStats.ADJ_MEM_FACTOR_MODERATE: 13226 pw.println("moderate)"); 13227 break; 13228 case ProcessStats.ADJ_MEM_FACTOR_LOW: 13229 pw.println("low)"); 13230 break; 13231 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 13232 pw.println("critical)"); 13233 break; 13234 default: 13235 pw.print(mLastMemoryLevel); 13236 pw.println(")"); 13237 break; 13238 } 13239 pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb() 13240 + memInfo.getFreeSizeKb()); pw.print(" kB ("); 13241 pw.print(cachedPss); pw.print(" cached pss + "); 13242 pw.print(memInfo.getCachedSizeKb()); pw.print(" cached + "); 13243 pw.print(memInfo.getFreeSizeKb()); pw.println(" free)"); 13244 } else { 13245 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 13246 pw.print(cachedPss + memInfo.getCachedSizeKb() 13247 + memInfo.getFreeSizeKb()); pw.print(","); 13248 pw.println(totalPss - cachedPss); 13249 } 13250 } 13251 if (!isCompact) { 13252 pw.print(" Used RAM: "); pw.print(totalPss - cachedPss 13253 + memInfo.getBuffersSizeKb() + memInfo.getShmemSizeKb() 13254 + memInfo.getSlabSizeKb()); pw.print(" kB ("); 13255 pw.print(totalPss - cachedPss); pw.print(" used pss + "); 13256 pw.print(memInfo.getBuffersSizeKb()); pw.print(" buffers + "); 13257 pw.print(memInfo.getShmemSizeKb()); pw.print(" shmem + "); 13258 pw.print(memInfo.getSlabSizeKb()); pw.println(" slab)"); 13259 pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb() 13260 - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 13261 - memInfo.getBuffersSizeKb() - memInfo.getShmemSizeKb() 13262 - memInfo.getSlabSizeKb()); pw.println(" kB"); 13263 } 13264 if (!brief) { 13265 if (memInfo.getZramTotalSizeKb() != 0) { 13266 if (!isCompact) { 13267 pw.print(" ZRAM: "); pw.print(memInfo.getZramTotalSizeKb()); 13268 pw.print(" kB physical used for "); 13269 pw.print(memInfo.getSwapTotalSizeKb() 13270 - memInfo.getSwapFreeSizeKb()); 13271 pw.print(" kB in swap ("); 13272 pw.print(memInfo.getSwapTotalSizeKb()); 13273 pw.println(" kB total swap)"); 13274 } else { 13275 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 13276 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 13277 pw.println(memInfo.getSwapFreeSizeKb()); 13278 } 13279 } 13280 final int[] SINGLE_LONG_FORMAT = new int[] { 13281 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG 13282 }; 13283 long[] longOut = new long[1]; 13284 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared", 13285 SINGLE_LONG_FORMAT, null, longOut, null); 13286 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 13287 longOut[0] = 0; 13288 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing", 13289 SINGLE_LONG_FORMAT, null, longOut, null); 13290 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024; 13291 longOut[0] = 0; 13292 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared", 13293 SINGLE_LONG_FORMAT, null, longOut, null); 13294 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024; 13295 longOut[0] = 0; 13296 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile", 13297 SINGLE_LONG_FORMAT, null, longOut, null); 13298 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024; 13299 if (!isCompact) { 13300 if (sharing != 0 || shared != 0 || unshared != 0 || voltile != 0) { 13301 pw.print(" KSM: "); pw.print(sharing); 13302 pw.print(" kB saved from shared "); 13303 pw.print(shared); pw.println(" kB"); 13304 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; "); 13305 pw.print(voltile); pw.println(" kB volatile"); 13306 } 13307 pw.print(" Tuning: "); 13308 pw.print(ActivityManager.staticGetMemoryClass()); 13309 pw.print(" (large "); 13310 pw.print(ActivityManager.staticGetLargeMemoryClass()); 13311 pw.print("), oom "); 13312 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 13313 pw.print(" kB"); 13314 pw.print(", restore limit "); 13315 pw.print(mProcessList.getCachedRestoreThresholdKb()); 13316 pw.print(" kB"); 13317 if (ActivityManager.isLowRamDeviceStatic()) { 13318 pw.print(" (low-ram)"); 13319 } 13320 if (ActivityManager.isHighEndGfx()) { 13321 pw.print(" (high-end-gfx)"); 13322 } 13323 pw.println(); 13324 } else { 13325 pw.print("ksm,"); pw.print(sharing); pw.print(","); 13326 pw.print(shared); pw.print(","); pw.print(unshared); pw.print(","); 13327 pw.println(voltile); 13328 pw.print("tuning,"); 13329 pw.print(ActivityManager.staticGetMemoryClass()); 13330 pw.print(','); 13331 pw.print(ActivityManager.staticGetLargeMemoryClass()); 13332 pw.print(','); 13333 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 13334 if (ActivityManager.isLowRamDeviceStatic()) { 13335 pw.print(",low-ram"); 13336 } 13337 if (ActivityManager.isHighEndGfx()) { 13338 pw.print(",high-end-gfx"); 13339 } 13340 pw.println(); 13341 } 13342 } 13343 } 13344 } 13345 13346 /** 13347 * Searches array of arguments for the specified string 13348 * @param args array of argument strings 13349 * @param value value to search for 13350 * @return true if the value is contained in the array 13351 */ 13352 private static boolean scanArgs(String[] args, String value) { 13353 if (args != null) { 13354 for (String arg : args) { 13355 if (value.equals(arg)) { 13356 return true; 13357 } 13358 } 13359 } 13360 return false; 13361 } 13362 13363 private final boolean removeDyingProviderLocked(ProcessRecord proc, 13364 ContentProviderRecord cpr, boolean always) { 13365 final boolean inLaunching = mLaunchingProviders.contains(cpr); 13366 13367 if (!inLaunching || always) { 13368 synchronized (cpr) { 13369 cpr.launchingApp = null; 13370 cpr.notifyAll(); 13371 } 13372 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid)); 13373 String names[] = cpr.info.authority.split(";"); 13374 for (int j = 0; j < names.length; j++) { 13375 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid)); 13376 } 13377 } 13378 13379 for (int i=0; i<cpr.connections.size(); i++) { 13380 ContentProviderConnection conn = cpr.connections.get(i); 13381 if (conn.waiting) { 13382 // If this connection is waiting for the provider, then we don't 13383 // need to mess with its process unless we are always removing 13384 // or for some reason the provider is not currently launching. 13385 if (inLaunching && !always) { 13386 continue; 13387 } 13388 } 13389 ProcessRecord capp = conn.client; 13390 conn.dead = true; 13391 if (conn.stableCount > 0) { 13392 if (!capp.persistent && capp.thread != null 13393 && capp.pid != 0 13394 && capp.pid != MY_PID) { 13395 killUnneededProcessLocked(capp, "depends on provider " 13396 + cpr.name.flattenToShortString() 13397 + " in dying proc " + (proc != null ? proc.processName : "??")); 13398 } 13399 } else if (capp.thread != null && conn.provider.provider != null) { 13400 try { 13401 capp.thread.unstableProviderDied(conn.provider.provider.asBinder()); 13402 } catch (RemoteException e) { 13403 } 13404 // In the protocol here, we don't expect the client to correctly 13405 // clean up this connection, we'll just remove it. 13406 cpr.connections.remove(i); 13407 conn.client.conProviders.remove(conn); 13408 } 13409 } 13410 13411 if (inLaunching && always) { 13412 mLaunchingProviders.remove(cpr); 13413 } 13414 return inLaunching; 13415 } 13416 13417 /** 13418 * Main code for cleaning up a process when it has gone away. This is 13419 * called both as a result of the process dying, or directly when stopping 13420 * a process when running in single process mode. 13421 */ 13422 private final void cleanUpApplicationRecordLocked(ProcessRecord app, 13423 boolean restarting, boolean allowRestart, int index) { 13424 if (index >= 0) { 13425 removeLruProcessLocked(app); 13426 ProcessList.remove(app.pid); 13427 } 13428 13429 mProcessesToGc.remove(app); 13430 mPendingPssProcesses.remove(app); 13431 13432 // Dismiss any open dialogs. 13433 if (app.crashDialog != null && !app.forceCrashReport) { 13434 app.crashDialog.dismiss(); 13435 app.crashDialog = null; 13436 } 13437 if (app.anrDialog != null) { 13438 app.anrDialog.dismiss(); 13439 app.anrDialog = null; 13440 } 13441 if (app.waitDialog != null) { 13442 app.waitDialog.dismiss(); 13443 app.waitDialog = null; 13444 } 13445 13446 app.crashing = false; 13447 app.notResponding = false; 13448 13449 app.resetPackageList(mProcessStats); 13450 app.unlinkDeathRecipient(); 13451 app.makeInactive(mProcessStats); 13452 app.waitingToKill = null; 13453 app.forcingToForeground = null; 13454 updateProcessForegroundLocked(app, false, false); 13455 app.foregroundActivities = false; 13456 app.hasShownUi = false; 13457 app.treatLikeActivity = false; 13458 app.hasAboveClient = false; 13459 app.hasClientActivities = false; 13460 13461 mServices.killServicesLocked(app, allowRestart); 13462 13463 boolean restart = false; 13464 13465 // Remove published content providers. 13466 for (int i=app.pubProviders.size()-1; i>=0; i--) { 13467 ContentProviderRecord cpr = app.pubProviders.valueAt(i); 13468 final boolean always = app.bad || !allowRestart; 13469 if (removeDyingProviderLocked(app, cpr, always) || always) { 13470 // We left the provider in the launching list, need to 13471 // restart it. 13472 restart = true; 13473 } 13474 13475 cpr.provider = null; 13476 cpr.proc = null; 13477 } 13478 app.pubProviders.clear(); 13479 13480 // Take care of any launching providers waiting for this process. 13481 if (checkAppInLaunchingProvidersLocked(app, false)) { 13482 restart = true; 13483 } 13484 13485 // Unregister from connected content providers. 13486 if (!app.conProviders.isEmpty()) { 13487 for (int i=0; i<app.conProviders.size(); i++) { 13488 ContentProviderConnection conn = app.conProviders.get(i); 13489 conn.provider.connections.remove(conn); 13490 } 13491 app.conProviders.clear(); 13492 } 13493 13494 // At this point there may be remaining entries in mLaunchingProviders 13495 // where we were the only one waiting, so they are no longer of use. 13496 // Look for these and clean up if found. 13497 // XXX Commented out for now. Trying to figure out a way to reproduce 13498 // the actual situation to identify what is actually going on. 13499 if (false) { 13500 for (int i=0; i<mLaunchingProviders.size(); i++) { 13501 ContentProviderRecord cpr = (ContentProviderRecord) 13502 mLaunchingProviders.get(i); 13503 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 13504 synchronized (cpr) { 13505 cpr.launchingApp = null; 13506 cpr.notifyAll(); 13507 } 13508 } 13509 } 13510 } 13511 13512 skipCurrentReceiverLocked(app); 13513 13514 // Unregister any receivers. 13515 for (int i=app.receivers.size()-1; i>=0; i--) { 13516 removeReceiverLocked(app.receivers.valueAt(i)); 13517 } 13518 app.receivers.clear(); 13519 13520 // If the app is undergoing backup, tell the backup manager about it 13521 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) { 13522 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App " 13523 + mBackupTarget.appInfo + " died during backup"); 13524 try { 13525 IBackupManager bm = IBackupManager.Stub.asInterface( 13526 ServiceManager.getService(Context.BACKUP_SERVICE)); 13527 bm.agentDisconnected(app.info.packageName); 13528 } catch (RemoteException e) { 13529 // can't happen; backup manager is local 13530 } 13531 } 13532 13533 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) { 13534 ProcessChangeItem item = mPendingProcessChanges.get(i); 13535 if (item.pid == app.pid) { 13536 mPendingProcessChanges.remove(i); 13537 mAvailProcessChanges.add(item); 13538 } 13539 } 13540 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget(); 13541 13542 // If the caller is restarting this app, then leave it in its 13543 // current lists and let the caller take care of it. 13544 if (restarting) { 13545 return; 13546 } 13547 13548 if (!app.persistent || app.isolated) { 13549 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, 13550 "Removing non-persistent process during cleanup: " + app); 13551 mProcessNames.remove(app.processName, app.uid); 13552 mIsolatedProcesses.remove(app.uid); 13553 if (mHeavyWeightProcess == app) { 13554 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 13555 mHeavyWeightProcess.userId, 0)); 13556 mHeavyWeightProcess = null; 13557 } 13558 } else if (!app.removed) { 13559 // This app is persistent, so we need to keep its record around. 13560 // If it is not already on the pending app list, add it there 13561 // and start a new process for it. 13562 if (mPersistentStartingProcesses.indexOf(app) < 0) { 13563 mPersistentStartingProcesses.add(app); 13564 restart = true; 13565 } 13566 } 13567 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG, 13568 "Clean-up removing on hold: " + app); 13569 mProcessesOnHold.remove(app); 13570 13571 if (app == mHomeProcess) { 13572 mHomeProcess = null; 13573 } 13574 if (app == mPreviousProcess) { 13575 mPreviousProcess = null; 13576 } 13577 13578 if (restart && !app.isolated) { 13579 // We have components that still need to be running in the 13580 // process, so re-launch it. 13581 mProcessNames.put(app.processName, app.uid, app); 13582 startProcessLocked(app, "restart", app.processName); 13583 } else if (app.pid > 0 && app.pid != MY_PID) { 13584 // Goodbye! 13585 boolean removed; 13586 synchronized (mPidsSelfLocked) { 13587 mPidsSelfLocked.remove(app.pid); 13588 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 13589 } 13590 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 13591 if (app.isolated) { 13592 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 13593 } 13594 app.setPid(0); 13595 } 13596 } 13597 13598 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 13599 // Look through the content providers we are waiting to have launched, 13600 // and if any run in this process then either schedule a restart of 13601 // the process or kill the client waiting for it if this process has 13602 // gone bad. 13603 int NL = mLaunchingProviders.size(); 13604 boolean restart = false; 13605 for (int i=0; i<NL; i++) { 13606 ContentProviderRecord cpr = mLaunchingProviders.get(i); 13607 if (cpr.launchingApp == app) { 13608 if (!alwaysBad && !app.bad) { 13609 restart = true; 13610 } else { 13611 removeDyingProviderLocked(app, cpr, true); 13612 // cpr should have been removed from mLaunchingProviders 13613 NL = mLaunchingProviders.size(); 13614 i--; 13615 } 13616 } 13617 } 13618 return restart; 13619 } 13620 13621 // ========================================================= 13622 // SERVICES 13623 // ========================================================= 13624 13625 @Override 13626 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, 13627 int flags) { 13628 enforceNotIsolatedCaller("getServices"); 13629 synchronized (this) { 13630 return mServices.getRunningServiceInfoLocked(maxNum, flags); 13631 } 13632 } 13633 13634 @Override 13635 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 13636 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 13637 synchronized (this) { 13638 return mServices.getRunningServiceControlPanelLocked(name); 13639 } 13640 } 13641 13642 @Override 13643 public ComponentName startService(IApplicationThread caller, Intent service, 13644 String resolvedType, int userId) { 13645 enforceNotIsolatedCaller("startService"); 13646 // Refuse possible leaked file descriptors 13647 if (service != null && service.hasFileDescriptors() == true) { 13648 throw new IllegalArgumentException("File descriptors passed in Intent"); 13649 } 13650 13651 if (DEBUG_SERVICE) 13652 Slog.v(TAG, "startService: " + service + " type=" + resolvedType); 13653 synchronized(this) { 13654 final int callingPid = Binder.getCallingPid(); 13655 final int callingUid = Binder.getCallingUid(); 13656 final long origId = Binder.clearCallingIdentity(); 13657 ComponentName res = mServices.startServiceLocked(caller, service, 13658 resolvedType, callingPid, callingUid, userId); 13659 Binder.restoreCallingIdentity(origId); 13660 return res; 13661 } 13662 } 13663 13664 ComponentName startServiceInPackage(int uid, 13665 Intent service, String resolvedType, int userId) { 13666 synchronized(this) { 13667 if (DEBUG_SERVICE) 13668 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType); 13669 final long origId = Binder.clearCallingIdentity(); 13670 ComponentName res = mServices.startServiceLocked(null, service, 13671 resolvedType, -1, uid, userId); 13672 Binder.restoreCallingIdentity(origId); 13673 return res; 13674 } 13675 } 13676 13677 @Override 13678 public int stopService(IApplicationThread caller, Intent service, 13679 String resolvedType, int userId) { 13680 enforceNotIsolatedCaller("stopService"); 13681 // Refuse possible leaked file descriptors 13682 if (service != null && service.hasFileDescriptors() == true) { 13683 throw new IllegalArgumentException("File descriptors passed in Intent"); 13684 } 13685 13686 synchronized(this) { 13687 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 13688 } 13689 } 13690 13691 @Override 13692 public IBinder peekService(Intent service, String resolvedType) { 13693 enforceNotIsolatedCaller("peekService"); 13694 // Refuse possible leaked file descriptors 13695 if (service != null && service.hasFileDescriptors() == true) { 13696 throw new IllegalArgumentException("File descriptors passed in Intent"); 13697 } 13698 synchronized(this) { 13699 return mServices.peekServiceLocked(service, resolvedType); 13700 } 13701 } 13702 13703 @Override 13704 public boolean stopServiceToken(ComponentName className, IBinder token, 13705 int startId) { 13706 synchronized(this) { 13707 return mServices.stopServiceTokenLocked(className, token, startId); 13708 } 13709 } 13710 13711 @Override 13712 public void setServiceForeground(ComponentName className, IBinder token, 13713 int id, Notification notification, boolean removeNotification) { 13714 synchronized(this) { 13715 mServices.setServiceForegroundLocked(className, token, id, notification, 13716 removeNotification); 13717 } 13718 } 13719 13720 @Override 13721 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 13722 boolean requireFull, String name, String callerPackage) { 13723 return handleIncomingUser(callingPid, callingUid, userId, allowAll, 13724 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 13725 } 13726 13727 int unsafeConvertIncomingUser(int userId) { 13728 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) 13729 ? mCurrentUserId : userId; 13730 } 13731 13732 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 13733 int allowMode, String name, String callerPackage) { 13734 final int callingUserId = UserHandle.getUserId(callingUid); 13735 if (callingUserId == userId) { 13736 return userId; 13737 } 13738 13739 // Note that we may be accessing mCurrentUserId outside of a lock... 13740 // shouldn't be a big deal, if this is being called outside 13741 // of a locked context there is intrinsically a race with 13742 // the value the caller will receive and someone else changing it. 13743 // We assume that USER_CURRENT_OR_SELF will use the current user; later 13744 // we will switch to the calling user if access to the current user fails. 13745 int targetUserId = unsafeConvertIncomingUser(userId); 13746 13747 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13748 final boolean allow; 13749 if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 13750 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 13751 // If the caller has this permission, they always pass go. And collect $200. 13752 allow = true; 13753 } else if (allowMode == ALLOW_FULL_ONLY) { 13754 // We require full access, sucks to be you. 13755 allow = false; 13756 } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 13757 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { 13758 // If the caller does not have either permission, they are always doomed. 13759 allow = false; 13760 } else if (allowMode == ALLOW_NON_FULL) { 13761 // We are blanket allowing non-full access, you lucky caller! 13762 allow = true; 13763 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) { 13764 // We may or may not allow this depending on whether the two users are 13765 // in the same profile. 13766 synchronized (mUserProfileGroupIdsSelfLocked) { 13767 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId, 13768 UserInfo.NO_PROFILE_GROUP_ID); 13769 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId, 13770 UserInfo.NO_PROFILE_GROUP_ID); 13771 allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID 13772 && callingProfile == targetProfile; 13773 } 13774 } else { 13775 throw new IllegalArgumentException("Unknown mode: " + allowMode); 13776 } 13777 if (!allow) { 13778 if (userId == UserHandle.USER_CURRENT_OR_SELF) { 13779 // In this case, they would like to just execute as their 13780 // owner user instead of failing. 13781 targetUserId = callingUserId; 13782 } else { 13783 StringBuilder builder = new StringBuilder(128); 13784 builder.append("Permission Denial: "); 13785 builder.append(name); 13786 if (callerPackage != null) { 13787 builder.append(" from "); 13788 builder.append(callerPackage); 13789 } 13790 builder.append(" asks to run as user "); 13791 builder.append(userId); 13792 builder.append(" but is calling from user "); 13793 builder.append(UserHandle.getUserId(callingUid)); 13794 builder.append("; this requires "); 13795 builder.append(INTERACT_ACROSS_USERS_FULL); 13796 if (allowMode != ALLOW_FULL_ONLY) { 13797 builder.append(" or "); 13798 builder.append(INTERACT_ACROSS_USERS); 13799 } 13800 String msg = builder.toString(); 13801 Slog.w(TAG, msg); 13802 throw new SecurityException(msg); 13803 } 13804 } 13805 } 13806 if (!allowAll && targetUserId < 0) { 13807 throw new IllegalArgumentException( 13808 "Call does not support special user #" + targetUserId); 13809 } 13810 return targetUserId; 13811 } 13812 13813 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 13814 String className, int flags) { 13815 boolean result = false; 13816 // For apps that don't have pre-defined UIDs, check for permission 13817 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) { 13818 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 13819 if (ActivityManager.checkUidPermission( 13820 INTERACT_ACROSS_USERS, 13821 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 13822 ComponentName comp = new ComponentName(aInfo.packageName, className); 13823 String msg = "Permission Denial: Component " + comp.flattenToShortString() 13824 + " requests FLAG_SINGLE_USER, but app does not hold " 13825 + INTERACT_ACROSS_USERS; 13826 Slog.w(TAG, msg); 13827 throw new SecurityException(msg); 13828 } 13829 // Permission passed 13830 result = true; 13831 } 13832 } else if ("system".equals(componentProcessName)) { 13833 result = true; 13834 } else { 13835 // App with pre-defined UID, check if it's a persistent app 13836 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 13837 } 13838 if (DEBUG_MU) { 13839 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo 13840 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result); 13841 } 13842 return result; 13843 } 13844 13845 /** 13846 * Checks to see if the caller is in the same app as the singleton 13847 * component, or the component is in a special app. It allows special apps 13848 * to export singleton components but prevents exporting singleton 13849 * components for regular apps. 13850 */ 13851 boolean isValidSingletonCall(int callingUid, int componentUid) { 13852 int componentAppId = UserHandle.getAppId(componentUid); 13853 return UserHandle.isSameApp(callingUid, componentUid) 13854 || componentAppId == Process.SYSTEM_UID 13855 || componentAppId == Process.PHONE_UID 13856 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 13857 == PackageManager.PERMISSION_GRANTED; 13858 } 13859 13860 public int bindService(IApplicationThread caller, IBinder token, 13861 Intent service, String resolvedType, 13862 IServiceConnection connection, int flags, int userId) { 13863 enforceNotIsolatedCaller("bindService"); 13864 // Refuse possible leaked file descriptors 13865 if (service != null && service.hasFileDescriptors() == true) { 13866 throw new IllegalArgumentException("File descriptors passed in Intent"); 13867 } 13868 13869 synchronized(this) { 13870 return mServices.bindServiceLocked(caller, token, service, resolvedType, 13871 connection, flags, userId); 13872 } 13873 } 13874 13875 public boolean unbindService(IServiceConnection connection) { 13876 synchronized (this) { 13877 return mServices.unbindServiceLocked(connection); 13878 } 13879 } 13880 13881 public void publishService(IBinder token, Intent intent, IBinder service) { 13882 // Refuse possible leaked file descriptors 13883 if (intent != null && intent.hasFileDescriptors() == true) { 13884 throw new IllegalArgumentException("File descriptors passed in Intent"); 13885 } 13886 13887 synchronized(this) { 13888 if (!(token instanceof ServiceRecord)) { 13889 throw new IllegalArgumentException("Invalid service token"); 13890 } 13891 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 13892 } 13893 } 13894 13895 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 13896 // Refuse possible leaked file descriptors 13897 if (intent != null && intent.hasFileDescriptors() == true) { 13898 throw new IllegalArgumentException("File descriptors passed in Intent"); 13899 } 13900 13901 synchronized(this) { 13902 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 13903 } 13904 } 13905 13906 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 13907 synchronized(this) { 13908 if (!(token instanceof ServiceRecord)) { 13909 throw new IllegalArgumentException("Invalid service token"); 13910 } 13911 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); 13912 } 13913 } 13914 13915 // ========================================================= 13916 // BACKUP AND RESTORE 13917 // ========================================================= 13918 13919 // Cause the target app to be launched if necessary and its backup agent 13920 // instantiated. The backup agent will invoke backupAgentCreated() on the 13921 // activity manager to announce its creation. 13922 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) { 13923 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode); 13924 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 13925 13926 synchronized(this) { 13927 // !!! TODO: currently no check here that we're already bound 13928 BatteryStatsImpl.Uid.Pkg.Serv ss = null; 13929 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 13930 synchronized (stats) { 13931 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name); 13932 } 13933 13934 // Backup agent is now in use, its package can't be stopped. 13935 try { 13936 AppGlobals.getPackageManager().setPackageStoppedState( 13937 app.packageName, false, UserHandle.getUserId(app.uid)); 13938 } catch (RemoteException e) { 13939 } catch (IllegalArgumentException e) { 13940 Slog.w(TAG, "Failed trying to unstop package " 13941 + app.packageName + ": " + e); 13942 } 13943 13944 BackupRecord r = new BackupRecord(ss, app, backupMode); 13945 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) 13946 ? new ComponentName(app.packageName, app.backupAgentName) 13947 : new ComponentName("android", "FullBackupAgent"); 13948 // startProcessLocked() returns existing proc's record if it's already running 13949 ProcessRecord proc = startProcessLocked(app.processName, app, 13950 false, 0, "backup", hostingName, false, false, false); 13951 if (proc == null) { 13952 Slog.e(TAG, "Unable to start backup agent process " + r); 13953 return false; 13954 } 13955 13956 r.app = proc; 13957 mBackupTarget = r; 13958 mBackupAppName = app.packageName; 13959 13960 // Try not to kill the process during backup 13961 updateOomAdjLocked(proc); 13962 13963 // If the process is already attached, schedule the creation of the backup agent now. 13964 // If it is not yet live, this will be done when it attaches to the framework. 13965 if (proc.thread != null) { 13966 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc); 13967 try { 13968 proc.thread.scheduleCreateBackupAgent(app, 13969 compatibilityInfoForPackageLocked(app), backupMode); 13970 } catch (RemoteException e) { 13971 // Will time out on the backup manager side 13972 } 13973 } else { 13974 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach"); 13975 } 13976 // Invariants: at this point, the target app process exists and the application 13977 // is either already running or in the process of coming up. mBackupTarget and 13978 // mBackupAppName describe the app, so that when it binds back to the AM we 13979 // know that it's scheduled for a backup-agent operation. 13980 } 13981 13982 return true; 13983 } 13984 13985 @Override 13986 public void clearPendingBackup() { 13987 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup"); 13988 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup"); 13989 13990 synchronized (this) { 13991 mBackupTarget = null; 13992 mBackupAppName = null; 13993 } 13994 } 13995 13996 // A backup agent has just come up 13997 public void backupAgentCreated(String agentPackageName, IBinder agent) { 13998 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName 13999 + " = " + agent); 14000 14001 synchronized(this) { 14002 if (!agentPackageName.equals(mBackupAppName)) { 14003 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 14004 return; 14005 } 14006 } 14007 14008 long oldIdent = Binder.clearCallingIdentity(); 14009 try { 14010 IBackupManager bm = IBackupManager.Stub.asInterface( 14011 ServiceManager.getService(Context.BACKUP_SERVICE)); 14012 bm.agentConnected(agentPackageName, agent); 14013 } catch (RemoteException e) { 14014 // can't happen; the backup manager service is local 14015 } catch (Exception e) { 14016 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 14017 e.printStackTrace(); 14018 } finally { 14019 Binder.restoreCallingIdentity(oldIdent); 14020 } 14021 } 14022 14023 // done with this agent 14024 public void unbindBackupAgent(ApplicationInfo appInfo) { 14025 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo); 14026 if (appInfo == null) { 14027 Slog.w(TAG, "unbind backup agent for null app"); 14028 return; 14029 } 14030 14031 synchronized(this) { 14032 try { 14033 if (mBackupAppName == null) { 14034 Slog.w(TAG, "Unbinding backup agent with no active backup"); 14035 return; 14036 } 14037 14038 if (!mBackupAppName.equals(appInfo.packageName)) { 14039 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 14040 return; 14041 } 14042 14043 // Not backing this app up any more; reset its OOM adjustment 14044 final ProcessRecord proc = mBackupTarget.app; 14045 updateOomAdjLocked(proc); 14046 14047 // If the app crashed during backup, 'thread' will be null here 14048 if (proc.thread != null) { 14049 try { 14050 proc.thread.scheduleDestroyBackupAgent(appInfo, 14051 compatibilityInfoForPackageLocked(appInfo)); 14052 } catch (Exception e) { 14053 Slog.e(TAG, "Exception when unbinding backup agent:"); 14054 e.printStackTrace(); 14055 } 14056 } 14057 } finally { 14058 mBackupTarget = null; 14059 mBackupAppName = null; 14060 } 14061 } 14062 } 14063 // ========================================================= 14064 // BROADCASTS 14065 // ========================================================= 14066 14067 private final List getStickiesLocked(String action, IntentFilter filter, 14068 List cur, int userId) { 14069 final ContentResolver resolver = mContext.getContentResolver(); 14070 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14071 if (stickies == null) { 14072 return cur; 14073 } 14074 final ArrayList<Intent> list = stickies.get(action); 14075 if (list == null) { 14076 return cur; 14077 } 14078 int N = list.size(); 14079 for (int i=0; i<N; i++) { 14080 Intent intent = list.get(i); 14081 if (filter.match(resolver, intent, true, TAG) >= 0) { 14082 if (cur == null) { 14083 cur = new ArrayList<Intent>(); 14084 } 14085 cur.add(intent); 14086 } 14087 } 14088 return cur; 14089 } 14090 14091 boolean isPendingBroadcastProcessLocked(int pid) { 14092 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 14093 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid); 14094 } 14095 14096 void skipPendingBroadcastLocked(int pid) { 14097 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 14098 for (BroadcastQueue queue : mBroadcastQueues) { 14099 queue.skipPendingBroadcastLocked(pid); 14100 } 14101 } 14102 14103 // The app just attached; send any pending broadcasts that it should receive 14104 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 14105 boolean didSomething = false; 14106 for (BroadcastQueue queue : mBroadcastQueues) { 14107 didSomething |= queue.sendPendingBroadcastsLocked(app); 14108 } 14109 return didSomething; 14110 } 14111 14112 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 14113 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) { 14114 enforceNotIsolatedCaller("registerReceiver"); 14115 int callingUid; 14116 int callingPid; 14117 synchronized(this) { 14118 ProcessRecord callerApp = null; 14119 if (caller != null) { 14120 callerApp = getRecordForAppLocked(caller); 14121 if (callerApp == null) { 14122 throw new SecurityException( 14123 "Unable to find app for caller " + caller 14124 + " (pid=" + Binder.getCallingPid() 14125 + ") when registering receiver " + receiver); 14126 } 14127 if (callerApp.info.uid != Process.SYSTEM_UID && 14128 !callerApp.pkgList.containsKey(callerPackage) && 14129 !"android".equals(callerPackage)) { 14130 throw new SecurityException("Given caller package " + callerPackage 14131 + " is not running in process " + callerApp); 14132 } 14133 callingUid = callerApp.info.uid; 14134 callingPid = callerApp.pid; 14135 } else { 14136 callerPackage = null; 14137 callingUid = Binder.getCallingUid(); 14138 callingPid = Binder.getCallingPid(); 14139 } 14140 14141 userId = this.handleIncomingUser(callingPid, callingUid, userId, 14142 true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 14143 14144 List allSticky = null; 14145 14146 // Look for any matching sticky broadcasts... 14147 Iterator actions = filter.actionsIterator(); 14148 if (actions != null) { 14149 while (actions.hasNext()) { 14150 String action = (String)actions.next(); 14151 allSticky = getStickiesLocked(action, filter, allSticky, 14152 UserHandle.USER_ALL); 14153 allSticky = getStickiesLocked(action, filter, allSticky, 14154 UserHandle.getUserId(callingUid)); 14155 } 14156 } else { 14157 allSticky = getStickiesLocked(null, filter, allSticky, 14158 UserHandle.USER_ALL); 14159 allSticky = getStickiesLocked(null, filter, allSticky, 14160 UserHandle.getUserId(callingUid)); 14161 } 14162 14163 // The first sticky in the list is returned directly back to 14164 // the client. 14165 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null; 14166 14167 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter 14168 + ": " + sticky); 14169 14170 if (receiver == null) { 14171 return sticky; 14172 } 14173 14174 ReceiverList rl 14175 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder()); 14176 if (rl == null) { 14177 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 14178 userId, receiver); 14179 if (rl.app != null) { 14180 rl.app.receivers.add(rl); 14181 } else { 14182 try { 14183 receiver.asBinder().linkToDeath(rl, 0); 14184 } catch (RemoteException e) { 14185 return sticky; 14186 } 14187 rl.linkedToDeath = true; 14188 } 14189 mRegisteredReceivers.put(receiver.asBinder(), rl); 14190 } else if (rl.uid != callingUid) { 14191 throw new IllegalArgumentException( 14192 "Receiver requested to register for uid " + callingUid 14193 + " was previously registered for uid " + rl.uid); 14194 } else if (rl.pid != callingPid) { 14195 throw new IllegalArgumentException( 14196 "Receiver requested to register for pid " + callingPid 14197 + " was previously registered for pid " + rl.pid); 14198 } else if (rl.userId != userId) { 14199 throw new IllegalArgumentException( 14200 "Receiver requested to register for user " + userId 14201 + " was previously registered for user " + rl.userId); 14202 } 14203 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, 14204 permission, callingUid, userId); 14205 rl.add(bf); 14206 if (!bf.debugCheck()) { 14207 Slog.w(TAG, "==> For Dynamic broadast"); 14208 } 14209 mReceiverResolver.addFilter(bf); 14210 14211 // Enqueue broadcasts for all existing stickies that match 14212 // this filter. 14213 if (allSticky != null) { 14214 ArrayList receivers = new ArrayList(); 14215 receivers.add(bf); 14216 14217 int N = allSticky.size(); 14218 for (int i=0; i<N; i++) { 14219 Intent intent = (Intent)allSticky.get(i); 14220 BroadcastQueue queue = broadcastQueueForIntent(intent); 14221 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 14222 null, -1, -1, null, null, AppOpsManager.OP_NONE, receivers, null, 0, 14223 null, null, false, true, true, -1); 14224 queue.enqueueParallelBroadcastLocked(r); 14225 queue.scheduleBroadcastsLocked(); 14226 } 14227 } 14228 14229 return sticky; 14230 } 14231 } 14232 14233 public void unregisterReceiver(IIntentReceiver receiver) { 14234 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver); 14235 14236 final long origId = Binder.clearCallingIdentity(); 14237 try { 14238 boolean doTrim = false; 14239 14240 synchronized(this) { 14241 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 14242 if (rl != null) { 14243 if (rl.curBroadcast != null) { 14244 BroadcastRecord r = rl.curBroadcast; 14245 final boolean doNext = finishReceiverLocked( 14246 receiver.asBinder(), r.resultCode, r.resultData, 14247 r.resultExtras, r.resultAbort); 14248 if (doNext) { 14249 doTrim = true; 14250 r.queue.processNextBroadcast(false); 14251 } 14252 } 14253 14254 if (rl.app != null) { 14255 rl.app.receivers.remove(rl); 14256 } 14257 removeReceiverLocked(rl); 14258 if (rl.linkedToDeath) { 14259 rl.linkedToDeath = false; 14260 rl.receiver.asBinder().unlinkToDeath(rl, 0); 14261 } 14262 } 14263 } 14264 14265 // If we actually concluded any broadcasts, we might now be able 14266 // to trim the recipients' apps from our working set 14267 if (doTrim) { 14268 trimApplications(); 14269 return; 14270 } 14271 14272 } finally { 14273 Binder.restoreCallingIdentity(origId); 14274 } 14275 } 14276 14277 void removeReceiverLocked(ReceiverList rl) { 14278 mRegisteredReceivers.remove(rl.receiver.asBinder()); 14279 int N = rl.size(); 14280 for (int i=0; i<N; i++) { 14281 mReceiverResolver.removeFilter(rl.get(i)); 14282 } 14283 } 14284 14285 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 14286 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 14287 ProcessRecord r = mLruProcesses.get(i); 14288 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) { 14289 try { 14290 r.thread.dispatchPackageBroadcast(cmd, packages); 14291 } catch (RemoteException ex) { 14292 } 14293 } 14294 } 14295 } 14296 14297 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 14298 int[] users) { 14299 List<ResolveInfo> receivers = null; 14300 try { 14301 HashSet<ComponentName> singleUserReceivers = null; 14302 boolean scannedFirstReceivers = false; 14303 for (int user : users) { 14304 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 14305 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user); 14306 if (user != 0 && newReceivers != null) { 14307 // If this is not the primary user, we need to check for 14308 // any receivers that should be filtered out. 14309 for (int i=0; i<newReceivers.size(); i++) { 14310 ResolveInfo ri = newReceivers.get(i); 14311 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 14312 newReceivers.remove(i); 14313 i--; 14314 } 14315 } 14316 } 14317 if (newReceivers != null && newReceivers.size() == 0) { 14318 newReceivers = null; 14319 } 14320 if (receivers == null) { 14321 receivers = newReceivers; 14322 } else if (newReceivers != null) { 14323 // We need to concatenate the additional receivers 14324 // found with what we have do far. This would be easy, 14325 // but we also need to de-dup any receivers that are 14326 // singleUser. 14327 if (!scannedFirstReceivers) { 14328 // Collect any single user receivers we had already retrieved. 14329 scannedFirstReceivers = true; 14330 for (int i=0; i<receivers.size(); i++) { 14331 ResolveInfo ri = receivers.get(i); 14332 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 14333 ComponentName cn = new ComponentName( 14334 ri.activityInfo.packageName, ri.activityInfo.name); 14335 if (singleUserReceivers == null) { 14336 singleUserReceivers = new HashSet<ComponentName>(); 14337 } 14338 singleUserReceivers.add(cn); 14339 } 14340 } 14341 } 14342 // Add the new results to the existing results, tracking 14343 // and de-dupping single user receivers. 14344 for (int i=0; i<newReceivers.size(); i++) { 14345 ResolveInfo ri = newReceivers.get(i); 14346 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 14347 ComponentName cn = new ComponentName( 14348 ri.activityInfo.packageName, ri.activityInfo.name); 14349 if (singleUserReceivers == null) { 14350 singleUserReceivers = new HashSet<ComponentName>(); 14351 } 14352 if (!singleUserReceivers.contains(cn)) { 14353 singleUserReceivers.add(cn); 14354 receivers.add(ri); 14355 } 14356 } else { 14357 receivers.add(ri); 14358 } 14359 } 14360 } 14361 } 14362 } catch (RemoteException ex) { 14363 // pm is in same process, this will never happen. 14364 } 14365 return receivers; 14366 } 14367 14368 private final int broadcastIntentLocked(ProcessRecord callerApp, 14369 String callerPackage, Intent intent, String resolvedType, 14370 IIntentReceiver resultTo, int resultCode, String resultData, 14371 Bundle map, String requiredPermission, int appOp, 14372 boolean ordered, boolean sticky, int callingPid, int callingUid, 14373 int userId) { 14374 intent = new Intent(intent); 14375 14376 // By default broadcasts do not go to stopped apps. 14377 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 14378 14379 if (DEBUG_BROADCAST_LIGHT) Slog.v( 14380 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 14381 + " ordered=" + ordered + " userid=" + userId); 14382 if ((resultTo != null) && !ordered) { 14383 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 14384 } 14385 14386 userId = handleIncomingUser(callingPid, callingUid, userId, 14387 true, ALLOW_NON_FULL, "broadcast", callerPackage); 14388 14389 // Make sure that the user who is receiving this broadcast is started. 14390 // If not, we will just skip it. 14391 14392 14393 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) { 14394 if (callingUid != Process.SYSTEM_UID || (intent.getFlags() 14395 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 14396 Slog.w(TAG, "Skipping broadcast of " + intent 14397 + ": user " + userId + " is stopped"); 14398 return ActivityManager.BROADCAST_SUCCESS; 14399 } 14400 } 14401 14402 /* 14403 * Prevent non-system code (defined here to be non-persistent 14404 * processes) from sending protected broadcasts. 14405 */ 14406 int callingAppId = UserHandle.getAppId(callingUid); 14407 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID 14408 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID 14409 || callingAppId == Process.NFC_UID || callingUid == 0) { 14410 // Always okay. 14411 } else if (callerApp == null || !callerApp.persistent) { 14412 try { 14413 if (AppGlobals.getPackageManager().isProtectedBroadcast( 14414 intent.getAction())) { 14415 String msg = "Permission Denial: not allowed to send broadcast " 14416 + intent.getAction() + " from pid=" 14417 + callingPid + ", uid=" + callingUid; 14418 Slog.w(TAG, msg); 14419 throw new SecurityException(msg); 14420 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) { 14421 // Special case for compatibility: we don't want apps to send this, 14422 // but historically it has not been protected and apps may be using it 14423 // to poke their own app widget. So, instead of making it protected, 14424 // just limit it to the caller. 14425 if (callerApp == null) { 14426 String msg = "Permission Denial: not allowed to send broadcast " 14427 + intent.getAction() + " from unknown caller."; 14428 Slog.w(TAG, msg); 14429 throw new SecurityException(msg); 14430 } else if (intent.getComponent() != null) { 14431 // They are good enough to send to an explicit component... verify 14432 // it is being sent to the calling app. 14433 if (!intent.getComponent().getPackageName().equals( 14434 callerApp.info.packageName)) { 14435 String msg = "Permission Denial: not allowed to send broadcast " 14436 + intent.getAction() + " to " 14437 + intent.getComponent().getPackageName() + " from " 14438 + callerApp.info.packageName; 14439 Slog.w(TAG, msg); 14440 throw new SecurityException(msg); 14441 } 14442 } else { 14443 // Limit broadcast to their own package. 14444 intent.setPackage(callerApp.info.packageName); 14445 } 14446 } 14447 } catch (RemoteException e) { 14448 Slog.w(TAG, "Remote exception", e); 14449 return ActivityManager.BROADCAST_SUCCESS; 14450 } 14451 } 14452 14453 // Handle special intents: if this broadcast is from the package 14454 // manager about a package being removed, we need to remove all of 14455 // its activities from the history stack. 14456 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals( 14457 intent.getAction()); 14458 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) 14459 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction()) 14460 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction()) 14461 || uidRemoved) { 14462 if (checkComponentPermission( 14463 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 14464 callingPid, callingUid, -1, true) 14465 == PackageManager.PERMISSION_GRANTED) { 14466 if (uidRemoved) { 14467 final Bundle intentExtras = intent.getExtras(); 14468 final int uid = intentExtras != null 14469 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 14470 if (uid >= 0) { 14471 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics(); 14472 synchronized (bs) { 14473 bs.removeUidStatsLocked(uid); 14474 } 14475 mAppOpsService.uidRemoved(uid); 14476 } 14477 } else { 14478 // If resources are unavailable just force stop all 14479 // those packages and flush the attribute cache as well. 14480 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) { 14481 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 14482 if (list != null && (list.length > 0)) { 14483 for (String pkg : list) { 14484 forceStopPackageLocked(pkg, -1, false, true, true, false, false, userId, 14485 "storage unmount"); 14486 } 14487 sendPackageBroadcastLocked( 14488 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId); 14489 } 14490 } else { 14491 Uri data = intent.getData(); 14492 String ssp; 14493 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 14494 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals( 14495 intent.getAction()); 14496 boolean fullUninstall = removed && 14497 !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 14498 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) { 14499 forceStopPackageLocked(ssp, UserHandle.getAppId( 14500 intent.getIntExtra(Intent.EXTRA_UID, -1)), false, true, true, 14501 false, fullUninstall, userId, 14502 removed ? "pkg removed" : "pkg changed"); 14503 } 14504 if (removed) { 14505 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED, 14506 new String[] {ssp}, userId); 14507 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 14508 mAppOpsService.packageRemoved( 14509 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 14510 14511 // Remove all permissions granted from/to this package 14512 removeUriPermissionsForPackageLocked(ssp, userId, true); 14513 } 14514 } 14515 } 14516 } 14517 } 14518 } else { 14519 String msg = "Permission Denial: " + intent.getAction() 14520 + " broadcast from " + callerPackage + " (pid=" + callingPid 14521 + ", uid=" + callingUid + ")" 14522 + " requires " 14523 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 14524 Slog.w(TAG, msg); 14525 throw new SecurityException(msg); 14526 } 14527 14528 // Special case for adding a package: by default turn on compatibility 14529 // mode. 14530 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) { 14531 Uri data = intent.getData(); 14532 String ssp; 14533 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 14534 mCompatModePackages.handlePackageAddedLocked(ssp, 14535 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)); 14536 } 14537 } 14538 14539 /* 14540 * If this is the time zone changed action, queue up a message that will reset the timezone 14541 * of all currently running processes. This message will get queued up before the broadcast 14542 * happens. 14543 */ 14544 if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) { 14545 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 14546 } 14547 14548 /* 14549 * If the user set the time, let all running processes know. 14550 */ 14551 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) { 14552 final int is24Hour = intent.getBooleanExtra( 14553 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 : 0; 14554 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0)); 14555 } 14556 14557 if (Intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) { 14558 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 14559 } 14560 14561 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) { 14562 ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO); 14563 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy)); 14564 } 14565 14566 // Add to the sticky list if requested. 14567 if (sticky) { 14568 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 14569 callingPid, callingUid) 14570 != PackageManager.PERMISSION_GRANTED) { 14571 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 14572 + callingPid + ", uid=" + callingUid 14573 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 14574 Slog.w(TAG, msg); 14575 throw new SecurityException(msg); 14576 } 14577 if (requiredPermission != null) { 14578 Slog.w(TAG, "Can't broadcast sticky intent " + intent 14579 + " and enforce permission " + requiredPermission); 14580 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 14581 } 14582 if (intent.getComponent() != null) { 14583 throw new SecurityException( 14584 "Sticky broadcasts can't target a specific component"); 14585 } 14586 // We use userId directly here, since the "all" target is maintained 14587 // as a separate set of sticky broadcasts. 14588 if (userId != UserHandle.USER_ALL) { 14589 // But first, if this is not a broadcast to all users, then 14590 // make sure it doesn't conflict with an existing broadcast to 14591 // all users. 14592 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 14593 UserHandle.USER_ALL); 14594 if (stickies != null) { 14595 ArrayList<Intent> list = stickies.get(intent.getAction()); 14596 if (list != null) { 14597 int N = list.size(); 14598 int i; 14599 for (i=0; i<N; i++) { 14600 if (intent.filterEquals(list.get(i))) { 14601 throw new IllegalArgumentException( 14602 "Sticky broadcast " + intent + " for user " 14603 + userId + " conflicts with existing global broadcast"); 14604 } 14605 } 14606 } 14607 } 14608 } 14609 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14610 if (stickies == null) { 14611 stickies = new ArrayMap<String, ArrayList<Intent>>(); 14612 mStickyBroadcasts.put(userId, stickies); 14613 } 14614 ArrayList<Intent> list = stickies.get(intent.getAction()); 14615 if (list == null) { 14616 list = new ArrayList<Intent>(); 14617 stickies.put(intent.getAction(), list); 14618 } 14619 int N = list.size(); 14620 int i; 14621 for (i=0; i<N; i++) { 14622 if (intent.filterEquals(list.get(i))) { 14623 // This sticky already exists, replace it. 14624 list.set(i, new Intent(intent)); 14625 break; 14626 } 14627 } 14628 if (i >= N) { 14629 list.add(new Intent(intent)); 14630 } 14631 } 14632 14633 int[] users; 14634 if (userId == UserHandle.USER_ALL) { 14635 // Caller wants broadcast to go to all started users. 14636 users = mStartedUserArray; 14637 } else { 14638 // Caller wants broadcast to go to one specific user. 14639 users = new int[] {userId}; 14640 } 14641 14642 // Figure out who all will receive this broadcast. 14643 List receivers = null; 14644 List<BroadcastFilter> registeredReceivers = null; 14645 // Need to resolve the intent to interested receivers... 14646 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 14647 == 0) { 14648 receivers = collectReceiverComponents(intent, resolvedType, users); 14649 } 14650 if (intent.getComponent() == null) { 14651 registeredReceivers = mReceiverResolver.queryIntent(intent, 14652 resolvedType, false, userId); 14653 } 14654 14655 final boolean replacePending = 14656 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 14657 14658 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction() 14659 + " replacePending=" + replacePending); 14660 14661 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 14662 if (!ordered && NR > 0) { 14663 // If we are not serializing this broadcast, then send the 14664 // registered receivers separately so they don't wait for the 14665 // components to be launched. 14666 final BroadcastQueue queue = broadcastQueueForIntent(intent); 14667 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 14668 callerPackage, callingPid, callingUid, resolvedType, requiredPermission, 14669 appOp, registeredReceivers, resultTo, resultCode, resultData, map, 14670 ordered, sticky, false, userId); 14671 if (DEBUG_BROADCAST) Slog.v( 14672 TAG, "Enqueueing parallel broadcast " + r); 14673 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r); 14674 if (!replaced) { 14675 queue.enqueueParallelBroadcastLocked(r); 14676 queue.scheduleBroadcastsLocked(); 14677 } 14678 registeredReceivers = null; 14679 NR = 0; 14680 } 14681 14682 // Merge into one list. 14683 int ir = 0; 14684 if (receivers != null) { 14685 // A special case for PACKAGE_ADDED: do not allow the package 14686 // being added to see this broadcast. This prevents them from 14687 // using this as a back door to get run as soon as they are 14688 // installed. Maybe in the future we want to have a special install 14689 // broadcast or such for apps, but we'd like to deliberately make 14690 // this decision. 14691 String skipPackages[] = null; 14692 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 14693 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 14694 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 14695 Uri data = intent.getData(); 14696 if (data != null) { 14697 String pkgName = data.getSchemeSpecificPart(); 14698 if (pkgName != null) { 14699 skipPackages = new String[] { pkgName }; 14700 } 14701 } 14702 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 14703 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 14704 } 14705 if (skipPackages != null && (skipPackages.length > 0)) { 14706 for (String skipPackage : skipPackages) { 14707 if (skipPackage != null) { 14708 int NT = receivers.size(); 14709 for (int it=0; it<NT; it++) { 14710 ResolveInfo curt = (ResolveInfo)receivers.get(it); 14711 if (curt.activityInfo.packageName.equals(skipPackage)) { 14712 receivers.remove(it); 14713 it--; 14714 NT--; 14715 } 14716 } 14717 } 14718 } 14719 } 14720 14721 int NT = receivers != null ? receivers.size() : 0; 14722 int it = 0; 14723 ResolveInfo curt = null; 14724 BroadcastFilter curr = null; 14725 while (it < NT && ir < NR) { 14726 if (curt == null) { 14727 curt = (ResolveInfo)receivers.get(it); 14728 } 14729 if (curr == null) { 14730 curr = registeredReceivers.get(ir); 14731 } 14732 if (curr.getPriority() >= curt.priority) { 14733 // Insert this broadcast record into the final list. 14734 receivers.add(it, curr); 14735 ir++; 14736 curr = null; 14737 it++; 14738 NT++; 14739 } else { 14740 // Skip to the next ResolveInfo in the final list. 14741 it++; 14742 curt = null; 14743 } 14744 } 14745 } 14746 while (ir < NR) { 14747 if (receivers == null) { 14748 receivers = new ArrayList(); 14749 } 14750 receivers.add(registeredReceivers.get(ir)); 14751 ir++; 14752 } 14753 14754 if ((receivers != null && receivers.size() > 0) 14755 || resultTo != null) { 14756 BroadcastQueue queue = broadcastQueueForIntent(intent); 14757 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 14758 callerPackage, callingPid, callingUid, resolvedType, 14759 requiredPermission, appOp, receivers, resultTo, resultCode, 14760 resultData, map, ordered, sticky, false, userId); 14761 if (DEBUG_BROADCAST) Slog.v( 14762 TAG, "Enqueueing ordered broadcast " + r 14763 + ": prev had " + queue.mOrderedBroadcasts.size()); 14764 if (DEBUG_BROADCAST) { 14765 int seq = r.intent.getIntExtra("seq", -1); 14766 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq); 14767 } 14768 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r); 14769 if (!replaced) { 14770 queue.enqueueOrderedBroadcastLocked(r); 14771 queue.scheduleBroadcastsLocked(); 14772 } 14773 } 14774 14775 return ActivityManager.BROADCAST_SUCCESS; 14776 } 14777 14778 final Intent verifyBroadcastLocked(Intent intent) { 14779 // Refuse possible leaked file descriptors 14780 if (intent != null && intent.hasFileDescriptors() == true) { 14781 throw new IllegalArgumentException("File descriptors passed in Intent"); 14782 } 14783 14784 int flags = intent.getFlags(); 14785 14786 if (!mProcessesReady) { 14787 // if the caller really truly claims to know what they're doing, go 14788 // ahead and allow the broadcast without launching any receivers 14789 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 14790 intent = new Intent(intent); 14791 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 14792 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 14793 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 14794 + " before boot completion"); 14795 throw new IllegalStateException("Cannot broadcast before boot completed"); 14796 } 14797 } 14798 14799 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 14800 throw new IllegalArgumentException( 14801 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 14802 } 14803 14804 return intent; 14805 } 14806 14807 public final int broadcastIntent(IApplicationThread caller, 14808 Intent intent, String resolvedType, IIntentReceiver resultTo, 14809 int resultCode, String resultData, Bundle map, 14810 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) { 14811 enforceNotIsolatedCaller("broadcastIntent"); 14812 synchronized(this) { 14813 intent = verifyBroadcastLocked(intent); 14814 14815 final ProcessRecord callerApp = getRecordForAppLocked(caller); 14816 final int callingPid = Binder.getCallingPid(); 14817 final int callingUid = Binder.getCallingUid(); 14818 final long origId = Binder.clearCallingIdentity(); 14819 int res = broadcastIntentLocked(callerApp, 14820 callerApp != null ? callerApp.info.packageName : null, 14821 intent, resolvedType, resultTo, 14822 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky, 14823 callingPid, callingUid, userId); 14824 Binder.restoreCallingIdentity(origId); 14825 return res; 14826 } 14827 } 14828 14829 int broadcastIntentInPackage(String packageName, int uid, 14830 Intent intent, String resolvedType, IIntentReceiver resultTo, 14831 int resultCode, String resultData, Bundle map, 14832 String requiredPermission, boolean serialized, boolean sticky, int userId) { 14833 synchronized(this) { 14834 intent = verifyBroadcastLocked(intent); 14835 14836 final long origId = Binder.clearCallingIdentity(); 14837 int res = broadcastIntentLocked(null, packageName, intent, resolvedType, 14838 resultTo, resultCode, resultData, map, requiredPermission, 14839 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId); 14840 Binder.restoreCallingIdentity(origId); 14841 return res; 14842 } 14843 } 14844 14845 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 14846 // Refuse possible leaked file descriptors 14847 if (intent != null && intent.hasFileDescriptors() == true) { 14848 throw new IllegalArgumentException("File descriptors passed in Intent"); 14849 } 14850 14851 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 14852 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 14853 14854 synchronized(this) { 14855 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 14856 != PackageManager.PERMISSION_GRANTED) { 14857 String msg = "Permission Denial: unbroadcastIntent() from pid=" 14858 + Binder.getCallingPid() 14859 + ", uid=" + Binder.getCallingUid() 14860 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 14861 Slog.w(TAG, msg); 14862 throw new SecurityException(msg); 14863 } 14864 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 14865 if (stickies != null) { 14866 ArrayList<Intent> list = stickies.get(intent.getAction()); 14867 if (list != null) { 14868 int N = list.size(); 14869 int i; 14870 for (i=0; i<N; i++) { 14871 if (intent.filterEquals(list.get(i))) { 14872 list.remove(i); 14873 break; 14874 } 14875 } 14876 if (list.size() <= 0) { 14877 stickies.remove(intent.getAction()); 14878 } 14879 } 14880 if (stickies.size() <= 0) { 14881 mStickyBroadcasts.remove(userId); 14882 } 14883 } 14884 } 14885 } 14886 14887 private final boolean finishReceiverLocked(IBinder receiver, int resultCode, 14888 String resultData, Bundle resultExtras, boolean resultAbort) { 14889 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver); 14890 if (r == null) { 14891 Slog.w(TAG, "finishReceiver called but not found on queue"); 14892 return false; 14893 } 14894 14895 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort, false); 14896 } 14897 14898 void backgroundServicesFinishedLocked(int userId) { 14899 for (BroadcastQueue queue : mBroadcastQueues) { 14900 queue.backgroundServicesFinishedLocked(userId); 14901 } 14902 } 14903 14904 public void finishReceiver(IBinder who, int resultCode, String resultData, 14905 Bundle resultExtras, boolean resultAbort) { 14906 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who); 14907 14908 // Refuse possible leaked file descriptors 14909 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 14910 throw new IllegalArgumentException("File descriptors passed in Bundle"); 14911 } 14912 14913 final long origId = Binder.clearCallingIdentity(); 14914 try { 14915 boolean doNext = false; 14916 BroadcastRecord r; 14917 14918 synchronized(this) { 14919 r = broadcastRecordForReceiverLocked(who); 14920 if (r != null) { 14921 doNext = r.queue.finishReceiverLocked(r, resultCode, 14922 resultData, resultExtras, resultAbort, true); 14923 } 14924 } 14925 14926 if (doNext) { 14927 r.queue.processNextBroadcast(false); 14928 } 14929 trimApplications(); 14930 } finally { 14931 Binder.restoreCallingIdentity(origId); 14932 } 14933 } 14934 14935 // ========================================================= 14936 // INSTRUMENTATION 14937 // ========================================================= 14938 14939 public boolean startInstrumentation(ComponentName className, 14940 String profileFile, int flags, Bundle arguments, 14941 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 14942 int userId, String abiOverride) { 14943 enforceNotIsolatedCaller("startInstrumentation"); 14944 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 14945 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 14946 // Refuse possible leaked file descriptors 14947 if (arguments != null && arguments.hasFileDescriptors()) { 14948 throw new IllegalArgumentException("File descriptors passed in Bundle"); 14949 } 14950 14951 synchronized(this) { 14952 InstrumentationInfo ii = null; 14953 ApplicationInfo ai = null; 14954 try { 14955 ii = mContext.getPackageManager().getInstrumentationInfo( 14956 className, STOCK_PM_FLAGS); 14957 ai = AppGlobals.getPackageManager().getApplicationInfo( 14958 ii.targetPackage, STOCK_PM_FLAGS, userId); 14959 } catch (PackageManager.NameNotFoundException e) { 14960 } catch (RemoteException e) { 14961 } 14962 if (ii == null) { 14963 reportStartInstrumentationFailure(watcher, className, 14964 "Unable to find instrumentation info for: " + className); 14965 return false; 14966 } 14967 if (ai == null) { 14968 reportStartInstrumentationFailure(watcher, className, 14969 "Unable to find instrumentation target package: " + ii.targetPackage); 14970 return false; 14971 } 14972 14973 int match = mContext.getPackageManager().checkSignatures( 14974 ii.targetPackage, ii.packageName); 14975 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 14976 String msg = "Permission Denial: starting instrumentation " 14977 + className + " from pid=" 14978 + Binder.getCallingPid() 14979 + ", uid=" + Binder.getCallingPid() 14980 + " not allowed because package " + ii.packageName 14981 + " does not have a signature matching the target " 14982 + ii.targetPackage; 14983 reportStartInstrumentationFailure(watcher, className, msg); 14984 throw new SecurityException(msg); 14985 } 14986 14987 final long origId = Binder.clearCallingIdentity(); 14988 // Instrumentation can kill and relaunch even persistent processes 14989 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, 14990 "start instr"); 14991 ProcessRecord app = addAppLocked(ai, false, abiOverride); 14992 app.instrumentationClass = className; 14993 app.instrumentationInfo = ai; 14994 app.instrumentationProfileFile = profileFile; 14995 app.instrumentationArguments = arguments; 14996 app.instrumentationWatcher = watcher; 14997 app.instrumentationUiAutomationConnection = uiAutomationConnection; 14998 app.instrumentationResultClass = className; 14999 Binder.restoreCallingIdentity(origId); 15000 } 15001 15002 return true; 15003 } 15004 15005 /** 15006 * Report errors that occur while attempting to start Instrumentation. Always writes the 15007 * error to the logs, but if somebody is watching, send the report there too. This enables 15008 * the "am" command to report errors with more information. 15009 * 15010 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 15011 * @param cn The component name of the instrumentation. 15012 * @param report The error report. 15013 */ 15014 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher, 15015 ComponentName cn, String report) { 15016 Slog.w(TAG, report); 15017 try { 15018 if (watcher != null) { 15019 Bundle results = new Bundle(); 15020 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 15021 results.putString("Error", report); 15022 watcher.instrumentationStatus(cn, -1, results); 15023 } 15024 } catch (RemoteException e) { 15025 Slog.w(TAG, e); 15026 } 15027 } 15028 15029 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 15030 if (app.instrumentationWatcher != null) { 15031 try { 15032 // NOTE: IInstrumentationWatcher *must* be oneway here 15033 app.instrumentationWatcher.instrumentationFinished( 15034 app.instrumentationClass, 15035 resultCode, 15036 results); 15037 } catch (RemoteException e) { 15038 } 15039 } 15040 if (app.instrumentationUiAutomationConnection != null) { 15041 try { 15042 app.instrumentationUiAutomationConnection.shutdown(); 15043 } catch (RemoteException re) { 15044 /* ignore */ 15045 } 15046 // Only a UiAutomation can set this flag and now that 15047 // it is finished we make sure it is reset to its default. 15048 mUserIsMonkey = false; 15049 } 15050 app.instrumentationWatcher = null; 15051 app.instrumentationUiAutomationConnection = null; 15052 app.instrumentationClass = null; 15053 app.instrumentationInfo = null; 15054 app.instrumentationProfileFile = null; 15055 app.instrumentationArguments = null; 15056 15057 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId, 15058 "finished inst"); 15059 } 15060 15061 public void finishInstrumentation(IApplicationThread target, 15062 int resultCode, Bundle results) { 15063 int userId = UserHandle.getCallingUserId(); 15064 // Refuse possible leaked file descriptors 15065 if (results != null && results.hasFileDescriptors()) { 15066 throw new IllegalArgumentException("File descriptors passed in Intent"); 15067 } 15068 15069 synchronized(this) { 15070 ProcessRecord app = getRecordForAppLocked(target); 15071 if (app == null) { 15072 Slog.w(TAG, "finishInstrumentation: no app for " + target); 15073 return; 15074 } 15075 final long origId = Binder.clearCallingIdentity(); 15076 finishInstrumentationLocked(app, resultCode, results); 15077 Binder.restoreCallingIdentity(origId); 15078 } 15079 } 15080 15081 // ========================================================= 15082 // CONFIGURATION 15083 // ========================================================= 15084 15085 public ConfigurationInfo getDeviceConfigurationInfo() { 15086 ConfigurationInfo config = new ConfigurationInfo(); 15087 synchronized (this) { 15088 config.reqTouchScreen = mConfiguration.touchscreen; 15089 config.reqKeyboardType = mConfiguration.keyboard; 15090 config.reqNavigation = mConfiguration.navigation; 15091 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD 15092 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) { 15093 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV; 15094 } 15095 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED 15096 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) { 15097 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD; 15098 } 15099 config.reqGlEsVersion = GL_ES_VERSION; 15100 } 15101 return config; 15102 } 15103 15104 ActivityStack getFocusedStack() { 15105 return mStackSupervisor.getFocusedStack(); 15106 } 15107 15108 public Configuration getConfiguration() { 15109 Configuration ci; 15110 synchronized(this) { 15111 ci = new Configuration(mConfiguration); 15112 } 15113 return ci; 15114 } 15115 15116 public void updatePersistentConfiguration(Configuration values) { 15117 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 15118 "updateConfiguration()"); 15119 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS, 15120 "updateConfiguration()"); 15121 if (values == null) { 15122 throw new NullPointerException("Configuration must not be null"); 15123 } 15124 15125 synchronized(this) { 15126 final long origId = Binder.clearCallingIdentity(); 15127 updateConfigurationLocked(values, null, true, false); 15128 Binder.restoreCallingIdentity(origId); 15129 } 15130 } 15131 15132 public void updateConfiguration(Configuration values) { 15133 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 15134 "updateConfiguration()"); 15135 15136 synchronized(this) { 15137 if (values == null && mWindowManager != null) { 15138 // sentinel: fetch the current configuration from the window manager 15139 values = mWindowManager.computeNewConfiguration(); 15140 } 15141 15142 if (mWindowManager != null) { 15143 mProcessList.applyDisplaySize(mWindowManager); 15144 } 15145 15146 final long origId = Binder.clearCallingIdentity(); 15147 if (values != null) { 15148 Settings.System.clearConfiguration(values); 15149 } 15150 updateConfigurationLocked(values, null, false, false); 15151 Binder.restoreCallingIdentity(origId); 15152 } 15153 } 15154 15155 /** 15156 * Do either or both things: (1) change the current configuration, and (2) 15157 * make sure the given activity is running with the (now) current 15158 * configuration. Returns true if the activity has been left running, or 15159 * false if <var>starting</var> is being destroyed to match the new 15160 * configuration. 15161 * @param persistent TODO 15162 */ 15163 boolean updateConfigurationLocked(Configuration values, 15164 ActivityRecord starting, boolean persistent, boolean initLocale) { 15165 int changes = 0; 15166 15167 if (values != null) { 15168 Configuration newConfig = new Configuration(mConfiguration); 15169 changes = newConfig.updateFrom(values); 15170 if (changes != 0) { 15171 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 15172 Slog.i(TAG, "Updating configuration to: " + values); 15173 } 15174 15175 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes); 15176 15177 if (values.locale != null && !initLocale) { 15178 saveLocaleLocked(values.locale, 15179 !values.locale.equals(mConfiguration.locale), 15180 values.userSetLocale); 15181 } 15182 15183 mConfigurationSeq++; 15184 if (mConfigurationSeq <= 0) { 15185 mConfigurationSeq = 1; 15186 } 15187 newConfig.seq = mConfigurationSeq; 15188 mConfiguration = newConfig; 15189 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig); 15190 //mUsageStatsService.noteStartConfig(newConfig); 15191 15192 final Configuration configCopy = new Configuration(mConfiguration); 15193 15194 // TODO: If our config changes, should we auto dismiss any currently 15195 // showing dialogs? 15196 mShowDialogs = shouldShowDialogs(newConfig); 15197 15198 AttributeCache ac = AttributeCache.instance(); 15199 if (ac != null) { 15200 ac.updateConfiguration(configCopy); 15201 } 15202 15203 // Make sure all resources in our process are updated 15204 // right now, so that anyone who is going to retrieve 15205 // resource values after we return will be sure to get 15206 // the new ones. This is especially important during 15207 // boot, where the first config change needs to guarantee 15208 // all resources have that config before following boot 15209 // code is executed. 15210 mSystemThread.applyConfigurationToResources(configCopy); 15211 15212 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) { 15213 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG); 15214 msg.obj = new Configuration(configCopy); 15215 mHandler.sendMessage(msg); 15216 } 15217 15218 for (int i=mLruProcesses.size()-1; i>=0; i--) { 15219 ProcessRecord app = mLruProcesses.get(i); 15220 try { 15221 if (app.thread != null) { 15222 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc " 15223 + app.processName + " new config " + mConfiguration); 15224 app.thread.scheduleConfigurationChanged(configCopy); 15225 } 15226 } catch (Exception e) { 15227 } 15228 } 15229 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 15230 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 15231 | Intent.FLAG_RECEIVER_REPLACE_PENDING 15232 | Intent.FLAG_RECEIVER_FOREGROUND); 15233 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, 15234 null, AppOpsManager.OP_NONE, false, false, MY_PID, 15235 Process.SYSTEM_UID, UserHandle.USER_ALL); 15236 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) { 15237 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 15238 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15239 broadcastIntentLocked(null, null, intent, 15240 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 15241 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 15242 } 15243 } 15244 } 15245 15246 boolean kept = true; 15247 final ActivityStack mainStack = mStackSupervisor.getFocusedStack(); 15248 // mainStack is null during startup. 15249 if (mainStack != null) { 15250 if (changes != 0 && starting == null) { 15251 // If the configuration changed, and the caller is not already 15252 // in the process of starting an activity, then find the top 15253 // activity to check if its configuration needs to change. 15254 starting = mainStack.topRunningActivityLocked(null); 15255 } 15256 15257 if (starting != null) { 15258 kept = mainStack.ensureActivityConfigurationLocked(starting, changes); 15259 // And we need to make sure at this point that all other activities 15260 // are made visible with the correct configuration. 15261 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes); 15262 } 15263 } 15264 15265 if (values != null && mWindowManager != null) { 15266 mWindowManager.setNewConfiguration(mConfiguration); 15267 } 15268 15269 return kept; 15270 } 15271 15272 /** 15273 * Decide based on the configuration whether we should shouw the ANR, 15274 * crash, etc dialogs. The idea is that if there is no affordnace to 15275 * press the on-screen buttons, we shouldn't show the dialog. 15276 * 15277 * A thought: SystemUI might also want to get told about this, the Power 15278 * dialog / global actions also might want different behaviors. 15279 */ 15280 private static final boolean shouldShowDialogs(Configuration config) { 15281 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS 15282 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH); 15283 } 15284 15285 /** 15286 * Save the locale. You must be inside a synchronized (this) block. 15287 */ 15288 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) { 15289 if(isDiff) { 15290 SystemProperties.set("user.language", l.getLanguage()); 15291 SystemProperties.set("user.region", l.getCountry()); 15292 } 15293 15294 if(isPersist) { 15295 SystemProperties.set("persist.sys.language", l.getLanguage()); 15296 SystemProperties.set("persist.sys.country", l.getCountry()); 15297 SystemProperties.set("persist.sys.localevar", l.getVariant()); 15298 } 15299 } 15300 15301 @Override 15302 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) { 15303 ActivityRecord srec = ActivityRecord.forToken(token); 15304 return srec != null && srec.task.affinity != null && 15305 srec.task.affinity.equals(destAffinity); 15306 } 15307 15308 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode, 15309 Intent resultData) { 15310 15311 synchronized (this) { 15312 final ActivityStack stack = ActivityRecord.getStackLocked(token); 15313 if (stack != null) { 15314 return stack.navigateUpToLocked(token, destIntent, resultCode, resultData); 15315 } 15316 return false; 15317 } 15318 } 15319 15320 public int getLaunchedFromUid(IBinder activityToken) { 15321 ActivityRecord srec = ActivityRecord.forToken(activityToken); 15322 if (srec == null) { 15323 return -1; 15324 } 15325 return srec.launchedFromUid; 15326 } 15327 15328 public String getLaunchedFromPackage(IBinder activityToken) { 15329 ActivityRecord srec = ActivityRecord.forToken(activityToken); 15330 if (srec == null) { 15331 return null; 15332 } 15333 return srec.launchedFromPackage; 15334 } 15335 15336 // ========================================================= 15337 // LIFETIME MANAGEMENT 15338 // ========================================================= 15339 15340 // Returns which broadcast queue the app is the current [or imminent] receiver 15341 // on, or 'null' if the app is not an active broadcast recipient. 15342 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) { 15343 BroadcastRecord r = app.curReceiver; 15344 if (r != null) { 15345 return r.queue; 15346 } 15347 15348 // It's not the current receiver, but it might be starting up to become one 15349 synchronized (this) { 15350 for (BroadcastQueue queue : mBroadcastQueues) { 15351 r = queue.mPendingBroadcast; 15352 if (r != null && r.curApp == app) { 15353 // found it; report which queue it's in 15354 return queue; 15355 } 15356 } 15357 } 15358 15359 return null; 15360 } 15361 15362 private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, 15363 boolean doingAll, long now) { 15364 if (mAdjSeq == app.adjSeq) { 15365 // This adjustment has already been computed. 15366 return app.curRawAdj; 15367 } 15368 15369 if (app.thread == null) { 15370 app.adjSeq = mAdjSeq; 15371 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 15372 app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15373 return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ); 15374 } 15375 15376 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN; 15377 app.adjSource = null; 15378 app.adjTarget = null; 15379 app.empty = false; 15380 app.cached = false; 15381 15382 final int activitiesSize = app.activities.size(); 15383 15384 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) { 15385 // The max adjustment doesn't allow this app to be anything 15386 // below foreground, so it is not worth doing work for it. 15387 app.adjType = "fixed"; 15388 app.adjSeq = mAdjSeq; 15389 app.curRawAdj = app.maxAdj; 15390 app.foregroundActivities = false; 15391 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 15392 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT; 15393 // System processes can do UI, and when they do we want to have 15394 // them trim their memory after the user leaves the UI. To 15395 // facilitate this, here we need to determine whether or not it 15396 // is currently showing UI. 15397 app.systemNoUi = true; 15398 if (app == TOP_APP) { 15399 app.systemNoUi = false; 15400 } else if (activitiesSize > 0) { 15401 for (int j = 0; j < activitiesSize; j++) { 15402 final ActivityRecord r = app.activities.get(j); 15403 if (r.visible) { 15404 app.systemNoUi = false; 15405 } 15406 } 15407 } 15408 if (!app.systemNoUi) { 15409 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI; 15410 } 15411 return (app.curAdj=app.maxAdj); 15412 } 15413 15414 app.systemNoUi = false; 15415 15416 // Determine the importance of the process, starting with most 15417 // important to least, and assign an appropriate OOM adjustment. 15418 int adj; 15419 int schedGroup; 15420 int procState; 15421 boolean foregroundActivities = false; 15422 BroadcastQueue queue; 15423 if (app == TOP_APP) { 15424 // The last app on the list is the foreground app. 15425 adj = ProcessList.FOREGROUND_APP_ADJ; 15426 schedGroup = Process.THREAD_GROUP_DEFAULT; 15427 app.adjType = "top-activity"; 15428 foregroundActivities = true; 15429 procState = ActivityManager.PROCESS_STATE_TOP; 15430 } else if (app.instrumentationClass != null) { 15431 // Don't want to kill running instrumentation. 15432 adj = ProcessList.FOREGROUND_APP_ADJ; 15433 schedGroup = Process.THREAD_GROUP_DEFAULT; 15434 app.adjType = "instrumentation"; 15435 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15436 } else if ((queue = isReceivingBroadcast(app)) != null) { 15437 // An app that is currently receiving a broadcast also 15438 // counts as being in the foreground for OOM killer purposes. 15439 // It's placed in a sched group based on the nature of the 15440 // broadcast as reflected by which queue it's active in. 15441 adj = ProcessList.FOREGROUND_APP_ADJ; 15442 schedGroup = (queue == mFgBroadcastQueue) 15443 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 15444 app.adjType = "broadcast"; 15445 procState = ActivityManager.PROCESS_STATE_RECEIVER; 15446 } else if (app.executingServices.size() > 0) { 15447 // An app that is currently executing a service callback also 15448 // counts as being in the foreground. 15449 adj = ProcessList.FOREGROUND_APP_ADJ; 15450 schedGroup = app.execServicesFg ? 15451 Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 15452 app.adjType = "exec-service"; 15453 procState = ActivityManager.PROCESS_STATE_SERVICE; 15454 //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app); 15455 } else { 15456 // As far as we know the process is empty. We may change our mind later. 15457 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 15458 // At this point we don't actually know the adjustment. Use the cached adj 15459 // value that the caller wants us to. 15460 adj = cachedAdj; 15461 procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15462 app.cached = true; 15463 app.empty = true; 15464 app.adjType = "cch-empty"; 15465 } 15466 15467 // Examine all activities if not already foreground. 15468 if (!foregroundActivities && activitiesSize > 0) { 15469 for (int j = 0; j < activitiesSize; j++) { 15470 final ActivityRecord r = app.activities.get(j); 15471 if (r.app != app) { 15472 Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc " 15473 + app + "?!?"); 15474 continue; 15475 } 15476 if (r.visible) { 15477 // App has a visible activity; only upgrade adjustment. 15478 if (adj > ProcessList.VISIBLE_APP_ADJ) { 15479 adj = ProcessList.VISIBLE_APP_ADJ; 15480 app.adjType = "visible"; 15481 } 15482 if (procState > ActivityManager.PROCESS_STATE_TOP) { 15483 procState = ActivityManager.PROCESS_STATE_TOP; 15484 } 15485 schedGroup = Process.THREAD_GROUP_DEFAULT; 15486 app.cached = false; 15487 app.empty = false; 15488 foregroundActivities = true; 15489 break; 15490 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) { 15491 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15492 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 15493 app.adjType = "pausing"; 15494 } 15495 if (procState > ActivityManager.PROCESS_STATE_TOP) { 15496 procState = ActivityManager.PROCESS_STATE_TOP; 15497 } 15498 schedGroup = Process.THREAD_GROUP_DEFAULT; 15499 app.cached = false; 15500 app.empty = false; 15501 foregroundActivities = true; 15502 } else if (r.state == ActivityState.STOPPING) { 15503 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15504 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 15505 app.adjType = "stopping"; 15506 } 15507 // For the process state, we will at this point consider the 15508 // process to be cached. It will be cached either as an activity 15509 // or empty depending on whether the activity is finishing. We do 15510 // this so that we can treat the process as cached for purposes of 15511 // memory trimming (determing current memory level, trim command to 15512 // send to process) since there can be an arbitrary number of stopping 15513 // processes and they should soon all go into the cached state. 15514 if (!r.finishing) { 15515 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 15516 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 15517 } 15518 } 15519 app.cached = false; 15520 app.empty = false; 15521 foregroundActivities = true; 15522 } else { 15523 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 15524 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 15525 app.adjType = "cch-act"; 15526 } 15527 } 15528 } 15529 } 15530 15531 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15532 if (app.foregroundServices) { 15533 // The user is aware of this app, so make it visible. 15534 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 15535 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15536 app.cached = false; 15537 app.adjType = "fg-service"; 15538 schedGroup = Process.THREAD_GROUP_DEFAULT; 15539 } else if (app.forcingToForeground != null) { 15540 // The user is aware of this app, so make it visible. 15541 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 15542 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15543 app.cached = false; 15544 app.adjType = "force-fg"; 15545 app.adjSource = app.forcingToForeground; 15546 schedGroup = Process.THREAD_GROUP_DEFAULT; 15547 } 15548 } 15549 15550 if (app == mHeavyWeightProcess) { 15551 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) { 15552 // We don't want to kill the current heavy-weight process. 15553 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ; 15554 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 15555 app.cached = false; 15556 app.adjType = "heavy"; 15557 } 15558 if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 15559 procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT; 15560 } 15561 } 15562 15563 if (app == mHomeProcess) { 15564 if (adj > ProcessList.HOME_APP_ADJ) { 15565 // This process is hosting what we currently consider to be the 15566 // home app, so we don't want to let it go into the background. 15567 adj = ProcessList.HOME_APP_ADJ; 15568 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 15569 app.cached = false; 15570 app.adjType = "home"; 15571 } 15572 if (procState > ActivityManager.PROCESS_STATE_HOME) { 15573 procState = ActivityManager.PROCESS_STATE_HOME; 15574 } 15575 } 15576 15577 if (app == mPreviousProcess && app.activities.size() > 0) { 15578 if (adj > ProcessList.PREVIOUS_APP_ADJ) { 15579 // This was the previous process that showed UI to the user. 15580 // We want to try to keep it around more aggressively, to give 15581 // a good experience around switching between two apps. 15582 adj = ProcessList.PREVIOUS_APP_ADJ; 15583 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 15584 app.cached = false; 15585 app.adjType = "previous"; 15586 } 15587 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 15588 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 15589 } 15590 } 15591 15592 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj 15593 + " reason=" + app.adjType); 15594 15595 // By default, we use the computed adjustment. It may be changed if 15596 // there are applications dependent on our services or providers, but 15597 // this gives us a baseline and makes sure we don't get into an 15598 // infinite recursion. 15599 app.adjSeq = mAdjSeq; 15600 app.curRawAdj = adj; 15601 app.hasStartedServices = false; 15602 15603 if (mBackupTarget != null && app == mBackupTarget.app) { 15604 // If possible we want to avoid killing apps while they're being backed up 15605 if (adj > ProcessList.BACKUP_APP_ADJ) { 15606 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app); 15607 adj = ProcessList.BACKUP_APP_ADJ; 15608 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 15609 procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 15610 } 15611 app.adjType = "backup"; 15612 app.cached = false; 15613 } 15614 if (procState > ActivityManager.PROCESS_STATE_BACKUP) { 15615 procState = ActivityManager.PROCESS_STATE_BACKUP; 15616 } 15617 } 15618 15619 boolean mayBeTop = false; 15620 15621 for (int is = app.services.size()-1; 15622 is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 15623 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 15624 || procState > ActivityManager.PROCESS_STATE_TOP); 15625 is--) { 15626 ServiceRecord s = app.services.valueAt(is); 15627 if (s.startRequested) { 15628 app.hasStartedServices = true; 15629 if (procState > ActivityManager.PROCESS_STATE_SERVICE) { 15630 procState = ActivityManager.PROCESS_STATE_SERVICE; 15631 } 15632 if (app.hasShownUi && app != mHomeProcess) { 15633 // If this process has shown some UI, let it immediately 15634 // go to the LRU list because it may be pretty heavy with 15635 // UI stuff. We'll tag it with a label just to help 15636 // debug and understand what is going on. 15637 if (adj > ProcessList.SERVICE_ADJ) { 15638 app.adjType = "cch-started-ui-services"; 15639 } 15640 } else { 15641 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) { 15642 // This service has seen some activity within 15643 // recent memory, so we will keep its process ahead 15644 // of the background processes. 15645 if (adj > ProcessList.SERVICE_ADJ) { 15646 adj = ProcessList.SERVICE_ADJ; 15647 app.adjType = "started-services"; 15648 app.cached = false; 15649 } 15650 } 15651 // If we have let the service slide into the background 15652 // state, still have some text describing what it is doing 15653 // even though the service no longer has an impact. 15654 if (adj > ProcessList.SERVICE_ADJ) { 15655 app.adjType = "cch-started-services"; 15656 } 15657 } 15658 } 15659 for (int conni = s.connections.size()-1; 15660 conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 15661 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 15662 || procState > ActivityManager.PROCESS_STATE_TOP); 15663 conni--) { 15664 ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni); 15665 for (int i = 0; 15666 i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ 15667 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 15668 || procState > ActivityManager.PROCESS_STATE_TOP); 15669 i++) { 15670 // XXX should compute this based on the max of 15671 // all connected clients. 15672 ConnectionRecord cr = clist.get(i); 15673 if (cr.binding.client == app) { 15674 // Binding to ourself is not interesting. 15675 continue; 15676 } 15677 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) { 15678 ProcessRecord client = cr.binding.client; 15679 int clientAdj = computeOomAdjLocked(client, cachedAdj, 15680 TOP_APP, doingAll, now); 15681 int clientProcState = client.curProcState; 15682 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 15683 // If the other app is cached for any reason, for purposes here 15684 // we are going to consider it empty. The specific cached state 15685 // doesn't propagate except under certain conditions. 15686 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15687 } 15688 String adjType = null; 15689 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) { 15690 // Not doing bind OOM management, so treat 15691 // this guy more like a started service. 15692 if (app.hasShownUi && app != mHomeProcess) { 15693 // If this process has shown some UI, let it immediately 15694 // go to the LRU list because it may be pretty heavy with 15695 // UI stuff. We'll tag it with a label just to help 15696 // debug and understand what is going on. 15697 if (adj > clientAdj) { 15698 adjType = "cch-bound-ui-services"; 15699 } 15700 app.cached = false; 15701 clientAdj = adj; 15702 clientProcState = procState; 15703 } else { 15704 if (now >= (s.lastActivity 15705 + ActiveServices.MAX_SERVICE_INACTIVITY)) { 15706 // This service has not seen activity within 15707 // recent memory, so allow it to drop to the 15708 // LRU list if there is no other reason to keep 15709 // it around. We'll also tag it with a label just 15710 // to help debug and undertand what is going on. 15711 if (adj > clientAdj) { 15712 adjType = "cch-bound-services"; 15713 } 15714 clientAdj = adj; 15715 } 15716 } 15717 } 15718 if (adj > clientAdj) { 15719 // If this process has recently shown UI, and 15720 // the process that is binding to it is less 15721 // important than being visible, then we don't 15722 // care about the binding as much as we care 15723 // about letting this process get into the LRU 15724 // list to be killed and restarted if needed for 15725 // memory. 15726 if (app.hasShownUi && app != mHomeProcess 15727 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15728 adjType = "cch-bound-ui-services"; 15729 } else { 15730 if ((cr.flags&(Context.BIND_ABOVE_CLIENT 15731 |Context.BIND_IMPORTANT)) != 0) { 15732 adj = clientAdj; 15733 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0 15734 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ 15735 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15736 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 15737 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) { 15738 adj = clientAdj; 15739 } else { 15740 if (adj > ProcessList.VISIBLE_APP_ADJ) { 15741 adj = ProcessList.VISIBLE_APP_ADJ; 15742 } 15743 } 15744 if (!client.cached) { 15745 app.cached = false; 15746 } 15747 adjType = "service"; 15748 } 15749 } 15750 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 15751 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 15752 schedGroup = Process.THREAD_GROUP_DEFAULT; 15753 } 15754 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 15755 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 15756 // Special handling of clients who are in the top state. 15757 // We *may* want to consider this process to be in the 15758 // top state as well, but only if there is not another 15759 // reason for it to be running. Being on the top is a 15760 // special state, meaning you are specifically running 15761 // for the current top app. If the process is already 15762 // running in the background for some other reason, it 15763 // is more important to continue considering it to be 15764 // in the background state. 15765 mayBeTop = true; 15766 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15767 } else { 15768 // Special handling for above-top states (persistent 15769 // processes). These should not bring the current process 15770 // into the top state, since they are not on top. Instead 15771 // give them the best state after that. 15772 clientProcState = 15773 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15774 } 15775 } 15776 } else { 15777 if (clientProcState < 15778 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 15779 clientProcState = 15780 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 15781 } 15782 } 15783 if (procState > clientProcState) { 15784 procState = clientProcState; 15785 } 15786 if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 15787 && (cr.flags&Context.BIND_SHOWING_UI) != 0) { 15788 app.pendingUiClean = true; 15789 } 15790 if (adjType != null) { 15791 app.adjType = adjType; 15792 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 15793 .REASON_SERVICE_IN_USE; 15794 app.adjSource = cr.binding.client; 15795 app.adjSourceProcState = clientProcState; 15796 app.adjTarget = s.name; 15797 } 15798 } 15799 if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 15800 app.treatLikeActivity = true; 15801 } 15802 final ActivityRecord a = cr.activity; 15803 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) { 15804 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ && 15805 (a.visible || a.state == ActivityState.RESUMED 15806 || a.state == ActivityState.PAUSING)) { 15807 adj = ProcessList.FOREGROUND_APP_ADJ; 15808 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 15809 schedGroup = Process.THREAD_GROUP_DEFAULT; 15810 } 15811 app.cached = false; 15812 app.adjType = "service"; 15813 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 15814 .REASON_SERVICE_IN_USE; 15815 app.adjSource = a; 15816 app.adjSourceProcState = procState; 15817 app.adjTarget = s.name; 15818 } 15819 } 15820 } 15821 } 15822 } 15823 15824 for (int provi = app.pubProviders.size()-1; 15825 provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 15826 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 15827 || procState > ActivityManager.PROCESS_STATE_TOP); 15828 provi--) { 15829 ContentProviderRecord cpr = app.pubProviders.valueAt(provi); 15830 for (int i = cpr.connections.size()-1; 15831 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 15832 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 15833 || procState > ActivityManager.PROCESS_STATE_TOP); 15834 i--) { 15835 ContentProviderConnection conn = cpr.connections.get(i); 15836 ProcessRecord client = conn.client; 15837 if (client == app) { 15838 // Being our own client is not interesting. 15839 continue; 15840 } 15841 int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now); 15842 int clientProcState = client.curProcState; 15843 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 15844 // If the other app is cached for any reason, for purposes here 15845 // we are going to consider it empty. 15846 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15847 } 15848 if (adj > clientAdj) { 15849 if (app.hasShownUi && app != mHomeProcess 15850 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 15851 app.adjType = "cch-ui-provider"; 15852 } else { 15853 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ 15854 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ; 15855 app.adjType = "provider"; 15856 } 15857 app.cached &= client.cached; 15858 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 15859 .REASON_PROVIDER_IN_USE; 15860 app.adjSource = client; 15861 app.adjSourceProcState = clientProcState; 15862 app.adjTarget = cpr.name; 15863 } 15864 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 15865 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 15866 // Special handling of clients who are in the top state. 15867 // We *may* want to consider this process to be in the 15868 // top state as well, but only if there is not another 15869 // reason for it to be running. Being on the top is a 15870 // special state, meaning you are specifically running 15871 // for the current top app. If the process is already 15872 // running in the background for some other reason, it 15873 // is more important to continue considering it to be 15874 // in the background state. 15875 mayBeTop = true; 15876 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 15877 } else { 15878 // Special handling for above-top states (persistent 15879 // processes). These should not bring the current process 15880 // into the top state, since they are not on top. Instead 15881 // give them the best state after that. 15882 clientProcState = 15883 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15884 } 15885 } 15886 if (procState > clientProcState) { 15887 procState = clientProcState; 15888 } 15889 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 15890 schedGroup = Process.THREAD_GROUP_DEFAULT; 15891 } 15892 } 15893 // If the provider has external (non-framework) process 15894 // dependencies, ensure that its adjustment is at least 15895 // FOREGROUND_APP_ADJ. 15896 if (cpr.hasExternalProcessHandles()) { 15897 if (adj > ProcessList.FOREGROUND_APP_ADJ) { 15898 adj = ProcessList.FOREGROUND_APP_ADJ; 15899 schedGroup = Process.THREAD_GROUP_DEFAULT; 15900 app.cached = false; 15901 app.adjType = "provider"; 15902 app.adjTarget = cpr.name; 15903 } 15904 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 15905 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15906 } 15907 } 15908 } 15909 15910 if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) { 15911 // A client of one of our services or providers is in the top state. We 15912 // *may* want to be in the top state, but not if we are already running in 15913 // the background for some other reason. For the decision here, we are going 15914 // to pick out a few specific states that we want to remain in when a client 15915 // is top (states that tend to be longer-term) and otherwise allow it to go 15916 // to the top state. 15917 switch (procState) { 15918 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 15919 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 15920 case ActivityManager.PROCESS_STATE_SERVICE: 15921 // These all are longer-term states, so pull them up to the top 15922 // of the background states, but not all the way to the top state. 15923 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 15924 break; 15925 default: 15926 // Otherwise, top is a better choice, so take it. 15927 procState = ActivityManager.PROCESS_STATE_TOP; 15928 break; 15929 } 15930 } 15931 15932 if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 15933 if (app.hasClientActivities) { 15934 // This is a cached process, but with client activities. Mark it so. 15935 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT; 15936 app.adjType = "cch-client-act"; 15937 } else if (app.treatLikeActivity) { 15938 // This is a cached process, but somebody wants us to treat it like it has 15939 // an activity, okay! 15940 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 15941 app.adjType = "cch-as-act"; 15942 } 15943 } 15944 15945 if (adj == ProcessList.SERVICE_ADJ) { 15946 if (doingAll) { 15947 app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3); 15948 mNewNumServiceProcs++; 15949 //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb); 15950 if (!app.serviceb) { 15951 // This service isn't far enough down on the LRU list to 15952 // normally be a B service, but if we are low on RAM and it 15953 // is large we want to force it down since we would prefer to 15954 // keep launcher over it. 15955 if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 15956 && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) { 15957 app.serviceHighRam = true; 15958 app.serviceb = true; 15959 //Slog.i(TAG, "ADJ " + app + " high ram!"); 15960 } else { 15961 mNewNumAServiceProcs++; 15962 //Slog.i(TAG, "ADJ " + app + " not high ram!"); 15963 } 15964 } else { 15965 app.serviceHighRam = false; 15966 } 15967 } 15968 if (app.serviceb) { 15969 adj = ProcessList.SERVICE_B_ADJ; 15970 } 15971 } 15972 15973 app.curRawAdj = adj; 15974 15975 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid + 15976 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj); 15977 if (adj > app.maxAdj) { 15978 adj = app.maxAdj; 15979 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 15980 schedGroup = Process.THREAD_GROUP_DEFAULT; 15981 } 15982 } 15983 15984 // Do final modification to adj. Everything we do between here and applying 15985 // the final setAdj must be done in this function, because we will also use 15986 // it when computing the final cached adj later. Note that we don't need to 15987 // worry about this for max adj above, since max adj will always be used to 15988 // keep it out of the cached vaues. 15989 app.curAdj = app.modifyRawOomAdj(adj); 15990 app.curSchedGroup = schedGroup; 15991 app.curProcState = procState; 15992 app.foregroundActivities = foregroundActivities; 15993 15994 return app.curRawAdj; 15995 } 15996 15997 /** 15998 * Schedule PSS collection of a process. 15999 */ 16000 void requestPssLocked(ProcessRecord proc, int procState) { 16001 if (mPendingPssProcesses.contains(proc)) { 16002 return; 16003 } 16004 if (mPendingPssProcesses.size() == 0) { 16005 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16006 } 16007 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of: " + proc); 16008 proc.pssProcState = procState; 16009 mPendingPssProcesses.add(proc); 16010 } 16011 16012 /** 16013 * Schedule PSS collection of all processes. 16014 */ 16015 void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) { 16016 if (!always) { 16017 if (now < (mLastFullPssTime + 16018 (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) { 16019 return; 16020 } 16021 } 16022 if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of all procs! memLowered=" + memLowered); 16023 mLastFullPssTime = now; 16024 mFullPssPending = true; 16025 mPendingPssProcesses.ensureCapacity(mLruProcesses.size()); 16026 mPendingPssProcesses.clear(); 16027 for (int i=mLruProcesses.size()-1; i>=0; i--) { 16028 ProcessRecord app = mLruProcesses.get(i); 16029 if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) { 16030 app.pssProcState = app.setProcState; 16031 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 16032 isSleeping(), now); 16033 mPendingPssProcesses.add(app); 16034 } 16035 } 16036 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 16037 } 16038 16039 /** 16040 * Ask a given process to GC right now. 16041 */ 16042 final void performAppGcLocked(ProcessRecord app) { 16043 try { 16044 app.lastRequestedGc = SystemClock.uptimeMillis(); 16045 if (app.thread != null) { 16046 if (app.reportLowMemory) { 16047 app.reportLowMemory = false; 16048 app.thread.scheduleLowMemory(); 16049 } else { 16050 app.thread.processInBackground(); 16051 } 16052 } 16053 } catch (Exception e) { 16054 // whatever. 16055 } 16056 } 16057 16058 /** 16059 * Returns true if things are idle enough to perform GCs. 16060 */ 16061 private final boolean canGcNowLocked() { 16062 boolean processingBroadcasts = false; 16063 for (BroadcastQueue q : mBroadcastQueues) { 16064 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) { 16065 processingBroadcasts = true; 16066 } 16067 } 16068 return !processingBroadcasts 16069 && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle()); 16070 } 16071 16072 /** 16073 * Perform GCs on all processes that are waiting for it, but only 16074 * if things are idle. 16075 */ 16076 final void performAppGcsLocked() { 16077 final int N = mProcessesToGc.size(); 16078 if (N <= 0) { 16079 return; 16080 } 16081 if (canGcNowLocked()) { 16082 while (mProcessesToGc.size() > 0) { 16083 ProcessRecord proc = mProcessesToGc.remove(0); 16084 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) { 16085 if ((proc.lastRequestedGc+GC_MIN_INTERVAL) 16086 <= SystemClock.uptimeMillis()) { 16087 // To avoid spamming the system, we will GC processes one 16088 // at a time, waiting a few seconds between each. 16089 performAppGcLocked(proc); 16090 scheduleAppGcsLocked(); 16091 return; 16092 } else { 16093 // It hasn't been long enough since we last GCed this 16094 // process... put it in the list to wait for its time. 16095 addProcessToGcListLocked(proc); 16096 break; 16097 } 16098 } 16099 } 16100 16101 scheduleAppGcsLocked(); 16102 } 16103 } 16104 16105 /** 16106 * If all looks good, perform GCs on all processes waiting for them. 16107 */ 16108 final void performAppGcsIfAppropriateLocked() { 16109 if (canGcNowLocked()) { 16110 performAppGcsLocked(); 16111 return; 16112 } 16113 // Still not idle, wait some more. 16114 scheduleAppGcsLocked(); 16115 } 16116 16117 /** 16118 * Schedule the execution of all pending app GCs. 16119 */ 16120 final void scheduleAppGcsLocked() { 16121 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG); 16122 16123 if (mProcessesToGc.size() > 0) { 16124 // Schedule a GC for the time to the next process. 16125 ProcessRecord proc = mProcessesToGc.get(0); 16126 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG); 16127 16128 long when = proc.lastRequestedGc + GC_MIN_INTERVAL; 16129 long now = SystemClock.uptimeMillis(); 16130 if (when < (now+GC_TIMEOUT)) { 16131 when = now + GC_TIMEOUT; 16132 } 16133 mHandler.sendMessageAtTime(msg, when); 16134 } 16135 } 16136 16137 /** 16138 * Add a process to the array of processes waiting to be GCed. Keeps the 16139 * list in sorted order by the last GC time. The process can't already be 16140 * on the list. 16141 */ 16142 final void addProcessToGcListLocked(ProcessRecord proc) { 16143 boolean added = false; 16144 for (int i=mProcessesToGc.size()-1; i>=0; i--) { 16145 if (mProcessesToGc.get(i).lastRequestedGc < 16146 proc.lastRequestedGc) { 16147 added = true; 16148 mProcessesToGc.add(i+1, proc); 16149 break; 16150 } 16151 } 16152 if (!added) { 16153 mProcessesToGc.add(0, proc); 16154 } 16155 } 16156 16157 /** 16158 * Set up to ask a process to GC itself. This will either do it 16159 * immediately, or put it on the list of processes to gc the next 16160 * time things are idle. 16161 */ 16162 final void scheduleAppGcLocked(ProcessRecord app) { 16163 long now = SystemClock.uptimeMillis(); 16164 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) { 16165 return; 16166 } 16167 if (!mProcessesToGc.contains(app)) { 16168 addProcessToGcListLocked(app); 16169 scheduleAppGcsLocked(); 16170 } 16171 } 16172 16173 final void checkExcessivePowerUsageLocked(boolean doKills) { 16174 updateCpuStatsNow(); 16175 16176 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 16177 boolean doWakeKills = doKills; 16178 boolean doCpuKills = doKills; 16179 if (mLastPowerCheckRealtime == 0) { 16180 doWakeKills = false; 16181 } 16182 if (mLastPowerCheckUptime == 0) { 16183 doCpuKills = false; 16184 } 16185 if (stats.isScreenOn()) { 16186 doWakeKills = false; 16187 } 16188 final long curRealtime = SystemClock.elapsedRealtime(); 16189 final long realtimeSince = curRealtime - mLastPowerCheckRealtime; 16190 final long curUptime = SystemClock.uptimeMillis(); 16191 final long uptimeSince = curUptime - mLastPowerCheckUptime; 16192 mLastPowerCheckRealtime = curRealtime; 16193 mLastPowerCheckUptime = curUptime; 16194 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) { 16195 doWakeKills = false; 16196 } 16197 if (uptimeSince < CPU_MIN_CHECK_DURATION) { 16198 doCpuKills = false; 16199 } 16200 int i = mLruProcesses.size(); 16201 while (i > 0) { 16202 i--; 16203 ProcessRecord app = mLruProcesses.get(i); 16204 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 16205 long wtime; 16206 synchronized (stats) { 16207 wtime = stats.getProcessWakeTime(app.info.uid, 16208 app.pid, curRealtime); 16209 } 16210 long wtimeUsed = wtime - app.lastWakeTime; 16211 long cputimeUsed = app.curCpuTime - app.lastCpuTime; 16212 if (DEBUG_POWER) { 16213 StringBuilder sb = new StringBuilder(128); 16214 sb.append("Wake for "); 16215 app.toShortString(sb); 16216 sb.append(": over "); 16217 TimeUtils.formatDuration(realtimeSince, sb); 16218 sb.append(" used "); 16219 TimeUtils.formatDuration(wtimeUsed, sb); 16220 sb.append(" ("); 16221 sb.append((wtimeUsed*100)/realtimeSince); 16222 sb.append("%)"); 16223 Slog.i(TAG, sb.toString()); 16224 sb.setLength(0); 16225 sb.append("CPU for "); 16226 app.toShortString(sb); 16227 sb.append(": over "); 16228 TimeUtils.formatDuration(uptimeSince, sb); 16229 sb.append(" used "); 16230 TimeUtils.formatDuration(cputimeUsed, sb); 16231 sb.append(" ("); 16232 sb.append((cputimeUsed*100)/uptimeSince); 16233 sb.append("%)"); 16234 Slog.i(TAG, sb.toString()); 16235 } 16236 // If a process has held a wake lock for more 16237 // than 50% of the time during this period, 16238 // that sounds bad. Kill! 16239 if (doWakeKills && realtimeSince > 0 16240 && ((wtimeUsed*100)/realtimeSince) >= 50) { 16241 synchronized (stats) { 16242 stats.reportExcessiveWakeLocked(app.info.uid, app.processName, 16243 realtimeSince, wtimeUsed); 16244 } 16245 killUnneededProcessLocked(app, "excessive wake held " + wtimeUsed 16246 + " during " + realtimeSince); 16247 app.baseProcessTracker.reportExcessiveWake(app.pkgList); 16248 } else if (doCpuKills && uptimeSince > 0 16249 && ((cputimeUsed*100)/uptimeSince) >= 25) { 16250 synchronized (stats) { 16251 stats.reportExcessiveCpuLocked(app.info.uid, app.processName, 16252 uptimeSince, cputimeUsed); 16253 } 16254 killUnneededProcessLocked(app, "excessive cpu " + cputimeUsed 16255 + " during " + uptimeSince); 16256 app.baseProcessTracker.reportExcessiveCpu(app.pkgList); 16257 } else { 16258 app.lastWakeTime = wtime; 16259 app.lastCpuTime = app.curCpuTime; 16260 } 16261 } 16262 } 16263 } 16264 16265 private final boolean applyOomAdjLocked(ProcessRecord app, 16266 ProcessRecord TOP_APP, boolean doingAll, long now) { 16267 boolean success = true; 16268 16269 if (app.curRawAdj != app.setRawAdj) { 16270 app.setRawAdj = app.curRawAdj; 16271 } 16272 16273 int changes = 0; 16274 16275 if (app.curAdj != app.setAdj) { 16276 ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj); 16277 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v( 16278 TAG, "Set " + app.pid + " " + app.processName + 16279 " adj " + app.curAdj + ": " + app.adjType); 16280 app.setAdj = app.curAdj; 16281 } 16282 16283 if (app.setSchedGroup != app.curSchedGroup) { 16284 app.setSchedGroup = app.curSchedGroup; 16285 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16286 "Setting process group of " + app.processName 16287 + " to " + app.curSchedGroup); 16288 if (app.waitingToKill != null && 16289 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 16290 killUnneededProcessLocked(app, app.waitingToKill); 16291 success = false; 16292 } else { 16293 if (true) { 16294 long oldId = Binder.clearCallingIdentity(); 16295 try { 16296 Process.setProcessGroup(app.pid, app.curSchedGroup); 16297 } catch (Exception e) { 16298 Slog.w(TAG, "Failed setting process group of " + app.pid 16299 + " to " + app.curSchedGroup); 16300 e.printStackTrace(); 16301 } finally { 16302 Binder.restoreCallingIdentity(oldId); 16303 } 16304 } else { 16305 if (app.thread != null) { 16306 try { 16307 app.thread.setSchedulingGroup(app.curSchedGroup); 16308 } catch (RemoteException e) { 16309 } 16310 } 16311 } 16312 Process.setSwappiness(app.pid, 16313 app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE); 16314 } 16315 } 16316 if (app.repForegroundActivities != app.foregroundActivities) { 16317 app.repForegroundActivities = app.foregroundActivities; 16318 changes |= ProcessChangeItem.CHANGE_ACTIVITIES; 16319 } 16320 if (app.repProcState != app.curProcState) { 16321 app.repProcState = app.curProcState; 16322 changes |= ProcessChangeItem.CHANGE_PROCESS_STATE; 16323 if (app.thread != null) { 16324 try { 16325 if (false) { 16326 //RuntimeException h = new RuntimeException("here"); 16327 Slog.i(TAG, "Sending new process state " + app.repProcState 16328 + " to " + app /*, h*/); 16329 } 16330 app.thread.setProcessState(app.repProcState); 16331 } catch (RemoteException e) { 16332 } 16333 } 16334 } 16335 if (app.setProcState < 0 || ProcessList.procStatesDifferForMem(app.curProcState, 16336 app.setProcState)) { 16337 app.lastStateTime = now; 16338 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 16339 isSleeping(), now); 16340 if (DEBUG_PSS) Slog.d(TAG, "Process state change from " 16341 + ProcessList.makeProcStateString(app.setProcState) + " to " 16342 + ProcessList.makeProcStateString(app.curProcState) + " next pss in " 16343 + (app.nextPssTime-now) + ": " + app); 16344 } else { 16345 if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL) 16346 && now > (app.lastStateTime+ProcessList.PSS_MIN_TIME_FROM_STATE_CHANGE))) { 16347 requestPssLocked(app, app.setProcState); 16348 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false, 16349 isSleeping(), now); 16350 } else if (false && DEBUG_PSS) { 16351 Slog.d(TAG, "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now)); 16352 } 16353 } 16354 if (app.setProcState != app.curProcState) { 16355 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16356 "Proc state change of " + app.processName 16357 + " to " + app.curProcState); 16358 boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE; 16359 boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE; 16360 if (setImportant && !curImportant) { 16361 // This app is no longer something we consider important enough to allow to 16362 // use arbitrary amounts of battery power. Note 16363 // its current wake lock time to later know to kill it if 16364 // it is not behaving well. 16365 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 16366 synchronized (stats) { 16367 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid, 16368 app.pid, SystemClock.elapsedRealtime()); 16369 } 16370 app.lastCpuTime = app.curCpuTime; 16371 16372 } 16373 app.setProcState = app.curProcState; 16374 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 16375 app.notCachedSinceIdle = false; 16376 } 16377 if (!doingAll) { 16378 setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now); 16379 } else { 16380 app.procStateChanged = true; 16381 } 16382 } 16383 16384 if (changes != 0) { 16385 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes); 16386 int i = mPendingProcessChanges.size()-1; 16387 ProcessChangeItem item = null; 16388 while (i >= 0) { 16389 item = mPendingProcessChanges.get(i); 16390 if (item.pid == app.pid) { 16391 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item); 16392 break; 16393 } 16394 i--; 16395 } 16396 if (i < 0) { 16397 // No existing item in pending changes; need a new one. 16398 final int NA = mAvailProcessChanges.size(); 16399 if (NA > 0) { 16400 item = mAvailProcessChanges.remove(NA-1); 16401 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item); 16402 } else { 16403 item = new ProcessChangeItem(); 16404 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item); 16405 } 16406 item.changes = 0; 16407 item.pid = app.pid; 16408 item.uid = app.info.uid; 16409 if (mPendingProcessChanges.size() == 0) { 16410 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, 16411 "*** Enqueueing dispatch processes changed!"); 16412 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget(); 16413 } 16414 mPendingProcessChanges.add(item); 16415 } 16416 item.changes |= changes; 16417 item.processState = app.repProcState; 16418 item.foregroundActivities = app.repForegroundActivities; 16419 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item " 16420 + Integer.toHexString(System.identityHashCode(item)) 16421 + " " + app.toShortString() + ": changes=" + item.changes 16422 + " procState=" + item.processState 16423 + " foreground=" + item.foregroundActivities 16424 + " type=" + app.adjType + " source=" + app.adjSource 16425 + " target=" + app.adjTarget); 16426 } 16427 16428 return success; 16429 } 16430 16431 private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) { 16432 if (proc.thread != null) { 16433 if (proc.baseProcessTracker != null) { 16434 proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList); 16435 } 16436 if (proc.repProcState >= 0) { 16437 mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid, 16438 proc.repProcState); 16439 } 16440 } 16441 } 16442 16443 private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj, 16444 ProcessRecord TOP_APP, boolean doingAll, long now) { 16445 if (app.thread == null) { 16446 return false; 16447 } 16448 16449 computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now); 16450 16451 return applyOomAdjLocked(app, TOP_APP, doingAll, now); 16452 } 16453 16454 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 16455 boolean oomAdj) { 16456 if (isForeground != proc.foregroundServices) { 16457 proc.foregroundServices = isForeground; 16458 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 16459 proc.info.uid); 16460 if (isForeground) { 16461 if (curProcs == null) { 16462 curProcs = new ArrayList<ProcessRecord>(); 16463 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 16464 } 16465 if (!curProcs.contains(proc)) { 16466 curProcs.add(proc); 16467 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 16468 proc.info.packageName, proc.info.uid); 16469 } 16470 } else { 16471 if (curProcs != null) { 16472 if (curProcs.remove(proc)) { 16473 mBatteryStatsService.noteEvent( 16474 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 16475 proc.info.packageName, proc.info.uid); 16476 if (curProcs.size() <= 0) { 16477 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 16478 } 16479 } 16480 } 16481 } 16482 if (oomAdj) { 16483 updateOomAdjLocked(); 16484 } 16485 } 16486 } 16487 16488 private final ActivityRecord resumedAppLocked() { 16489 ActivityRecord act = mStackSupervisor.resumedAppLocked(); 16490 String pkg; 16491 int uid; 16492 if (act != null) { 16493 pkg = act.packageName; 16494 uid = act.info.applicationInfo.uid; 16495 } else { 16496 pkg = null; 16497 uid = -1; 16498 } 16499 // Has the UID or resumed package name changed? 16500 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 16501 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 16502 if (mCurResumedPackage != null) { 16503 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 16504 mCurResumedPackage, mCurResumedUid); 16505 } 16506 mCurResumedPackage = pkg; 16507 mCurResumedUid = uid; 16508 if (mCurResumedPackage != null) { 16509 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 16510 mCurResumedPackage, mCurResumedUid); 16511 } 16512 } 16513 return act; 16514 } 16515 16516 final boolean updateOomAdjLocked(ProcessRecord app) { 16517 final ActivityRecord TOP_ACT = resumedAppLocked(); 16518 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 16519 final boolean wasCached = app.cached; 16520 16521 mAdjSeq++; 16522 16523 // This is the desired cached adjusment we want to tell it to use. 16524 // If our app is currently cached, we know it, and that is it. Otherwise, 16525 // we don't know it yet, and it needs to now be cached we will then 16526 // need to do a complete oom adj. 16527 final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ 16528 ? app.curRawAdj : ProcessList.UNKNOWN_ADJ; 16529 boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false, 16530 SystemClock.uptimeMillis()); 16531 if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) { 16532 // Changed to/from cached state, so apps after it in the LRU 16533 // list may also be changed. 16534 updateOomAdjLocked(); 16535 } 16536 return success; 16537 } 16538 16539 final void updateOomAdjLocked() { 16540 final ActivityRecord TOP_ACT = resumedAppLocked(); 16541 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 16542 final long now = SystemClock.uptimeMillis(); 16543 final long oldTime = now - ProcessList.MAX_EMPTY_TIME; 16544 final int N = mLruProcesses.size(); 16545 16546 if (false) { 16547 RuntimeException e = new RuntimeException(); 16548 e.fillInStackTrace(); 16549 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e); 16550 } 16551 16552 mAdjSeq++; 16553 mNewNumServiceProcs = 0; 16554 mNewNumAServiceProcs = 0; 16555 16556 final int emptyProcessLimit; 16557 final int cachedProcessLimit; 16558 if (mProcessLimit <= 0) { 16559 emptyProcessLimit = cachedProcessLimit = 0; 16560 } else if (mProcessLimit == 1) { 16561 emptyProcessLimit = 1; 16562 cachedProcessLimit = 0; 16563 } else { 16564 emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit); 16565 cachedProcessLimit = mProcessLimit - emptyProcessLimit; 16566 } 16567 16568 // Let's determine how many processes we have running vs. 16569 // how many slots we have for background processes; we may want 16570 // to put multiple processes in a slot of there are enough of 16571 // them. 16572 int numSlots = (ProcessList.CACHED_APP_MAX_ADJ 16573 - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2; 16574 int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs; 16575 if (numEmptyProcs > cachedProcessLimit) { 16576 // If there are more empty processes than our limit on cached 16577 // processes, then use the cached process limit for the factor. 16578 // This ensures that the really old empty processes get pushed 16579 // down to the bottom, so if we are running low on memory we will 16580 // have a better chance at keeping around more cached processes 16581 // instead of a gazillion empty processes. 16582 numEmptyProcs = cachedProcessLimit; 16583 } 16584 int emptyFactor = numEmptyProcs/numSlots; 16585 if (emptyFactor < 1) emptyFactor = 1; 16586 int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots; 16587 if (cachedFactor < 1) cachedFactor = 1; 16588 int stepCached = 0; 16589 int stepEmpty = 0; 16590 int numCached = 0; 16591 int numEmpty = 0; 16592 int numTrimming = 0; 16593 16594 mNumNonCachedProcs = 0; 16595 mNumCachedHiddenProcs = 0; 16596 16597 // First update the OOM adjustment for each of the 16598 // application processes based on their current state. 16599 int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ; 16600 int nextCachedAdj = curCachedAdj+1; 16601 int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ; 16602 int nextEmptyAdj = curEmptyAdj+2; 16603 for (int i=N-1; i>=0; i--) { 16604 ProcessRecord app = mLruProcesses.get(i); 16605 if (!app.killedByAm && app.thread != null) { 16606 app.procStateChanged = false; 16607 computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now); 16608 16609 // If we haven't yet assigned the final cached adj 16610 // to the process, do that now. 16611 if (app.curAdj >= ProcessList.UNKNOWN_ADJ) { 16612 switch (app.curProcState) { 16613 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 16614 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 16615 // This process is a cached process holding activities... 16616 // assign it the next cached value for that type, and then 16617 // step that cached level. 16618 app.curRawAdj = curCachedAdj; 16619 app.curAdj = app.modifyRawOomAdj(curCachedAdj); 16620 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning activity LRU #" + i 16621 + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj 16622 + ")"); 16623 if (curCachedAdj != nextCachedAdj) { 16624 stepCached++; 16625 if (stepCached >= cachedFactor) { 16626 stepCached = 0; 16627 curCachedAdj = nextCachedAdj; 16628 nextCachedAdj += 2; 16629 if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) { 16630 nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ; 16631 } 16632 } 16633 } 16634 break; 16635 default: 16636 // For everything else, assign next empty cached process 16637 // level and bump that up. Note that this means that 16638 // long-running services that have dropped down to the 16639 // cached level will be treated as empty (since their process 16640 // state is still as a service), which is what we want. 16641 app.curRawAdj = curEmptyAdj; 16642 app.curAdj = app.modifyRawOomAdj(curEmptyAdj); 16643 if (DEBUG_LRU && false) Slog.d(TAG, "Assigning empty LRU #" + i 16644 + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj 16645 + ")"); 16646 if (curEmptyAdj != nextEmptyAdj) { 16647 stepEmpty++; 16648 if (stepEmpty >= emptyFactor) { 16649 stepEmpty = 0; 16650 curEmptyAdj = nextEmptyAdj; 16651 nextEmptyAdj += 2; 16652 if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) { 16653 nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ; 16654 } 16655 } 16656 } 16657 break; 16658 } 16659 } 16660 16661 applyOomAdjLocked(app, TOP_APP, true, now); 16662 16663 // Count the number of process types. 16664 switch (app.curProcState) { 16665 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 16666 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 16667 mNumCachedHiddenProcs++; 16668 numCached++; 16669 if (numCached > cachedProcessLimit) { 16670 killUnneededProcessLocked(app, "cached #" + numCached); 16671 } 16672 break; 16673 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 16674 if (numEmpty > ProcessList.TRIM_EMPTY_APPS 16675 && app.lastActivityTime < oldTime) { 16676 killUnneededProcessLocked(app, "empty for " 16677 + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime) 16678 / 1000) + "s"); 16679 } else { 16680 numEmpty++; 16681 if (numEmpty > emptyProcessLimit) { 16682 killUnneededProcessLocked(app, "empty #" + numEmpty); 16683 } 16684 } 16685 break; 16686 default: 16687 mNumNonCachedProcs++; 16688 break; 16689 } 16690 16691 if (app.isolated && app.services.size() <= 0) { 16692 // If this is an isolated process, and there are no 16693 // services running in it, then the process is no longer 16694 // needed. We agressively kill these because we can by 16695 // definition not re-use the same process again, and it is 16696 // good to avoid having whatever code was running in them 16697 // left sitting around after no longer needed. 16698 killUnneededProcessLocked(app, "isolated not needed"); 16699 } 16700 16701 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 16702 && !app.killedByAm) { 16703 numTrimming++; 16704 } 16705 } 16706 } 16707 16708 mNumServiceProcs = mNewNumServiceProcs; 16709 16710 // Now determine the memory trimming level of background processes. 16711 // Unfortunately we need to start at the back of the list to do this 16712 // properly. We only do this if the number of background apps we 16713 // are managing to keep around is less than half the maximum we desire; 16714 // if we are keeping a good number around, we'll let them use whatever 16715 // memory they want. 16716 final int numCachedAndEmpty = numCached + numEmpty; 16717 int memFactor; 16718 if (numCached <= ProcessList.TRIM_CACHED_APPS 16719 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) { 16720 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) { 16721 memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL; 16722 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) { 16723 memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW; 16724 } else { 16725 memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE; 16726 } 16727 } else { 16728 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 16729 } 16730 // We always allow the memory level to go up (better). We only allow it to go 16731 // down if we are in a state where that is allowed, *and* the total number of processes 16732 // has gone down since last time. 16733 if (DEBUG_OOM_ADJ) Slog.d(TAG, "oom: memFactor=" + memFactor + " last=" + mLastMemoryLevel 16734 + " allowLow=" + mAllowLowerMemLevel + " numProcs=" + mLruProcesses.size() 16735 + " last=" + mLastNumProcesses); 16736 if (memFactor > mLastMemoryLevel) { 16737 if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) { 16738 memFactor = mLastMemoryLevel; 16739 if (DEBUG_OOM_ADJ) Slog.d(TAG, "Keeping last mem factor!"); 16740 } 16741 } 16742 mLastMemoryLevel = memFactor; 16743 mLastNumProcesses = mLruProcesses.size(); 16744 boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now); 16745 final int trackerMemFactor = mProcessStats.getMemFactorLocked(); 16746 if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) { 16747 if (mLowRamStartTime == 0) { 16748 mLowRamStartTime = now; 16749 } 16750 int step = 0; 16751 int fgTrimLevel; 16752 switch (memFactor) { 16753 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 16754 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 16755 break; 16756 case ProcessStats.ADJ_MEM_FACTOR_LOW: 16757 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 16758 break; 16759 default: 16760 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 16761 break; 16762 } 16763 int factor = numTrimming/3; 16764 int minFactor = 2; 16765 if (mHomeProcess != null) minFactor++; 16766 if (mPreviousProcess != null) minFactor++; 16767 if (factor < minFactor) factor = minFactor; 16768 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 16769 for (int i=N-1; i>=0; i--) { 16770 ProcessRecord app = mLruProcesses.get(i); 16771 if (allChanged || app.procStateChanged) { 16772 setProcessTrackerStateLocked(app, trackerMemFactor, now); 16773 app.procStateChanged = false; 16774 } 16775 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 16776 && !app.killedByAm) { 16777 if (app.trimMemoryLevel < curLevel && app.thread != null) { 16778 try { 16779 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16780 "Trimming memory of " + app.processName 16781 + " to " + curLevel); 16782 app.thread.scheduleTrimMemory(curLevel); 16783 } catch (RemoteException e) { 16784 } 16785 if (false) { 16786 // For now we won't do this; our memory trimming seems 16787 // to be good enough at this point that destroying 16788 // activities causes more harm than good. 16789 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE 16790 && app != mHomeProcess && app != mPreviousProcess) { 16791 // Need to do this on its own message because the stack may not 16792 // be in a consistent state at this point. 16793 // For these apps we will also finish their activities 16794 // to help them free memory. 16795 mStackSupervisor.scheduleDestroyAllActivities(app, "trim"); 16796 } 16797 } 16798 } 16799 app.trimMemoryLevel = curLevel; 16800 step++; 16801 if (step >= factor) { 16802 step = 0; 16803 switch (curLevel) { 16804 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: 16805 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 16806 break; 16807 case ComponentCallbacks2.TRIM_MEMORY_MODERATE: 16808 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 16809 break; 16810 } 16811 } 16812 } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 16813 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND 16814 && app.thread != null) { 16815 try { 16816 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16817 "Trimming memory of heavy-weight " + app.processName 16818 + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 16819 app.thread.scheduleTrimMemory( 16820 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 16821 } catch (RemoteException e) { 16822 } 16823 } 16824 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 16825 } else { 16826 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16827 || app.systemNoUi) && app.pendingUiClean) { 16828 // If this application is now in the background and it 16829 // had done UI, then give it the special trim level to 16830 // have it free UI resources. 16831 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 16832 if (app.trimMemoryLevel < level && app.thread != null) { 16833 try { 16834 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16835 "Trimming memory of bg-ui " + app.processName 16836 + " to " + level); 16837 app.thread.scheduleTrimMemory(level); 16838 } catch (RemoteException e) { 16839 } 16840 } 16841 app.pendingUiClean = false; 16842 } 16843 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) { 16844 try { 16845 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16846 "Trimming memory of fg " + app.processName 16847 + " to " + fgTrimLevel); 16848 app.thread.scheduleTrimMemory(fgTrimLevel); 16849 } catch (RemoteException e) { 16850 } 16851 } 16852 app.trimMemoryLevel = fgTrimLevel; 16853 } 16854 } 16855 } else { 16856 if (mLowRamStartTime != 0) { 16857 mLowRamTimeSinceLastIdle += now - mLowRamStartTime; 16858 mLowRamStartTime = 0; 16859 } 16860 for (int i=N-1; i>=0; i--) { 16861 ProcessRecord app = mLruProcesses.get(i); 16862 if (allChanged || app.procStateChanged) { 16863 setProcessTrackerStateLocked(app, trackerMemFactor, now); 16864 app.procStateChanged = false; 16865 } 16866 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 16867 || app.systemNoUi) && app.pendingUiClean) { 16868 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN 16869 && app.thread != null) { 16870 try { 16871 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG, 16872 "Trimming memory of ui hidden " + app.processName 16873 + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 16874 app.thread.scheduleTrimMemory( 16875 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 16876 } catch (RemoteException e) { 16877 } 16878 } 16879 app.pendingUiClean = false; 16880 } 16881 app.trimMemoryLevel = 0; 16882 } 16883 } 16884 16885 if (mAlwaysFinishActivities) { 16886 // Need to do this on its own message because the stack may not 16887 // be in a consistent state at this point. 16888 mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish"); 16889 } 16890 16891 if (allChanged) { 16892 requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered()); 16893 } 16894 16895 if (mProcessStats.shouldWriteNowLocked(now)) { 16896 mHandler.post(new Runnable() { 16897 @Override public void run() { 16898 synchronized (ActivityManagerService.this) { 16899 mProcessStats.writeStateAsyncLocked(); 16900 } 16901 } 16902 }); 16903 } 16904 16905 if (DEBUG_OOM_ADJ) { 16906 Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms"); 16907 } 16908 } 16909 16910 final void trimApplications() { 16911 synchronized (this) { 16912 int i; 16913 16914 // First remove any unused application processes whose package 16915 // has been removed. 16916 for (i=mRemovedProcesses.size()-1; i>=0; i--) { 16917 final ProcessRecord app = mRemovedProcesses.get(i); 16918 if (app.activities.size() == 0 16919 && app.curReceiver == null && app.services.size() == 0) { 16920 Slog.i( 16921 TAG, "Exiting empty application process " 16922 + app.processName + " (" 16923 + (app.thread != null ? app.thread.asBinder() : null) 16924 + ")\n"); 16925 if (app.pid > 0 && app.pid != MY_PID) { 16926 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid, 16927 app.processName, app.setAdj, "empty"); 16928 app.killedByAm = true; 16929 Process.killProcessQuiet(app.pid); 16930 Process.killProcessGroup(app.info.uid, app.pid); 16931 } else { 16932 try { 16933 app.thread.scheduleExit(); 16934 } catch (Exception e) { 16935 // Ignore exceptions. 16936 } 16937 } 16938 cleanUpApplicationRecordLocked(app, false, true, -1); 16939 mRemovedProcesses.remove(i); 16940 16941 if (app.persistent) { 16942 addAppLocked(app.info, false, null /* ABI override */); 16943 } 16944 } 16945 } 16946 16947 // Now update the oom adj for all processes. 16948 updateOomAdjLocked(); 16949 } 16950 } 16951 16952 /** This method sends the specified signal to each of the persistent apps */ 16953 public void signalPersistentProcesses(int sig) throws RemoteException { 16954 if (sig != Process.SIGNAL_USR1) { 16955 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 16956 } 16957 16958 synchronized (this) { 16959 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 16960 != PackageManager.PERMISSION_GRANTED) { 16961 throw new SecurityException("Requires permission " 16962 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 16963 } 16964 16965 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 16966 ProcessRecord r = mLruProcesses.get(i); 16967 if (r.thread != null && r.persistent) { 16968 Process.sendSignal(r.pid, sig); 16969 } 16970 } 16971 } 16972 } 16973 16974 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) { 16975 if (proc == null || proc == mProfileProc) { 16976 proc = mProfileProc; 16977 path = mProfileFile; 16978 profileType = mProfileType; 16979 clearProfilerLocked(); 16980 } 16981 if (proc == null) { 16982 return; 16983 } 16984 try { 16985 proc.thread.profilerControl(false, path, null, profileType); 16986 } catch (RemoteException e) { 16987 throw new IllegalStateException("Process disappeared"); 16988 } 16989 } 16990 16991 private void clearProfilerLocked() { 16992 if (mProfileFd != null) { 16993 try { 16994 mProfileFd.close(); 16995 } catch (IOException e) { 16996 } 16997 } 16998 mProfileApp = null; 16999 mProfileProc = null; 17000 mProfileFile = null; 17001 mProfileType = 0; 17002 mAutoStopProfiler = false; 17003 } 17004 17005 public boolean profileControl(String process, int userId, boolean start, 17006 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException { 17007 17008 try { 17009 synchronized (this) { 17010 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17011 // its own permission. 17012 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17013 != PackageManager.PERMISSION_GRANTED) { 17014 throw new SecurityException("Requires permission " 17015 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17016 } 17017 17018 if (start && fd == null) { 17019 throw new IllegalArgumentException("null fd"); 17020 } 17021 17022 ProcessRecord proc = null; 17023 if (process != null) { 17024 proc = findProcessLocked(process, userId, "profileControl"); 17025 } 17026 17027 if (start && (proc == null || proc.thread == null)) { 17028 throw new IllegalArgumentException("Unknown process: " + process); 17029 } 17030 17031 if (start) { 17032 stopProfilerLocked(null, null, 0); 17033 setProfileApp(proc.info, proc.processName, path, fd, false); 17034 mProfileProc = proc; 17035 mProfileType = profileType; 17036 try { 17037 fd = fd.dup(); 17038 } catch (IOException e) { 17039 fd = null; 17040 } 17041 proc.thread.profilerControl(start, path, fd, profileType); 17042 fd = null; 17043 mProfileFd = null; 17044 } else { 17045 stopProfilerLocked(proc, path, profileType); 17046 if (fd != null) { 17047 try { 17048 fd.close(); 17049 } catch (IOException e) { 17050 } 17051 } 17052 } 17053 17054 return true; 17055 } 17056 } catch (RemoteException e) { 17057 throw new IllegalStateException("Process disappeared"); 17058 } finally { 17059 if (fd != null) { 17060 try { 17061 fd.close(); 17062 } catch (IOException e) { 17063 } 17064 } 17065 } 17066 } 17067 17068 private ProcessRecord findProcessLocked(String process, int userId, String callName) { 17069 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17070 userId, true, ALLOW_FULL_ONLY, callName, null); 17071 ProcessRecord proc = null; 17072 try { 17073 int pid = Integer.parseInt(process); 17074 synchronized (mPidsSelfLocked) { 17075 proc = mPidsSelfLocked.get(pid); 17076 } 17077 } catch (NumberFormatException e) { 17078 } 17079 17080 if (proc == null) { 17081 ArrayMap<String, SparseArray<ProcessRecord>> all 17082 = mProcessNames.getMap(); 17083 SparseArray<ProcessRecord> procs = all.get(process); 17084 if (procs != null && procs.size() > 0) { 17085 proc = procs.valueAt(0); 17086 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 17087 for (int i=1; i<procs.size(); i++) { 17088 ProcessRecord thisProc = procs.valueAt(i); 17089 if (thisProc.userId == userId) { 17090 proc = thisProc; 17091 break; 17092 } 17093 } 17094 } 17095 } 17096 } 17097 17098 return proc; 17099 } 17100 17101 public boolean dumpHeap(String process, int userId, boolean managed, 17102 String path, ParcelFileDescriptor fd) throws RemoteException { 17103 17104 try { 17105 synchronized (this) { 17106 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 17107 // its own permission (same as profileControl). 17108 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 17109 != PackageManager.PERMISSION_GRANTED) { 17110 throw new SecurityException("Requires permission " 17111 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 17112 } 17113 17114 if (fd == null) { 17115 throw new IllegalArgumentException("null fd"); 17116 } 17117 17118 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap"); 17119 if (proc == null || proc.thread == null) { 17120 throw new IllegalArgumentException("Unknown process: " + process); 17121 } 17122 17123 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 17124 if (!isDebuggable) { 17125 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 17126 throw new SecurityException("Process not debuggable: " + proc); 17127 } 17128 } 17129 17130 proc.thread.dumpHeap(managed, path, fd); 17131 fd = null; 17132 return true; 17133 } 17134 } catch (RemoteException e) { 17135 throw new IllegalStateException("Process disappeared"); 17136 } finally { 17137 if (fd != null) { 17138 try { 17139 fd.close(); 17140 } catch (IOException e) { 17141 } 17142 } 17143 } 17144 } 17145 17146 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ 17147 public void monitor() { 17148 synchronized (this) { } 17149 } 17150 17151 void onCoreSettingsChange(Bundle settings) { 17152 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 17153 ProcessRecord processRecord = mLruProcesses.get(i); 17154 try { 17155 if (processRecord.thread != null) { 17156 processRecord.thread.setCoreSettings(settings); 17157 } 17158 } catch (RemoteException re) { 17159 /* ignore */ 17160 } 17161 } 17162 } 17163 17164 // Multi-user methods 17165 17166 /** 17167 * Start user, if its not already running, but don't bring it to foreground. 17168 */ 17169 @Override 17170 public boolean startUserInBackground(final int userId) { 17171 return startUser(userId, /* foreground */ false); 17172 } 17173 17174 /** 17175 * Refreshes the list of users related to the current user when either a 17176 * user switch happens or when a new related user is started in the 17177 * background. 17178 */ 17179 private void updateCurrentProfileIdsLocked() { 17180 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 17181 mCurrentUserId, false /* enabledOnly */); 17182 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null 17183 for (int i = 0; i < currentProfileIds.length; i++) { 17184 currentProfileIds[i] = profiles.get(i).id; 17185 } 17186 mCurrentProfileIds = currentProfileIds; 17187 17188 synchronized (mUserProfileGroupIdsSelfLocked) { 17189 mUserProfileGroupIdsSelfLocked.clear(); 17190 final List<UserInfo> users = getUserManagerLocked().getUsers(false); 17191 for (int i = 0; i < users.size(); i++) { 17192 UserInfo user = users.get(i); 17193 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 17194 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId); 17195 } 17196 } 17197 } 17198 } 17199 17200 private Set getProfileIdsLocked(int userId) { 17201 Set userIds = new HashSet<Integer>(); 17202 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 17203 userId, false /* enabledOnly */); 17204 for (UserInfo user : profiles) { 17205 userIds.add(Integer.valueOf(user.id)); 17206 } 17207 return userIds; 17208 } 17209 17210 @Override 17211 public boolean switchUser(final int userId) { 17212 return startUser(userId, /* foregound */ true); 17213 } 17214 17215 private boolean startUser(final int userId, boolean foreground) { 17216 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 17217 != PackageManager.PERMISSION_GRANTED) { 17218 String msg = "Permission Denial: switchUser() from pid=" 17219 + Binder.getCallingPid() 17220 + ", uid=" + Binder.getCallingUid() 17221 + " requires " + INTERACT_ACROSS_USERS_FULL; 17222 Slog.w(TAG, msg); 17223 throw new SecurityException(msg); 17224 } 17225 17226 if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground); 17227 17228 final long ident = Binder.clearCallingIdentity(); 17229 try { 17230 synchronized (this) { 17231 final int oldUserId = mCurrentUserId; 17232 if (oldUserId == userId) { 17233 return true; 17234 } 17235 17236 mStackSupervisor.setLockTaskModeLocked(null, false); 17237 17238 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 17239 if (userInfo == null) { 17240 Slog.w(TAG, "No user info for user #" + userId); 17241 return false; 17242 } 17243 17244 if (foreground) { 17245 mWindowManager.startFreezingScreen(R.anim.screen_user_exit, 17246 R.anim.screen_user_enter); 17247 } 17248 17249 boolean needStart = false; 17250 17251 // If the user we are switching to is not currently started, then 17252 // we need to start it now. 17253 if (mStartedUsers.get(userId) == null) { 17254 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false)); 17255 updateStartedUserArrayLocked(); 17256 needStart = true; 17257 } 17258 17259 final Integer userIdInt = Integer.valueOf(userId); 17260 mUserLru.remove(userIdInt); 17261 mUserLru.add(userIdInt); 17262 17263 if (foreground) { 17264 mCurrentUserId = userId; 17265 updateCurrentProfileIdsLocked(); 17266 mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 17267 // Once the internal notion of the active user has switched, we lock the device 17268 // with the option to show the user switcher on the keyguard. 17269 mWindowManager.lockNow(null); 17270 } else { 17271 final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId); 17272 updateCurrentProfileIdsLocked(); 17273 mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 17274 mUserLru.remove(currentUserIdInt); 17275 mUserLru.add(currentUserIdInt); 17276 } 17277 17278 final UserStartedState uss = mStartedUsers.get(userId); 17279 17280 // Make sure user is in the started state. If it is currently 17281 // stopping, we need to knock that off. 17282 if (uss.mState == UserStartedState.STATE_STOPPING) { 17283 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 17284 // so we can just fairly silently bring the user back from 17285 // the almost-dead. 17286 uss.mState = UserStartedState.STATE_RUNNING; 17287 updateStartedUserArrayLocked(); 17288 needStart = true; 17289 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) { 17290 // This means ACTION_SHUTDOWN has been sent, so we will 17291 // need to treat this as a new boot of the user. 17292 uss.mState = UserStartedState.STATE_BOOTING; 17293 updateStartedUserArrayLocked(); 17294 needStart = true; 17295 } 17296 17297 if (uss.mState == UserStartedState.STATE_BOOTING) { 17298 // Booting up a new user, need to tell system services about it. 17299 // Note that this is on the same handler as scheduling of broadcasts, 17300 // which is important because it needs to go first. 17301 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId)); 17302 } 17303 17304 if (foreground) { 17305 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 17306 oldUserId)); 17307 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 17308 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 17309 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 17310 oldUserId, userId, uss)); 17311 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 17312 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 17313 } 17314 17315 if (needStart) { 17316 // Send USER_STARTED broadcast 17317 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 17318 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17319 | Intent.FLAG_RECEIVER_FOREGROUND); 17320 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17321 broadcastIntentLocked(null, null, intent, 17322 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 17323 false, false, MY_PID, Process.SYSTEM_UID, userId); 17324 } 17325 17326 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) { 17327 if (userId != UserHandle.USER_OWNER) { 17328 // Send PRE_BOOT_COMPLETED broadcasts for this new user 17329 final ArrayList<ComponentName> doneReceivers 17330 = new ArrayList<ComponentName>(); 17331 deliverPreBootCompleted(null, doneReceivers, userId); 17332 17333 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); 17334 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 17335 broadcastIntentLocked(null, null, intent, null, 17336 new IIntentReceiver.Stub() { 17337 public void performReceive(Intent intent, int resultCode, 17338 String data, Bundle extras, boolean ordered, 17339 boolean sticky, int sendingUser) { 17340 userInitialized(uss, userId); 17341 } 17342 }, 0, null, null, null, AppOpsManager.OP_NONE, 17343 true, false, MY_PID, Process.SYSTEM_UID, 17344 userId); 17345 uss.initializing = true; 17346 } else { 17347 getUserManagerLocked().makeInitialized(userInfo.id); 17348 } 17349 } 17350 17351 if (foreground) { 17352 boolean homeInFront = mStackSupervisor.switchUserLocked(userId, uss); 17353 if (homeInFront) { 17354 startHomeActivityLocked(userId); 17355 } else { 17356 mStackSupervisor.resumeTopActivitiesLocked(); 17357 } 17358 EventLogTags.writeAmSwitchUser(userId); 17359 getUserManagerLocked().userForeground(userId); 17360 sendUserSwitchBroadcastsLocked(oldUserId, userId); 17361 } else { 17362 mStackSupervisor.startBackgroundUserLocked(userId, uss); 17363 } 17364 17365 if (needStart) { 17366 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 17367 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 17368 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17369 broadcastIntentLocked(null, null, intent, 17370 null, new IIntentReceiver.Stub() { 17371 @Override 17372 public void performReceive(Intent intent, int resultCode, String data, 17373 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 17374 throws RemoteException { 17375 } 17376 }, 0, null, null, 17377 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 17378 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 17379 } 17380 } 17381 } finally { 17382 Binder.restoreCallingIdentity(ident); 17383 } 17384 17385 return true; 17386 } 17387 17388 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) { 17389 long ident = Binder.clearCallingIdentity(); 17390 try { 17391 Intent intent; 17392 if (oldUserId >= 0) { 17393 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user 17394 List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false); 17395 int count = profiles.size(); 17396 for (int i = 0; i < count; i++) { 17397 int profileUserId = profiles.get(i).id; 17398 intent = new Intent(Intent.ACTION_USER_BACKGROUND); 17399 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17400 | Intent.FLAG_RECEIVER_FOREGROUND); 17401 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 17402 broadcastIntentLocked(null, null, intent, 17403 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 17404 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 17405 } 17406 } 17407 if (newUserId >= 0) { 17408 // Send USER_FOREGROUND broadcast to all profiles of the incoming user 17409 List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false); 17410 int count = profiles.size(); 17411 for (int i = 0; i < count; i++) { 17412 int profileUserId = profiles.get(i).id; 17413 intent = new Intent(Intent.ACTION_USER_FOREGROUND); 17414 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17415 | Intent.FLAG_RECEIVER_FOREGROUND); 17416 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 17417 broadcastIntentLocked(null, null, intent, 17418 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 17419 false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 17420 } 17421 intent = new Intent(Intent.ACTION_USER_SWITCHED); 17422 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17423 | Intent.FLAG_RECEIVER_FOREGROUND); 17424 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId); 17425 broadcastIntentLocked(null, null, intent, 17426 null, null, 0, null, null, 17427 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE, 17428 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 17429 } 17430 } finally { 17431 Binder.restoreCallingIdentity(ident); 17432 } 17433 } 17434 17435 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId, 17436 final int newUserId) { 17437 final int N = mUserSwitchObservers.beginBroadcast(); 17438 if (N > 0) { 17439 final IRemoteCallback callback = new IRemoteCallback.Stub() { 17440 int mCount = 0; 17441 @Override 17442 public void sendResult(Bundle data) throws RemoteException { 17443 synchronized (ActivityManagerService.this) { 17444 if (mCurUserSwitchCallback == this) { 17445 mCount++; 17446 if (mCount == N) { 17447 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 17448 } 17449 } 17450 } 17451 } 17452 }; 17453 synchronized (this) { 17454 uss.switching = true; 17455 mCurUserSwitchCallback = callback; 17456 } 17457 for (int i=0; i<N; i++) { 17458 try { 17459 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching( 17460 newUserId, callback); 17461 } catch (RemoteException e) { 17462 } 17463 } 17464 } else { 17465 synchronized (this) { 17466 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 17467 } 17468 } 17469 mUserSwitchObservers.finishBroadcast(); 17470 } 17471 17472 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 17473 synchronized (this) { 17474 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId); 17475 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 17476 } 17477 } 17478 17479 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) { 17480 mCurUserSwitchCallback = null; 17481 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 17482 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG, 17483 oldUserId, newUserId, uss)); 17484 } 17485 17486 void userInitialized(UserStartedState uss, int newUserId) { 17487 completeSwitchAndInitalize(uss, newUserId, true, false); 17488 } 17489 17490 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) { 17491 completeSwitchAndInitalize(uss, newUserId, false, true); 17492 } 17493 17494 void completeSwitchAndInitalize(UserStartedState uss, int newUserId, 17495 boolean clearInitializing, boolean clearSwitching) { 17496 boolean unfrozen = false; 17497 synchronized (this) { 17498 if (clearInitializing) { 17499 uss.initializing = false; 17500 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier()); 17501 } 17502 if (clearSwitching) { 17503 uss.switching = false; 17504 } 17505 if (!uss.switching && !uss.initializing) { 17506 mWindowManager.stopFreezingScreen(); 17507 unfrozen = true; 17508 } 17509 } 17510 if (unfrozen) { 17511 final int N = mUserSwitchObservers.beginBroadcast(); 17512 for (int i=0; i<N; i++) { 17513 try { 17514 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId); 17515 } catch (RemoteException e) { 17516 } 17517 } 17518 mUserSwitchObservers.finishBroadcast(); 17519 } 17520 } 17521 17522 void scheduleStartProfilesLocked() { 17523 if (!mHandler.hasMessages(START_PROFILES_MSG)) { 17524 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG), 17525 DateUtils.SECOND_IN_MILLIS); 17526 } 17527 } 17528 17529 void startProfilesLocked() { 17530 if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked"); 17531 List<UserInfo> profiles = getUserManagerLocked().getProfiles( 17532 mCurrentUserId, false /* enabledOnly */); 17533 List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size()); 17534 for (UserInfo user : profiles) { 17535 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 17536 && user.id != mCurrentUserId) { 17537 toStart.add(user); 17538 } 17539 } 17540 final int n = toStart.size(); 17541 int i = 0; 17542 for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) { 17543 startUserInBackground(toStart.get(i).id); 17544 } 17545 if (i < n) { 17546 Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS"); 17547 } 17548 } 17549 17550 void finishUserBoot(UserStartedState uss) { 17551 synchronized (this) { 17552 if (uss.mState == UserStartedState.STATE_BOOTING 17553 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) { 17554 uss.mState = UserStartedState.STATE_RUNNING; 17555 final int userId = uss.mHandle.getIdentifier(); 17556 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 17557 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17558 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 17559 broadcastIntentLocked(null, null, intent, 17560 null, null, 0, null, null, 17561 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE, 17562 true, false, MY_PID, Process.SYSTEM_UID, userId); 17563 } 17564 } 17565 } 17566 17567 void finishUserSwitch(UserStartedState uss) { 17568 synchronized (this) { 17569 finishUserBoot(uss); 17570 17571 startProfilesLocked(); 17572 17573 int num = mUserLru.size(); 17574 int i = 0; 17575 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) { 17576 Integer oldUserId = mUserLru.get(i); 17577 UserStartedState oldUss = mStartedUsers.get(oldUserId); 17578 if (oldUss == null) { 17579 // Shouldn't happen, but be sane if it does. 17580 mUserLru.remove(i); 17581 num--; 17582 continue; 17583 } 17584 if (oldUss.mState == UserStartedState.STATE_STOPPING 17585 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) { 17586 // This user is already stopping, doesn't count. 17587 num--; 17588 i++; 17589 continue; 17590 } 17591 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) { 17592 // Owner and current can't be stopped, but count as running. 17593 i++; 17594 continue; 17595 } 17596 // This is a user to be stopped. 17597 stopUserLocked(oldUserId, null); 17598 num--; 17599 i++; 17600 } 17601 } 17602 } 17603 17604 @Override 17605 public int stopUser(final int userId, final IStopUserCallback callback) { 17606 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 17607 != PackageManager.PERMISSION_GRANTED) { 17608 String msg = "Permission Denial: switchUser() from pid=" 17609 + Binder.getCallingPid() 17610 + ", uid=" + Binder.getCallingUid() 17611 + " requires " + INTERACT_ACROSS_USERS_FULL; 17612 Slog.w(TAG, msg); 17613 throw new SecurityException(msg); 17614 } 17615 if (userId <= 0) { 17616 throw new IllegalArgumentException("Can't stop primary user " + userId); 17617 } 17618 synchronized (this) { 17619 return stopUserLocked(userId, callback); 17620 } 17621 } 17622 17623 private int stopUserLocked(final int userId, final IStopUserCallback callback) { 17624 if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId); 17625 if (mCurrentUserId == userId) { 17626 return ActivityManager.USER_OP_IS_CURRENT; 17627 } 17628 17629 final UserStartedState uss = mStartedUsers.get(userId); 17630 if (uss == null) { 17631 // User is not started, nothing to do... but we do need to 17632 // callback if requested. 17633 if (callback != null) { 17634 mHandler.post(new Runnable() { 17635 @Override 17636 public void run() { 17637 try { 17638 callback.userStopped(userId); 17639 } catch (RemoteException e) { 17640 } 17641 } 17642 }); 17643 } 17644 return ActivityManager.USER_OP_SUCCESS; 17645 } 17646 17647 if (callback != null) { 17648 uss.mStopCallbacks.add(callback); 17649 } 17650 17651 if (uss.mState != UserStartedState.STATE_STOPPING 17652 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 17653 uss.mState = UserStartedState.STATE_STOPPING; 17654 updateStartedUserArrayLocked(); 17655 17656 long ident = Binder.clearCallingIdentity(); 17657 try { 17658 // We are going to broadcast ACTION_USER_STOPPING and then 17659 // once that is done send a final ACTION_SHUTDOWN and then 17660 // stop the user. 17661 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING); 17662 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 17663 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17664 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 17665 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 17666 // This is the result receiver for the final shutdown broadcast. 17667 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 17668 @Override 17669 public void performReceive(Intent intent, int resultCode, String data, 17670 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 17671 finishUserStop(uss); 17672 } 17673 }; 17674 // This is the result receiver for the initial stopping broadcast. 17675 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() { 17676 @Override 17677 public void performReceive(Intent intent, int resultCode, String data, 17678 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 17679 // On to the next. 17680 synchronized (ActivityManagerService.this) { 17681 if (uss.mState != UserStartedState.STATE_STOPPING) { 17682 // Whoops, we are being started back up. Abort, abort! 17683 return; 17684 } 17685 uss.mState = UserStartedState.STATE_SHUTDOWN; 17686 } 17687 mBatteryStatsService.noteEvent( 17688 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 17689 Integer.toString(userId), userId); 17690 mSystemServiceManager.stopUser(userId); 17691 broadcastIntentLocked(null, null, shutdownIntent, 17692 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE, 17693 true, false, MY_PID, Process.SYSTEM_UID, userId); 17694 } 17695 }; 17696 // Kick things off. 17697 broadcastIntentLocked(null, null, stoppingIntent, 17698 null, stoppingReceiver, 0, null, null, 17699 INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE, 17700 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 17701 } finally { 17702 Binder.restoreCallingIdentity(ident); 17703 } 17704 } 17705 17706 return ActivityManager.USER_OP_SUCCESS; 17707 } 17708 17709 void finishUserStop(UserStartedState uss) { 17710 final int userId = uss.mHandle.getIdentifier(); 17711 boolean stopped; 17712 ArrayList<IStopUserCallback> callbacks; 17713 synchronized (this) { 17714 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks); 17715 if (mStartedUsers.get(userId) != uss) { 17716 stopped = false; 17717 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) { 17718 stopped = false; 17719 } else { 17720 stopped = true; 17721 // User can no longer run. 17722 mStartedUsers.remove(userId); 17723 mUserLru.remove(Integer.valueOf(userId)); 17724 updateStartedUserArrayLocked(); 17725 17726 // Clean up all state and processes associated with the user. 17727 // Kill all the processes for the user. 17728 forceStopUserLocked(userId, "finish user"); 17729 } 17730 17731 // Explicitly remove the old information in mRecentTasks. 17732 removeRecentTasksForUserLocked(userId); 17733 } 17734 17735 for (int i=0; i<callbacks.size(); i++) { 17736 try { 17737 if (stopped) callbacks.get(i).userStopped(userId); 17738 else callbacks.get(i).userStopAborted(userId); 17739 } catch (RemoteException e) { 17740 } 17741 } 17742 17743 if (stopped) { 17744 mSystemServiceManager.cleanupUser(userId); 17745 synchronized (this) { 17746 mStackSupervisor.removeUserLocked(userId); 17747 } 17748 } 17749 } 17750 17751 @Override 17752 public UserInfo getCurrentUser() { 17753 if ((checkCallingPermission(INTERACT_ACROSS_USERS) 17754 != PackageManager.PERMISSION_GRANTED) && ( 17755 checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 17756 != PackageManager.PERMISSION_GRANTED)) { 17757 String msg = "Permission Denial: getCurrentUser() from pid=" 17758 + Binder.getCallingPid() 17759 + ", uid=" + Binder.getCallingUid() 17760 + " requires " + INTERACT_ACROSS_USERS; 17761 Slog.w(TAG, msg); 17762 throw new SecurityException(msg); 17763 } 17764 synchronized (this) { 17765 return getUserManagerLocked().getUserInfo(mCurrentUserId); 17766 } 17767 } 17768 17769 int getCurrentUserIdLocked() { 17770 return mCurrentUserId; 17771 } 17772 17773 @Override 17774 public boolean isUserRunning(int userId, boolean orStopped) { 17775 if (checkCallingPermission(INTERACT_ACROSS_USERS) 17776 != PackageManager.PERMISSION_GRANTED) { 17777 String msg = "Permission Denial: isUserRunning() from pid=" 17778 + Binder.getCallingPid() 17779 + ", uid=" + Binder.getCallingUid() 17780 + " requires " + INTERACT_ACROSS_USERS; 17781 Slog.w(TAG, msg); 17782 throw new SecurityException(msg); 17783 } 17784 synchronized (this) { 17785 return isUserRunningLocked(userId, orStopped); 17786 } 17787 } 17788 17789 boolean isUserRunningLocked(int userId, boolean orStopped) { 17790 UserStartedState state = mStartedUsers.get(userId); 17791 if (state == null) { 17792 return false; 17793 } 17794 if (orStopped) { 17795 return true; 17796 } 17797 return state.mState != UserStartedState.STATE_STOPPING 17798 && state.mState != UserStartedState.STATE_SHUTDOWN; 17799 } 17800 17801 @Override 17802 public int[] getRunningUserIds() { 17803 if (checkCallingPermission(INTERACT_ACROSS_USERS) 17804 != PackageManager.PERMISSION_GRANTED) { 17805 String msg = "Permission Denial: isUserRunning() from pid=" 17806 + Binder.getCallingPid() 17807 + ", uid=" + Binder.getCallingUid() 17808 + " requires " + INTERACT_ACROSS_USERS; 17809 Slog.w(TAG, msg); 17810 throw new SecurityException(msg); 17811 } 17812 synchronized (this) { 17813 return mStartedUserArray; 17814 } 17815 } 17816 17817 private void updateStartedUserArrayLocked() { 17818 int num = 0; 17819 for (int i=0; i<mStartedUsers.size(); i++) { 17820 UserStartedState uss = mStartedUsers.valueAt(i); 17821 // This list does not include stopping users. 17822 if (uss.mState != UserStartedState.STATE_STOPPING 17823 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 17824 num++; 17825 } 17826 } 17827 mStartedUserArray = new int[num]; 17828 num = 0; 17829 for (int i=0; i<mStartedUsers.size(); i++) { 17830 UserStartedState uss = mStartedUsers.valueAt(i); 17831 if (uss.mState != UserStartedState.STATE_STOPPING 17832 && uss.mState != UserStartedState.STATE_SHUTDOWN) { 17833 mStartedUserArray[num] = mStartedUsers.keyAt(i); 17834 num++; 17835 } 17836 } 17837 } 17838 17839 @Override 17840 public void registerUserSwitchObserver(IUserSwitchObserver observer) { 17841 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 17842 != PackageManager.PERMISSION_GRANTED) { 17843 String msg = "Permission Denial: registerUserSwitchObserver() from pid=" 17844 + Binder.getCallingPid() 17845 + ", uid=" + Binder.getCallingUid() 17846 + " requires " + INTERACT_ACROSS_USERS_FULL; 17847 Slog.w(TAG, msg); 17848 throw new SecurityException(msg); 17849 } 17850 17851 mUserSwitchObservers.register(observer); 17852 } 17853 17854 @Override 17855 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 17856 mUserSwitchObservers.unregister(observer); 17857 } 17858 17859 private boolean userExists(int userId) { 17860 if (userId == 0) { 17861 return true; 17862 } 17863 UserManagerService ums = getUserManagerLocked(); 17864 return ums != null ? (ums.getUserInfo(userId) != null) : false; 17865 } 17866 17867 int[] getUsersLocked() { 17868 UserManagerService ums = getUserManagerLocked(); 17869 return ums != null ? ums.getUserIds() : new int[] { 0 }; 17870 } 17871 17872 UserManagerService getUserManagerLocked() { 17873 if (mUserManager == null) { 17874 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 17875 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b); 17876 } 17877 return mUserManager; 17878 } 17879 17880 private int applyUserId(int uid, int userId) { 17881 return UserHandle.getUid(userId, uid); 17882 } 17883 17884 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 17885 if (info == null) return null; 17886 ApplicationInfo newInfo = new ApplicationInfo(info); 17887 newInfo.uid = applyUserId(info.uid, userId); 17888 newInfo.dataDir = USER_DATA_DIR + userId + "/" 17889 + info.packageName; 17890 return newInfo; 17891 } 17892 17893 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 17894 if (aInfo == null 17895 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 17896 return aInfo; 17897 } 17898 17899 ActivityInfo info = new ActivityInfo(aInfo); 17900 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 17901 return info; 17902 } 17903 17904 private final class LocalService extends ActivityManagerInternal { 17905 @Override 17906 public void goingToSleep() { 17907 ActivityManagerService.this.goingToSleep(); 17908 } 17909 17910 @Override 17911 public void wakingUp() { 17912 ActivityManagerService.this.wakingUp(); 17913 } 17914 17915 @Override 17916 public int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 17917 String processName, String abiOverride, int uid, Runnable crashHandler) { 17918 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 17919 processName, abiOverride, uid, crashHandler); 17920 } 17921 } 17922 17923 /** 17924 * An implementation of IAppTask, that allows an app to manage its own tasks via 17925 * {@link android.app.ActivityManager.AppTask}. We keep track of the callingUid to ensure that 17926 * only the process that calls getAppTasks() can call the AppTask methods. 17927 */ 17928 class AppTaskImpl extends IAppTask.Stub { 17929 private int mTaskId; 17930 private int mCallingUid; 17931 17932 public AppTaskImpl(int taskId, int callingUid) { 17933 mTaskId = taskId; 17934 mCallingUid = callingUid; 17935 } 17936 17937 @Override 17938 public void finishAndRemoveTask() { 17939 // Ensure that we are called from the same process that created this AppTask 17940 if (mCallingUid != Binder.getCallingUid()) { 17941 Slog.w(TAG, "finishAndRemoveTask: caller " + mCallingUid 17942 + " does not match caller of getAppTasks(): " + Binder.getCallingUid()); 17943 return; 17944 } 17945 17946 synchronized (ActivityManagerService.this) { 17947 long origId = Binder.clearCallingIdentity(); 17948 try { 17949 TaskRecord tr = recentTaskForIdLocked(mTaskId); 17950 if (tr != null) { 17951 // Only kill the process if we are not a new document 17952 int flags = tr.getBaseIntent().getFlags(); 17953 boolean isDocument = (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) == 17954 Intent.FLAG_ACTIVITY_NEW_DOCUMENT; 17955 removeTaskByIdLocked(mTaskId, 17956 !isDocument ? ActivityManager.REMOVE_TASK_KILL_PROCESS : 0); 17957 } 17958 } finally { 17959 Binder.restoreCallingIdentity(origId); 17960 } 17961 } 17962 } 17963 17964 @Override 17965 public ActivityManager.RecentTaskInfo getTaskInfo() { 17966 // Ensure that we are called from the same process that created this AppTask 17967 if (mCallingUid != Binder.getCallingUid()) { 17968 Slog.w(TAG, "finishAndRemoveTask: caller " + mCallingUid 17969 + " does not match caller of getAppTasks(): " + Binder.getCallingUid()); 17970 return null; 17971 } 17972 17973 synchronized (ActivityManagerService.this) { 17974 long origId = Binder.clearCallingIdentity(); 17975 try { 17976 TaskRecord tr = recentTaskForIdLocked(mTaskId); 17977 if (tr != null) { 17978 return createRecentTaskInfoFromTaskRecord(tr); 17979 } 17980 } finally { 17981 Binder.restoreCallingIdentity(origId); 17982 } 17983 return null; 17984 } 17985 } 17986 } 17987} 17988